@yeaft/webchat-agent 1.0.399 → 1.0.400

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 +1 @@
1
- {"version":"1.0.399"}
1
+ {"version":"1.0.400"}
@@ -1,4 +1,4 @@
1
- var O=(e,t,s)=>()=>{if(s)throw s[0];try{return e&&(t=e(e=0)),t}catch(n){throw s=[n],n}};var Yh=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(s){throw t=0,s}};function Xl(e,t){let s=nacl.randomBytes(24),n=JSON.stringify(e),r,i=!1;n.length>512?(r=pako.gzip(n),i=!0):r=nacl.util.decodeUTF8(n);let o=nacl.secretbox(r,s,t),a={n:nacl.util.encodeBase64(s),c:nacl.util.encodeBase64(o)};return i&&(a.z=!0),a}function Zl(e,t){try{let s=nacl.util.decodeBase64(e.n),n=nacl.util.decodeBase64(e.c),r=nacl.secretbox.open(n,s,t);if(!r)return null;if(e.z){let i=pako.ungzip(r,{to:"string"});return JSON.parse(i)}else return JSON.parse(nacl.util.encodeUTF8(r))}catch{return null}}function Jl(e){return e&&typeof e=="object"&&typeof e.n=="string"&&typeof e.c=="string"}function yt(e){return nacl.util.decodeBase64(e)}var Fr=O(()=>{});function Ht(){return globalThis.localStorage||null}function tc(){let e=Nr();for(let t of _o)try{t(e)}catch{}}function Gh(){try{Ht()?.removeItem(En),Ht()?.removeItem(Ln)}catch{}}function Qh(e){return String(e||"").trim()||null}function ec(e,t){if(!$n(t))return{};try{let s=JSON.parse(Ht()?.getItem(e)||"null");return!s||typeof s!="object"||Array.isArray(s)||s.ownerId!==t.ownerId||!s.records||typeof s.records!="object"||Array.isArray(s.records)?(Ht()?.removeItem(e),{}):s.records}catch{try{Ht()?.removeItem(e)}catch{}return{}}}function sc(e,t,s){if(!$n(s))return!1;try{return Ht()?.setItem(e,JSON.stringify({ownerId:s.ownerId,records:t||{}})),!0}catch{return!1}}function bt(e){let t=Qh(e);if(!t)return Do(),null;if(vs!==t){vs=t,Br+=1;for(let s of[En,Ln])try{let n=JSON.parse(Ht()?.getItem(s)||"null");(!n||n.ownerId!==t)&&Ht()?.removeItem(s)}catch{try{Ht()?.removeItem(s)}catch{}}tc()}return Nr()}function Do(){vs=null,Br+=1,Gh(),tc()}function Nr(){return vs?{ownerId:vs,epoch:Br}:null}function $n(e){return!!e&&!!vs&&e.ownerId===vs&&e.epoch===Br}function nc(e){return{drafts:ec(En,e),outbox:ec(Ln,e)}}function Eo(e,t){return sc(En,e,t)}function Vn(e,t){return sc(Ln,e,t)}function rc(e){return typeof e!="function"?()=>{}:(_o.add(e),()=>_o.delete(e))}var En,Ln,vs,Br,_o,Jb,Lo=O(()=>{En="yeaft-work-center-composer-drafts-v1",Ln="yeaft-work-center-message-outbox-v1",vs=null,Br=0,_o=new Set;Jb=Object.freeze({drafts:En,outbox:Ln})});function $o(){try{globalThis.Pinia?.useChatStore?.()?.clearYeaftHistoryMemory?.()}catch{}}function Ot(e){let t=String(e||"").trim()||null;qr!==t&&$o(),qr=t}function Zh(){$o(),qr=null}var Xh,qr,Jh,Re,wt=O(()=>{Fr();Lo();({defineStore:Xh}=Pinia);qr=null;Jh=1800*1e3,Re=Xh("auth",{state:()=>({skipAuth:!1,emailVerification:!1,passwordResetEnabled:!1,totpEnabled:!1,registrationEnabled:!1,aadEnabled:!1,aadClientId:null,aadTenantId:null,ssoProviders:{github:!1,google:!1,wechat:!1,alipay:!1},linkedIdentities:[],hasPassword:!1,identitiesLoading:!1,identitiesError:null,initialized:!1,authGeneration:0,isAuthenticated:!1,token:null,sessionKey:null,userId:null,role:null,loginStep:"credentials",tempToken:null,emailHint:null,setupToken:null,totpSecret:null,qrCode:null,error:null,loading:!1,qrPanel:null,_qrPollTimer:null,_sessionRefreshTimer:null,_sessionRefreshVisibilityHandler:null}),actions:{async initialize(){if(this.initialized)return this.isAuthenticated;try{if(await this.checkAuthMode(),this.skipAuth&&this.isAuthenticated)return!0;let e=!1;return typeof window<"u"&&typeof this.consumeSsoRedirect=="function"&&(e=this.consumeSsoRedirect()),!this.isAuthenticated&&!e&&await this.restoreSession(),this.isAuthenticated}finally{this.initialized=!0}},async checkAuthMode(){try{let t=await(await fetch("/api/auth/mode")).json();this.skipAuth=t.skipAuth,this.emailVerification=t.emailVerification,this.passwordResetEnabled=!!t.passwordResetEnabled,this.totpEnabled=t.totpEnabled,this.registrationEnabled=t.registrationEnabled||!1,this.aadEnabled=t.aadEnabled||!1,this.aadClientId=t.aadClientId||null,this.aadTenantId=t.aadTenantId||null,this.ssoProviders=Object.assign({github:!1,google:!1,wechat:!1,alipay:!1},t.ssoProviders||{}),this.skipAuth&&(this.userId="skip-auth",bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated")}catch{}},async login(e,t){this.loading=!0,this.error=null;try{let n=await(await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t})})).json();return n.success?n.needTotpSetup?(this.setupToken=n.setupToken,this.totpSecret=n.totpSecret,this.qrCode=n.qrCode,this.loginStep="totp-setup",!0):n.needTotpCode?(this.tempToken=n.tempToken,this.loginStep="totp",!0):n.needEmailCode?(this.tempToken=n.tempToken,this.emailHint=n.emailHint,this.loginStep="verification",!0):(this.token=n.token,this.sessionKey=n.sessionKey?yt(n.sessionKey):null,this.role=n.role||"pro",this.userId=n.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",localStorage.setItem("authToken",n.token),this.startSessionRefresh(),!0):(this.error=n.error||"Login failed",!1)}catch(s){return this.error=s.message||"Network error",!1}finally{this.loading=!1}},async loginWithMicrosoft(){if(!this.aadEnabled||!this.aadClientId||!this.aadTenantId)return this.error="Microsoft login is not configured",!1;if(typeof msal>"u"||!msal.PublicClientApplication)return this.error="Microsoft authentication library not loaded",!1;this.loading=!0,this.error=null;try{let e={auth:{clientId:this.aadClientId,authority:`https://login.microsoftonline.com/${this.aadTenantId}`,redirectUri:window.location.origin+"/auth/callback"},cache:{cacheLocation:"sessionStorage",storeAuthStateInCookie:!1}},t=new msal.PublicClientApplication(e);await t.initialize();let s=await t.loginPopup({scopes:["openid","profile","email"]});if(!s||!s.idToken)return this.error="Microsoft login failed: no token received",!1;let r=await(await fetch("/api/auth/aad",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({idToken:s.idToken})})).json();return r.success?(this.token=r.token,this.sessionKey=r.sessionKey?yt(r.sessionKey):null,this.role=r.role||"pro",this.userId=r.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",localStorage.setItem("authToken",r.token),this.startSessionRefresh(),!0):(this.error=r.error||"Microsoft login failed",!1)}catch(e){return e.errorCode==="user_cancelled"||e.name==="BrowserAuthError"?(this.error=null,!1):(this.error=e.message||"Microsoft login failed",!1)}finally{this.loading=!1}},async verifyTotpCode(e){this.loading=!0,this.error=null;try{let s=await(await fetch("/api/auth/verify-totp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tempToken:this.tempToken,totpCode:e})})).json();return s.success?s.needEmailCode?(this.tempToken=s.tempToken,this.emailHint=s.emailHint,this.loginStep="verification",!0):(this.token=s.token,this.sessionKey=s.sessionKey?yt(s.sessionKey):null,this.role=s.role||"pro",this.userId=s.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",this.tempToken=null,localStorage.setItem("authToken",s.token),this.startSessionRefresh(),!0):(this.error=s.error||"TOTP verification failed",!1)}catch(t){return this.error=t.message||"Network error",!1}finally{this.loading=!1}},async completeTotpSetup(e){this.loading=!0,this.error=null;try{let s=await(await fetch("/api/auth/setup-totp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({setupToken:this.setupToken,totpCode:e})})).json();return s.success?(this.setupToken=null,this.totpSecret=null,this.qrCode=null,s.needEmailCode?(this.tempToken=s.tempToken,this.emailHint=s.emailHint,this.loginStep="verification",!0):(this.token=s.token,this.sessionKey=s.sessionKey?yt(s.sessionKey):null,this.role=s.role||"pro",this.userId=s.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",localStorage.setItem("authToken",s.token),this.startSessionRefresh(),!0)):(this.error=s.error||"TOTP setup failed",!1)}catch(t){return this.error=t.message||"Network error",!1}finally{this.loading=!1}},async verifyCode(e){this.loading=!0,this.error=null;try{let s=await(await fetch("/api/auth/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tempToken:this.tempToken,code:e})})).json();return s.success?(this.token=s.token,this.sessionKey=s.sessionKey?yt(s.sessionKey):null,this.role=s.role||"pro",this.userId=s.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",this.tempToken=null,this.emailHint=null,localStorage.setItem("authToken",s.token),this.startSessionRefresh(),!0):(this.error=s.error||"Verification failed",!1)}catch(t){return this.error=t.message||"Network error",!1}finally{this.loading=!1}},async register(e,t,s,n){this.loading=!0,this.error=null;try{let i=await(await fetch("/api/auth/register",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t,email:s||void 0,invitationCode:n})})).json();return i.success?!0:(this.error=i.error||"Registration failed",!1)}catch(r){return this.error=r.message||"Network error",!1}finally{this.loading=!1}},showRegister(){this.loginStep="register",this.error=null},loginWithSso(e){window.location.href=`/api/auth/sso/${encodeURIComponent(e)}/start`},async loginWithAlipayMobile({intent:e="login"}={}){if(!await this.startSsoQr("alipay",{intent:e}))return!1;let s=this.qrPanel?.authorizeUrl;if(!s)return!1;let n=`alipays://platformapi/startapp?appId=20000067&url=${encodeURIComponent(s)}`;return this.qrPanel={...this.qrPanel,mobileDeepLink:!0},window.location.href=n,!0},async startSsoQr(e,{intent:t="login"}={}){this.cancelSsoQr(),this.error=null;try{let s=new URLSearchParams;if(t==="bind"){if(!this.isAuthenticated)return this.error="You must be logged in to bind an identity",!1;s.set("intent","bind")}let n=s.toString(),r=`/api/auth/sso/${encodeURIComponent(e)}/start-qr${n?"?"+n:""}`,i=await fetch(r),o=await i.json();return!i.ok||!o.success?(this.error=o.error||"Failed to start QR login",!1):(this.qrPanel={provider:e,intent:t,authorizeUrl:o.authorizeUrl,state:o.state,status:"pending",error:null},this._startQrPoll(),!0)}catch(s){return this.error=s.message||"Network error",!1}},_startQrPoll(){this._stopQrPollTimer();let e=async()=>{if(!this.qrPanel)return;let t=this.qrPanel.state;try{let n=await(await fetch(`/api/auth/sso/poll/${encodeURIComponent(t)}`)).json();if(!this.qrPanel||this.qrPanel.state!==t||n.status==="pending")return;if(n.status==="login"){this.token=n.token,this.sessionKey=n.sessionKey?yt(n.sessionKey):null,this.role=n.role||"pro",this.userId=n.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",localStorage.setItem("authToken",n.token),this.startSessionRefresh(),this.cancelSsoQr();return}if(n.status==="bind"){this.qrPanel={...this.qrPanel,status:"bound"},this._stopQrPollTimer();return}this.qrPanel={...this.qrPanel,status:"error",error:n.error||"SSO failed"},this._stopQrPollTimer()}catch{}};this._qrPollTick=e,this._qrPollTimer=setInterval(e,2e3),typeof document<"u"&&!this._qrVisHandler&&(this._qrVisHandler=()=>{typeof document<"u"&&document.visibilityState&&document.visibilityState!=="visible"||!this.qrPanel||!this._qrPollTick||(this._qrPollTick(),this._qrPollTimer&&clearInterval(this._qrPollTimer),this._qrPollTimer=setInterval(this._qrPollTick,2e3))},document.addEventListener("visibilitychange",this._qrVisHandler),typeof window<"u"&&window.addEventListener("pageshow",this._qrVisHandler))},_stopQrPollTimer(){this._qrPollTimer&&(clearInterval(this._qrPollTimer),this._qrPollTimer=null),this._qrVisHandler&&(typeof document<"u"&&document.removeEventListener("visibilitychange",this._qrVisHandler),typeof window<"u"&&window.removeEventListener("pageshow",this._qrVisHandler),this._qrVisHandler=null),this._qrPollTick=null},cancelSsoQr(){this._stopQrPollTimer(),this.qrPanel=null},bindSso(e){if(!this.isAuthenticated){this.error="You must be logged in to bind an identity";return}let t=new URLSearchParams({intent:"bind"});window.location.href=`/api/auth/sso/${encodeURIComponent(e)}/start?${t.toString()}`},consumeSsoRedirect(){let e=window.location.hash||"",t=e.indexOf("?");if(!e.startsWith("#/sso-complete")||t<0)return!1;let s=new URLSearchParams(e.slice(t+1)),n=s.get("token"),r=s.get("sessionKey"),i=s.get("role"),o=s.get("userId");if(!n)return!1;this.token=n,this.sessionKey=r?yt(r):null,this.role=i||"pro",this.userId=o||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",localStorage.setItem("authToken",n),this.startSessionRefresh();try{history.replaceState(null,"",window.location.pathname+window.location.search)}catch{}return!0},async loadIdentities(){if(this.isAuthenticated){this.identitiesLoading=!0,this.identitiesError=null;try{let e=await fetch("/api/auth/identities"),t=await e.json();if(!e.ok||!t.success){this.identitiesError=t.error||"Failed to load identities";return}this.linkedIdentities=t.identities||[],this.hasPassword=!!t.hasPassword}catch(e){this.identitiesError=e.message||"Network error"}finally{this.identitiesLoading=!1}}},async unbindIdentity(e){if(!this.isAuthenticated)return!1;this.identitiesError=null;try{let t=await fetch(`/api/auth/identities/${encodeURIComponent(e)}`,{method:"DELETE"}),s=await t.json();return!t.ok||!s.success?(this.identitiesError=s.error||"Failed to unbind",!1):(this.linkedIdentities=this.linkedIdentities.filter(n=>n.provider!==e),!0)}catch(t){return this.identitiesError=t.message||"Network error",!1}},async refreshSession(){let e=this.token,t=this.authGeneration,s=this.isAuthenticated;try{let n=await fetch("/api/user/profile",{headers:e?{Authorization:`Bearer ${e}`}:{}});if(this.handleAuthResponse(n,e,t,s)||!n.ok)return!1;let r=await n.json().catch(()=>({}));if(t!==this.authGeneration||this.token!==e)return this.isAuthenticated;let i=n.headers?.get?.("X-New-Token"),o=localStorage.getItem("authToken");i&&this.token===e&&(!o||o===e)&&(this.token=i,localStorage.setItem("authToken",i)),r?.role&&(this.role=r.role);let a=this.userId;return this.userId=r?.userId||null,bt(this.userId),a!==this.userId&&$o(),qr=this.userId,!0}catch{return!1}},startSessionRefresh(){if(this.stopSessionRefresh(),!this.isAuthenticated||this.skipAuth)return;let e=()=>{typeof document<"u"&&document.visibilityState&&document.visibilityState!=="visible"||this.refreshSession()};this._sessionRefreshTimer=setInterval(e,Jh),this._sessionRefreshVisibilityHandler=e,typeof document<"u"&&document.addEventListener("visibilitychange",e),typeof window<"u"&&window.addEventListener("pageshow",e)},stopSessionRefresh(){this._sessionRefreshTimer&&(clearInterval(this._sessionRefreshTimer),this._sessionRefreshTimer=null),this._sessionRefreshVisibilityHandler&&(typeof document<"u"&&document.removeEventListener("visibilitychange",this._sessionRefreshVisibilityHandler),typeof window<"u"&&window.removeEventListener("pageshow",this._sessionRefreshVisibilityHandler),this._sessionRefreshVisibilityHandler=null)},async logout(){try{let e={"Content-Type":"application/json"};this.token&&(e.Authorization=`Bearer ${this.token}`),await fetch("/api/auth/logout",{method:"POST",headers:e})}catch{}await this.clearStoredSession()},clearStoredSession(e=null){let t=this.reset();return localStorage.removeItem("authToken"),e&&(this.error=e),t},getActiveToken(){if(this.token)return this.token;let e=localStorage.getItem("authToken");return e&&(this.token=e),this.token},handleAuthResponse(e,t=null,s=this.authGeneration,n=this.isAuthenticated,r=void 0){if(!e||e.status!==401||!n||s!==this.authGeneration)return!1;let i=this.token||localStorage.getItem("authToken")||null;return t!==i?!1:(this.handleAuthFailure(r,t,s),!0)},handleAuthFailure(e="Session expired. Please log in again.",t=null,s=this.authGeneration){if(s!==this.authGeneration)return!1;let n=this.token||localStorage.getItem("authToken")||null;return t!==n||this.clearStoredSession(e),!1},async restoreSession(){let e=localStorage.getItem("authToken"),t=this.authGeneration,s=this.isAuthenticated||!!e;try{let n=await fetch("/api/user/profile",{headers:e?{Authorization:`Bearer ${e}`}:{}});if(this.handleAuthResponse(n,e,t,s))return!1;if(!n.ok)return this.error="Failed to restore session",!1;let r=await n.json();if(t!==this.authGeneration)return this.isAuthenticated;let i=n.headers?.get?.("X-New-Token"),o=this.getActiveToken();if(o!==e)return this.isAuthenticated;let a=i&&(!o||o===e)?i:o||e;return this.token=a,a&&a!==e&&localStorage.setItem("authToken",a),this.role=r?.role||"pro",this.userId=r?.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",this.startSessionRefresh(),!0}catch(n){return this.error=n.message||"Failed to restore session",!1}},setSessionKey(e){e&&(this.sessionKey=yt(e))},backToCredentials(){this.loginStep="credentials",this.tempToken=null,this.emailHint=null,this.setupToken=null,this.totpSecret=null,this.qrCode=null,this.error=null},async requestPasswordReset(e){this.error=null;try{let s=await(await fetch("/api/auth/password-reset/request",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})})).json();return s.success?s.resetToken||null:(this.error=s.error||"Failed to request password reset",null)}catch(t){return this.error=t.message||"Network error",null}},async verifyPasswordReset(e,t,s){this.error=null;try{let r=await(await fetch("/api/auth/password-reset/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resetToken:e,code:t,newPassword:s})})).json();return r.success?!0:(this.error=r.error||"Failed to reset password",!1)}catch(n){return this.error=n.message||"Network error",!1}},async deleteAccount({currentPassword:e,confirm:t}={}){if(!this.isAuthenticated)return{success:!1,error:"Not authenticated"};try{let s=await fetch("/api/user/me",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:e,confirm:t})}),n=await s.json();return!s.ok||!n.success?{success:!1,error:n.error||"Failed to delete account"}:(await this.clearStoredSession(),{success:!0})}catch(s){return{success:!1,error:s.message||"Network error"}}},reset(){Do(),Zh(),this.authGeneration+=1,this.stopSessionRefresh(),this.isAuthenticated=!1,this.token=null,this.sessionKey=null,this.userId=null,this.role=null,this.loginStep="credentials",this.tempToken=null,this.emailHint=null,this.setupToken=null,this.totpSecret=null,this.qrCode=null,this.error=null,this.loading=!1}}})});function _e(e,t){let s=Ft?.value||"zh-CN",r=(zs[s]||zs["zh-CN"]||{})[e];if(r===void 0&&s!=="zh-CN"&&(r=(zs["zh-CN"]||{})[e]),r===void 0)return e;if(t)for(let[i,o]of Object.entries(t))r=r.replace(new RegExp(`\\{${i}\\}`,"g"),o);return r}function em(){return Ft?.value||"zh-CN"}function Hn(e){zs[e]&&(Ft&&(Ft.value=e),localStorage.setItem("locale",e),document.documentElement.setAttribute("lang",e))}function tm(){let e=localStorage.getItem("locale");return e&&zs[e]?e:(navigator.language||navigator.userLanguage||"").startsWith("en")?"en":"zh-CN"}function ic(e,t){return zs=t,Ft=Vue.ref(tm()),document.documentElement.setAttribute("lang",Ft.value),e.config.globalProperties.$t=_e,e.config.globalProperties.$locale=Ft,e.provide("t",_e),e.provide("locale",Ft),{t:_e,setLocale:Hn,getLocale:em,locale:Ft}}var Ft,zs,Bt=O(()=>{Ft=null,zs={}});function Wr(e){if(e==null||e==="")return"claude-code";if(sm.has(e))return e;throw new Error(`Unknown Chat runtime provider: ${e}`)}function Jt(e){if(typeof e!="string"||!e)throw new Error("Chat catalog key requires conversationId");return`chat:${e}`}function jr(e,t){if(typeof e!="string"||!e||typeof t!="string"||!t)throw new Error("Yeaft catalog key requires agentId and sessionId");return`yeaft:${e}:${t}`}function On(e,t,s={}){let n=e.sessionCatalog.map(i=>({...i})),r=Array.isArray(e.hiddenSessionCatalog)?e.hiddenSessionCatalog.map(i=>({...i})):null;return e.sessionCatalogMutationRequests[t]={previousCatalog:n,previousHiddenCatalog:r,...s},n}function oc(e,t){let s=t?.requestId?e.sessionCatalogMutationRequests[t.requestId]:null;return s?(delete e.sessionCatalogMutationRequests[t.requestId],t.ok!==!0&&(e.sessionCatalog=s.previousCatalog,Array.isArray(s.previousHiddenCatalog)&&(e.hiddenSessionCatalog=s.previousHiddenCatalog)),!0):!1}function ac(e,t,s="recent",n=null){let r=Jt(t),i=e.chatHistoryRequests[r]||{},o=Number(i.generation||0)+1,a=`chat_history_${o}_${crypto.randomUUID()}`;return e.chatHistoryRequests[r]={requestId:a,catalogKey:r,generation:o,mode:s,cursor:n,connectionGeneration:Number(e.chatHistoryConnectionGeneration||0),loading:!0,cancelled:!1,error:null},a}function Vo(e,t,s,n){let r=e.chatHistoryRequests[t];return r?.requestId!==s?!1:(e.chatHistoryRequests[t]={...r,loading:!1,cancelled:!0,error:n},!0)}var sm,Ho=O(()=>{sm=new Set(["claude-code","copilot"])});function Ys(e,t,s=""){Fn&&(clearTimeout(Fn),Fn=null),e.sessionLoading=t,e.sessionLoadingText=s,t&&(Fn=setTimeout(()=>{e.sessionLoading&&(e.sessionLoading=!1,e.sessionLoadingText=""),Fn=null},nm))}function At(e){Ys(e,!1)}function lc(e){if(e.currentConversation){e.pendingRecovery=null;return}let t=e.lastUsedSession,s=e.lastUsedAgent;if(t&&t.sessionId&&s){let n=e.agents.find(r=>r.id===s&&r.online);n&&(e.pendingRecovery={agentId:s,agentName:n.name,sessionId:t.sessionId,workDir:t.workDir,provider:Wr(t.provider),catalogKey:t.catalogKey||null},e.recoveryDismissed=!1)}}function cc(e){if(!e.pendingRecovery)return;let{agentId:t,sessionId:s,workDir:n,provider:r}=e.pendingRecovery;e.selectAgent(t),setTimeout(()=>{e.resumeConversation(s,n,t,{provider:Wr(r)}),e.pendingRecovery=null,e.recoveryDismissed=!1},500)}function dc(e){e.recoveryDismissed=!0,e.pendingRecovery=null}function uc(e,t){let s=e.conversations.find(n=>n.id===t);s&&(e.activeConversations=[t],e.currentWorkDir=s.workDir,e.messagesMap[t]?.length>0||(s.claudeSessionId?(e.messagesMap[t]=[],Ys(e,!0,_e("chat.session.loadingHistory")),e.sendWsMessage({type:"resume_conversation",agentId:s.agentId||e.currentAgent,claudeSessionId:s.claudeSessionId,workDir:s.workDir,conversationId:t})):(e.messagesMap[t]=[],e.requestChatHistory?.(t,{mode:"recent",turns:5}))),e.sendWsMessage({type:"select_conversation",conversationId:t}))}function pc(e){if(e.panels.length>0)return;let t=localStorage.getItem("panels");if(!t)return;let s;try{s=JSON.parse(t)}catch{localStorage.removeItem("panels");return}if(!Array.isArray(s)||s.length<2){localStorage.removeItem("panels");return}let n=new Set(e.conversations.map(i=>i.id)),r=s.filter(i=>i&&typeof i.id=="string").map(i=>({id:i.id,conversationId:i.conversationId&&n.has(i.conversationId)?i.conversationId:null,activeRightPanel:i.activeRightPanel||null}));if(r.length<2){localStorage.removeItem("panels");return}e.panels=r,e.activePanelId=r[0]?.id||null;for(let i of r)i.conversationId&&(e.activeConversations.includes(i.conversationId)||e.activeConversations.push(i.conversationId),e.messagesMap[i.conversationId]||(e.messagesMap[i.conversationId]=[]),e.messagesMap[i.conversationId].length||e.requestChatHistory?.(i.conversationId,{mode:"recent",turns:5}))}function ys(e){if(e.currentAgent){if(localStorage.setItem("lastUsedAgent",e.currentAgent),localStorage.setItem("lastViewedConversation",e.currentConversation||""),e.lastViewedConversation=e.currentConversation,e.currentConversation){let t=e.conversations.find(s=>s.id===e.currentConversation);if(t?.claudeSessionId&&t?.workDir){let s=Wr(t.provider),n={sessionId:t.claudeSessionId,workDir:t.workDir,agentId:t.agentId||e.currentAgent,provider:s,catalogKey:Jt(t.id),version:2};localStorage.setItem("lastUsedSession",JSON.stringify(n)),localStorage.setItem("lastViewedSessionRef",JSON.stringify(n)),e.lastUsedSession=n}}e.lastUsedAgent=e.currentAgent,e.panels.length>0?localStorage.setItem("panels",JSON.stringify(e.panels)):localStorage.removeItem("panels")}}function fc(e){return e.lastUsedSession}function gc(e){localStorage.removeItem("lastUsedAgent"),localStorage.removeItem("lastUsedSession"),localStorage.removeItem("lastViewedSessionRef"),localStorage.removeItem("lastViewedConversation"),localStorage.removeItem("panels"),localStorage.removeItem("splitPanesSaved"),e.lastUsedAgent=null,e.lastUsedSession=null,e.lastViewedConversation=null}function hc(e,t,s){if(!e.currentAgent){e.historySessionsLoading=!1;return}if(!t){e.historySessions=[],e.historySessionsLoading=!1;return}let n=Date.now().toString();e._historySessionsRequestId=n,e.historySessionsLoading=!0,e.historySessions=[],e.sendWsMessage({type:"list_history_sessions",workDir:t,provider:s||"claude-code",requestId:n})}function mc(e,t){if(!e.currentAgent)return e.foldersLoading=!1,Promise.resolve();e.foldersLoading=!0,e.folders=[];let s=Date.now().toString();return e._foldersRequestId=s,new Promise(n=>{e._foldersResolve&&e._foldersResolve(),e._foldersResolve=n,e.sendWsMessage({type:"list_folders",provider:t||"claude-code",requestId:s}),setTimeout(()=>{e._foldersResolve===n&&(e._foldersResolve(),e._foldersResolve=null,e.foldersLoading=!1)},1e4)})}function vc(e,t,s){if(!t)return e.foldersLoading=!1,Promise.resolve();e.foldersLoading=!0,e.folders=[];let n=Date.now().toString();return e._foldersRequestId=n,new Promise(r=>{e._foldersResolve&&e._foldersResolve(),e._foldersResolve=r,e.sendWsMessage({type:"list_folders",agentId:t,provider:s||"claude-code",requestId:n}),setTimeout(()=>{e._foldersResolve===r&&(e._foldersResolve(),e._foldersResolve=null,e.foldersLoading=!1)},1e4)})}function yc(e,t,s){if(!t)return Promise.resolve([]);let n=`models-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return e._modelsRequestId=n,e.providerModelsLoading=!0,new Promise(r=>{e._modelsResolve&&e._modelsResolve([]),e._modelsTimeout&&clearTimeout(e._modelsTimeout),e._modelsResolve=r,e.sendWsMessage({type:"list_models",agentId:t,provider:s||"claude-code",requestId:n}),e._modelsTimeout=setTimeout(()=>{e._modelsResolve===r&&(e._modelsResolve([]),e._modelsResolve=null,e.providerModelsLoading=!1),e._modelsTimeout=null},1e4)})}function bc(e,t,s,n){if(!t){e.historySessionsLoading=!1;return}if(!s){e.historySessions=[],e.historySessionsLoading=!1;return}let r=Date.now().toString();e._historySessionsRequestId=r,e.historySessionsLoading=!0,e.historySessions=[],e.sendWsMessage({type:"list_history_sessions",agentId:t,workDir:s,provider:n||"claude-code",requestId:r})}async function wc(e,t=20){if(Re().isAuthenticated){e.globalSessionsLoading=!0;try{let n=await fetch(`/api/sessions?limit=${t}`);if(n.ok){let r=await n.json();e.globalSessions=r.sessions||[]}}catch{}finally{e.globalSessionsLoading=!1}}}async function kc(e,t){if(!Re().isAuthenticated)return!1;try{if((await fetch(`/api/sessions/${t}`,{method:"DELETE"})).ok)return e.globalSessions=e.globalSessions.filter(r=>r.id!==t),!0}catch{}return!1}function Oo(e,t){return t.agentId?e.agents.find(s=>s.id===t.agentId):t.agentName?e.agents.find(s=>s.name===t.agentName):null}function Sc(e,t){let s=Oo(e,t);return s&&s.online}var nm,Fn,bs=O(()=>{wt();Bt();Ho();nm=3e4,Fn=null});function Ic(e){return e?.code===1008&&String(e.reason||"").toLowerCase().includes("authentication")}function Cc(e){let t=Bn;Bn=[];for(let{resolve:s,reject:n,timer:r}of t)clearTimeout(r),e?s():n(new Error("WebSocket reconnect failed"))}function Ac(e,t){if(!e.ws||e.ws.readyState!==WebSocket.OPEN)return!1;if(e.currentView==="yeaft"&&im.has(t.type)){let s=t.conversationId;if(!s||typeof s=="string"&&s.startsWith("yeaft-")||s===e.yeaftConversationId)return!1}try{if(e.serverEncryptionRequired&&e.sessionKey){let s=Xl(t,e.sessionKey);e.ws.send(JSON.stringify(s))}else e.ws.send(JSON.stringify(t));return!0}catch{return!1}}function Nn(e,t=1e4){return e.ws&&e.ws.readyState===WebSocket.OPEN?Promise.resolve():new Promise((s,n)=>{let r=setTimeout(()=>{Bn=Bn.filter(i=>i.resolve!==s),n(new Error("WebSocket reconnect timeout"))},t);Bn.push({resolve:s,reject:n,timer:r}),(!e.ws||e.ws.readyState!==WebSocket.CONNECTING)&&(e.reconnectAttempts=0,e.connect())})}function xc(e,t){try{let s=JSON.parse(t);return e.sessionKey&&Jl(s)?Zl(s,e.sessionKey):s}catch{return null}}function Tc(e){let t=Re(),s=location.protocol==="https:"?"wss:":"ws:";e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);let n=t.getActiveToken?.()||t.token||null,r=t.authGeneration;if(e.ws&&e.ws.readyState===WebSocket.CONNECTING&&e._wsAuthToken===n&&e._wsAuthGeneration===r)return;clearTimeout(e._legacyYeaftSessionHydrateTimer),e._legacyYeaftSessionHydrateTimer=null,e._hasHandledAgentList=!1,e._hasHandledYeaftSessionHydrate=!1,e.yeaftSessionInventoryCompleteSupported=null,e.yeaftSessionHydrateRequestId=null,e.yeaftSessionHydrateSlices=[],e.yeaftSessionHydrateError=null,e._yeaftSessionInventorySocketQuarantined=!1,e.pendingAgentSelection=null,e.agentSwitching=!1,e.ws&&(e.ws.onopen=null,e.ws.onmessage=null,e.ws.onclose=null,e.ws.close(),e.ws=null),e.connectionState=e.reconnectAttempts>0?"reconnecting":"connecting",e.serverEncryptionRequired=!0,e.chatHistoryRequestIdSupported=null,e.chatHistoryConnectionGeneration=Number(e.chatHistoryConnectionGeneration||0)+1;for(let[l,c]of Object.entries(e.projectMutationRequests||{}))c?.resolve?.({ok:!1,requestId:l,error:{code:"connection_changed"}});e.projectMutationRequests={},e.sessionProjects=[];for(let[l,c]of Object.entries(e.chatHistoryRequests||{}))c?.loading&&(e.chatHistoryRequests[l]={...c,loading:!1,cancelled:!0,error:"connection_changed"});let i=Object.values(e.sessionCatalogMutationRequests||{});i.length>0&&(e.sessionCatalog=i[0].previousCatalog,Array.isArray(i[0].previousHiddenCatalog)&&(e.hiddenSessionCatalog=i[0].previousHiddenCatalog),e.sessionCatalogMutationRequests={}),e.sessionCatalogLoaded=!1,e.sessionCatalog=[],e.hiddenSessionCatalog=[],e.activeCatalogKey=null,e._wsAuthToken=n,e._wsAuthGeneration=r;let o=`${s}//${location.host}?type=web`;n&&(o+=`&token=${encodeURIComponent(n)}`);let a=new WebSocket(o);e.ws=a,a.onopen=()=>{if(a===e.ws){e.connectionState="connected",e.reconnectAttempts=0,e.startHeartbeat();try{a.send(JSON.stringify({type:"client_hello",plaintextOk:!0}))}catch{}Cc(!0)}},a.onmessage=l=>{if(a!==e.ws)return;let c=e.parseWsMessage(l.data);c&&(c.type,e.handleMessage({...c,_wsAuthToken:n,_wsAuthGeneration:r}))},a.onclose=l=>{if(a!==e.ws){Ic(l)&&t.handleAuthFailure?.(void 0,n,r);return}e.authenticated=!1,clearTimeout(e._legacyYeaftSessionHydrateTimer),e._legacyYeaftSessionHydrateTimer=null,e._hasHandledAgentList=!1,e._hasHandledYeaftSessionHydrate=!1,e.yeaftSessionInventoryCompleteSupported=null,e.yeaftSessionHydrateRequestId=null,e.yeaftSessionHydrateSlices=[],e.yeaftSessionHydrateError=null,e.pendingAgentSelection=null,e.agentSwitching=!1;let c=e.connectionState==="updating";if(e.connectionState=c?"updating":"disconnected",e.stopHeartbeat(),At(e),Ic(l)){t.handleAuthFailure?.(void 0,n,r),e.reconnectAttempts=0,Cc(!1);return}if(e._yeaftReconnectCatchUpPending=!0,c){e.reconnectAttempts=0,e.reconnectTimer=setTimeout(()=>{e.connect()},2e3);return}e.scheduleReconnect()},e.ws.onerror=l=>{}}function Mc(e){if(e.reconnectAttempts>=e.maxReconnectAttempts){e.connectionState="disconnected";return}let t=Math.min(1e3*Math.pow(2,e.reconnectAttempts),3e4);e.reconnectAttempts++,e.connectionState="reconnecting",e.reconnectTimer=setTimeout(()=>{e.connect()},t)}function Pc(e){e.reconnectAttempts=0,e.connect()}function Rc(e){e.stopHeartbeat(),e._lastPongAt=Date.now(),e.heartbeatTimer=setInterval(()=>{if(e.ws&&e.ws.readyState===WebSocket.OPEN){if(Date.now()-e._lastPongAt>45e3){e.ws.close(4e3,"Heartbeat timeout");return}try{e.sendWsMessage({type:"ping"})}catch{}}},25e3)}function _c(e){e.heartbeatTimer&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=null)}function Dc(e){e._visibilityHandlerInstalled||(e._visibilityHandlerInstalled=!0,document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="visible")if(!e.ws||e.ws.readyState!==WebSocket.OPEN)e.reconnectAttempts=0,e.connect();else try{e.sendWsMessage({type:"ping"});let t=e._lastPongAt;setTimeout(()=>{e._lastPongAt===t&&e.ws&&e.ws.close(4001,"Visibility resume timeout")},3e3)}catch{e.reconnectAttempts=0,e.connect()}}))}var Bn,im,Fo=O(()=>{wt();Fr();bs();Bn=[];im=new Set(["sync_messages","refresh_conversation","select_conversation","cancel_execution","update_conversation_settings","ask_user_answer"])});function ye(e,t){let s=t==null?"__all__":String(t);return e?`${e}${s}`:s}function qn(e){return typeof e?.entryId=="string"&&e.entryId?`entry:${e.entryId}`:e?.role==="assistant"&&e?.turnId?`live-response:${e.turnId}:${e.speakerVpId||e.vpId||""}`:typeof e?.clientMessageId=="string"&&e.clientMessageId?`client:${e.clientMessageId}`:`message:${e?.messageId||""}`}function Wn(e,t,s){return typeof s!="string"||!s?null:`${ye(e,t)}message:${s}`}function es(e,t,s){return typeof s!="string"||!s?null:`${ye(e,t)}client:${s}`}var Gs=O(()=>{});function Bo(e){return typeof e=="string"&&e?e:null}function Qs(e,t){return e?.yeaftSessionHistoryState?.[t]||null}function kt(e){let t=e?.yeaftActiveSessionFilter||null;if(!t)try{t=(typeof window<"u"&&window.Pinia?.useSessionsStore?.())?.activeSessionId||null}catch{}if(!t)return{agentId:e?.currentAgent||null,sessionId:null,sessionKey:""};let s=(()=>{try{let n=typeof window<"u"&&window.Pinia?.useSessionsStore?.(),r=n?.activeSessionKey?n.sessions?.[n.activeSessionKey]:null;if(r?.id===t&&r.agentId)return r.agentId}catch{}return typeof e?.resolveYeaftSessionAgentId=="function"?e.resolveYeaftSessionAgentId(t):e?.currentAgent||null})();return{agentId:s,sessionId:t,sessionKey:ye(s,t)}}function Lc(e,{agentId:t,sessionId:s,mode:n="recent",preserveLoaded:r=!1,latestSeq:i=null}={}){if(!t||!s)return null;let o=ye(t,s),a=Qs(e,o)||{},l=Number(a.generation||0)+1,c=`yeaft_history_${l}_${crypto.randomUUID()}`,d={...a,loaded:!!a.loaded,loading:!0,error:null,requestId:c,generation:l,mode:n,background:n==="prefetch",requestedAt:Date.now(),latestSeq:Number.isFinite(i)?i:a.latestSeq??null};return delete d.completionSeen,r||(d.syncingAfterSeq=null,a.loaded||(d.hasMore=!1,d.oldestSeq=null,d.serverOldestFetchedSeq=null,d.serverHasMore=!1,d.gapQueue=[],d.requestedBeforeSeqs=[],d.count=0)),e.yeaftSessionHistoryState={...e.yeaftSessionHistoryState||{},[o]:d},ws(e),{sessionKey:o,requestId:c,generation:l,state:d}}function No(e,t={}){let s=t.sessionId??t.groupId??null;if(!s)return!1;let n=t.agentId||e?.yeaftSessionAgentById?.[s]||null,r=ye(n,s),i=Qs(e,r),o=Bo(t.requestId);if(!i)return o===null;let a=Bo(i.requestId);return o?o===a:a===null}function $c(e,t={},s={},n="chunk"){if(!No(e,t))return null;let r=t.sessionId??t.groupId??null,i=t.agentId||e?.yeaftSessionAgentById?.[r]||null,o=ye(i,r),a=Qs(e,o)||{},l=Bo(t.requestId),c=l!==null&&n==="completion",d={...a,...c?{}:s,...c?{completionSeen:!0}:{},error:null};return c?(d.loading=!0,d.requestId=l):(d.loading=!1,d.requestId=null,d.completedAt=Date.now(),delete d.completionSeen),e.yeaftSessionHistoryState={...e.yeaftSessionHistoryState||{},[o]:d},ws(e),d}function jn(e,{agentId:t,sessionId:s,requestId:n,error:r="history_load_failed"}={}){if(!t||!s||!n)return!1;let i=ye(t,s),o=Qs(e,i);return!o||o.requestId!==n||!o.loading?!1:(e.yeaftSessionHistoryState={...e.yeaftSessionHistoryState||{},[i]:{...o,loading:!1,error:r,requestId:null,completedAt:Date.now()}},ws(e),!0)}function ws(e){let{sessionKey:t}=kt(e),s=t?Qs(e,t):null;return e.yeaftLoadingMoreHistory=!!s?.loading&&s?.mode!=="prefetch",e.yeaftHistoryLoadError=s?.error||null,e.yeaftHasMoreHistory=!!s?.hasMore,e.yeaftOldestLoadedSeq=Number.isFinite(s?.serverOldestFetchedSeq)?s.serverOldestFetchedSeq:Number.isFinite(s?.oldestSeq)?s.oldestSeq:null,s}function qo(e){let{sessionKey:t}=kt(e);return t?Qs(e,t):null}var Ec,Ur=O(()=>{Gs();Ec=15e3});function Wo(e){return e?.sessionId??e?.groupId??null}function Uo(e){for(let t of[e?.persistedMessageId,e?.messageId,e?.id]){if(typeof t!="string")continue;let s=t.match(/^(m\d+)/);if(s)return s[1]}return null}function je(e){return e?.isStreaming||e?.status==="pending"?!1:Number.isFinite(e?.seq)||!!Uo(e)||e?.isHistory===!0&&!e?.clientMessageId}function Ko(e){if(Number.isFinite(e?.seq))return Number(e.seq);let s=Uo(e)?.match(/^m(\d+)$/);if(s)return Number(s[1]);let n=typeof e?.id=="string"?e.id.match(/^(\d+)/):null;return n?Number(n[1]):null}function am(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}function lm(e){return e?e.isStreaming||e.status==="pending"||e.type==="tool-use"&&(e.askPending||!e.hasResult&&(e.toolName==="AskUser"||e.toolName==="AskUserQuestion"))?!0:e.type!=="user"||!e.clientMessageId?!1:!e.dbMessageId&&!Uo(e):!1}function cm(e){let t=[],s=null;for(let n of e)(n?.type==="user"||!s)&&(s={rows:[],protected:!1},t.push(s)),s.rows.push(n),lm(n)&&(s.protected=!0);return t}function Hc(e,{conversationId:t,agentId:s=null,sessionId:n=null,limits:r=Vc}={}){let i=e?.messagesMap?.[t];if(!Array.isArray(i)||i.length===0||!s||!n)return{evictedRows:0,keptRows:0};let o=v=>Wo(v)===n,a=i.filter(o),l=cm(a);if(l.length===0)return{evictedRows:0,keptRows:0};let c=l.filter(v=>v.protected),d=new Set(c),u=Number.isFinite(r.maxTurnsPerSession)?Math.max(0,Math.floor(r.maxTurnsPerSession)):jo,p=Math.max(0,u-c.length);for(let v=l.length-1;v>=0&&p>0;v-=1){let k=l[v];d.has(k)||(d.add(k),p-=1)}let f=new Set(l.filter(v=>d.has(v)).flatMap(v=>v.rows)),g=a.filter(v=>!f.has(v));if(g.length===0)return{evictedRows:0,keptRows:f.size};let h=i.filter(v=>!o(v)||f.has(v));i.splice(0,i.length,...h);let m=ye(s,n),b=e.yeaftHistoryCacheState?.[m]||null,y=Oc(a.filter(v=>f.has(v))),w=JSON.stringify(b?.ranges||[])===JSON.stringify(y.ranges)?Number(b?.rangeEpoch)||0:(Number(b?.rangeEpoch)||0)+1;if(e.yeaftHistoryCacheState={...e.yeaftHistoryCacheState||{},[m]:{...b||{},agentId:s,sessionId:n,conversationId:t,lastAccessed:Date.now(),rangeEpoch:w,...y}},g.some(je)){let v=y.ranges[0]?.startSeq??null,k=e.yeaftSessionHistoryState?.[m]||{};e.yeaftSessionHistoryState={...e.yeaftSessionHistoryState||{},[m]:{...k,serverOldestFetchedSeq:v,oldestSeq:v,serverHasMore:v!==null,hasMore:v!==null,gapTraversalInitialized:!1,gapQueue:[],requestedBeforeSeqs:[],completedHistoryWorkKeys:[],pendingPageKind:null,pendingPageBeforeSeq:null,pendingGapStopAtSeq:null,pendingCacheEpoch:null,pendingHistoryWorkKey:null,paginationError:null,count:y.rowCount}};let x=kt(e);x.agentId===s&&x.sessionId===n&&ws(e)}return{evictedRows:g.length,keptRows:f.size}}function dm(e){let t=[],s=null;for(let n of e)je(n)&&((n?.type==="user"||!s)&&(s=[],t.push(s)),s.push(n));return t}function um(e,t){let s=Number.isFinite(t.maxTurnsPerSession)?Math.max(0,Math.floor(t.maxTurnsPerSession)):jo,n=dm(e),r=new Set(n.slice(-s).flat());for(let i of n)if(i.some(o=>o?._historyWindowDetached===!0))for(let o of i)r.add(o);return r}function pm(e){let t=Array.from(new Set(e.map(Ko).filter(Number.isFinite))).sort((n,r)=>n-r),s=[];for(let n of t){let r=s.at(-1);r&&n<=r.endSeq+1?r.endSeq=n:s.push({startSeq:n,endSeq:n})}return s}function Oc(e){let t=e.filter(je);return{rowCount:t.length,byteCount:t.reduce((s,n)=>s+am(n),0),ranges:pm(t)}}function fm(e,t,s){let n=new Set((t||[]).map(r=>r?.stableKey).filter(Boolean));if(n.size!==0)for(let r of e)r?.stableKey&&n.has(r.stableKey)&&(r._historyCacheTouchedAt=s)}function gm(e,{conversationId:t,agentId:s,sessionId:n,incomingRows:r,now:i,limits:o}){let a=e.messagesMap?.[t]||[],l=a.filter(y=>Wo(y)===n);fm(l,r,i);let c=um(l,o),d=l.filter(y=>!je(y)||c.has(y)),u=new Set(d),p=a.filter(y=>Wo(y)!==n||u.has(y));a.splice(0,a.length,...p);let f=Oc(d),g=ye(s,n),h=e.yeaftHistoryCacheState?.[g]||null,b=JSON.stringify(h?.ranges||[])===JSON.stringify(f.ranges)?Number(h?.rangeEpoch)||0:(Number(h?.rangeEpoch)||0)+1;e.yeaftHistoryCacheState={...e.yeaftHistoryCacheState||{},[g]:{agentId:s,sessionId:n,conversationId:t,lastAccessed:i,rangeEpoch:b,...f}}}function Fc(e,t,s,n=Date.now()){if(!t||!s)return;let r=ye(t,s),i=e.yeaftHistoryCacheState?.[r];i&&(e.yeaftHistoryCacheState={...e.yeaftHistoryCacheState||{},[r]:{...i,lastAccessed:n}})}function zo(e,{conversationId:t,agentId:s,sessionId:n,incomingRows:r=[],now:i=Date.now(),limits:o=Vc}={}){!e||!t||!s||!n||gm(e,{conversationId:t,agentId:s,sessionId:n,incomingRows:r,now:i,limits:o})}var jo,Vc,Kr=O(()=>{Gs();Ur();jo=500,Vc=Object.freeze({maxTurnsPerSession:jo})});function ts(e){return e?.sessionId??e?.groupId??null}function Nc(e){let t=e?.stableKey??e?.uiKey??e?.messageId??e?.dbMessageId??e?.id;return t==null||t===""?null:String(t)}function hm(e,t){if(e?.type!=="assistant"||t?.type!=="assistant"||ts(e)!==ts(t)||e.isHistory===!0&&!e.isStreaming||t._hasPersistedTurnId!==!0||!e.turnId||!t.turnId||e.turnId!==t.turnId)return!1;let s=e.speakerVpId||e.vpId||"",n=t.speakerVpId||t.vpId||"";if(s&&n&&s!==n)return!1;let r=e.threadId||"",i=t.threadId||"";if(r&&i&&r!==i)return!1;let o=typeof e.content=="string"?e.content:"",a=typeof t.content=="string"?t.content:"";return!!o&&!!a&&(a.startsWith(o)||o.startsWith(a))}function Yo(e,t){let s=e.uiKey||t.uiKey||null;return Object.assign(e,t),s&&(e.uiKey=s),je(t)&&(e.isStreaming=!1,e.status==="pending"&&(e.status="completed")),e}function qc(e){let t=je(e),s=Ko(e),n=Number(e?.timestamp)||0;return[t?0:1,n,Number.isFinite(s)?s:-1]}function zr(e){return e.sort((t,s)=>{let n=je(t),r=je(s);if(!n&&!r)return 0;let i=qc(t),o=qc(s);for(let a=0;a<i.length;a+=1)if(i[a]!==o[a])return i[a]-o[a];return 0}),e}function mm(e,t){return Array.isArray(e.messagesMap?.[t])||(e.messagesMap=e.messagesMap||{},e.messagesMap[t]=[]),e.messagesMap[t]}function Go(e,t){return e.filter(s=>t===void 0||ts(s)===t)}function Qo(e,t){let s=Nc(t);if(s){let n=e.find(r=>Nc(r)===s);if(n)return n}if(t?.type==="user"&&t.clientMessageId){let n=e.find(r=>r?.type==="user"&&r.clientMessageId===t.clientMessageId&&ts(r)===ts(t));if(n)return n}return t?.type==="assistant"&&e.find(n=>hm(n,t))||null}function xt(e){if(!e||typeof e!="object")return null;let t=Bc.get(e);return t||(t=new Xo(e),Bc.set(e,t)),t}var Bc,Xo,Un=O(()=>{Kr();Bc=new WeakMap;Xo=class{constructor(t){this.store=t}rows(t){return mm(this.store,t)}durableRows(t,s=void 0){return Go(this.rows(t),s).filter(je)}overlayRows(t,s=void 0){return Go(this.rows(t),s).filter(n=>!je(n))}snapshot(t,s=void 0){return{durableRows:this.durableRows(t,s),overlayRows:this.overlayRows(t,s)}}commitDurable({conversationId:t,sessionId:s=void 0,rows:n=[],mode:r="delta",replaceDurable:i=!1,preserveEmpty:o=!0}={}){if(!t)return{insertedRows:0,preservedEmpty:!1};let a=this.rows(t),l=Array.isArray(n)?n.filter(Boolean):[],c=Go(a,s).length>0;if(o&&r==="recent"&&l.length===0&&c)return{insertedRows:0,inserted:[],preservedEmpty:!0};if(i){let p=a.filter(f=>ts(f)!==s||!je(f));a.splice(0,a.length,...p)}let d=0,u=[];for(let p of l){let f=Qo(a,p);f?Yo(f,p):(a.push(p),u.push(p),d+=1)}return zr(a),{insertedRows:d,inserted:u,preservedEmpty:!1}}upsertOverlay({conversationId:t,row:s}={}){if(!t||!s)return null;if(je(s)){let i=this.rows(t),o=Qo(i,s);return o?Yo(o,s):(i.push(s),zr(i),s)}let n=this.rows(t),r=Qo(n,s);return r?Yo(r,s):n.push(s),zr(n),r||s}appendOverlayText({conversationId:t,sessionId:s=void 0,turnId:n=null,text:r=""}={}){if(!t||!r)return null;let o=this.rows(t).findLast(a=>a?.type==="assistant"&&!je(a)&&(s===void 0||ts(a)===s)&&(!n||a.turnId===n));return o?(o.content?r.startsWith(o.content)?o.content=r:o.content.endsWith(r)||(o.content+=r):o.content=r,o):null}replaceProjection(t,s=[]){let n=this.rows(t);return n.splice(0,n.length,...Array.isArray(s)?s:[]),zr(n),n}removeDurable({conversationId:t,sessionId:s}={}){if(!t)return 0;let n=this.rows(t),r=n.filter(o=>ts(o)!==s||!je(o)),i=n.length-r.length;return n.splice(0,n.length,...r),i}}});function Kn(e,t){return t?t===e.yeaftConversationId?!0:Object.values(e.yeaftConversationIdsByAgent||{}).includes(t):!1}function Xs(e,t,s){s&&(s.type!=="assistant"&&s.type!=="tool-use"||Kn(e,t)&&(!s.vpId&&e._currentYeaftVpId&&(s.vpId=e._currentYeaftVpId),!s.turnId&&e._currentYeaftTurnId&&(s.turnId=e._currentYeaftTurnId),!s.speakerVpId&&s.vpId&&(s.speakerVpId=s.vpId)))}function ym(e){let t=[e?.timestamp,e?.createdAt,e?.ts,e?.time,e?.created_at];for(let s of t){if(typeof s=="number"&&Number.isFinite(s)&&s>0)return s;if(typeof s=="string"&&s.trim()){let n=Date.parse(s);if(Number.isFinite(n))return n;let r=Number(s);if(Number.isFinite(r)&&r>0)return r}}return Date.now()}function Yr(e){let t=e?.stableKey??e?.messageId??e?.dbMessageId??e?.id;return t==null||t===""?null:String(t)}function Zo(e,t,s){if(!s||typeof s!="object")return null;if(typeof s.uiKey=="string"&&s.uiKey)return s.uiKey;let n=s.entryId||s.stableKey||s.atMessageId||s.messageId||s.dbMessageId||s.id||null;if(n!=null&&n!=="")return s.uiKey=String(n),s.uiKey;let r=`legacy:${t||"conversation"}:`,i=new Set((e?.messagesMap?.[t]||[]).map(a=>a?.uiKey).filter(a=>typeof a=="string"&&a)),o=Number(e?._messageUiKeySequence)||0;do o+=1;while(i.has(`${r}${o}`));return e&&(e._messageUiKeySequence=o),s.uiKey=`${r}${o}`,s.uiKey}function zn(e,t,s){for(let n of Array.isArray(s)?s:[])Zo(e,t,n);return s}function Jo(e,t){if(!e||!t)return e;let s=e.type==="user"&&typeof e.id=="string"&&e.id===e.clientMessageId;for(let[n,r]of Object.entries(t))if(r!=null){if(n==="isStreaming"){e.isStreaming&&r===!1&&(e.isStreaming=!1);continue}if(!(n==="uiKey"&&e.uiKey)){if(n==="id"||n==="messageId"){if(s&&t.clientMessageId===e.clientMessageId&&t.messageId&&t.messageId!==e.clientMessageId)continue;(e[n]===void 0||e[n]===null||e[n]==="")&&(e[n]=r);continue}if(!(n==="turnId"&&s&&e.turnId===e.clientMessageId)){if(n==="content"&&typeof r=="string"){e.content||(e.content=r);continue}if(n==="responseKind"&&(r==="progress"||r==="result")){e.responseKind=r;continue}if(n==="attachments"&&Array.isArray(r)){(!Array.isArray(e.attachments)||e.attachments.length===0)&&(e.attachments=r);continue}(e[n]===void 0||e[n]===null||e[n]==="")&&(e[n]=r)}}}return e}function Wc(e=[],t=[]){let s=[],n=new Map,r=new Map;for(let i of[...e,...t]){if(!i)continue;let o=Yr(i),a=i.type==="user"&&i.clientMessageId?String(i.clientMessageId):null;if(o&&n.has(o)){Jo(n.get(o),i);continue}if(a&&r.has(a)){let l=r.get(a);Jo(l,i),o&&!n.has(o)&&n.set(o,l);continue}s.push(i),o&&n.set(o,i),a&&r.set(a,i)}return s}function jc(e,t,s){return!e||e!==t?!1:!s?.loaded&&!s?.loading}function Uc(e,t){return!!t&&!!e?.loaded&&!e?.loading&&Number.isFinite(e?.latestSeq)}function Kc({sessionState:e,hasCachedSessionRows:t,force:s=!1}={}){return e?.loading?!1:s?!e?.loaded:e?.loaded?!1:!t}function bm(e,t,s,n){let r=s?.id?String(s.id):null;if(!r)return!1;let o=(e.messagesMap[t]||[]).find(a=>a?.type==="assistant"&&Yr(a)===r);return o?(o.id||(o.id=r),o.messageId||(o.messageId=r),s.ts&&!o.ts&&(o.ts=s.ts),s.timestamp&&!o.timestamp&&(o.timestamp=s.timestamp),s.sessionId&&!o.sessionId&&(o.sessionId=s.sessionId),s.vpId&&!o.vpId&&(o.vpId=s.vpId),s.turnId&&!o.turnId&&(o.turnId=s.turnId),s.threadId&&!o.threadId&&(o.threadId=s.threadId),o.content?typeof o.content=="string"&&(n.startsWith(o.content)?o.content=n:o.content.endsWith(n)||(o.content+=n)):o.content=n,Xs(e,t,o),!0):!1}function Gr(e,t,s){if(!t)return;let n={...s};Zo(e,t,n);let r={...n,id:s.dbMessageId||s.id||Date.now().toString()+Math.random().toString(36).substr(2,9),timestamp:ym(s)};if(Kn(e,t)&&!r.sessionId&&(r.sessionId=e._currentYeaftSessionId||e.yeaftActiveSessionFilter||vm),Kn(e,t)){let o=e._currentYeaftAgentId||Object.entries(e.yeaftConversationIdsByAgent||{}).find(([,c])=>c===t)?.[0]||e.currentAgent||null,a=typeof r.messageId=="string"&&/^m\d+$/.test(r.messageId)?r.messageId:typeof r.id=="string"&&/^m\d+$/.test(r.id)?r.id:null,l=typeof r.clientMessageId=="string"?r.clientMessageId:null;r.stableKey||(r.stableKey=a?Wn(o,r.sessionId,a):es(o,r.sessionId,l)),r.uiKey||(r.uiKey=r.stableKey||null),!r.vpId&&e._currentYeaftVpId&&(r.vpId=e._currentYeaftVpId),!r.turnId&&e._currentYeaftTurnId&&(r.turnId=e._currentYeaftTurnId),Xs(e,t,r)}if(e.messagesMap[t]||(e.messagesMap[t]=[]),Zo(e,t,r),Kn(e,t))return xt(e).upsertOverlay({conversationId:t,sessionId:r.sessionId,row:r});let i=Yr(s);if(i){let o=e.messagesMap[t].find(a=>Yr(a)===i);if(o)return Jo(o,r),t===e.yeaftConversationId&&e.messagesMap[t].sort((a,l)=>a.timestamp-l.timestamp),o}return e.messagesMap[t].push(r),t===e.yeaftConversationId&&e.messagesMap[t].sort((o,a)=>o.timestamp-a.timestamp),r}function zc(e,t,s,n={}){if(!t||!s)return;e.messagesMap[t]||(e.messagesMap[t]=[]);let r=e.messagesMap[t];if(bm(e,t,n,s))return;if(Kn(e,t)){let l=xt(e).appendOverlayText({conversationId:t,sessionId:n.sessionId||e._currentYeaftSessionId||void 0,turnId:n.turnId||e._currentYeaftTurnId||null,text:s});if(l){Xs(e,t,l),n.id&&!l.id&&(l.id=n.id),n.id&&!l.messageId&&(l.messageId=n.id);return}}let i=e._currentYeaftTurnId;if(i){for(let a=r.length-1;a>=0;a--)if(r[a].turnId===i&&r[a].type==="assistant"&&r[a].isStreaming){if(Xs(e,t,r[a]),n.id&&!r[a].id&&(r[a].id=n.id),n.id&&!r[a].messageId&&(r[a].messageId=n.id),r[a].content.endsWith(s))return;r[a].content+=s;return}Gr(e,t,{...n.id?{id:n.id,messageId:n.id}:{},...n.ts?{ts:n.ts}:{},...n.timestamp?{timestamp:n.timestamp}:{},...n.sessionId?{sessionId:n.sessionId}:{},...n.vpId?{vpId:n.vpId}:{},...n.turnId?{turnId:n.turnId}:{},...n.threadId?{threadId:n.threadId}:{},type:"assistant",content:s,isStreaming:!0,status:"pending",turnStartAt:n.timestamp||Date.now()});return}let o=r[r.length-1];if(o&&o.type==="assistant"&&o.isStreaming){if(Xs(e,t,o),n.id&&!o.id&&(o.id=n.id),n.id&&!o.messageId&&(o.messageId=n.id),o.content.endsWith(s))return;o.content+=s}else Gr(e,t,{...n.id?{id:n.id,messageId:n.id}:{},...n.ts?{ts:n.ts}:{},...n.timestamp?{timestamp:n.timestamp}:{},...n.sessionId?{sessionId:n.sessionId}:{},...n.vpId?{vpId:n.vpId}:{},...n.turnId?{turnId:n.turnId}:{},...n.threadId?{threadId:n.threadId}:{},type:"assistant",content:s,isStreaming:!0,status:"pending",turnStartAt:n.timestamp||Date.now()})}function Yc(e,t,{completeLifecycle:s=!0}={}){if(!t)return;let n=e.messagesMap[t];if(!n||n.length===0)return;let r=e._currentYeaftTurnId||null;for(let i=n.length-1;i>=0;i--){let o=n[i];if(r&&o.turnId&&o.turnId!==r){if(o.type==="user")break;continue}if(o.isStreaming&&(o.isStreaming=!1,s&&o.status==="pending"&&(o.status="completed",o.turnEndAt=Date.now())),Xs(e,t,o),o.type==="user")break}}function Gc(e,t){if(!t||e.processingConversations&&e.processingConversations[t]||e.activeVpTurns&&Object.keys(e.activeVpTurns).length>0)return;let s=e.messagesMap&&e.messagesMap[t];if(!(!s||s.length===0))for(let n of s)n&&n.isStreaming&&(n.isStreaming=!1)}function Qc(e,t){let s=e.currentConversation;if(!s)return;e.messagesMap[s]||(e.messagesMap[s]=[]);let n=e.messagesMap[s],r=null;for(let i of t)if(i.type==="user"){let o=i.message?.content;if(o){let a=typeof o=="string"?o:Array.isArray(o)?o.map(l=>l.text||"").join(""):"";a&&(r=a,e.addMessage({type:"user",content:a,isHistory:!0}))}}else if(i.type==="assistant"){let o=i.message?.content;if(o&&Array.isArray(o)){for(let a of o)if(a.type==="text"&&a.text)e.addMessage({type:"assistant",content:a.text,isHistory:!0});else if(a.type==="tool_use")e.addMessage({type:"tool-use",toolName:a.name,toolInput:a.input,isHistory:!0});else if(a.type==="tool_result"){for(let l=n.length-1;l>=0;l--)if(n[l].type==="tool-use"&&!n[l].hasResult){n[l].hasResult=!0,n[l].toolResult=a.content;break}}}}if(r&&s&&!e.conversationTitles[s]){let i=r.trim().substring(0,100);e.conversationTitles[s]=i}}function ks(e){if(!Array.isArray(e))return null;let t=null;for(let s of e)typeof s?.dbMessageId=="number"&&s.dbMessageId>0&&(t===null||s.dbMessageId>t)&&(t=s.dbMessageId);return t}function wm(e){return{id:e.id,dbMessageId:e.id,timestamp:e.created_at}}function Xc(e){if(!e)return null;let t=wm(e);if(e.message_type==="tool_use"){let n={...t,type:"tool-use",toolName:e.tool_name||"unknown",toolInput:(()=>{try{return JSON.parse(e.tool_input||e.content||"{}")}catch{return{}}})(),hasResult:!0,isHistory:!0,startTime:e.created_at||0};if(e.metadata)try{let r=JSON.parse(e.metadata);r.askRequestId&&(n.askRequestId=r.askRequestId,n.askQuestions=r.askQuestions,n.askAnswered=!!r.askAnswered,n.selectedAnswers=r.selectedAnswers||null,r.askAnswered||(n.isHistory=!1))}catch{}return n}let s=n=>{if(!n)return"";if(typeof n!="string")return String(n);if(n.startsWith("["))try{let r=JSON.parse(n);if(Array.isArray(r))return r.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join("")}catch{}return n};if(e.role==="user"){let n=null;if(e.metadata)try{let r=JSON.parse(e.metadata);r&&typeof r.clientMessageId=="string"&&(n=r.clientMessageId)}catch{}return{...t,type:"user",content:typeof e.content=="string"?e.content:String(e.content||""),...n?{clientMessageId:n}:{}}}else if(e.role==="assistant"){let n=s(e.content),r=(()=>{if(!e.content||typeof e.content!="string"||!e.content.startsWith("["))return[];try{let i=JSON.parse(e.content);return Array.isArray(i)?i.filter(o=>o.type==="tool_use"&&o.name):[]}catch{return[]}})();if(!n&&r.length===0)return null;if(r.length>0){let i=[];n&&i.push({...t,type:"assistant",content:n});for(let o=0;o<r.length;o++){let a=r[o];i.push({id:e.id+"_tool_"+o,dbMessageId:e.id,timestamp:e.created_at,type:"tool-use",toolName:a.name,toolInput:a.input||{},hasResult:!0,isHistory:!0,startTime:e.created_at||0})}return i}return{...t,type:"assistant",content:n}}else if(e.role==="tool"||e.message_type==="tool_result")return{...t,type:"tool_result",tool:e.tool_name||"unknown",content:typeof e.content=="string"?e.content:String(e.content||"")};return null}var vm,Yn=O(()=>{Un();Gs();vm="grp_default"});function Ss(e,t){return e._closedAt?.[t]?Date.now()-e._closedAt[t]<3e4:!1}function Zs(e,t){Ce(e,t),e._processingWatchdogs||(e._processingWatchdogs={});let s=()=>{if(!e.processingConversations[t])return;let r=e.conversations.find(o=>o.id===t);e.sendWsMessage({type:"ping_session",conversationId:t,agentId:r?.agentId});let i=setTimeout(()=>{e.processingConversations[t]&&(e.sessionHealth||(e.sessionHealth={}),e.sessionHealth[t]={status:"agent-offline"})},1e4);e._pongTimeouts||(e._pongTimeouts={}),e._pongTimeouts[t]=i},n=setTimeout(()=>{e.processingConversations[t]&&(s(),e._processingWatchdogs[t]=setInterval(()=>{if(!e.processingConversations[t]){Ce(e,t);return}s()},3e4))},45e3);e._processingWatchdogs[t]=n}function Qr(e,t){e._yeaftWatchdogPauseReasons?.[t]?.size||e.processingConversations[t]&&e._processingWatchdogs?.[t]&&(e._pongTimeouts?.[t]&&(clearTimeout(e._pongTimeouts[t]),delete e._pongTimeouts[t]),e.sessionHealth?.[t]&&delete e.sessionHealth[t],e._yeaftWatchdogConvs?.has(t)?en(e,t):Zs(e,t))}function Ce(e,t){e._processingWatchdogs?.[t]&&(clearTimeout(e._processingWatchdogs[t]),clearInterval(e._processingWatchdogs[t]),delete e._processingWatchdogs[t]),e._pongTimeouts?.[t]&&(clearTimeout(e._pongTimeouts[t]),delete e._pongTimeouts[t]),e.sessionHealth?.[t]&&delete e.sessionHealth[t],e._autoRefreshed?.[t]&&delete e._autoRefreshed[t],e._yeaftWatchdogConvs?.delete(t),e._yeaftWatchdogPauseReasons&&delete e._yeaftWatchdogPauseReasons[t]}function Gn(e,t,s="phase"){if(!t||!e.processingConversations[t])return;e._yeaftWatchdogPauseReasons||(e._yeaftWatchdogPauseReasons={});let n=e._yeaftWatchdogPauseReasons[t]||new Set;n.add(s),e._yeaftWatchdogPauseReasons[t]=n,e._processingWatchdogs?.[t]&&(clearTimeout(e._processingWatchdogs[t]),clearInterval(e._processingWatchdogs[t]),delete e._processingWatchdogs[t])}function Js(e,t,s=null){if(!t)return;let n=e._yeaftWatchdogPauseReasons?.[t];n&&(s?n.delete(s):n.clear(),!n.size&&(delete e._yeaftWatchdogPauseReasons[t],e.processingConversations[t]&&en(e,t)))}function Zc(e,t){Ce(e,t),e._processingWatchdogs||(e._processingWatchdogs={}),e._processingWatchdogs[t]=setTimeout(()=>{if(e.processingConversations[t]){let s=e.conversations.find(n=>n.id===t);e.sendWsMessage({type:"refresh_conversation",conversationId:t,agentId:s?.agentId}),e._processingWatchdogs[t]=setTimeout(()=>{if(e.processingConversations[t]){delete e.processingConversations[t];let n=e.executionStatusMap[t];n&&(n.currentTool=null),e.finishStreamingForConversation(t)}delete e._processingWatchdogs[t]},1e4)}},9e4)}function en(e,t){let s=e._yeaftWatchdogPauseReasons?.[t];if(Ce(e,t),e._processingWatchdogs||(e._processingWatchdogs={}),s?.size){e._yeaftWatchdogConvs||(e._yeaftWatchdogConvs=new Set),e._yeaftWatchdogPauseReasons||(e._yeaftWatchdogPauseReasons={}),e._yeaftWatchdogConvs.add(t),e._yeaftWatchdogPauseReasons[t]=new Set(s);return}e._yeaftWatchdogConvs||(e._yeaftWatchdogConvs=new Set),e._yeaftWatchdogConvs.add(t),e._processingWatchdogs[t]=setTimeout(()=>{if(e.processingConversations[t]){delete e.processingConversations[t];let n=e.executionStatusMap[t];n&&(n.currentTool=null),e.finishStreamingForConversation(t)}delete e._processingWatchdogs[t]},15e4)}var ss=O(()=>{});function ea(e,t){return t&&Array.isArray(e?._yeaftRetiredConversationIdsByAgent?.[t])?e._yeaftRetiredConversationIdsByAgent[t]:[]}function tn(e,t,s){return!t||!s?!1:ea(e,t).includes(s)}function ta(e,t){let s=e?._yeaftRetiredConversationTargetsByAgent?.[t];return s&&typeof s=="object"?s:{}}function Jc(e,t,s){if(!t||!s)return null;let n=ta(e,t),r=s,i=new Set;for(let o=0;o<8;o++){if(i.has(r))return null;i.add(r);let a=n[r];if(!a||a===r)return r===s?null:r;r=a}return null}function Qn(e,t,s,n=null){if(!t||!s)return;let r=ea(e,t).filter(a=>a!==s).concat(s).slice(-8);e._yeaftRetiredConversationIdsByAgent={...e._yeaftRetiredConversationIdsByAgent||{},[t]:r};let i=ta(e,t),o={};for(let a of r){let l=i[a];l&&(o[a]=l===s&&n?n:l)}n&&n!==s&&(o[s]=n),e._yeaftRetiredConversationTargetsByAgent={...e._yeaftRetiredConversationTargetsByAgent||{},[t]:o}}function sa(e,t,s){if(!t||!s||!e?._yeaftRetiredConversationIdsByAgent)return;let n=ea(e,t).filter(i=>i!==s);e._yeaftRetiredConversationIdsByAgent={...e._yeaftRetiredConversationIdsByAgent,[t]:n};let r={...ta(e,t)};delete r[s],e._yeaftRetiredConversationTargetsByAgent={...e._yeaftRetiredConversationTargetsByAgent||{},[t]:r}}var Xr=O(()=>{});function Im(e,t,s){let n=e.messagesMap?.[t]||[],r=e.messagesMap?.[s]||[];e.messagesMap||(e.messagesMap={}),zn(e,t,n),zn(e,s,r);let i=Wc(r,n).sort((o,a)=>{let l=Number.isFinite(o?.seq)?o.seq:null,c=Number.isFinite(a?.seq)?a.seq:null;return l!==null&&c!==null&&l!==c?l-c:l!==null&&c===null?-1:l===null&&c!==null?1:(o?.timestamp||0)-(a?.timestamp||0)});xt(e).replaceProjection(s,i)}function Cm(e){if(!e||typeof e!="object")return e;if(typeof structuredClone=="function")try{return structuredClone(e)}catch{}return Array.isArray(e)?e.slice():{...e}}function Zr(e,t){return!!e&&Object.prototype.hasOwnProperty.call(e,t)}function sn(e,t,s,{removeSource:n}){Zr(e,t)&&(Zr(e,s)||(e[s]=n?e[t]:Cm(e[t])),n&&delete e[t])}function Tt(e,t,s=null){if(!t)return null;let n=e?._yeaftPendingConversationPromotions?.[t]||null;return!n?.sourceConversationId||!n.targetConversationId||s&&n.targetConversationId!==s?null:n}function Jr(e,t,s,n){return!t||!s||!n||s===n?!1:(e._yeaftPendingConversationPromotions={...e._yeaftPendingConversationPromotions||{},[t]:{sourceConversationId:s,targetConversationId:n}},!0)}function Xn(e,t,s=null){let n=Tt(e,t,s);if(!n)return null;let r={...e._yeaftPendingConversationPromotions||{}};return delete r[t],e._yeaftPendingConversationPromotions=r,n}function Zn(e,t,s){let n=Tt(e,t);return!n||!s||n.targetConversationId===s?null:(Mt(e,n.targetConversationId,s,{removeSource:!0}),Qn(e,t,n.targetConversationId,s),Jr(e,t,n.sourceConversationId,s),n)}function Mt(e,t,s,{removeSource:n=!0}={}){if(!t||!s||t===s)return!1;Im(e,t,s),e.yeaftHistoryCacheState&&(e.yeaftHistoryCacheState=Object.fromEntries(Object.entries(e.yeaftHistoryCacheState).map(([c,d])=>[c,d?.conversationId===t?{...d,conversationId:s}:d]))),sn(e.processingConversations,t,s,{removeSource:n}),sn(e.executionStatusMap,t,s,{removeSource:n}),sn(e.refreshingSessionMap,t,s,{removeSource:n}),sn(e._closedAt,t,s,{removeSource:n}),sn(e._autoRefreshed,t,s,{removeSource:n}),sn(e.sessionHealth,t,s,{removeSource:n}),e._turnCompletedConvs?.has(t)&&(e._turnCompletedConvs.add(s),n&&e._turnCompletedConvs.delete(t));let r=!!e._yeaftWatchdogConvs?.has(t),i=e._yeaftWatchdogPauseReasons?.[t],o=!!i?.size,a=!!e._processingWatchdogs?.[t];if(o&&(e._yeaftWatchdogPauseReasons||(e._yeaftWatchdogPauseReasons={}),e._yeaftWatchdogPauseReasons[s]=new Set(i)),n&&(a||o)&&Ce(e,t),n&&e._pongTimeouts?.[t]&&(clearTimeout(e._pongTimeouts[t]),delete e._pongTimeouts[t]),n&&(a||r||o)&&!!e.processingConversations?.[s])if(e._processingWatchdogs?.[s])e._yeaftWatchdogConvs?.add(s);else{let c=Zr(e.sessionHealth,s),d=e.sessionHealth?.[s],u=Zr(e._autoRefreshed,s),p=e._autoRefreshed?.[s];en(e,s),c&&(e.sessionHealth||(e.sessionHealth={}),e.sessionHealth[s]=d),u&&(e._autoRefreshed||(e._autoRefreshed={}),e._autoRefreshed[s]=p)}return n&&e.messagesMap&&delete e.messagesMap[t],!0}var na=O(()=>{Yn();Un();Xr();ss()});function ei(e,t){return!e||!t||e.type!=="user"||t.type!=="user"?!1:e.clientMessageId&&t.clientMessageId?e.clientMessageId===t.clientMessageId:e.clientMessageId||t.clientMessageId?!1:e.content===t.content}var ra=O(()=>{});function ia(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Am(){return Date.now()}function xm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`pt_${crypto.randomUUID()}`:`pt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}function Tm(e,t=160){return typeof e!="string"?e:e.length>t?`${e.slice(0,t)}...[truncated]`:e}function Mm(e){if(!e||typeof e!="object")return e||null;let t={};for(let[s,n]of Object.entries(e))s==="text"||s==="prompt"||s==="content"||s==="data"||(t[s]=typeof n=="string"?Tm(n):n);return t}function Is(){return xm()}function Ze(e,t={}){!e||!t.traceId||(Array.isArray(e._perfTraceQueue)||(e._perfTraceQueue=[]),e._perfTraceQueue.push({traceId:t.traceId,source:"web",phase:t.phase||"unknown",at:Am(),monotonicMs:ia(),durationMs:Number.isFinite(t.durationMs)?t.durationMs:null,agentId:t.agentId||null,sessionId:t.sessionId||null,vpId:t.vpId||null,turnId:t.turnId||null,threadId:t.threadId||null,messageType:t.messageType||null,bytes:Number.isFinite(t.bytes)?t.bytes:null,ok:typeof t.ok=="boolean"?t.ok:null,detail:Mm(t.detail)}),e._perfTraceQueue.length>200&&e._perfTraceQueue.splice(0,e._perfTraceQueue.length-200),Pm(e))}function Pm(e){!e||e._perfTraceFlushTimer||(e._perfTraceFlushTimer=setTimeout(()=>Rm(e),250))}function Rm(e){if(!e||!Array.isArray(e._perfTraceQueue)||e._perfTraceQueue.length===0){e&&(e._perfTraceFlushTimer=null);return}let t=e._perfTraceQueue.splice(0,e._perfTraceQueue.length);e._perfTraceFlushTimer=null,typeof e.sendWsMessage=="function"&&e.sendWsMessage({type:"perf_trace_events",events:t})}function ti(e,t={}){if(typeof requestAnimationFrame!="function")return;let s=ia();requestAnimationFrame(()=>{requestAnimationFrame(()=>{Ze(e,{...t,phase:t.phase||"render.next_paint",durationMs:ia()-s})})})}var oa=O(()=>{});function Pt(e){return Number.isFinite(e)?Number(e):null}function _m(e){return(Array.isArray(e)?e:[]).map(t=>({startSeq:Pt(t?.startSeq),endSeq:Pt(t?.endSeq)})).filter(t=>t.startSeq!==null&&t.endSeq!==null&&t.startSeq<=t.endSeq).sort((t,s)=>t.startSeq-s.startSeq)}function Jn(e){return Number.isFinite(e)&&e>=0?Math.floor(e):0}function Cs(e){let t=Pt(e?.beforeSeq);if(t===null)return null;if(e?.kind==="gap"){let s=Pt(e.stopAtSeq);return s===null?null:`gap:${Jn(e.cacheEpoch)}:${s}:${t}`}return`server:${t}`}function er(e){let t=new Set((Array.isArray(e?.completedHistoryWorkKeys)?e.completedHistoryWorkKeys:[]).filter(s=>typeof s=="string"&&s));for(let s of Array.isArray(e?.requestedBeforeSeqs)?e.requestedBeforeSeqs:[])Number.isFinite(s)&&t.add(`server:${s}`);return t}function Dm(e,t){let s=Cs(t);if(!s)return e.completedHistoryWorkKeys||[];let n=er(e);return n.add(s),Array.from(n).slice(-256)}function Em(e,t){if(!Number.isFinite(t))return e.requestedBeforeSeqs||[];let s=new Set((Array.isArray(e?.requestedBeforeSeqs)?e.requestedBeforeSeqs:[]).filter(Number.isFinite));return s.add(t),Array.from(s).sort((n,r)=>r-n).slice(-256)}function Lm(e,t={},s=0){let n=_m(e),r=Jn(s),i=er(t),o=[];for(let a=1;a<n.length;a+=1){let l=n[a-1],c=n[a];if(l.endSeq+1>=c.startSeq)continue;let d={kind:"gap",beforeSeq:c.startSeq,stopAtSeq:l.endSeq+1,cacheEpoch:r};d.workKey=Cs(d),i.has(d.workKey)||o.push(d)}return o.sort((a,l)=>l.beforeSeq-a.beforeSeq)}function ed(e,t,s){let n=Lm(e,t,s),r=Pt(t.serverOldestFetchedSeq??t.oldestSeq),i=n[0]||null;if(!i||r===null||i.beforeSeq<=r)return[];let o={kind:"gap",beforeSeq:i.beforeSeq,stopAtSeq:r,cacheEpoch:i.cacheEpoch};return o.workKey=Cs(o),er(t).has(o.workKey)?[]:[o]}function td(e={},t=[],s=0){let n=Jn(s),r=er(e),i=e.serverHasMore!==!1,o=Pt(e.serverOldestFetchedSeq??e.oldestSeq),a=e.gapTraversalInitialized===!0,l=Array.isArray(e.gapQueue)?e.gapQueue.slice():[],c=null,d=null;if(i&&o!==null){let u={kind:"server",beforeSeq:o,stopAtSeq:null,cacheEpoch:n};u.workKey=Cs(u),r.has(u.workKey)?(i=!1,d="history_cursor_repeated"):c=u}return!c&&!i&&(a||(l=ed(t,e,n),a=!0),c=l[0]||null),c?{request:c,state:{...e,serverHasMore:i,gapTraversalInitialized:a,gapQueue:l,pendingPageKind:c.kind,pendingPageBeforeSeq:c.beforeSeq,pendingGapStopAtSeq:c.stopAtSeq,pendingCacheEpoch:c.cacheEpoch,pendingHistoryWorkKey:c.workKey,hasMore:!0,paginationError:null}}:{request:null,state:{...e,serverHasMore:i,gapTraversalInitialized:a,gapQueue:l,hasMore:!1,paginationError:d}}}function sd(e={},{mode:t,oldestSeq:s,hasMore:n,ranges:r=[],pageKind:i=null,stopAtSeq:o=null,cacheEpoch:a=0}={}){if(t==="delta")return e;let l=Jn(a),c=Pt(s),d=Pt(e.pendingPageBeforeSeq),u=i||e.pendingPageKind||(t==="older"?"server":null),p=Pt(o??e.pendingGapStopAtSeq),f=Jn(e.pendingCacheEpoch??l),g={kind:u,beforeSeq:d,stopAtSeq:p,cacheEpoch:f},h=Pt(e.serverOldestFetchedSeq??e.oldestSeq),m=e.serverHasMore!==!1,b=Number(e.noProgressCount)||0,y=null,S=e.requestedBeforeSeqs||[],w=e.completedHistoryWorkKeys||[],v=e.gapTraversalInitialized===!0,k=Array.isArray(e.gapQueue)?e.gapQueue.slice():[];if(t==="recent")h=c,m=!!n,b=0,S=[],w=[],v=!1,k=[];else if(d===null)c!==null&&(h=h===null?c:Math.min(h,c)),m=!!n,b=0;else{S=Em(e,d),w=Dm(e,g);let T=c!==null&&c<d;if(u==="server")T?(h=h===null?c:Math.min(h,c),m=!!n,b=0):(m=!1,b+=1,y="history_cursor_no_progress");else if(u==="gap"){let D=Cs(g);k=k.filter(_=>Cs(_)!==D);let L=p!==null&&c!==null&&c<=p;if(T||L||n===!1){if(b=0,!L&&n!==!1&&c!==null&&p!==null){let _={kind:"gap",beforeSeq:c,stopAtSeq:p,cacheEpoch:f};_.workKey=Cs(_),er({completedHistoryWorkKeys:w}).has(_.workKey)||k.unshift(_)}}else b+=1,y="history_cursor_no_progress"}}t==="older"&&!m&&!v&&(k=ed(r,{...e,serverOldestFetchedSeq:h,completedHistoryWorkKeys:w},l),v=!0);let x={...e,serverOldestFetchedSeq:h,serverHasMore:m,requestedBeforeSeqs:S,completedHistoryWorkKeys:w,gapTraversalInitialized:v,gapQueue:k,noProgressCount:b,oldestSeq:h,paginationError:y};return delete x.pendingPageKind,delete x.pendingPageBeforeSeq,delete x.pendingGapStopAtSeq,delete x.pendingCacheEpoch,delete x.pendingHistoryWorkKey,{...x,hasMore:m||k.length>0}}var aa=O(()=>{});function od(e){return e.filter(t=>!(t.type==="user"&&(!t.content||!t.content.trim())))}function As(e){let t=typeof e=="string"?e.match(/^m(\d+)$/):null,s=t?Number(t[1]):null;return Number.isFinite(s)?s:null}function nd(e){let t=[e?.timestamp,e?.createdAt,e?.ts,e?.time,e?.created_at];for(let s of t){if(typeof s=="number"&&Number.isFinite(s)&&s>0)return s;if(typeof s=="string"&&s.trim()){let n=Date.parse(s);if(Number.isFinite(n))return n;let r=Number(s);if(Number.isFinite(r)&&r>0)return r}}return null}function $m(e){if(!Array.isArray(e))return null;for(let t=e.length-1;t>=0;t-=1){let s=e[t];if(s?.name==="TodoWrite"&&Array.isArray(s?.input?.todos))return s.input.todos}return null}function Vm(e){if(!e||typeof window>"u")return null;try{let t=window.Pinia||null,s=t&&typeof t.useSessionsStore=="function"?t.useSessionsStore():null;if(!s)return null;let n=typeof t.useChatStore=="function"?t.useChatStore():null,r=typeof s.sessionById=="function"?s.sessionById(e,n?.currentAgent||null):s.sessions&&s.sessions[e];return(r&&typeof r.defaultVpId=="string"?r.defaultVpId.trim():"")||null}catch{return null}}function Hm(e,t){return e.speakerVpId||e.vpId||e.vp_id||e.authorVpId||e.authorVP||Vm(t)}function Om(e){return e?.stableKey||(e&&(e.messageId||e.id)?e.messageId||e.id:null)}function Fm(e,t=null){if(!e||e.stableKey)return e;let s=ns(e),n=e.messageId||e.id||null,r=e.type==="user"&&e.clientMessageId||null;return e.stableKey=r&&n===r?es(t,s,r):Wn(t,s,n),Number.isFinite(e.seq)||(e.seq=As(n)),e.uiKey||(e.uiKey=e.stableKey||null),e}function ns(e){return e?e.sessionId??e.groupId??null:null}function Bm(e){return!e||e.type!=="user"||!e.clientMessageId?!1:(e.messageId||e.id||null)===e.clientMessageId}function Nm(e,t,s,n){let r=e.rows(t),i=r.some(c=>c&&(n==null||ns(c)===n));if(s.length===0&&i)return{insertedRows:0,preservedEmpty:!0};let o=s.reduce((c,d)=>Math.max(c,d?.timestamp||0),0),a=r.filter(c=>c?n!=null&&ns(c)!==n||je(c)||c.isStreaming||c.type==="tool-use"&&c.toolName==="AskUserQuestion"&&(c.askAnswered||c.askPending||c.askExpired)||Bm(c)?!0:o>0&&(c.timestamp||0)>o:!1);return e.replaceProjection(t,a),{insertedRows:e.commitDurable({conversationId:t,sessionId:n,rows:s,mode:"recent",preserveEmpty:!1}).insertedRows,preservedEmpty:!1}}function qm(e){if(typeof e!="string")return!1;let t=e.trimStart();return t.startsWith("<task-result ")||/^\[system note\] You have called \S+ with the same arguments \d+ times\./.test(t)}function Wm(e,t){let s=typeof e.yeaftConversationId=="string"?e.yeaftConversationId:"";return s.startsWith(`yeaft-local-${t}-`)||/^yeaft-local-\d/.test(s)?s:null}function jm(e,t,s,n){let r=t.agentId||s&&e.yeaftSessionAgentById?.[s]||null;if(!r||!n||e.currentView!=="yeaft")return;let i=kt(e);if(i.sessionId!==(s||null)||i.agentId&&i.agentId!==r)return;let o=e.yeaftConversationId||null;if(tn(e,r,n)){let d=e.yeaftConversationIdsByAgent?.[r]||null;d&&d!==n&&Mt(e,n,d,{removeSource:n!==e.yeaftConversationId});return}let a=Tt(e,r);a&&a.targetConversationId!==n&&Zn(e,r,n);let l=Tt(e,r,n);if(l&&(Mt(e,l.sourceConversationId,n,{removeSource:!0}),Xn(e,r,n),e.yeaftConversationId=n),o===n||l){e.messagesMap[n]||(e.messagesMap[n]=[]),e.yeaftConversationIdsByAgent={...e.yeaftConversationIdsByAgent||{},[r]:n},e.activeConversations=[n];return}let c=Wm(e,r);c&&(Mt(e,c,n,{removeSource:!0}),e.yeaftConversationIdsByAgent={...e.yeaftConversationIdsByAgent||{},[r]:n},e.yeaftConversationId=n,e.activeConversations=[n])}function rs(e,t){let s=e.messagesMap[t]||[];for(let n of s)n.type==="tool-use"&&!n.hasResult&&(n.hasResult=!0,n.toolName==="AskUserQuestion"&&!n.askAnswered&&!n.selectedAnswers&&(n.isHistory=!0,n.askRequestId=null))}function ad(e,t){At(e);let s=e.agents.find(r=>r.id===t.agentId);e.conversations=e.conversations.filter(r=>r.id!==t.conversationId);let n=t.provider||"claude-code";if(e.conversations.push({id:t.conversationId,agentId:t.agentId,agentName:s?.name||t.agentId,workDir:t.workDir,claudeSessionId:null,createdAt:Date.now(),processing:!1,connecting:n!=="claude-code",type:"chat",provider:n,capabilities:t.capabilities||null,disallowedTools:t.disallowedTools??null}),e.currentAgent=t.agentId,e.currentAgentInfo=s,e.panels.length>1){let r=e._pendingPaneId;if(e._pendingPaneId=null,r){let i=e.panels.find(o=>o.id===r);i&&(i.conversationId=t.conversationId)}else{let i=e.panels.find(o=>!o.conversationId);i&&(i.conversationId=t.conversationId)}e.activeConversations.includes(t.conversationId)||e.activeConversations.push(t.conversationId)}else e.activeConversations=[t.conversationId];e.currentWorkDir=t.workDir,e.messagesMap[t.conversationId]=[],e.sendWsMessage({type:"select_conversation",conversationId:t.conversationId}),e.addMessage({type:"system",content:_e("store.convCreated",{agent:s?.name||t.agentId,workDir:t.workDir})}),e.saveOpenSessions()}function ld(e,t){At(e);let s=e.agents.find(n=>n.id===t.agentId);if(e.conversations=e.conversations.filter(n=>n.id!==t.conversationId&&!(n.claudeSessionId&&n.claudeSessionId===t.claudeSessionId)),e.conversations.push({id:t.conversationId,agentId:t.agentId,agentName:s?.name||t.agentId,workDir:t.workDir,claudeSessionId:t.claudeSessionId,createdAt:Date.now(),processing:!1,connecting:(t.provider||"claude-code")!=="claude-code",type:"chat",provider:t.provider||"claude-code",capabilities:t.capabilities||null,disallowedTools:t.disallowedTools??null}),e.currentAgent=t.agentId,e.currentAgentInfo=s,e.panels.length>1){let n=e._pendingPaneId;if(e._pendingPaneId=null,n){let r=e.panels.find(i=>i.id===n);r&&(r.conversationId=t.conversationId)}else{let r=e.panels.find(i=>!i.conversationId);r&&(r.conversationId=t.conversationId)}e.activeConversations.includes(t.conversationId)||e.activeConversations.push(t.conversationId)}else e.activeConversations=[t.conversationId];if(e.currentWorkDir=t.workDir,e.messagesMap[t.conversationId]=[],e._pendingSessionTitle&&(e.conversationTitles[t.conversationId]=e._pendingSessionTitle,e._pendingSessionTitle=null),e.sendWsMessage({type:"select_conversation",conversationId:t.conversationId}),e.addMessage({type:"system",content:_e("store.convResumed",{agent:s?.name||t.agentId,sessionId:t.claudeSessionId?t.claudeSessionId.slice(0,8)+"...":""})}),t.dbMessages&&t.dbMessages.length>0){let n=od(t.dbMessages.map(i=>e.formatDbMessage(i)).flat().filter(Boolean)),r=e.messagesMap[t.conversationId]||[];for(let i of n)r.push(i)}e.hasMoreMessages=!!t.hasMoreMessages,e.chatSessionState[t.conversationId]={lastSeenDbId:ks(e.messagesMap[t.conversationId]),hasMoreOlder:!!t.hasMoreMessages},e.saveOpenSessions()}function la(e,t){e.conversations=e.conversations.filter(n=>n.id!==t.conversationId),delete e.messagesMap[t.conversationId],delete e.chatSessionState[t.conversationId],delete e.conversationTitles[t.conversationId],delete e.customConversationTitles[t.conversationId],delete e.processingConversations[t.conversationId],e._closedAt&&delete e._closedAt[t.conversationId],Ce(e,t.conversationId),delete e.executionStatusMap[t.conversationId],delete e.subagents[t.conversationId],window.dispatchEvent(new CustomEvent("conversation-deleted",{detail:{conversationId:t.conversationId}}));let s=e.activeConversations.indexOf(t.conversationId);s>=0&&(e.activeConversations.splice(s,1),e.activeConversations.length===0&&e.addMessage({type:"system",content:_e("chat.session.closed")}));for(let n of e.panels)n.conversationId===t.conversationId&&(n.conversationId=null);e.saveOpenSessions()}function cd(e,t){let s=t.conversationId;if(s){delete e.processingConversations[s],Ce(e,s),e._closedAt||(e._closedAt={}),e._closedAt[s]=Date.now(),e._turnCompletedConvs||(e._turnCompletedConvs=new Set),e._turnCompletedConvs.add(s);let n=e.executionStatusMap[s];n&&(n.currentTool=null),e.finishStreamingForConversation(s),rs(e,s);let r=e.conversations.find(i=>i.id===s);r&&(t.claudeSessionId&&(r.claudeSessionId=t.claudeSessionId),t.workDir&&(r.workDir=t.workDir)),e.clearStatus?.conversationId===s&&e.clearStatus?.status==="clearing"&&(e.clearStatus={conversationId:s,status:"completed"},setTimeout(()=>{e.clearStatus?.conversationId===s&&e.clearStatus?.status==="completed"&&(e.clearStatus=null)},3e3)),e.saveOpenSessions()}}function dd(e,t){let s=t.conversationId;if(s){delete e.processingConversations[s],Ce(e,s),e._closedAt||(e._closedAt={}),e._closedAt[s]=Date.now(),e._turnCompletedConvs||(e._turnCompletedConvs=new Set),e._turnCompletedConvs.add(s);let n=e.executionStatusMap[s];n&&(n.currentTool=null),e.finishStreamingForConversation(s),rs(e,s);let r=e.conversations.find(i=>i.id===s);r&&(t.claudeSessionId&&(r.claudeSessionId=t.claudeSessionId),t.workDir&&(r.workDir=t.workDir)),e.saveOpenSessions()}}function ud(e,t){if(t.conversationId){if(t.isProcessing&&!Ss(e,t.conversationId)&&!e._turnCompletedConvs?.has(t.conversationId))e.processingConversations[t.conversationId]=!0;else if(e.processingConversations[t.conversationId]){delete e.processingConversations[t.conversationId],Ce(e,t.conversationId);let s=e.executionStatusMap[t.conversationId];s&&(s.currentTool=null),e.finishStreamingForConversation(t.conversationId)}}}function pd(e,t){let s=t.conversationId||e.currentConversation;if(s){delete e.processingConversations[s],Ce(e,s),e._closedAt||(e._closedAt={}),e._closedAt[s]=Date.now(),e._turnCompletedConvs||(e._turnCompletedConvs=new Set),e._turnCompletedConvs.add(s);let n=e.executionStatusMap[s];n&&(n.currentTool=null),e.finishStreamingForConversation(s),rs(e,s)}}function fd(e,t){if(!!t.requestId){if(e.chatHistoryRequestIdSupported=!0,!e.isCurrentChatHistoryResponse?.(t))return!1}else{let i=`chat:${t.conversationId}`,o=e.chatHistoryRequests?.[i];if(e.chatHistoryRequestIdSupported===!0||!o?.loading)return!1;t={...t,requestId:o.requestId,catalogKey:i,mode:o.mode||t.mode,...o.mode==="delta"?{afterMessageId:o.cursor}:{}}}e.messagesMap[t.conversationId]||(e.messagesMap[t.conversationId]=[]);let n=e.messagesMap[t.conversationId],r=t.mode==="delta"||typeof t.afterMessageId=="number"&&t.afterMessageId>0;if(t.conversationId&&e.activeConversations.includes(t.conversationId)){let i=od((t.messages||[]).map(a=>e.formatDbMessage(a)).flat().filter(Boolean));if(i.length>0){let a=n.find(l=>l.dbMessageId);if(a&&i[0].dbMessageId&&i[i.length-1].dbMessageId<a.dbMessageId){let l=n.indexOf(a);e.debug,n.splice(l,0,...i)}else{e.debug;for(let l of i)if(!(l.dbMessageId&&n.some(c=>c.dbMessageId===l.dbMessageId))){if(l.dbMessageId&&(l.type==="assistant"||l.type==="user")){let c=null;if(l.type==="user"?c=n.find(d=>!d.dbMessageId&&!d.isStreaming&&ei(d,l)):c=n.find(d=>!d.dbMessageId&&!d.isStreaming&&d.type==="assistant"&&d.content===l.content),c){c.dbMessageId=l.dbMessageId,c.id=l.id,l.timestamp&&(c.timestamp=l.timestamp),l.clientMessageId&&!c.clientMessageId&&(c.clientMessageId=l.clientMessageId);continue}}n.push(l)}}}r||(e.hasMoreMessages=t.hasMore??!1),At(e);let o=e.chatSessionState[t.conversationId]?.hasMoreOlder;e.chatSessionState[t.conversationId]={lastSeenDbId:ks(e.messagesMap[t.conversationId]),hasMoreOlder:r?!!o:!!t.hasMore}}return e.finishChatHistoryRequest?.(t)&&(e.currentConversation===t.conversationId&&(e.loadingMoreMessages=!1),e.setRefreshingSession(t.conversationId,!1)),!0}function gd(e,t){let s=t.sessionId??null,n=t.agentId||s&&e.yeaftSessionAgentById?.[s]||null,r=t.conversationId||n&&e.yeaftConversationIdsByAgent?.[n]||e.yeaftConversationId;if(!r||!s||!Array.isArray(t.messages))return null;e.messagesMap[r]||(e.messagesMap[r]=[]);let i=new Set(Array.isArray(t.sourceMessageIds)?t.sourceMessageIds:[]),o=new Set,a=new Set;for(let b of e.messagesMap[r]){if(ns(b)!==s)continue;let y=b?.persistedMessageId||b?.messageId||b?.id||null;y&&o.add(y),y&&(b?._historyWindowPrefetched===!0||b?._historyWindowDetached===!0)&&a.add(y),!(!t.entryId||!i.has(y))&&(b.historyEntryId=t.entryId,Number.isFinite(t.indexGeneration)&&(b.historyIndexGeneration=t.indexGeneration))}let l=t.messages.filter(b=>t.prefetch===!0||!o.has(b?.id)||a.has(b?.id)).map(b=>t.entryId&&i.has(b?.id)?{...b,historyEntryId:t.entryId,...t.prefetch===!0?{_historyWindowPrefetched:!0}:{},...Number.isFinite(t.indexGeneration)?{historyIndexGeneration:t.indexGeneration}:{}}:b),{formatted:c}=hd(l,s,"window",e.messagesMap[r],n),d=`history-window:${t.requestId||t.anchorMessageId||Date.now()}`;for(let b of c)b._historyWindowKey=d,b._historyWindowDetached=t.prefetch!==!0,b._historyWindowPrefetched=t.prefetch===!0;let u=xt(e),p=u.rows(r),f=new Set(t.messages.map(b=>b?.id).filter(Boolean)),g=[];if(t.prefetch!==!0){for(let y of p){if(ns(y)!==s)continue;let S=y?.persistedMessageId||y?.messageId||y?.id||null;f.has(S)&&(y._historyWindowPrefetched!==!0&&y._historyWindowDetached!==!0||(y._historyWindowKey=d,y._historyWindowDetached=!0,y._historyWindowPrefetched=!1,g.push(y)))}let b=p.filter(y=>ns(y)!==s||y._historyWindowDetached!==!0||y._historyWindowKey===d);b.length!==p.length&&u.replaceProjection(r,b)}u.commitDurable({conversationId:r,sessionId:s,rows:c,mode:"window"});let h=c.length>0?c:g,m=kt(e);return zo(e,{conversationId:r,agentId:n,sessionId:s,incomingRows:h,activeAgentId:m.agentId,activeSessionId:m.sessionId}),r}function rd(e){return e?.toolId?[ns(e)??"",e.vpId||e.speakerVpId||"",e.turnId||"",e.threadId||"main",e.toolId].join("\0"):null}function id(e,t,s){return e.toolName="AskUserQuestion",e.toolId=t.toolCallId,e.toolInput={questions:s},e.askQuestions=s,e.askRequestId=null,e.askPending=!1,e.pendingAnswers=null,e.askSubmitGeneration=null,e.hasResult=!0,e.isHistory=!0,t.status==="answered"?(e.askAnswered=!0,e.selectedAnswers=t.answers,e.askExpired=!1):(e.askAnswered=!1,e.selectedAnswers=null,e.askExpired=!0),e}function Um(e,t){return(e||[]).find(s=>s?.type==="tool-use"&&(s.toolName==="AskUser"||s.toolName==="AskUserQuestion")&&s.toolId===t.toolCallId&&ns(s)===t.sessionId&&(s.vpId||s.speakerVpId||"")===(t.vpId||"")&&(s.turnId||"")===(t.turnId||"")&&(s.threadId||"main")===(t.threadId||"main"))||null}function hd(e,t,s,n,r=null){let i=new Set((n||[]).map(c=>Om(Fm(c,r))).filter(Boolean)),o=new Set,a=[],l=0;for(let c of e){if(!c||c._reflection||c.internal||c.systemOnly||c.systemOnlyMessage||qm(c.content))continue;let d=c.id||c.messageId||null,u=c.clientMessageId||null,p=c.sessionId??c.groupId??t??null,f=Wn(r,p,d),g=u?es(r,p,u):f,h=c.historyEntryId?{historyEntryId:c.historyEntryId,...Number.isFinite(c.historyIndexGeneration)?{historyIndexGeneration:c.historyIndexGeneration}:{}}:{};if(!(f&&o.has(f))&&!(f&&s!=="recent"&&i.has(f))){if(f&&o.add(f),c.role==="user"){l+=1;let m=d||c.messageId||c.turnId||null;a.push({...d?{id:d,messageId:d}:{},...f?{stableKey:f}:{},...g?{uiKey:g}:{},...h,seq:Number.isFinite(c.seq)?c.seq:As(d),type:"user",content:c.content,timestamp:nd(c),sessionId:p,turnId:c.turnId||m,...u?{clientMessageId:u}:{},...Array.isArray(c.attachments)&&c.attachments.length>0?{attachments:c.attachments}:{},...c.quote?{quote:c.quote}:{},isStreaming:!1,isHistory:!0})}else if(c.role==="assistant"){l+=1;let m=d||c.messageId||c.turnId||null,b=Hm(c,p),y=nd(c),S=!!c.turnId,w=c.turnId||m,v=typeof c.content=="string"?c.content:c.content||"",k=Array.isArray(c.todos)?c.todos:$m(c.toolCalls),x=c.executionOrigin==="route_forward"?{executionOrigin:"route_forward"}:{};(typeof v!="string"||v.trim())&&a.push({...d?{id:d,messageId:d}:{},...f?{stableKey:f}:{},...g?{uiKey:g}:{},...h,seq:Number.isFinite(c.seq)?c.seq:As(d),...c.entryId?{entryId:c.entryId}:{},...Array.isArray(c.sourceMessageIds)?{sourceMessageIds:c.sourceMessageIds}:{},type:"assistant",content:v,timestamp:y,sessionId:p,turnId:w,_hasPersistedTurnId:S,...x,...b?{vpId:b,speakerVpId:b}:{},...c.responseKind==="progress"||c.responseKind==="result"?{responseKind:c.responseKind}:{},...c.incomplete===!0?{incomplete:!0}:{},...typeof c.stopReason=="string"&&c.stopReason?{stopReason:c.stopReason}:{},isStreaming:!1,isHistory:!0}),Array.isArray(k)&&k.length>0&&a.push({...d?{id:`${d}:todos`,messageId:`${d}:todos`}:{},...f?{stableKey:`${f}:todos`}:{},...h,seq:Number.isFinite(c.seq)?c.seq:As(d),type:"tool-use",toolName:"TodoWrite",toolInput:{todos:k},timestamp:y,sessionId:p,turnId:w,...x,...b?{vpId:b,speakerVpId:b}:{},isStreaming:!1,isHistory:!0,hasResult:!0});for(let[T,D]of(Array.isArray(c.toolCalls)?c.toolCalls:[]).entries()){if(!D||D.name==="TodoWrite")continue;let L=D.id||`index:${T}`,_=encodeURIComponent(String(L));a.push({...d?{id:`${d}:tool:${_}`,messageId:`${d}:tool:${_}`,persistedMessageId:d}:{},...f?{stableKey:`${f}:tool:${_}`}:{},...h,seq:Number.isFinite(c.seq)?c.seq:As(d),type:"tool-use",toolId:D.id||null,toolName:D.name||"unknown",toolInput:D.input||{},timestamp:y,sessionId:p,turnId:w,...x,...b?{vpId:b,speakerVpId:b}:{},isStreaming:!1,isHistory:!0,hasResult:!0})}for(let T of Array.isArray(c.images)?c.images:[])T?.assetId&&a.push({id:`${d||m||w}:image:${T.assetId}`,messageId:`${d||m||w}:image:${T.assetId}`,...f?{stableKey:`${f}:image:${T.assetId}`}:{},...h,seq:Number.isFinite(c.seq)?c.seq:As(d),type:"chat-image",...T,timestamp:y,sessionId:p,turnId:w,...x,...b?{vpId:b,speakerVpId:b}:{},isStreaming:!1,isHistory:!0});for(let T of Array.isArray(c.askUserResults)?c.askUserResults:[]){if(!T?.toolCallId||T.status!=="answered"&&T.status!=="expired")continue;let D=[{question:typeof T.question=="string"?T.question:"",options:(Array.isArray(T.options)?T.options:[]).filter(R=>typeof R=="string").map(R=>({label:R,description:""})),multiSelect:!1}],L={toolCallId:T.toolCallId,sessionId:p,vpId:b||"",turnId:w||"",threadId:c.threadId||"main"},_=Um(n,L);if(_){Object.assign(_,h),id(_,T,D);let R=a.findIndex(N=>N?.type==="tool-use"&&N.toolId===T.toolCallId&&(N.sessionId??N.groupId??null)===(_.sessionId??_.groupId??null)&&(N.turnId||"")===(_.turnId||""));R>=0&&a.splice(R,1);continue}let E=id({id:`${d||m||w}:ask:${T.toolCallId}`,messageId:`${d||m||w}:ask:${T.toolCallId}`,...f?{stableKey:`${f}:ask:${T.toolCallId}`}:{},...h,seq:Number.isFinite(c.seq)?c.seq:As(d),type:"tool-use",timestamp:y,sessionId:p,turnId:w,threadId:L.threadId,...x,...b?{vpId:b,speakerVpId:b}:{},isStreaming:!1},T,D),M=rd(E);(!M||!a.some(R=>rd(R)===M))&&a.push(E);let A=a.findIndex(R=>R!==E&&R?.type==="tool-use"&&R.toolId===T.toolCallId&&(R.sessionId??R.groupId??null)===(E.sessionId??E.groupId??null)&&(R.turnId||"")===(E.turnId||""));A>=0&&a.splice(A,1)}}}}return{formatted:a,acceptedHistoryMessages:l}}function md(e,t){let s=t.sessionId!=null?t.sessionId:t.groupId,n=t.agentId||s&&e.yeaftSessionAgentById?.[s]||null;if(tn(e,n,t.conversationId)){let j=e.yeaftConversationIdsByAgent?.[n]||null;if(!j||j===t.conversationId)return;Mt(e,t.conversationId,j,{removeSource:t.conversationId!==e.yeaftConversationId}),t={...t,conversationId:j}}if(t.requestId&&typeof e.isCurrentYeaftHistoryResponse=="function"&&!e.isCurrentYeaftHistoryResponse(t))return;let r=t.mode==="recent"||t.mode==="delta"?t.mode:"older",i=Array.isArray(t.messages)?t.messages:[],o=t.agentId||s&&e.yeaftSessionAgentById?.[s]||null,a=ye(o,s),l=e.yeaftSessionHistoryState?.[a]||null;typeof t.streamId=="string"&&typeof l?.streamId=="string"&&(t.streamId!==l.streamId||Number.isFinite(t.revision)&&Number.isFinite(l.revision)&&t.revision!==l.revision)&&(r="recent",typeof e.clearYeaftHistoryMemory=="function"&&e.clearYeaftHistoryMemory({agentId:o,sessionId:s,preserveLiveRows:!0,preserveSessionOwner:!0})),t.perfTraceId&&Ze(e,{traceId:t.perfTraceId,phase:"history.chunk_received",agentId:t.agentId||null,sessionId:s||null,messageType:t.type,bytes:(()=>{try{return JSON.stringify(t).length}catch{return null}})(),detail:{mode:r,rawCount:i.length}});let d=t.agentId||(s&&e.yeaftSessionAgentById?e.yeaftSessionAgentById[s]:null),u=d&&e.yeaftConversationIdsByAgent?e.yeaftConversationIdsByAgent[d]:null,p=t.conversationId||u||e.yeaftConversationId;if(!p){e.yeaftLoadingMoreHistory=!1;return}jm(e,t,s,p),e.messagesMap[p]||(e.messagesMap[p]=[]);let{formatted:f,acceptedHistoryMessages:g}=hd(i,s,r,e.messagesMap[p],d);zn(e,p,f);let h=xt(e),m=0,b=!1;if(r==="recent"){let j=Nm(h,p,f,s??null);m=j.insertedRows,b=j.preservedEmpty}else if(f.length>0&&(m=h.commitDurable({conversationId:p,sessionId:s??null,rows:f,mode:r}).insertedRows,r==="older"&&typeof e.expandYeaftMessageWindow=="function")){let te=e.yeaftActiveSessionFilter?s??null:null;e.expandYeaftMessageWindow(te,t.turns||10,d)}let y=kt(e);zo(e,{conversationId:p,agentId:d,sessionId:s,incomingRows:f,activeAgentId:y.agentId,activeSessionId:y.sessionId});let S=ye(t.agentId||null,s),w=e.yeaftHistoryCacheState?.[S]||null,v=e.yeaftSessionHistoryState?.[S]||{},k=Number.isFinite(v.serverOldestFetchedSeq)?v.serverOldestFetchedSeq:Number.isFinite(v.oldestSeq)?v.oldestSeq:null,x=Number.isFinite(t.nextBeforeSeq)?t.nextBeforeSeq:Number.isFinite(t.oldestSeq)?t.oldestSeq:b?k:null,T=b&&!Number.isFinite(t.nextBeforeSeq)&&!Number.isFinite(t.oldestSeq)?v.serverHasMore??v.hasMore??!1:t.hasMore,D=r==="delta"?v:sd(v,{mode:r,oldestSeq:x,hasMore:T,ranges:w?.ranges||[],pageKind:t.pageKind,stopAtSeq:t.gapStopAtSeq,cacheEpoch:w?.rangeEpoch??t.cacheEpoch??0}),L=typeof t.latestSeq=="number"?t.latestSeq:v.latestSeq??null,_={streamId:typeof t.streamId=="string"?t.streamId:v.streamId??null,revision:Number.isFinite(t.revision)?t.revision:v.revision??null},E=r==="delta"?{...v,..._,loaded:!0,loading:!1,latestSeq:L,syncingAfterSeq:null,count:(v.count||0)+m}:{...D,..._,loaded:!0,loading:!1,count:w?w.rowCount:r==="older"?(v.count||0)+m:b?v.count||0:g,latestSeq:b&&!Number.isFinite(t.latestSeq)?v.latestSeq??null:L,syncingAfterSeq:null};t.requestId&&typeof e.finishYeaftHistoryLoad=="function"?e.finishYeaftHistoryLoad(t,E,"chunk"):e.yeaftSessionHistoryState&&(e.yeaftSessionHistoryState={...e.yeaftSessionHistoryState,[S]:E}),r==="delta"&&t.hasMoreAfter===!0&&Number.isFinite(E.latestSeq)&&E.latestSeq>Number(t.afterSeq??-1)&&typeof e.continueYeaftHistoryDelta=="function"&&queueMicrotask(()=>e.continueYeaftHistoryDelta(s,d,E.latestSeq));let M=kt(e),A=M.sessionId===(s||null),R=!t.agentId||!M.agentId||t.agentId===M.agentId,N=A&&R,F=ye(null,M.sessionId);if(t.perfTraceId&&(Ze(e,{traceId:t.perfTraceId,phase:"history.chunk_applied",agentId:t.agentId||null,sessionId:s||null,messageType:t.type,detail:{mode:r,formattedCount:f.length,insertedRows:m,acceptedHistoryMessages:g,preservedEmptyRecent:b}}),ti(e,{traceId:t.perfTraceId,phase:"history.next_paint",agentId:t.agentId||null,sessionId:s||null,messageType:t.type,detail:{mode:r,insertedRows:m}})),N)e.yeaftHasMoreHistory=E.hasMore,e.yeaftOldestLoadedSeq=Number.isFinite(E.serverOldestFetchedSeq)?E.serverOldestFetchedSeq:Number.isFinite(E.oldestSeq)?E.oldestSeq:e.yeaftOldestLoadedSeq,e.yeaftLoadingMoreHistory=!1;else if(e.yeaftLoadingMoreHistory){let j=e.yeaftSessionHistoryState?.[M.sessionKey]||e.yeaftSessionHistoryState?.[F]||null;e.yeaftLoadingMoreHistory=!!j?.loading}}var si=O(()=>{ss();na();Xr();bs();ra();Yn();Bt();oa();Ur();Gs();Kr();aa();Un()});function vd(e,t,s=null){if(!s)return!1;if(e.promoteYeaftHistoryOutlineRow?.(t,s))return!0;let n=t?.sessionId??t?.groupId??e._currentYeaftSessionId??null;return n?!!e.invalidateYeaftHistoryOutline?.(n,s):!1}function Km(e){let t=e;if(typeof t=="string"){let s=t.trim();if(s.startsWith("[")&&s.endsWith("]")||s.startsWith("{")&&s.endsWith("}"))try{t=JSON.parse(s)}catch{t=e}}return Array.isArray(t)?t.map(s=>typeof s=="string"?s:!s||typeof s!="object"?"":s.type==="text"&&typeof s.text=="string"||s.type==="input_text"&&typeof s.text=="string"?s.text:"").join("").replace(/\n\n\[Uploaded files\][\s\S]*$/m,"").trim():t&&typeof t=="object"?typeof t.text=="string"?t.text.trim():typeof t.content=="string"?t.content.trim():"":typeof t=="string"?t.replace(/\n\n\[Uploaded files\][\s\S]*$/m,"").trim():""}function ca(e,t){return e.executionStatusMap[t]||(e.executionStatusMap[t]={currentTool:null,toolHistory:[],lastActivity:null}),e.executionStatusMap[t]}function yd(e,t,s,n=null){if(!t)return;let r=ca(e,t);if(r.lastActivity=Date.now(),Qr(e,t),s.type==="system"){if(s.subtype==="init"){let i=e.conversations.find(o=>o.id===t);i&&i.connecting&&(i.connecting=!1);return}s.message&&e.addMessageToConversation(t,{type:"system",content:typeof s.message=="string"?s.message:JSON.stringify(s.message,null,2)});return}if(s.type==="assistant"){let i=s.message?.content;if(!i)return;let o=e.messagesMap[t]||[];for(let a of o)a.type==="tool-use"&&!a.hasResult&&(a.hasResult=!0);for(let a of r.toolHistory)a.status==="running"&&(a.status="done");if(r.currentTool=null,typeof i=="string"){e.appendToAssistantMessageForConversation(t,i,{id:s.message?.id||s.message?.messageId||null,ts:s.ts||s.message?.ts||s.message?.time||null,sessionId:e._currentYeaftSessionId||null,vpId:e._currentYeaftVpId||null,turnId:e._currentYeaftTurnId||null,threadId:e._currentYeaftThreadId||null});return}if(!Array.isArray(i))return;if(i.length===0){e.finishStreamingForConversation(t);return}for(let a of i)a.type==="text"?e.appendToAssistantMessageForConversation(t,a.text,{id:s.message?.id||s.message?.messageId||null,ts:s.ts||s.message?.ts||s.message?.time||null,sessionId:e._currentYeaftSessionId||null,vpId:e._currentYeaftVpId||null,turnId:e._currentYeaftTurnId||null,threadId:e._currentYeaftThreadId||null}):a.type==="image_asset"&&a.image?e.addMessageToConversation(t,{type:"chat-image",...a.image,sessionId:e._currentYeaftSessionId||null,vpId:e._currentYeaftVpId||null,speakerVpId:e._currentYeaftVpId||null,turnId:e._currentYeaftTurnId||null,threadId:e._currentYeaftThreadId||null}):a.type==="tool_use"&&(e.finishStreamingForConversation(t,{completeLifecycle:!1}),r.currentTool={name:a.name,input:a.input,startTime:Date.now()},r.toolHistory.unshift({name:a.name,input:a.input,timestamp:Date.now(),status:"running"}),r.toolHistory.length>20&&r.toolHistory.pop(),e.addMessageToConversation(t,{type:"tool-use",toolId:a.id||a.tool_use_id||null,toolName:a.name,toolInput:a.input,startTime:Date.now(),isHistory:a.history===!0||s.history===!0||s.isHistory===!0,sessionId:e._currentYeaftSessionId||null,vpId:e._currentYeaftVpId||null,turnId:e._currentYeaftTurnId||null,threadId:e._currentYeaftThreadId||null}))}else if(s.type==="user"){let i=s.internal===!0||s.message?.internal===!0||s.userAuthored===!1||s.message?.userAuthored===!1,o=s.message?.content,a=Km(o);if(typeof a=="string"&&(a.includes("<local-command-caveat>")||a.includes("<command-name>")))return;if(typeof a=="string"&&a.includes("<local-command-stdout>")){let c=a.match(/<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/);if(c){e.appendToAssistantMessageForConversation(t,c[1].trim()),e.finishStreamingForConversation(t);return}}let l=[];if(s.tool_use_result)l=Array.isArray(s.tool_use_result)?s.tool_use_result:[s.tool_use_result];else if(s.message?.content){let c=s.message.content;l=(Array.isArray(c)?c:[]).filter(u=>u.type==="tool_result")}if(l.length>0){let c=e.messagesMap[t]||[];for(let d of l){if(r.toolHistory.length>0){let g=r.toolHistory.findIndex(h=>h.status==="running");g>=0&&(r.toolHistory[g].status="done")}let u=d.tool_use_id||d.toolUseId||d.tool_call_id||d.toolCallId||null,p=d.content||d,f=!1;if(u){for(let g=c.length-1;g>=0;g--)if(c[g].type==="tool-use"&&c[g].toolId===u){c[g].hasResult=!0,c[g].toolResult=d.is_update&&c[g].toolResult?`${c[g].toolResult}
1
+ var O=(e,t,s)=>()=>{if(s)throw s[0];try{return e&&(t=e(e=0)),t}catch(n){throw s=[n],n}};var Yh=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(s){throw t=0,s}};function Xl(e,t){let s=nacl.randomBytes(24),n=JSON.stringify(e),r,i=!1;n.length>512?(r=pako.gzip(n),i=!0):r=nacl.util.decodeUTF8(n);let o=nacl.secretbox(r,s,t),a={n:nacl.util.encodeBase64(s),c:nacl.util.encodeBase64(o)};return i&&(a.z=!0),a}function Zl(e,t){try{let s=nacl.util.decodeBase64(e.n),n=nacl.util.decodeBase64(e.c),r=nacl.secretbox.open(n,s,t);if(!r)return null;if(e.z){let i=pako.ungzip(r,{to:"string"});return JSON.parse(i)}else return JSON.parse(nacl.util.encodeUTF8(r))}catch{return null}}function Jl(e){return e&&typeof e=="object"&&typeof e.n=="string"&&typeof e.c=="string"}function yt(e){return nacl.util.decodeBase64(e)}var Fr=O(()=>{});function Ht(){return globalThis.localStorage||null}function tc(){let e=Nr();for(let t of _o)try{t(e)}catch{}}function Gh(){try{Ht()?.removeItem(En),Ht()?.removeItem(Ln)}catch{}}function Qh(e){return String(e||"").trim()||null}function ec(e,t){if(!$n(t))return{};try{let s=JSON.parse(Ht()?.getItem(e)||"null");return!s||typeof s!="object"||Array.isArray(s)||s.ownerId!==t.ownerId||!s.records||typeof s.records!="object"||Array.isArray(s.records)?(Ht()?.removeItem(e),{}):s.records}catch{try{Ht()?.removeItem(e)}catch{}return{}}}function sc(e,t,s){if(!$n(s))return!1;try{return Ht()?.setItem(e,JSON.stringify({ownerId:s.ownerId,records:t||{}})),!0}catch{return!1}}function bt(e){let t=Qh(e);if(!t)return Do(),null;if(vs!==t){vs=t,Br+=1;for(let s of[En,Ln])try{let n=JSON.parse(Ht()?.getItem(s)||"null");(!n||n.ownerId!==t)&&Ht()?.removeItem(s)}catch{try{Ht()?.removeItem(s)}catch{}}tc()}return Nr()}function Do(){vs=null,Br+=1,Gh(),tc()}function Nr(){return vs?{ownerId:vs,epoch:Br}:null}function $n(e){return!!e&&!!vs&&e.ownerId===vs&&e.epoch===Br}function nc(e){return{drafts:ec(En,e),outbox:ec(Ln,e)}}function Eo(e,t){return sc(En,e,t)}function Vn(e,t){return sc(Ln,e,t)}function rc(e){return typeof e!="function"?()=>{}:(_o.add(e),()=>_o.delete(e))}var En,Ln,vs,Br,_o,Jb,Lo=O(()=>{En="yeaft-work-center-composer-drafts-v1",Ln="yeaft-work-center-message-outbox-v1",vs=null,Br=0,_o=new Set;Jb=Object.freeze({drafts:En,outbox:Ln})});function $o(){try{globalThis.Pinia?.useChatStore?.()?.clearYeaftHistoryMemory?.()}catch{}}function Ot(e){let t=String(e||"").trim()||null;qr!==t&&$o(),qr=t}function Zh(){$o(),qr=null}var Xh,qr,Jh,Re,wt=O(()=>{Fr();Lo();({defineStore:Xh}=Pinia);qr=null;Jh=1800*1e3,Re=Xh("auth",{state:()=>({skipAuth:!1,emailVerification:!1,passwordResetEnabled:!1,totpEnabled:!1,registrationEnabled:!1,aadEnabled:!1,aadClientId:null,aadTenantId:null,ssoProviders:{github:!1,google:!1,wechat:!1,alipay:!1},linkedIdentities:[],hasPassword:!1,identitiesLoading:!1,identitiesError:null,initialized:!1,authGeneration:0,isAuthenticated:!1,token:null,sessionKey:null,userId:null,role:null,loginStep:"credentials",tempToken:null,emailHint:null,setupToken:null,totpSecret:null,qrCode:null,error:null,loading:!1,qrPanel:null,_qrPollTimer:null,_sessionRefreshTimer:null,_sessionRefreshVisibilityHandler:null}),actions:{async initialize(){if(this.initialized)return this.isAuthenticated;try{if(await this.checkAuthMode(),this.skipAuth&&this.isAuthenticated)return!0;let e=!1;return typeof window<"u"&&typeof this.consumeSsoRedirect=="function"&&(e=this.consumeSsoRedirect()),!this.isAuthenticated&&!e&&await this.restoreSession(),this.isAuthenticated}finally{this.initialized=!0}},async checkAuthMode(){try{let t=await(await fetch("/api/auth/mode")).json();this.skipAuth=t.skipAuth,this.emailVerification=t.emailVerification,this.passwordResetEnabled=!!t.passwordResetEnabled,this.totpEnabled=t.totpEnabled,this.registrationEnabled=t.registrationEnabled||!1,this.aadEnabled=t.aadEnabled||!1,this.aadClientId=t.aadClientId||null,this.aadTenantId=t.aadTenantId||null,this.ssoProviders=Object.assign({github:!1,google:!1,wechat:!1,alipay:!1},t.ssoProviders||{}),this.skipAuth&&(this.userId="skip-auth",bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated")}catch{}},async login(e,t){this.loading=!0,this.error=null;try{let n=await(await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t})})).json();return n.success?n.needTotpSetup?(this.setupToken=n.setupToken,this.totpSecret=n.totpSecret,this.qrCode=n.qrCode,this.loginStep="totp-setup",!0):n.needTotpCode?(this.tempToken=n.tempToken,this.loginStep="totp",!0):n.needEmailCode?(this.tempToken=n.tempToken,this.emailHint=n.emailHint,this.loginStep="verification",!0):(this.token=n.token,this.sessionKey=n.sessionKey?yt(n.sessionKey):null,this.role=n.role||"pro",this.userId=n.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",localStorage.setItem("authToken",n.token),this.startSessionRefresh(),!0):(this.error=n.error||"Login failed",!1)}catch(s){return this.error=s.message||"Network error",!1}finally{this.loading=!1}},async loginWithMicrosoft(){if(!this.aadEnabled||!this.aadClientId||!this.aadTenantId)return this.error="Microsoft login is not configured",!1;if(typeof msal>"u"||!msal.PublicClientApplication)return this.error="Microsoft authentication library not loaded",!1;this.loading=!0,this.error=null;try{let e={auth:{clientId:this.aadClientId,authority:`https://login.microsoftonline.com/${this.aadTenantId}`,redirectUri:window.location.origin+"/auth/callback"},cache:{cacheLocation:"sessionStorage",storeAuthStateInCookie:!1}},t=new msal.PublicClientApplication(e);await t.initialize();let s=await t.loginPopup({scopes:["openid","profile","email"]});if(!s||!s.idToken)return this.error="Microsoft login failed: no token received",!1;let r=await(await fetch("/api/auth/aad",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({idToken:s.idToken})})).json();return r.success?(this.token=r.token,this.sessionKey=r.sessionKey?yt(r.sessionKey):null,this.role=r.role||"pro",this.userId=r.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",localStorage.setItem("authToken",r.token),this.startSessionRefresh(),!0):(this.error=r.error||"Microsoft login failed",!1)}catch(e){return e.errorCode==="user_cancelled"||e.name==="BrowserAuthError"?(this.error=null,!1):(this.error=e.message||"Microsoft login failed",!1)}finally{this.loading=!1}},async verifyTotpCode(e){this.loading=!0,this.error=null;try{let s=await(await fetch("/api/auth/verify-totp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tempToken:this.tempToken,totpCode:e})})).json();return s.success?s.needEmailCode?(this.tempToken=s.tempToken,this.emailHint=s.emailHint,this.loginStep="verification",!0):(this.token=s.token,this.sessionKey=s.sessionKey?yt(s.sessionKey):null,this.role=s.role||"pro",this.userId=s.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",this.tempToken=null,localStorage.setItem("authToken",s.token),this.startSessionRefresh(),!0):(this.error=s.error||"TOTP verification failed",!1)}catch(t){return this.error=t.message||"Network error",!1}finally{this.loading=!1}},async completeTotpSetup(e){this.loading=!0,this.error=null;try{let s=await(await fetch("/api/auth/setup-totp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({setupToken:this.setupToken,totpCode:e})})).json();return s.success?(this.setupToken=null,this.totpSecret=null,this.qrCode=null,s.needEmailCode?(this.tempToken=s.tempToken,this.emailHint=s.emailHint,this.loginStep="verification",!0):(this.token=s.token,this.sessionKey=s.sessionKey?yt(s.sessionKey):null,this.role=s.role||"pro",this.userId=s.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",localStorage.setItem("authToken",s.token),this.startSessionRefresh(),!0)):(this.error=s.error||"TOTP setup failed",!1)}catch(t){return this.error=t.message||"Network error",!1}finally{this.loading=!1}},async verifyCode(e){this.loading=!0,this.error=null;try{let s=await(await fetch("/api/auth/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tempToken:this.tempToken,code:e})})).json();return s.success?(this.token=s.token,this.sessionKey=s.sessionKey?yt(s.sessionKey):null,this.role=s.role||"pro",this.userId=s.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",this.tempToken=null,this.emailHint=null,localStorage.setItem("authToken",s.token),this.startSessionRefresh(),!0):(this.error=s.error||"Verification failed",!1)}catch(t){return this.error=t.message||"Network error",!1}finally{this.loading=!1}},async register(e,t,s,n){this.loading=!0,this.error=null;try{let i=await(await fetch("/api/auth/register",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t,email:s||void 0,invitationCode:n})})).json();return i.success?!0:(this.error=i.error||"Registration failed",!1)}catch(r){return this.error=r.message||"Network error",!1}finally{this.loading=!1}},showRegister(){this.loginStep="register",this.error=null},loginWithSso(e){window.location.href=`/api/auth/sso/${encodeURIComponent(e)}/start`},async loginWithAlipayMobile({intent:e="login"}={}){if(!await this.startSsoQr("alipay",{intent:e}))return!1;let s=this.qrPanel?.authorizeUrl;if(!s)return!1;let n=`alipays://platformapi/startapp?appId=20000067&url=${encodeURIComponent(s)}`;return this.qrPanel={...this.qrPanel,mobileDeepLink:!0},window.location.href=n,!0},async startSsoQr(e,{intent:t="login"}={}){this.cancelSsoQr(),this.error=null;try{let s=new URLSearchParams;if(t==="bind"){if(!this.isAuthenticated)return this.error="You must be logged in to bind an identity",!1;s.set("intent","bind")}let n=s.toString(),r=`/api/auth/sso/${encodeURIComponent(e)}/start-qr${n?"?"+n:""}`,i=await fetch(r),o=await i.json();return!i.ok||!o.success?(this.error=o.error||"Failed to start QR login",!1):(this.qrPanel={provider:e,intent:t,authorizeUrl:o.authorizeUrl,state:o.state,status:"pending",error:null},this._startQrPoll(),!0)}catch(s){return this.error=s.message||"Network error",!1}},_startQrPoll(){this._stopQrPollTimer();let e=async()=>{if(!this.qrPanel)return;let t=this.qrPanel.state;try{let n=await(await fetch(`/api/auth/sso/poll/${encodeURIComponent(t)}`)).json();if(!this.qrPanel||this.qrPanel.state!==t||n.status==="pending")return;if(n.status==="login"){this.token=n.token,this.sessionKey=n.sessionKey?yt(n.sessionKey):null,this.role=n.role||"pro",this.userId=n.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",localStorage.setItem("authToken",n.token),this.startSessionRefresh(),this.cancelSsoQr();return}if(n.status==="bind"){this.qrPanel={...this.qrPanel,status:"bound"},this._stopQrPollTimer();return}this.qrPanel={...this.qrPanel,status:"error",error:n.error||"SSO failed"},this._stopQrPollTimer()}catch{}};this._qrPollTick=e,this._qrPollTimer=setInterval(e,2e3),typeof document<"u"&&!this._qrVisHandler&&(this._qrVisHandler=()=>{typeof document<"u"&&document.visibilityState&&document.visibilityState!=="visible"||!this.qrPanel||!this._qrPollTick||(this._qrPollTick(),this._qrPollTimer&&clearInterval(this._qrPollTimer),this._qrPollTimer=setInterval(this._qrPollTick,2e3))},document.addEventListener("visibilitychange",this._qrVisHandler),typeof window<"u"&&window.addEventListener("pageshow",this._qrVisHandler))},_stopQrPollTimer(){this._qrPollTimer&&(clearInterval(this._qrPollTimer),this._qrPollTimer=null),this._qrVisHandler&&(typeof document<"u"&&document.removeEventListener("visibilitychange",this._qrVisHandler),typeof window<"u"&&window.removeEventListener("pageshow",this._qrVisHandler),this._qrVisHandler=null),this._qrPollTick=null},cancelSsoQr(){this._stopQrPollTimer(),this.qrPanel=null},bindSso(e){if(!this.isAuthenticated){this.error="You must be logged in to bind an identity";return}let t=new URLSearchParams({intent:"bind"});window.location.href=`/api/auth/sso/${encodeURIComponent(e)}/start?${t.toString()}`},consumeSsoRedirect(){let e=window.location.hash||"",t=e.indexOf("?");if(!e.startsWith("#/sso-complete")||t<0)return!1;let s=new URLSearchParams(e.slice(t+1)),n=s.get("token"),r=s.get("sessionKey"),i=s.get("role"),o=s.get("userId");if(!n)return!1;this.token=n,this.sessionKey=r?yt(r):null,this.role=i||"pro",this.userId=o||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",localStorage.setItem("authToken",n),this.startSessionRefresh();try{history.replaceState(null,"",window.location.pathname+window.location.search)}catch{}return!0},async loadIdentities(){if(this.isAuthenticated){this.identitiesLoading=!0,this.identitiesError=null;try{let e=await fetch("/api/auth/identities"),t=await e.json();if(!e.ok||!t.success){this.identitiesError=t.error||"Failed to load identities";return}this.linkedIdentities=t.identities||[],this.hasPassword=!!t.hasPassword}catch(e){this.identitiesError=e.message||"Network error"}finally{this.identitiesLoading=!1}}},async unbindIdentity(e){if(!this.isAuthenticated)return!1;this.identitiesError=null;try{let t=await fetch(`/api/auth/identities/${encodeURIComponent(e)}`,{method:"DELETE"}),s=await t.json();return!t.ok||!s.success?(this.identitiesError=s.error||"Failed to unbind",!1):(this.linkedIdentities=this.linkedIdentities.filter(n=>n.provider!==e),!0)}catch(t){return this.identitiesError=t.message||"Network error",!1}},async refreshSession(){let e=this.token,t=this.authGeneration,s=this.isAuthenticated;try{let n=await fetch("/api/user/profile",{headers:e?{Authorization:`Bearer ${e}`}:{}});if(this.handleAuthResponse(n,e,t,s)||!n.ok)return!1;let r=await n.json().catch(()=>({}));if(t!==this.authGeneration||this.token!==e)return this.isAuthenticated;let i=n.headers?.get?.("X-New-Token"),o=localStorage.getItem("authToken");i&&this.token===e&&(!o||o===e)&&(this.token=i,localStorage.setItem("authToken",i)),r?.role&&(this.role=r.role);let a=this.userId;return this.userId=r?.userId||null,bt(this.userId),a!==this.userId&&$o(),qr=this.userId,!0}catch{return!1}},startSessionRefresh(){if(this.stopSessionRefresh(),!this.isAuthenticated||this.skipAuth)return;let e=()=>{typeof document<"u"&&document.visibilityState&&document.visibilityState!=="visible"||this.refreshSession()};this._sessionRefreshTimer=setInterval(e,Jh),this._sessionRefreshVisibilityHandler=e,typeof document<"u"&&document.addEventListener("visibilitychange",e),typeof window<"u"&&window.addEventListener("pageshow",e)},stopSessionRefresh(){this._sessionRefreshTimer&&(clearInterval(this._sessionRefreshTimer),this._sessionRefreshTimer=null),this._sessionRefreshVisibilityHandler&&(typeof document<"u"&&document.removeEventListener("visibilitychange",this._sessionRefreshVisibilityHandler),typeof window<"u"&&window.removeEventListener("pageshow",this._sessionRefreshVisibilityHandler),this._sessionRefreshVisibilityHandler=null)},async logout(){try{let e={"Content-Type":"application/json"};this.token&&(e.Authorization=`Bearer ${this.token}`),await fetch("/api/auth/logout",{method:"POST",headers:e})}catch{}await this.clearStoredSession()},clearStoredSession(e=null){let t=this.reset();return localStorage.removeItem("authToken"),e&&(this.error=e),t},getActiveToken(){if(this.token)return this.token;let e=localStorage.getItem("authToken");return e&&(this.token=e),this.token},handleAuthResponse(e,t=null,s=this.authGeneration,n=this.isAuthenticated,r=void 0){if(!e||e.status!==401||!n||s!==this.authGeneration)return!1;let i=this.token||localStorage.getItem("authToken")||null;return t!==i?!1:(this.handleAuthFailure(r,t,s),!0)},handleAuthFailure(e="Session expired. Please log in again.",t=null,s=this.authGeneration){if(s!==this.authGeneration)return!1;let n=this.token||localStorage.getItem("authToken")||null;return t!==n||this.clearStoredSession(e),!1},async restoreSession(){let e=localStorage.getItem("authToken"),t=this.authGeneration,s=this.isAuthenticated||!!e;try{let n=await fetch("/api/user/profile",{headers:e?{Authorization:`Bearer ${e}`}:{}});if(this.handleAuthResponse(n,e,t,s))return!1;if(!n.ok)return this.error="Failed to restore session",!1;let r=await n.json();if(t!==this.authGeneration)return this.isAuthenticated;let i=n.headers?.get?.("X-New-Token"),o=this.getActiveToken();if(o!==e)return this.isAuthenticated;let a=i&&(!o||o===e)?i:o||e;return this.token=a,a&&a!==e&&localStorage.setItem("authToken",a),this.role=r?.role||"pro",this.userId=r?.userId||null,bt(this.userId),Ot(this.userId),this.authGeneration+=1,this.isAuthenticated=!0,this.loginStep="authenticated",this.startSessionRefresh(),!0}catch(n){return this.error=n.message||"Failed to restore session",!1}},setSessionKey(e){e&&(this.sessionKey=yt(e))},backToCredentials(){this.loginStep="credentials",this.tempToken=null,this.emailHint=null,this.setupToken=null,this.totpSecret=null,this.qrCode=null,this.error=null},async requestPasswordReset(e){this.error=null;try{let s=await(await fetch("/api/auth/password-reset/request",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})})).json();return s.success?s.resetToken||null:(this.error=s.error||"Failed to request password reset",null)}catch(t){return this.error=t.message||"Network error",null}},async verifyPasswordReset(e,t,s){this.error=null;try{let r=await(await fetch("/api/auth/password-reset/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resetToken:e,code:t,newPassword:s})})).json();return r.success?!0:(this.error=r.error||"Failed to reset password",!1)}catch(n){return this.error=n.message||"Network error",!1}},async deleteAccount({currentPassword:e,confirm:t}={}){if(!this.isAuthenticated)return{success:!1,error:"Not authenticated"};try{let s=await fetch("/api/user/me",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:e,confirm:t})}),n=await s.json();return!s.ok||!n.success?{success:!1,error:n.error||"Failed to delete account"}:(await this.clearStoredSession(),{success:!0})}catch(s){return{success:!1,error:s.message||"Network error"}}},reset(){Do(),Zh(),this.authGeneration+=1,this.stopSessionRefresh(),this.isAuthenticated=!1,this.token=null,this.sessionKey=null,this.userId=null,this.role=null,this.loginStep="credentials",this.tempToken=null,this.emailHint=null,this.setupToken=null,this.totpSecret=null,this.qrCode=null,this.error=null,this.loading=!1}}})});function _e(e,t){let s=Ft?.value||"zh-CN",r=(zs[s]||zs["zh-CN"]||{})[e];if(r===void 0&&s!=="zh-CN"&&(r=(zs["zh-CN"]||{})[e]),r===void 0)return e;if(t)for(let[i,o]of Object.entries(t))r=r.replace(new RegExp(`\\{${i}\\}`,"g"),o);return r}function em(){return Ft?.value||"zh-CN"}function Hn(e){zs[e]&&(Ft&&(Ft.value=e),localStorage.setItem("locale",e),document.documentElement.setAttribute("lang",e))}function tm(){let e=localStorage.getItem("locale");return e&&zs[e]?e:(navigator.language||navigator.userLanguage||"").startsWith("en")?"en":"zh-CN"}function ic(e,t){return zs=t,Ft=Vue.ref(tm()),document.documentElement.setAttribute("lang",Ft.value),e.config.globalProperties.$t=_e,e.config.globalProperties.$locale=Ft,e.provide("t",_e),e.provide("locale",Ft),{t:_e,setLocale:Hn,getLocale:em,locale:Ft}}var Ft,zs,Bt=O(()=>{Ft=null,zs={}});function Wr(e){if(e==null||e==="")return"claude-code";if(sm.has(e))return e;throw new Error(`Unknown Chat runtime provider: ${e}`)}function Jt(e){if(typeof e!="string"||!e)throw new Error("Chat catalog key requires conversationId");return`chat:${e}`}function jr(e,t){if(typeof e!="string"||!e||typeof t!="string"||!t)throw new Error("Yeaft catalog key requires agentId and sessionId");return`yeaft:${e}:${t}`}function On(e,t,s={}){let n=e.sessionCatalog.map(i=>({...i})),r=Array.isArray(e.hiddenSessionCatalog)?e.hiddenSessionCatalog.map(i=>({...i})):null;return e.sessionCatalogMutationRequests[t]={previousCatalog:n,previousHiddenCatalog:r,...s},n}function oc(e,t){let s=t?.requestId?e.sessionCatalogMutationRequests[t.requestId]:null;return s?(delete e.sessionCatalogMutationRequests[t.requestId],t.ok!==!0&&(e.sessionCatalog=s.previousCatalog,Array.isArray(s.previousHiddenCatalog)&&(e.hiddenSessionCatalog=s.previousHiddenCatalog)),!0):!1}function ac(e,t,s="recent",n=null){let r=Jt(t),i=e.chatHistoryRequests[r]||{},o=Number(i.generation||0)+1,a=`chat_history_${o}_${crypto.randomUUID()}`;return e.chatHistoryRequests[r]={requestId:a,catalogKey:r,generation:o,mode:s,cursor:n,connectionGeneration:Number(e.chatHistoryConnectionGeneration||0),loading:!0,cancelled:!1,error:null},a}function Vo(e,t,s,n){let r=e.chatHistoryRequests[t];return r?.requestId!==s?!1:(e.chatHistoryRequests[t]={...r,loading:!1,cancelled:!0,error:n},!0)}var sm,Ho=O(()=>{sm=new Set(["claude-code","copilot"])});function Ys(e,t,s=""){Fn&&(clearTimeout(Fn),Fn=null),e.sessionLoading=t,e.sessionLoadingText=s,t&&(Fn=setTimeout(()=>{e.sessionLoading&&(e.sessionLoading=!1,e.sessionLoadingText=""),Fn=null},nm))}function At(e){Ys(e,!1)}function lc(e){if(e.currentConversation){e.pendingRecovery=null;return}let t=e.lastUsedSession,s=e.lastUsedAgent;if(t&&t.sessionId&&s){let n=e.agents.find(r=>r.id===s&&r.online);n&&(e.pendingRecovery={agentId:s,agentName:n.name,sessionId:t.sessionId,workDir:t.workDir,provider:Wr(t.provider),catalogKey:t.catalogKey||null},e.recoveryDismissed=!1)}}function cc(e){if(!e.pendingRecovery)return;let{agentId:t,sessionId:s,workDir:n,provider:r}=e.pendingRecovery;e.selectAgent(t),setTimeout(()=>{e.resumeConversation(s,n,t,{provider:Wr(r)}),e.pendingRecovery=null,e.recoveryDismissed=!1},500)}function dc(e){e.recoveryDismissed=!0,e.pendingRecovery=null}function uc(e,t){let s=e.conversations.find(n=>n.id===t);s&&(e.activeConversations=[t],e.currentWorkDir=s.workDir,e.messagesMap[t]?.length>0||(s.claudeSessionId?(e.messagesMap[t]=[],Ys(e,!0,_e("chat.session.loadingHistory")),e.sendWsMessage({type:"resume_conversation",agentId:s.agentId||e.currentAgent,claudeSessionId:s.claudeSessionId,workDir:s.workDir,conversationId:t})):(e.messagesMap[t]=[],e.requestChatHistory?.(t,{mode:"recent",turns:5}))),e.sendWsMessage({type:"select_conversation",conversationId:t}))}function pc(e){if(e.panels.length>0)return;let t=localStorage.getItem("panels");if(!t)return;let s;try{s=JSON.parse(t)}catch{localStorage.removeItem("panels");return}if(!Array.isArray(s)||s.length<2){localStorage.removeItem("panels");return}let n=new Set(e.conversations.map(i=>i.id)),r=s.filter(i=>i&&typeof i.id=="string").map(i=>({id:i.id,conversationId:i.conversationId&&n.has(i.conversationId)?i.conversationId:null,activeRightPanel:i.activeRightPanel||null}));if(r.length<2){localStorage.removeItem("panels");return}e.panels=r,e.activePanelId=r[0]?.id||null;for(let i of r)i.conversationId&&(e.activeConversations.includes(i.conversationId)||e.activeConversations.push(i.conversationId),e.messagesMap[i.conversationId]||(e.messagesMap[i.conversationId]=[]),e.messagesMap[i.conversationId].length||e.requestChatHistory?.(i.conversationId,{mode:"recent",turns:5}))}function ys(e){if(e.currentAgent){if(localStorage.setItem("lastUsedAgent",e.currentAgent),localStorage.setItem("lastViewedConversation",e.currentConversation||""),e.lastViewedConversation=e.currentConversation,e.currentConversation){let t=e.conversations.find(s=>s.id===e.currentConversation);if(t?.claudeSessionId&&t?.workDir){let s=Wr(t.provider),n={sessionId:t.claudeSessionId,workDir:t.workDir,agentId:t.agentId||e.currentAgent,provider:s,catalogKey:Jt(t.id),version:2};localStorage.setItem("lastUsedSession",JSON.stringify(n)),localStorage.setItem("lastViewedSessionRef",JSON.stringify(n)),e.lastUsedSession=n}}e.lastUsedAgent=e.currentAgent,e.panels.length>0?localStorage.setItem("panels",JSON.stringify(e.panels)):localStorage.removeItem("panels")}}function fc(e){return e.lastUsedSession}function gc(e){localStorage.removeItem("lastUsedAgent"),localStorage.removeItem("lastUsedSession"),localStorage.removeItem("lastViewedSessionRef"),localStorage.removeItem("lastViewedConversation"),localStorage.removeItem("panels"),localStorage.removeItem("splitPanesSaved"),e.lastUsedAgent=null,e.lastUsedSession=null,e.lastViewedConversation=null}function hc(e,t,s){if(!e.currentAgent){e.historySessionsLoading=!1;return}if(!t){e.historySessions=[],e.historySessionsLoading=!1;return}let n=Date.now().toString();e._historySessionsRequestId=n,e.historySessionsLoading=!0,e.historySessions=[],e.sendWsMessage({type:"list_history_sessions",workDir:t,provider:s||"claude-code",requestId:n})}function mc(e,t){if(!e.currentAgent)return e.foldersLoading=!1,Promise.resolve();e.foldersLoading=!0,e.folders=[];let s=Date.now().toString();return e._foldersRequestId=s,new Promise(n=>{e._foldersResolve&&e._foldersResolve(),e._foldersResolve=n,e.sendWsMessage({type:"list_folders",provider:t||"claude-code",requestId:s}),setTimeout(()=>{e._foldersResolve===n&&(e._foldersResolve(),e._foldersResolve=null,e.foldersLoading=!1)},1e4)})}function vc(e,t,s){if(!t)return e.foldersLoading=!1,Promise.resolve();e.foldersLoading=!0,e.folders=[];let n=Date.now().toString();return e._foldersRequestId=n,new Promise(r=>{e._foldersResolve&&e._foldersResolve(),e._foldersResolve=r,e.sendWsMessage({type:"list_folders",agentId:t,provider:s||"claude-code",requestId:n}),setTimeout(()=>{e._foldersResolve===r&&(e._foldersResolve(),e._foldersResolve=null,e.foldersLoading=!1)},1e4)})}function yc(e,t,s){if(!t)return Promise.resolve([]);let n=`models-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return e._modelsRequestId=n,e.providerModelsLoading=!0,new Promise(r=>{e._modelsResolve&&e._modelsResolve([]),e._modelsTimeout&&clearTimeout(e._modelsTimeout),e._modelsResolve=r,e.sendWsMessage({type:"list_models",agentId:t,provider:s||"claude-code",requestId:n}),e._modelsTimeout=setTimeout(()=>{e._modelsResolve===r&&(e._modelsResolve([]),e._modelsResolve=null,e.providerModelsLoading=!1),e._modelsTimeout=null},1e4)})}function bc(e,t,s,n){if(!t){e.historySessionsLoading=!1;return}if(!s){e.historySessions=[],e.historySessionsLoading=!1;return}let r=Date.now().toString();e._historySessionsRequestId=r,e.historySessionsLoading=!0,e.historySessions=[],e.sendWsMessage({type:"list_history_sessions",agentId:t,workDir:s,provider:n||"claude-code",requestId:r})}async function wc(e,t=20){if(Re().isAuthenticated){e.globalSessionsLoading=!0;try{let n=await fetch(`/api/sessions?limit=${t}`);if(n.ok){let r=await n.json();e.globalSessions=r.sessions||[]}}catch{}finally{e.globalSessionsLoading=!1}}}async function kc(e,t){if(!Re().isAuthenticated)return!1;try{if((await fetch(`/api/sessions/${t}`,{method:"DELETE"})).ok)return e.globalSessions=e.globalSessions.filter(r=>r.id!==t),!0}catch{}return!1}function Oo(e,t){return t.agentId?e.agents.find(s=>s.id===t.agentId):t.agentName?e.agents.find(s=>s.name===t.agentName):null}function Sc(e,t){let s=Oo(e,t);return s&&s.online}var nm,Fn,bs=O(()=>{wt();Bt();Ho();nm=3e4,Fn=null});function Ic(e){return e?.code===1008&&String(e.reason||"").toLowerCase().includes("authentication")}function Cc(e){let t=Bn;Bn=[];for(let{resolve:s,reject:n,timer:r}of t)clearTimeout(r),e?s():n(new Error("WebSocket reconnect failed"))}function Ac(e,t){if(!e.ws||e.ws.readyState!==WebSocket.OPEN)return!1;if(e.currentView==="yeaft"&&im.has(t.type)){let s=t.conversationId;if(!s||typeof s=="string"&&s.startsWith("yeaft-")||s===e.yeaftConversationId)return!1}try{if(e.serverEncryptionRequired&&e.sessionKey){let s=Xl(t,e.sessionKey);e.ws.send(JSON.stringify(s))}else e.ws.send(JSON.stringify(t));return!0}catch{return!1}}function Nn(e,t=1e4){return e.ws&&e.ws.readyState===WebSocket.OPEN?Promise.resolve():new Promise((s,n)=>{let r=setTimeout(()=>{Bn=Bn.filter(i=>i.resolve!==s),n(new Error("WebSocket reconnect timeout"))},t);Bn.push({resolve:s,reject:n,timer:r}),(!e.ws||e.ws.readyState!==WebSocket.CONNECTING)&&(e.reconnectAttempts=0,e.connect())})}function xc(e,t){try{let s=JSON.parse(t);return e.sessionKey&&Jl(s)?Zl(s,e.sessionKey):s}catch{return null}}function Tc(e){let t=Re(),s=location.protocol==="https:"?"wss:":"ws:";e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);let n=t.getActiveToken?.()||t.token||null,r=t.authGeneration;if(e.ws&&e.ws.readyState===WebSocket.CONNECTING&&e._wsAuthToken===n&&e._wsAuthGeneration===r)return;clearTimeout(e._legacyYeaftSessionHydrateTimer),e._legacyYeaftSessionHydrateTimer=null,e._hasHandledAgentList=!1,e._hasHandledYeaftSessionHydrate=!1,e.yeaftSessionInventoryCompleteSupported=null,e.yeaftSessionHydrateRequestId=null,e.yeaftSessionHydrateSlices=[],e.yeaftSessionHydrateError=null,e._yeaftSessionInventorySocketQuarantined=!1,e.pendingAgentSelection=null,e.agentSwitching=!1,e.ws&&(e.ws.onopen=null,e.ws.onmessage=null,e.ws.onclose=null,e.ws.close(),e.ws=null),e.connectionState=e.reconnectAttempts>0?"reconnecting":"connecting",e.serverEncryptionRequired=!0,e.chatHistoryRequestIdSupported=null,e.chatHistoryConnectionGeneration=Number(e.chatHistoryConnectionGeneration||0)+1;for(let[l,c]of Object.entries(e.projectMutationRequests||{}))c?.resolve?.({ok:!1,requestId:l,error:{code:"connection_changed"}});e.projectMutationRequests={},e.sessionProjects=[];for(let[l,c]of Object.entries(e.chatHistoryRequests||{}))c?.loading&&(e.chatHistoryRequests[l]={...c,loading:!1,cancelled:!0,error:"connection_changed"});let i=Object.values(e.sessionCatalogMutationRequests||{});i.length>0&&(e.sessionCatalog=i[0].previousCatalog,Array.isArray(i[0].previousHiddenCatalog)&&(e.hiddenSessionCatalog=i[0].previousHiddenCatalog),e.sessionCatalogMutationRequests={}),e.sessionCatalogLoaded=!1,e.sessionCatalog=[],e.hiddenSessionCatalog=[],e.activeCatalogKey=null,e._wsAuthToken=n,e._wsAuthGeneration=r;let o=`${s}//${location.host}?type=web`;n&&(o+=`&token=${encodeURIComponent(n)}`);let a=new WebSocket(o);e.ws=a,a.onopen=()=>{if(a===e.ws){e.connectionState="connected",e.reconnectAttempts=0,e.startHeartbeat();try{a.send(JSON.stringify({type:"client_hello",plaintextOk:!0}))}catch{}Cc(!0)}},a.onmessage=l=>{if(a!==e.ws)return;let c=e.parseWsMessage(l.data);c&&(c.type,e.handleMessage({...c,_wsAuthToken:n,_wsAuthGeneration:r}))},a.onclose=l=>{if(a!==e.ws){Ic(l)&&t.handleAuthFailure?.(void 0,n,r);return}e.authenticated=!1,clearTimeout(e._legacyYeaftSessionHydrateTimer),e._legacyYeaftSessionHydrateTimer=null,e._hasHandledAgentList=!1,e._hasHandledYeaftSessionHydrate=!1,e.yeaftSessionInventoryCompleteSupported=null,e.yeaftSessionHydrateRequestId=null,e.yeaftSessionHydrateSlices=[],e.yeaftSessionHydrateError=null,e.pendingAgentSelection=null,e.agentSwitching=!1;let c=e.connectionState==="updating";if(e.connectionState=c?"updating":"disconnected",e.stopHeartbeat(),At(e),Ic(l)){t.handleAuthFailure?.(void 0,n,r),e.reconnectAttempts=0,Cc(!1);return}if(e._yeaftReconnectCatchUpPending=!0,c){e.reconnectAttempts=0,e.reconnectTimer=setTimeout(()=>{e.connect()},2e3);return}e.scheduleReconnect()},e.ws.onerror=l=>{}}function Mc(e){if(e.reconnectAttempts>=e.maxReconnectAttempts){e.connectionState="disconnected";return}let t=Math.min(1e3*Math.pow(2,e.reconnectAttempts),3e4);e.reconnectAttempts++,e.connectionState="reconnecting",e.reconnectTimer=setTimeout(()=>{e.connect()},t)}function Pc(e){e.reconnectAttempts=0,e.connect()}function Rc(e){e.stopHeartbeat(),e._lastPongAt=Date.now(),e.heartbeatTimer=setInterval(()=>{if(e.ws&&e.ws.readyState===WebSocket.OPEN){if(Date.now()-e._lastPongAt>45e3){e.ws.close(4e3,"Heartbeat timeout");return}try{e.sendWsMessage({type:"ping"})}catch{}}},25e3)}function _c(e){e.heartbeatTimer&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=null)}function Dc(e){e._visibilityHandlerInstalled||(e._visibilityHandlerInstalled=!0,document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="visible")if(!e.ws||e.ws.readyState!==WebSocket.OPEN)e.reconnectAttempts=0,e.connect();else try{e.sendWsMessage({type:"ping"});let t=e._lastPongAt;setTimeout(()=>{e._lastPongAt===t&&e.ws&&e.ws.close(4001,"Visibility resume timeout")},3e3)}catch{e.reconnectAttempts=0,e.connect()}}))}var Bn,im,Fo=O(()=>{wt();Fr();bs();Bn=[];im=new Set(["sync_messages","refresh_conversation","select_conversation","cancel_execution","update_conversation_settings","ask_user_answer"])});function ye(e,t){let s=t==null?"__all__":String(t);return e?`${e}${s}`:s}function qn(e){return typeof e?.entryId=="string"&&e.entryId?`entry:${e.entryId}`:e?.role==="assistant"&&e?.turnId?`live-response:${e.turnId}:${e.speakerVpId||e.vpId||""}`:typeof e?.clientMessageId=="string"&&e.clientMessageId?`client:${e.clientMessageId}`:`message:${e?.messageId||""}`}function Wn(e,t,s){return typeof s!="string"||!s?null:`${ye(e,t)}message:${s}`}function es(e,t,s){return typeof s!="string"||!s?null:`${ye(e,t)}client:${s}`}var Gs=O(()=>{});function Bo(e){return typeof e=="string"&&e?e:null}function Qs(e,t){return e?.yeaftSessionHistoryState?.[t]||null}function kt(e){let t=e?.yeaftActiveSessionFilter||null;if(!t)try{t=(typeof window<"u"&&window.Pinia?.useSessionsStore?.())?.activeSessionId||null}catch{}if(!t)return{agentId:e?.currentAgent||null,sessionId:null,sessionKey:""};let s=(()=>{try{let n=typeof window<"u"&&window.Pinia?.useSessionsStore?.(),r=n?.activeSessionKey?n.sessions?.[n.activeSessionKey]:null;if(r?.id===t&&r.agentId)return r.agentId}catch{}return typeof e?.resolveYeaftSessionAgentId=="function"?e.resolveYeaftSessionAgentId(t):e?.currentAgent||null})();return{agentId:s,sessionId:t,sessionKey:ye(s,t)}}function Lc(e,{agentId:t,sessionId:s,mode:n="recent",preserveLoaded:r=!1,latestSeq:i=null}={}){if(!t||!s)return null;let o=ye(t,s),a=Qs(e,o)||{},l=Number(a.generation||0)+1,c=`yeaft_history_${l}_${crypto.randomUUID()}`,d={...a,loaded:!!a.loaded,loading:!0,error:null,requestId:c,generation:l,mode:n,background:n==="prefetch",requestedAt:Date.now(),latestSeq:Number.isFinite(i)?i:a.latestSeq??null};return delete d.completionSeen,r||(d.syncingAfterSeq=null,a.loaded||(d.hasMore=!1,d.oldestSeq=null,d.serverOldestFetchedSeq=null,d.serverHasMore=!1,d.gapQueue=[],d.requestedBeforeSeqs=[],d.count=0)),e.yeaftSessionHistoryState={...e.yeaftSessionHistoryState||{},[o]:d},ws(e),{sessionKey:o,requestId:c,generation:l,state:d}}function No(e,t={}){let s=t.sessionId??t.groupId??null;if(!s)return!1;let n=t.agentId||e?.yeaftSessionAgentById?.[s]||null,r=ye(n,s),i=Qs(e,r),o=Bo(t.requestId);if(!i)return o===null;let a=Bo(i.requestId);return o?o===a:a===null}function $c(e,t={},s={},n="chunk"){if(!No(e,t))return null;let r=t.sessionId??t.groupId??null,i=t.agentId||e?.yeaftSessionAgentById?.[r]||null,o=ye(i,r),a=Qs(e,o)||{},l=Bo(t.requestId),c=l!==null&&n==="completion",d={...a,...c?{}:s,...c?{completionSeen:!0}:{},error:null};return c?(d.loading=!0,d.requestId=l):(d.loading=!1,d.requestId=null,d.completedAt=Date.now(),delete d.completionSeen),e.yeaftSessionHistoryState={...e.yeaftSessionHistoryState||{},[o]:d},ws(e),d}function jn(e,{agentId:t,sessionId:s,requestId:n,error:r="history_load_failed"}={}){if(!t||!s||!n)return!1;let i=ye(t,s),o=Qs(e,i);return!o||o.requestId!==n||!o.loading?!1:(e.yeaftSessionHistoryState={...e.yeaftSessionHistoryState||{},[i]:{...o,loading:!1,error:r,requestId:null,completedAt:Date.now()}},ws(e),!0)}function ws(e){let{sessionKey:t}=kt(e),s=t?Qs(e,t):null;return e.yeaftLoadingMoreHistory=!!s?.loading&&s?.mode!=="prefetch",e.yeaftHistoryLoadError=s?.error||null,e.yeaftHasMoreHistory=!!s?.hasMore,e.yeaftOldestLoadedSeq=Number.isFinite(s?.serverOldestFetchedSeq)?s.serverOldestFetchedSeq:Number.isFinite(s?.oldestSeq)?s.oldestSeq:null,s}function qo(e){let{sessionKey:t}=kt(e);return t?Qs(e,t):null}var Ec,Ur=O(()=>{Gs();Ec=15e3});function Wo(e){return e?.sessionId??e?.groupId??null}function Uo(e){for(let t of[e?.persistedMessageId,e?.messageId,e?.id]){if(typeof t!="string")continue;let s=t.match(/^(m\d+)/);if(s)return s[1]}return null}function je(e){return e?.isStreaming||e?.status==="pending"?!1:Number.isFinite(e?.seq)||!!Uo(e)||e?.isHistory===!0&&!e?.clientMessageId}function Ko(e){if(Number.isFinite(e?.seq))return Number(e.seq);let s=Uo(e)?.match(/^m(\d+)$/);if(s)return Number(s[1]);let n=typeof e?.id=="string"?e.id.match(/^(\d+)/):null;return n?Number(n[1]):null}function am(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}function lm(e){return e?e.isStreaming||e.status==="pending"||e.type==="tool-use"&&(e.askPending||!e.hasResult&&(e.toolName==="AskUser"||e.toolName==="AskUserQuestion"))?!0:e.type!=="user"||!e.clientMessageId?!1:!e.dbMessageId&&!Uo(e):!1}function cm(e){let t=[],s=null;for(let n of e)(n?.type==="user"||!s)&&(s={rows:[],protected:!1},t.push(s)),s.rows.push(n),lm(n)&&(s.protected=!0);return t}function Hc(e,{conversationId:t,agentId:s=null,sessionId:n=null,limits:r=Vc}={}){let i=e?.messagesMap?.[t];if(!Array.isArray(i)||i.length===0||!s||!n)return{evictedRows:0,keptRows:0};let o=v=>Wo(v)===n,a=i.filter(o),l=cm(a);if(l.length===0)return{evictedRows:0,keptRows:0};let c=l.filter(v=>v.protected),d=new Set(c),u=Number.isFinite(r.maxTurnsPerSession)?Math.max(0,Math.floor(r.maxTurnsPerSession)):jo,p=Math.max(0,u-c.length);for(let v=l.length-1;v>=0&&p>0;v-=1){let k=l[v];d.has(k)||(d.add(k),p-=1)}let f=new Set(l.filter(v=>d.has(v)).flatMap(v=>v.rows)),g=a.filter(v=>!f.has(v));if(g.length===0)return{evictedRows:0,keptRows:f.size};let h=i.filter(v=>!o(v)||f.has(v));i.splice(0,i.length,...h);let m=ye(s,n),b=e.yeaftHistoryCacheState?.[m]||null,y=Oc(a.filter(v=>f.has(v))),w=JSON.stringify(b?.ranges||[])===JSON.stringify(y.ranges)?Number(b?.rangeEpoch)||0:(Number(b?.rangeEpoch)||0)+1;if(e.yeaftHistoryCacheState={...e.yeaftHistoryCacheState||{},[m]:{...b||{},agentId:s,sessionId:n,conversationId:t,lastAccessed:Date.now(),rangeEpoch:w,...y}},g.some(je)){let v=y.ranges[0]?.startSeq??null,k=e.yeaftSessionHistoryState?.[m]||{};e.yeaftSessionHistoryState={...e.yeaftSessionHistoryState||{},[m]:{...k,serverOldestFetchedSeq:v,oldestSeq:v,serverHasMore:v!==null,hasMore:v!==null,gapTraversalInitialized:!1,gapQueue:[],requestedBeforeSeqs:[],completedHistoryWorkKeys:[],pendingPageKind:null,pendingPageBeforeSeq:null,pendingGapStopAtSeq:null,pendingCacheEpoch:null,pendingHistoryWorkKey:null,paginationError:null,count:y.rowCount}};let x=kt(e);x.agentId===s&&x.sessionId===n&&ws(e)}return{evictedRows:g.length,keptRows:f.size}}function dm(e){let t=[],s=null;for(let n of e)je(n)&&((n?.type==="user"||!s)&&(s=[],t.push(s)),s.push(n));return t}function um(e,t){let s=Number.isFinite(t.maxTurnsPerSession)?Math.max(0,Math.floor(t.maxTurnsPerSession)):jo,n=dm(e),r=new Set(n.slice(-s).flat());for(let i of n)if(i.some(o=>o?._historyWindowDetached===!0))for(let o of i)r.add(o);return r}function pm(e){let t=Array.from(new Set(e.map(Ko).filter(Number.isFinite))).sort((n,r)=>n-r),s=[];for(let n of t){let r=s.at(-1);r&&n<=r.endSeq+1?r.endSeq=n:s.push({startSeq:n,endSeq:n})}return s}function Oc(e){let t=e.filter(je);return{rowCount:t.length,byteCount:t.reduce((s,n)=>s+am(n),0),ranges:pm(t)}}function fm(e,t,s){let n=new Set((t||[]).map(r=>r?.stableKey).filter(Boolean));if(n.size!==0)for(let r of e)r?.stableKey&&n.has(r.stableKey)&&(r._historyCacheTouchedAt=s)}function gm(e,{conversationId:t,agentId:s,sessionId:n,incomingRows:r,now:i,limits:o}){let a=e.messagesMap?.[t]||[],l=a.filter(y=>Wo(y)===n);fm(l,r,i);let c=um(l,o),d=l.filter(y=>!je(y)||c.has(y)),u=new Set(d),p=a.filter(y=>Wo(y)!==n||u.has(y));a.splice(0,a.length,...p);let f=Oc(d),g=ye(s,n),h=e.yeaftHistoryCacheState?.[g]||null,b=JSON.stringify(h?.ranges||[])===JSON.stringify(f.ranges)?Number(h?.rangeEpoch)||0:(Number(h?.rangeEpoch)||0)+1;e.yeaftHistoryCacheState={...e.yeaftHistoryCacheState||{},[g]:{agentId:s,sessionId:n,conversationId:t,lastAccessed:i,rangeEpoch:b,...f}}}function Fc(e,t,s,n=Date.now()){if(!t||!s)return;let r=ye(t,s),i=e.yeaftHistoryCacheState?.[r];i&&(e.yeaftHistoryCacheState={...e.yeaftHistoryCacheState||{},[r]:{...i,lastAccessed:n}})}function zo(e,{conversationId:t,agentId:s,sessionId:n,incomingRows:r=[],now:i=Date.now(),limits:o=Vc}={}){!e||!t||!s||!n||gm(e,{conversationId:t,agentId:s,sessionId:n,incomingRows:r,now:i,limits:o})}var jo,Vc,Kr=O(()=>{Gs();Ur();jo=500,Vc=Object.freeze({maxTurnsPerSession:jo})});function ts(e){return e?.sessionId??e?.groupId??null}function Nc(e){let t=e?.stableKey??e?.uiKey??e?.messageId??e?.dbMessageId??e?.id;return t==null||t===""?null:String(t)}function hm(e,t){if(e?.type!=="assistant"||t?.type!=="assistant"||ts(e)!==ts(t)||e.isHistory===!0&&!e.isStreaming||t._hasPersistedTurnId!==!0||!e.turnId||!t.turnId||e.turnId!==t.turnId)return!1;let s=e.speakerVpId||e.vpId||"",n=t.speakerVpId||t.vpId||"";if(s&&n&&s!==n)return!1;let r=e.threadId||"",i=t.threadId||"";if(r&&i&&r!==i)return!1;let o=typeof e.content=="string"?e.content:"",a=typeof t.content=="string"?t.content:"";return!!o&&!!a&&(a.startsWith(o)||o.startsWith(a))}function Yo(e,t){let s=e.uiKey||t.uiKey||null;return Object.assign(e,t),s&&(e.uiKey=s),je(t)&&(e.isStreaming=!1,e.status==="pending"&&(e.status="completed")),e}function qc(e){let t=je(e),s=Ko(e),n=Number(e?.timestamp)||0;return[t?0:1,n,Number.isFinite(s)?s:-1]}function zr(e){return e.sort((t,s)=>{let n=je(t),r=je(s);if(!n&&!r)return 0;let i=qc(t),o=qc(s);for(let a=0;a<i.length;a+=1)if(i[a]!==o[a])return i[a]-o[a];return 0}),e}function mm(e,t){return Array.isArray(e.messagesMap?.[t])||(e.messagesMap=e.messagesMap||{},e.messagesMap[t]=[]),e.messagesMap[t]}function Go(e,t){return e.filter(s=>t===void 0||ts(s)===t)}function Qo(e,t){let s=Nc(t);if(s){let n=e.find(r=>Nc(r)===s);if(n)return n}if(t?.type==="user"&&t.clientMessageId){let n=e.find(r=>r?.type==="user"&&r.clientMessageId===t.clientMessageId&&ts(r)===ts(t));if(n)return n}return t?.type==="assistant"&&e.find(n=>hm(n,t))||null}function xt(e){if(!e||typeof e!="object")return null;let t=Bc.get(e);return t||(t=new Xo(e),Bc.set(e,t)),t}var Bc,Xo,Un=O(()=>{Kr();Bc=new WeakMap;Xo=class{constructor(t){this.store=t}rows(t){return mm(this.store,t)}durableRows(t,s=void 0){return Go(this.rows(t),s).filter(je)}overlayRows(t,s=void 0){return Go(this.rows(t),s).filter(n=>!je(n))}snapshot(t,s=void 0){return{durableRows:this.durableRows(t,s),overlayRows:this.overlayRows(t,s)}}commitDurable({conversationId:t,sessionId:s=void 0,rows:n=[],mode:r="delta",replaceDurable:i=!1,preserveEmpty:o=!0}={}){if(!t)return{insertedRows:0,preservedEmpty:!1};let a=this.rows(t),l=Array.isArray(n)?n.filter(Boolean):[],c=Go(a,s).length>0;if(o&&r==="recent"&&l.length===0&&c)return{insertedRows:0,inserted:[],preservedEmpty:!0};if(i){let p=a.filter(f=>ts(f)!==s||!je(f));a.splice(0,a.length,...p)}let d=0,u=[];for(let p of l){let f=Qo(a,p);f?Yo(f,p):(a.push(p),u.push(p),d+=1)}return zr(a),{insertedRows:d,inserted:u,preservedEmpty:!1}}upsertOverlay({conversationId:t,row:s}={}){if(!t||!s)return null;if(je(s)){let i=this.rows(t),o=Qo(i,s);return o?Yo(o,s):(i.push(s),zr(i),s)}let n=this.rows(t),r=Qo(n,s);return r?Yo(r,s):n.push(s),zr(n),r||s}appendOverlayText({conversationId:t,sessionId:s=void 0,turnId:n=null,text:r=""}={}){if(!t||!r)return null;let o=this.rows(t).findLast(a=>a?.type==="assistant"&&!je(a)&&(s===void 0||ts(a)===s)&&(!n||a.turnId===n));return o?(o.content?r.startsWith(o.content)?o.content=r:o.content.endsWith(r)||(o.content+=r):o.content=r,o):null}replaceProjection(t,s=[]){let n=this.rows(t);return n.splice(0,n.length,...Array.isArray(s)?s:[]),zr(n),n}removeDurable({conversationId:t,sessionId:s}={}){if(!t)return 0;let n=this.rows(t),r=n.filter(o=>ts(o)!==s||!je(o)),i=n.length-r.length;return n.splice(0,n.length,...r),i}}});function Kn(e,t){return t?t===e.yeaftConversationId?!0:Object.values(e.yeaftConversationIdsByAgent||{}).includes(t):!1}function Xs(e,t,s){s&&(s.type!=="assistant"&&s.type!=="tool-use"||Kn(e,t)&&(!s.vpId&&e._currentYeaftVpId&&(s.vpId=e._currentYeaftVpId),!s.turnId&&e._currentYeaftTurnId&&(s.turnId=e._currentYeaftTurnId),!s.speakerVpId&&s.vpId&&(s.speakerVpId=s.vpId)))}function ym(e){let t=[e?.timestamp,e?.createdAt,e?.ts,e?.time,e?.created_at];for(let s of t){if(typeof s=="number"&&Number.isFinite(s)&&s>0)return s;if(typeof s=="string"&&s.trim()){let n=Date.parse(s);if(Number.isFinite(n))return n;let r=Number(s);if(Number.isFinite(r)&&r>0)return r}}return Date.now()}function Yr(e){let t=e?.stableKey??e?.messageId??e?.dbMessageId??e?.id;return t==null||t===""?null:String(t)}function Zo(e,t,s){if(!s||typeof s!="object")return null;if(typeof s.uiKey=="string"&&s.uiKey)return s.uiKey;let n=s.entryId||s.stableKey||s.atMessageId||s.messageId||s.dbMessageId||s.id||null;if(n!=null&&n!=="")return s.uiKey=String(n),s.uiKey;let r=`legacy:${t||"conversation"}:`,i=new Set((e?.messagesMap?.[t]||[]).map(a=>a?.uiKey).filter(a=>typeof a=="string"&&a)),o=Number(e?._messageUiKeySequence)||0;do o+=1;while(i.has(`${r}${o}`));return e&&(e._messageUiKeySequence=o),s.uiKey=`${r}${o}`,s.uiKey}function zn(e,t,s){for(let n of Array.isArray(s)?s:[])Zo(e,t,n);return s}function Jo(e,t){if(!e||!t)return e;let s=e.type==="user"&&typeof e.id=="string"&&e.id===e.clientMessageId;for(let[n,r]of Object.entries(t))if(r!=null){if(n==="isStreaming"){e.isStreaming&&r===!1&&(e.isStreaming=!1);continue}if(!(n==="uiKey"&&e.uiKey)){if(n==="id"||n==="messageId"){if(s&&t.clientMessageId===e.clientMessageId&&t.messageId&&t.messageId!==e.clientMessageId)continue;(e[n]===void 0||e[n]===null||e[n]==="")&&(e[n]=r);continue}if(!(n==="turnId"&&s&&e.turnId===e.clientMessageId)){if(n==="content"&&typeof r=="string"){e.content||(e.content=r);continue}if(n==="responseKind"&&(r==="progress"||r==="result")){e.responseKind=r;continue}if(n==="attachments"&&Array.isArray(r)){(!Array.isArray(e.attachments)||e.attachments.length===0)&&(e.attachments=r);continue}(e[n]===void 0||e[n]===null||e[n]==="")&&(e[n]=r)}}}return e}function Wc(e=[],t=[]){let s=[],n=new Map,r=new Map;for(let i of[...e,...t]){if(!i)continue;let o=Yr(i),a=i.type==="user"&&i.clientMessageId?String(i.clientMessageId):null;if(o&&n.has(o)){Jo(n.get(o),i);continue}if(a&&r.has(a)){let l=r.get(a);Jo(l,i),o&&!n.has(o)&&n.set(o,l);continue}s.push(i),o&&n.set(o,i),a&&r.set(a,i)}return s}function jc(e,t,s){return!e||e!==t?!1:!s?.loaded&&!s?.loading}function Uc(e,t){return!!t&&!!e?.loaded&&!e?.loading&&Number.isFinite(e?.latestSeq)}function Kc({sessionState:e,hasCachedSessionRows:t,force:s=!1}={}){return e?.loading?!1:s?!e?.loaded:e?.loaded?!1:!t}function bm(e,t,s,n){let r=s?.id?String(s.id):null;if(!r)return!1;let o=(e.messagesMap[t]||[]).find(a=>a?.type==="assistant"&&Yr(a)===r);return o?(o.id||(o.id=r),o.messageId||(o.messageId=r),s.ts&&!o.ts&&(o.ts=s.ts),s.timestamp&&!o.timestamp&&(o.timestamp=s.timestamp),s.sessionId&&!o.sessionId&&(o.sessionId=s.sessionId),s.vpId&&!o.vpId&&(o.vpId=s.vpId),s.turnId&&!o.turnId&&(o.turnId=s.turnId),s.threadId&&!o.threadId&&(o.threadId=s.threadId),o.content?typeof o.content=="string"&&(n.startsWith(o.content)?o.content=n:o.content.endsWith(n)||(o.content+=n)):o.content=n,Xs(e,t,o),!0):!1}function Gr(e,t,s){if(!t)return;let n={...s};Zo(e,t,n);let r={...n,id:s.dbMessageId||s.id||Date.now().toString()+Math.random().toString(36).substr(2,9),timestamp:ym(s)};if(Kn(e,t)&&!r.sessionId&&(r.sessionId=e._currentYeaftSessionId||e.yeaftActiveSessionFilter||vm),Kn(e,t)){let o=e._currentYeaftAgentId||Object.entries(e.yeaftConversationIdsByAgent||{}).find(([,c])=>c===t)?.[0]||e.currentAgent||null,a=typeof r.messageId=="string"&&/^m\d+$/.test(r.messageId)?r.messageId:typeof r.id=="string"&&/^m\d+$/.test(r.id)?r.id:null,l=typeof r.clientMessageId=="string"?r.clientMessageId:null;r.stableKey||(r.stableKey=a?Wn(o,r.sessionId,a):es(o,r.sessionId,l)),r.uiKey||(r.uiKey=r.stableKey||null),!r.vpId&&e._currentYeaftVpId&&(r.vpId=e._currentYeaftVpId),!r.turnId&&e._currentYeaftTurnId&&(r.turnId=e._currentYeaftTurnId),Xs(e,t,r)}if(e.messagesMap[t]||(e.messagesMap[t]=[]),Zo(e,t,r),Kn(e,t))return xt(e).upsertOverlay({conversationId:t,sessionId:r.sessionId,row:r});let i=Yr(s);if(i){let o=e.messagesMap[t].find(a=>Yr(a)===i);if(o)return Jo(o,r),t===e.yeaftConversationId&&e.messagesMap[t].sort((a,l)=>a.timestamp-l.timestamp),o}return e.messagesMap[t].push(r),t===e.yeaftConversationId&&e.messagesMap[t].sort((o,a)=>o.timestamp-a.timestamp),r}function zc(e,t,s,n={}){if(!t||!s)return;e.messagesMap[t]||(e.messagesMap[t]=[]);let r=e.messagesMap[t];if(bm(e,t,n,s))return;if(Kn(e,t)){let l=xt(e).appendOverlayText({conversationId:t,sessionId:n.sessionId||e._currentYeaftSessionId||void 0,turnId:n.turnId||e._currentYeaftTurnId||null,text:s});if(l){Xs(e,t,l),n.id&&!l.id&&(l.id=n.id),n.id&&!l.messageId&&(l.messageId=n.id);return}}let i=e._currentYeaftTurnId;if(i){for(let a=r.length-1;a>=0;a--)if(r[a].turnId===i&&r[a].type==="assistant"&&r[a].isStreaming){if(Xs(e,t,r[a]),n.id&&!r[a].id&&(r[a].id=n.id),n.id&&!r[a].messageId&&(r[a].messageId=n.id),r[a].content.endsWith(s))return;r[a].content+=s;return}Gr(e,t,{...n.id?{id:n.id,messageId:n.id}:{},...n.ts?{ts:n.ts}:{},...n.timestamp?{timestamp:n.timestamp}:{},...n.sessionId?{sessionId:n.sessionId}:{},...n.vpId?{vpId:n.vpId}:{},...n.turnId?{turnId:n.turnId}:{},...n.threadId?{threadId:n.threadId}:{},type:"assistant",content:s,isStreaming:!0,status:"pending",turnStartAt:n.timestamp||Date.now()});return}let o=r[r.length-1];if(o&&o.type==="assistant"&&o.isStreaming){if(Xs(e,t,o),n.id&&!o.id&&(o.id=n.id),n.id&&!o.messageId&&(o.messageId=n.id),o.content.endsWith(s))return;o.content+=s}else Gr(e,t,{...n.id?{id:n.id,messageId:n.id}:{},...n.ts?{ts:n.ts}:{},...n.timestamp?{timestamp:n.timestamp}:{},...n.sessionId?{sessionId:n.sessionId}:{},...n.vpId?{vpId:n.vpId}:{},...n.turnId?{turnId:n.turnId}:{},...n.threadId?{threadId:n.threadId}:{},type:"assistant",content:s,isStreaming:!0,status:"pending",turnStartAt:n.timestamp||Date.now()})}function Yc(e,t,{completeLifecycle:s=!0}={}){if(!t)return;let n=e.messagesMap[t];if(!n||n.length===0)return;let r=e._currentYeaftTurnId||null;for(let i=n.length-1;i>=0;i--){let o=n[i];if(r&&o.turnId&&o.turnId!==r){if(o.type==="user")break;continue}if(o.isStreaming&&(o.isStreaming=!1,s&&o.status==="pending"&&(o.status="completed",o.turnEndAt=Date.now())),Xs(e,t,o),o.type==="user")break}}function Gc(e,t){if(!t||e.processingConversations&&e.processingConversations[t]||e.activeVpTurns&&Object.keys(e.activeVpTurns).length>0)return;let s=e.messagesMap&&e.messagesMap[t];if(!(!s||s.length===0))for(let n of s)n&&n.isStreaming&&(n.isStreaming=!1)}function Qc(e,t){let s=e.currentConversation;if(!s)return;e.messagesMap[s]||(e.messagesMap[s]=[]);let n=e.messagesMap[s],r=null;for(let i of t)if(i.type==="user"){let o=i.message?.content;if(o){let a=typeof o=="string"?o:Array.isArray(o)?o.map(l=>l.text||"").join(""):"";a&&(r=a,e.addMessage({type:"user",content:a,isHistory:!0}))}}else if(i.type==="assistant"){let o=i.message?.content;if(o&&Array.isArray(o)){for(let a of o)if(a.type==="text"&&a.text)e.addMessage({type:"assistant",content:a.text,isHistory:!0});else if(a.type==="tool_use")e.addMessage({type:"tool-use",toolName:a.name,toolInput:a.input,isHistory:!0});else if(a.type==="tool_result"){for(let l=n.length-1;l>=0;l--)if(n[l].type==="tool-use"&&!n[l].hasResult){n[l].hasResult=!0,n[l].toolResult=a.content;break}}}}if(r&&s&&!e.conversationTitles[s]){let i=r.trim().substring(0,100);e.conversationTitles[s]=i}}function ks(e){if(!Array.isArray(e))return null;let t=null;for(let s of e)typeof s?.dbMessageId=="number"&&s.dbMessageId>0&&(t===null||s.dbMessageId>t)&&(t=s.dbMessageId);return t}function wm(e){return{id:e.id,dbMessageId:e.id,timestamp:e.created_at}}function Xc(e){if(!e)return null;let t=wm(e);if(e.message_type==="tool_use"){let n={...t,type:"tool-use",toolName:e.tool_name||"unknown",toolInput:(()=>{try{return JSON.parse(e.tool_input||e.content||"{}")}catch{return{}}})(),hasResult:!0,isHistory:!0,startTime:e.created_at||0};if(e.metadata)try{let r=JSON.parse(e.metadata);r.askRequestId&&(n.askRequestId=r.askRequestId,n.askQuestions=r.askQuestions,n.askAnswered=!!r.askAnswered,n.selectedAnswers=r.selectedAnswers||null,r.askAnswered||(n.isHistory=!1))}catch{}return n}let s=n=>{if(!n)return"";if(typeof n!="string")return String(n);if(n.startsWith("["))try{let r=JSON.parse(n);if(Array.isArray(r))return r.filter(i=>i.type==="text"&&i.text).map(i=>i.text).join("")}catch{}return n};if(e.role==="user"){let n=null;if(e.metadata)try{let r=JSON.parse(e.metadata);r&&typeof r.clientMessageId=="string"&&(n=r.clientMessageId)}catch{}return{...t,type:"user",content:typeof e.content=="string"?e.content:String(e.content||""),...n?{clientMessageId:n}:{}}}else if(e.role==="assistant"){let n=s(e.content),r=(()=>{if(!e.content||typeof e.content!="string"||!e.content.startsWith("["))return[];try{let i=JSON.parse(e.content);return Array.isArray(i)?i.filter(o=>o.type==="tool_use"&&o.name):[]}catch{return[]}})();if(!n&&r.length===0)return null;if(r.length>0){let i=[];n&&i.push({...t,type:"assistant",content:n});for(let o=0;o<r.length;o++){let a=r[o];i.push({id:e.id+"_tool_"+o,dbMessageId:e.id,timestamp:e.created_at,type:"tool-use",toolName:a.name,toolInput:a.input||{},hasResult:!0,isHistory:!0,startTime:e.created_at||0})}return i}return{...t,type:"assistant",content:n}}else if(e.role==="tool"||e.message_type==="tool_result")return{...t,type:"tool_result",tool:e.tool_name||"unknown",content:typeof e.content=="string"?e.content:String(e.content||"")};return null}var vm,Yn=O(()=>{Un();Gs();vm="grp_default"});function Ss(e,t){return e._closedAt?.[t]?Date.now()-e._closedAt[t]<3e4:!1}function Zs(e,t){Ce(e,t),e._processingWatchdogs||(e._processingWatchdogs={});let s=()=>{if(!e.processingConversations[t])return;let r=e.conversations.find(o=>o.id===t);e.sendWsMessage({type:"ping_session",conversationId:t,agentId:r?.agentId});let i=setTimeout(()=>{e.processingConversations[t]&&(e.sessionHealth||(e.sessionHealth={}),e.sessionHealth[t]={status:"agent-offline"})},1e4);e._pongTimeouts||(e._pongTimeouts={}),e._pongTimeouts[t]=i},n=setTimeout(()=>{e.processingConversations[t]&&(s(),e._processingWatchdogs[t]=setInterval(()=>{if(!e.processingConversations[t]){Ce(e,t);return}s()},3e4))},45e3);e._processingWatchdogs[t]=n}function Qr(e,t){e._yeaftWatchdogPauseReasons?.[t]?.size||e.processingConversations[t]&&e._processingWatchdogs?.[t]&&(e._pongTimeouts?.[t]&&(clearTimeout(e._pongTimeouts[t]),delete e._pongTimeouts[t]),e.sessionHealth?.[t]&&delete e.sessionHealth[t],e._yeaftWatchdogConvs?.has(t)?en(e,t):Zs(e,t))}function Ce(e,t){e._processingWatchdogs?.[t]&&(clearTimeout(e._processingWatchdogs[t]),clearInterval(e._processingWatchdogs[t]),delete e._processingWatchdogs[t]),e._pongTimeouts?.[t]&&(clearTimeout(e._pongTimeouts[t]),delete e._pongTimeouts[t]),e.sessionHealth?.[t]&&delete e.sessionHealth[t],e._autoRefreshed?.[t]&&delete e._autoRefreshed[t],e._yeaftWatchdogConvs?.delete(t),e._yeaftWatchdogPauseReasons&&delete e._yeaftWatchdogPauseReasons[t]}function Gn(e,t,s="phase"){if(!t||!e.processingConversations[t])return;e._yeaftWatchdogPauseReasons||(e._yeaftWatchdogPauseReasons={});let n=e._yeaftWatchdogPauseReasons[t]||new Set;n.add(s),e._yeaftWatchdogPauseReasons[t]=n,e._processingWatchdogs?.[t]&&(clearTimeout(e._processingWatchdogs[t]),clearInterval(e._processingWatchdogs[t]),delete e._processingWatchdogs[t])}function Js(e,t,s=null){if(!t)return;let n=e._yeaftWatchdogPauseReasons?.[t];n&&(s?n.delete(s):n.clear(),!n.size&&(delete e._yeaftWatchdogPauseReasons[t],e.processingConversations[t]&&en(e,t)))}function Zc(e,t){Ce(e,t),e._processingWatchdogs||(e._processingWatchdogs={}),e._processingWatchdogs[t]=setTimeout(()=>{if(e.processingConversations[t]){let s=e.conversations.find(n=>n.id===t);e.sendWsMessage({type:"refresh_conversation",conversationId:t,agentId:s?.agentId}),e._processingWatchdogs[t]=setTimeout(()=>{if(e.processingConversations[t]){delete e.processingConversations[t];let n=e.executionStatusMap[t];n&&(n.currentTool=null),e.finishStreamingForConversation(t)}delete e._processingWatchdogs[t]},1e4)}},9e4)}function en(e,t){let s=e._yeaftWatchdogPauseReasons?.[t];if(Ce(e,t),e._processingWatchdogs||(e._processingWatchdogs={}),s?.size){e._yeaftWatchdogConvs||(e._yeaftWatchdogConvs=new Set),e._yeaftWatchdogPauseReasons||(e._yeaftWatchdogPauseReasons={}),e._yeaftWatchdogConvs.add(t),e._yeaftWatchdogPauseReasons[t]=new Set(s);return}e._yeaftWatchdogConvs||(e._yeaftWatchdogConvs=new Set),e._yeaftWatchdogConvs.add(t),e._processingWatchdogs[t]=setTimeout(()=>{if(e.processingConversations[t]){delete e.processingConversations[t];let n=e.executionStatusMap[t];n&&(n.currentTool=null),e.finishStreamingForConversation(t)}delete e._processingWatchdogs[t]},15e4)}var ss=O(()=>{});function ea(e,t){return t&&Array.isArray(e?._yeaftRetiredConversationIdsByAgent?.[t])?e._yeaftRetiredConversationIdsByAgent[t]:[]}function tn(e,t,s){return!t||!s?!1:ea(e,t).includes(s)}function ta(e,t){let s=e?._yeaftRetiredConversationTargetsByAgent?.[t];return s&&typeof s=="object"?s:{}}function Jc(e,t,s){if(!t||!s)return null;let n=ta(e,t),r=s,i=new Set;for(let o=0;o<8;o++){if(i.has(r))return null;i.add(r);let a=n[r];if(!a||a===r)return r===s?null:r;r=a}return null}function Qn(e,t,s,n=null){if(!t||!s)return;let r=ea(e,t).filter(a=>a!==s).concat(s).slice(-8);e._yeaftRetiredConversationIdsByAgent={...e._yeaftRetiredConversationIdsByAgent||{},[t]:r};let i=ta(e,t),o={};for(let a of r){let l=i[a];l&&(o[a]=l===s&&n?n:l)}n&&n!==s&&(o[s]=n),e._yeaftRetiredConversationTargetsByAgent={...e._yeaftRetiredConversationTargetsByAgent||{},[t]:o}}function sa(e,t,s){if(!t||!s||!e?._yeaftRetiredConversationIdsByAgent)return;let n=ea(e,t).filter(i=>i!==s);e._yeaftRetiredConversationIdsByAgent={...e._yeaftRetiredConversationIdsByAgent,[t]:n};let r={...ta(e,t)};delete r[s],e._yeaftRetiredConversationTargetsByAgent={...e._yeaftRetiredConversationTargetsByAgent||{},[t]:r}}var Xr=O(()=>{});function Im(e,t,s){let n=e.messagesMap?.[t]||[],r=e.messagesMap?.[s]||[];e.messagesMap||(e.messagesMap={}),zn(e,t,n),zn(e,s,r);let i=Wc(r,n).sort((o,a)=>{let l=Number.isFinite(o?.seq)?o.seq:null,c=Number.isFinite(a?.seq)?a.seq:null;return l!==null&&c!==null&&l!==c?l-c:l!==null&&c===null?-1:l===null&&c!==null?1:(o?.timestamp||0)-(a?.timestamp||0)});xt(e).replaceProjection(s,i)}function Cm(e){if(!e||typeof e!="object")return e;if(typeof structuredClone=="function")try{return structuredClone(e)}catch{}return Array.isArray(e)?e.slice():{...e}}function Zr(e,t){return!!e&&Object.prototype.hasOwnProperty.call(e,t)}function sn(e,t,s,{removeSource:n}){Zr(e,t)&&(Zr(e,s)||(e[s]=n?e[t]:Cm(e[t])),n&&delete e[t])}function Tt(e,t,s=null){if(!t)return null;let n=e?._yeaftPendingConversationPromotions?.[t]||null;return!n?.sourceConversationId||!n.targetConversationId||s&&n.targetConversationId!==s?null:n}function Jr(e,t,s,n){return!t||!s||!n||s===n?!1:(e._yeaftPendingConversationPromotions={...e._yeaftPendingConversationPromotions||{},[t]:{sourceConversationId:s,targetConversationId:n}},!0)}function Xn(e,t,s=null){let n=Tt(e,t,s);if(!n)return null;let r={...e._yeaftPendingConversationPromotions||{}};return delete r[t],e._yeaftPendingConversationPromotions=r,n}function Zn(e,t,s){let n=Tt(e,t);return!n||!s||n.targetConversationId===s?null:(Mt(e,n.targetConversationId,s,{removeSource:!0}),Qn(e,t,n.targetConversationId,s),Jr(e,t,n.sourceConversationId,s),n)}function Mt(e,t,s,{removeSource:n=!0}={}){if(!t||!s||t===s)return!1;Im(e,t,s),e.yeaftHistoryCacheState&&(e.yeaftHistoryCacheState=Object.fromEntries(Object.entries(e.yeaftHistoryCacheState).map(([c,d])=>[c,d?.conversationId===t?{...d,conversationId:s}:d]))),sn(e.processingConversations,t,s,{removeSource:n}),sn(e.executionStatusMap,t,s,{removeSource:n}),sn(e.refreshingSessionMap,t,s,{removeSource:n}),sn(e._closedAt,t,s,{removeSource:n}),sn(e._autoRefreshed,t,s,{removeSource:n}),sn(e.sessionHealth,t,s,{removeSource:n}),e._turnCompletedConvs?.has(t)&&(e._turnCompletedConvs.add(s),n&&e._turnCompletedConvs.delete(t));let r=!!e._yeaftWatchdogConvs?.has(t),i=e._yeaftWatchdogPauseReasons?.[t],o=!!i?.size,a=!!e._processingWatchdogs?.[t];if(o&&(e._yeaftWatchdogPauseReasons||(e._yeaftWatchdogPauseReasons={}),e._yeaftWatchdogPauseReasons[s]=new Set(i)),n&&(a||o)&&Ce(e,t),n&&e._pongTimeouts?.[t]&&(clearTimeout(e._pongTimeouts[t]),delete e._pongTimeouts[t]),n&&(a||r||o)&&!!e.processingConversations?.[s])if(e._processingWatchdogs?.[s])e._yeaftWatchdogConvs?.add(s);else{let c=Zr(e.sessionHealth,s),d=e.sessionHealth?.[s],u=Zr(e._autoRefreshed,s),p=e._autoRefreshed?.[s];en(e,s),c&&(e.sessionHealth||(e.sessionHealth={}),e.sessionHealth[s]=d),u&&(e._autoRefreshed||(e._autoRefreshed={}),e._autoRefreshed[s]=p)}return n&&e.messagesMap&&delete e.messagesMap[t],!0}var na=O(()=>{Yn();Un();Xr();ss()});function ei(e,t){return!e||!t||e.type!=="user"||t.type!=="user"?!1:e.clientMessageId&&t.clientMessageId?e.clientMessageId===t.clientMessageId:e.clientMessageId||t.clientMessageId?!1:e.content===t.content}var ra=O(()=>{});function ia(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Am(){return Date.now()}function xm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`pt_${crypto.randomUUID()}`:`pt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}function Tm(e,t=160){return typeof e!="string"?e:e.length>t?`${e.slice(0,t)}...[truncated]`:e}function Mm(e){if(!e||typeof e!="object")return e||null;let t={};for(let[s,n]of Object.entries(e))s==="text"||s==="prompt"||s==="content"||s==="data"||(t[s]=typeof n=="string"?Tm(n):n);return t}function Is(){return xm()}function Ze(e,t={}){!e||!t.traceId||(Array.isArray(e._perfTraceQueue)||(e._perfTraceQueue=[]),e._perfTraceQueue.push({traceId:t.traceId,source:"web",phase:t.phase||"unknown",at:Am(),monotonicMs:ia(),durationMs:Number.isFinite(t.durationMs)?t.durationMs:null,agentId:t.agentId||null,sessionId:t.sessionId||null,vpId:t.vpId||null,turnId:t.turnId||null,threadId:t.threadId||null,messageType:t.messageType||null,bytes:Number.isFinite(t.bytes)?t.bytes:null,ok:typeof t.ok=="boolean"?t.ok:null,detail:Mm(t.detail)}),e._perfTraceQueue.length>200&&e._perfTraceQueue.splice(0,e._perfTraceQueue.length-200),Pm(e))}function Pm(e){!e||e._perfTraceFlushTimer||(e._perfTraceFlushTimer=setTimeout(()=>Rm(e),250))}function Rm(e){if(!e||!Array.isArray(e._perfTraceQueue)||e._perfTraceQueue.length===0){e&&(e._perfTraceFlushTimer=null);return}let t=e._perfTraceQueue.splice(0,e._perfTraceQueue.length);e._perfTraceFlushTimer=null,typeof e.sendWsMessage=="function"&&e.sendWsMessage({type:"perf_trace_events",events:t})}function ti(e,t={}){if(typeof requestAnimationFrame!="function")return;let s=ia();requestAnimationFrame(()=>{requestAnimationFrame(()=>{Ze(e,{...t,phase:t.phase||"render.next_paint",durationMs:ia()-s})})})}var oa=O(()=>{});function Pt(e){return Number.isFinite(e)?Number(e):null}function _m(e){return(Array.isArray(e)?e:[]).map(t=>({startSeq:Pt(t?.startSeq),endSeq:Pt(t?.endSeq)})).filter(t=>t.startSeq!==null&&t.endSeq!==null&&t.startSeq<=t.endSeq).sort((t,s)=>t.startSeq-s.startSeq)}function Jn(e){return Number.isFinite(e)&&e>=0?Math.floor(e):0}function Cs(e){let t=Pt(e?.beforeSeq);if(t===null)return null;if(e?.kind==="gap"){let s=Pt(e.stopAtSeq);return s===null?null:`gap:${Jn(e.cacheEpoch)}:${s}:${t}`}return`server:${t}`}function er(e){let t=new Set((Array.isArray(e?.completedHistoryWorkKeys)?e.completedHistoryWorkKeys:[]).filter(s=>typeof s=="string"&&s));for(let s of Array.isArray(e?.requestedBeforeSeqs)?e.requestedBeforeSeqs:[])Number.isFinite(s)&&t.add(`server:${s}`);return t}function Dm(e,t){let s=Cs(t);if(!s)return e.completedHistoryWorkKeys||[];let n=er(e);return n.add(s),Array.from(n).slice(-256)}function Em(e,t){if(!Number.isFinite(t))return e.requestedBeforeSeqs||[];let s=new Set((Array.isArray(e?.requestedBeforeSeqs)?e.requestedBeforeSeqs:[]).filter(Number.isFinite));return s.add(t),Array.from(s).sort((n,r)=>r-n).slice(-256)}function Lm(e,t={},s=0){let n=_m(e),r=Jn(s),i=er(t),o=[];for(let a=1;a<n.length;a+=1){let l=n[a-1],c=n[a];if(l.endSeq+1>=c.startSeq)continue;let d={kind:"gap",beforeSeq:c.startSeq,stopAtSeq:l.endSeq+1,cacheEpoch:r};d.workKey=Cs(d),i.has(d.workKey)||o.push(d)}return o.sort((a,l)=>l.beforeSeq-a.beforeSeq)}function ed(e,t,s){let n=Lm(e,t,s),r=Pt(t.serverOldestFetchedSeq??t.oldestSeq),i=n[0]||null;if(!i||r===null||i.beforeSeq<=r)return[];let o={kind:"gap",beforeSeq:i.beforeSeq,stopAtSeq:r,cacheEpoch:i.cacheEpoch};return o.workKey=Cs(o),er(t).has(o.workKey)?[]:[o]}function td(e={},t=[],s=0){let n=Jn(s),r=er(e),i=e.serverHasMore!==!1,o=Pt(e.serverOldestFetchedSeq??e.oldestSeq),a=e.gapTraversalInitialized===!0,l=Array.isArray(e.gapQueue)?e.gapQueue.slice():[],c=null,d=null;if(i&&o!==null){let u={kind:"server",beforeSeq:o,stopAtSeq:null,cacheEpoch:n};u.workKey=Cs(u),r.has(u.workKey)?(i=!1,d="history_cursor_repeated"):c=u}return!c&&!i&&(a||(l=ed(t,e,n),a=!0),c=l[0]||null),c?{request:c,state:{...e,serverHasMore:i,gapTraversalInitialized:a,gapQueue:l,pendingPageKind:c.kind,pendingPageBeforeSeq:c.beforeSeq,pendingGapStopAtSeq:c.stopAtSeq,pendingCacheEpoch:c.cacheEpoch,pendingHistoryWorkKey:c.workKey,hasMore:!0,paginationError:null}}:{request:null,state:{...e,serverHasMore:i,gapTraversalInitialized:a,gapQueue:l,hasMore:!1,paginationError:d}}}function sd(e={},{mode:t,oldestSeq:s,hasMore:n,ranges:r=[],pageKind:i=null,stopAtSeq:o=null,cacheEpoch:a=0}={}){if(t==="delta")return e;let l=Jn(a),c=Pt(s),d=Pt(e.pendingPageBeforeSeq),u=i||e.pendingPageKind||(t==="older"?"server":null),p=Pt(o??e.pendingGapStopAtSeq),f=Jn(e.pendingCacheEpoch??l),g={kind:u,beforeSeq:d,stopAtSeq:p,cacheEpoch:f},h=Pt(e.serverOldestFetchedSeq??e.oldestSeq),m=e.serverHasMore!==!1,b=Number(e.noProgressCount)||0,y=null,S=e.requestedBeforeSeqs||[],w=e.completedHistoryWorkKeys||[],v=e.gapTraversalInitialized===!0,k=Array.isArray(e.gapQueue)?e.gapQueue.slice():[];if(t==="recent")h=c,m=!!n,b=0,S=[],w=[],v=!1,k=[];else if(d===null)c!==null&&(h=h===null?c:Math.min(h,c)),m=!!n,b=0;else{S=Em(e,d),w=Dm(e,g);let T=c!==null&&c<d;if(u==="server")T?(h=h===null?c:Math.min(h,c),m=!!n,b=0):(m=!1,b+=1,y="history_cursor_no_progress");else if(u==="gap"){let D=Cs(g);k=k.filter(_=>Cs(_)!==D);let L=p!==null&&c!==null&&c<=p;if(T||L||n===!1){if(b=0,!L&&n!==!1&&c!==null&&p!==null){let _={kind:"gap",beforeSeq:c,stopAtSeq:p,cacheEpoch:f};_.workKey=Cs(_),er({completedHistoryWorkKeys:w}).has(_.workKey)||k.unshift(_)}}else b+=1,y="history_cursor_no_progress"}}t==="older"&&!m&&!v&&(k=ed(r,{...e,serverOldestFetchedSeq:h,completedHistoryWorkKeys:w},l),v=!0);let x={...e,serverOldestFetchedSeq:h,serverHasMore:m,requestedBeforeSeqs:S,completedHistoryWorkKeys:w,gapTraversalInitialized:v,gapQueue:k,noProgressCount:b,oldestSeq:h,paginationError:y};return delete x.pendingPageKind,delete x.pendingPageBeforeSeq,delete x.pendingGapStopAtSeq,delete x.pendingCacheEpoch,delete x.pendingHistoryWorkKey,{...x,hasMore:m||k.length>0}}var aa=O(()=>{});function od(e){return e.filter(t=>!(t.type==="user"&&(!t.content||!t.content.trim())))}function As(e){let t=typeof e=="string"?e.match(/^m(\d+)$/):null,s=t?Number(t[1]):null;return Number.isFinite(s)?s:null}function nd(e){let t=[e?.timestamp,e?.createdAt,e?.ts,e?.time,e?.created_at];for(let s of t){if(typeof s=="number"&&Number.isFinite(s)&&s>0)return s;if(typeof s=="string"&&s.trim()){let n=Date.parse(s);if(Number.isFinite(n))return n;let r=Number(s);if(Number.isFinite(r)&&r>0)return r}}return null}function $m(e){if(!Array.isArray(e))return null;for(let t=e.length-1;t>=0;t-=1){let s=e[t];if(s?.name==="TodoWrite"&&Array.isArray(s?.input?.todos))return s.input.todos}return null}function Vm(e){if(!e||typeof window>"u")return null;try{let t=window.Pinia||null,s=t&&typeof t.useSessionsStore=="function"?t.useSessionsStore():null;if(!s)return null;let n=typeof t.useChatStore=="function"?t.useChatStore():null,r=typeof s.sessionById=="function"?s.sessionById(e,n?.currentAgent||null):s.sessions&&s.sessions[e];return(r&&typeof r.defaultVpId=="string"?r.defaultVpId.trim():"")||null}catch{return null}}function Hm(e,t){return e.speakerVpId||e.vpId||e.vp_id||e.authorVpId||e.authorVP||Vm(t)}function Om(e){return e?.stableKey||(e&&(e.messageId||e.id)?e.messageId||e.id:null)}function Fm(e,t=null){if(!e||e.stableKey)return e;let s=ns(e),n=e.messageId||e.id||null,r=e.type==="user"&&e.clientMessageId||null;return e.stableKey=r&&n===r?es(t,s,r):Wn(t,s,n),Number.isFinite(e.seq)||(e.seq=As(n)),e.uiKey||(e.uiKey=e.stableKey||null),e}function ns(e){return e?e.sessionId??e.groupId??null:null}function Bm(e){return!e||e.type!=="user"||!e.clientMessageId?!1:(e.messageId||e.id||null)===e.clientMessageId}function Nm(e,t,s,n){let r=e.rows(t),i=r.some(c=>c&&(n==null||ns(c)===n));if(s.length===0&&i)return{insertedRows:0,preservedEmpty:!0};let o=s.reduce((c,d)=>Math.max(c,d?.timestamp||0),0),a=r.filter(c=>c?n!=null&&ns(c)!==n||je(c)||c.isStreaming||c.type==="tool-use"&&c.toolName==="AskUserQuestion"&&(c.askAnswered||c.askPending||c.askExpired)||Bm(c)?!0:o>0&&(c.timestamp||0)>o:!1);return e.replaceProjection(t,a),{insertedRows:e.commitDurable({conversationId:t,sessionId:n,rows:s,mode:"recent",preserveEmpty:!1}).insertedRows,preservedEmpty:!1}}function qm(e){if(typeof e!="string")return!1;let t=e.trimStart();return t.startsWith("<task-result ")||/^\[system note\] You have called \S+ with the same arguments \d+ times\./.test(t)}function Wm(e,t){let s=typeof e.yeaftConversationId=="string"?e.yeaftConversationId:"";return s.startsWith(`yeaft-local-${t}-`)||/^yeaft-local-\d/.test(s)?s:null}function jm(e,t,s,n){let r=t.agentId||s&&e.yeaftSessionAgentById?.[s]||null;if(!r||!n||e.currentView!=="yeaft")return;let i=kt(e);if(i.sessionId!==(s||null)||i.agentId&&i.agentId!==r)return;let o=e.yeaftConversationId||null;if(tn(e,r,n)){let d=e.yeaftConversationIdsByAgent?.[r]||null;d&&d!==n&&Mt(e,n,d,{removeSource:n!==e.yeaftConversationId});return}let a=Tt(e,r);a&&a.targetConversationId!==n&&Zn(e,r,n);let l=Tt(e,r,n);if(l&&(Mt(e,l.sourceConversationId,n,{removeSource:!0}),Xn(e,r,n),e.yeaftConversationId=n),o===n||l){e.messagesMap[n]||(e.messagesMap[n]=[]),e.yeaftConversationIdsByAgent={...e.yeaftConversationIdsByAgent||{},[r]:n},e.activeConversations=[n];return}let c=Wm(e,r);c&&(Mt(e,c,n,{removeSource:!0}),e.yeaftConversationIdsByAgent={...e.yeaftConversationIdsByAgent||{},[r]:n},e.yeaftConversationId=n,e.activeConversations=[n])}function rs(e,t){let s=e.messagesMap[t]||[];for(let n of s)n.type==="tool-use"&&!n.hasResult&&(n.hasResult=!0,n.toolName==="AskUserQuestion"&&!n.askAnswered&&!n.selectedAnswers&&(n.isHistory=!0,n.askRequestId=null))}function ad(e,t){At(e);let s=e.agents.find(r=>r.id===t.agentId);e.conversations=e.conversations.filter(r=>r.id!==t.conversationId);let n=t.provider||"claude-code";if(e.conversations.push({id:t.conversationId,agentId:t.agentId,agentName:s?.name||t.agentId,workDir:t.workDir,claudeSessionId:null,createdAt:Date.now(),processing:!1,connecting:n!=="claude-code",type:"chat",provider:n,capabilities:t.capabilities||null,disallowedTools:t.disallowedTools??null}),e.currentAgent=t.agentId,e.currentAgentInfo=s,e.panels.length>1){let r=e._pendingPaneId;if(e._pendingPaneId=null,r){let i=e.panels.find(o=>o.id===r);i&&(i.conversationId=t.conversationId)}else{let i=e.panels.find(o=>!o.conversationId);i&&(i.conversationId=t.conversationId)}e.activeConversations.includes(t.conversationId)||e.activeConversations.push(t.conversationId)}else e.activeConversations=[t.conversationId];e.currentWorkDir=t.workDir,e.messagesMap[t.conversationId]=[],e.sendWsMessage({type:"select_conversation",conversationId:t.conversationId}),e.addMessage({type:"system",content:_e("store.convCreated",{agent:s?.name||t.agentId,workDir:t.workDir})}),e.saveOpenSessions()}function ld(e,t){At(e);let s=e.agents.find(n=>n.id===t.agentId);if(e.conversations=e.conversations.filter(n=>n.id!==t.conversationId&&!(n.claudeSessionId&&n.claudeSessionId===t.claudeSessionId)),e.conversations.push({id:t.conversationId,agentId:t.agentId,agentName:s?.name||t.agentId,workDir:t.workDir,claudeSessionId:t.claudeSessionId,createdAt:Date.now(),processing:!1,connecting:(t.provider||"claude-code")!=="claude-code",type:"chat",provider:t.provider||"claude-code",capabilities:t.capabilities||null,disallowedTools:t.disallowedTools??null}),e.currentAgent=t.agentId,e.currentAgentInfo=s,e.panels.length>1){let n=e._pendingPaneId;if(e._pendingPaneId=null,n){let r=e.panels.find(i=>i.id===n);r&&(r.conversationId=t.conversationId)}else{let r=e.panels.find(i=>!i.conversationId);r&&(r.conversationId=t.conversationId)}e.activeConversations.includes(t.conversationId)||e.activeConversations.push(t.conversationId)}else e.activeConversations=[t.conversationId];if(e.currentWorkDir=t.workDir,e.messagesMap[t.conversationId]=[],e._pendingSessionTitle&&(e.conversationTitles[t.conversationId]=e._pendingSessionTitle,e._pendingSessionTitle=null),e.sendWsMessage({type:"select_conversation",conversationId:t.conversationId}),e.addMessage({type:"system",content:_e("store.convResumed",{agent:s?.name||t.agentId,sessionId:t.claudeSessionId?t.claudeSessionId.slice(0,8)+"...":""})}),t.dbMessages&&t.dbMessages.length>0){let n=od(t.dbMessages.map(i=>e.formatDbMessage(i)).flat().filter(Boolean)),r=e.messagesMap[t.conversationId]||[];for(let i of n)r.push(i)}e.hasMoreMessages=!!t.hasMoreMessages,e.chatSessionState[t.conversationId]={lastSeenDbId:ks(e.messagesMap[t.conversationId]),hasMoreOlder:!!t.hasMoreMessages},e.saveOpenSessions()}function la(e,t){e.conversations=e.conversations.filter(n=>n.id!==t.conversationId),delete e.messagesMap[t.conversationId],delete e.chatSessionState[t.conversationId],delete e.conversationTitles[t.conversationId],delete e.customConversationTitles[t.conversationId],delete e.processingConversations[t.conversationId],e._closedAt&&delete e._closedAt[t.conversationId],Ce(e,t.conversationId),delete e.executionStatusMap[t.conversationId],delete e.subagents[t.conversationId],window.dispatchEvent(new CustomEvent("conversation-deleted",{detail:{conversationId:t.conversationId}}));let s=e.activeConversations.indexOf(t.conversationId);s>=0&&(e.activeConversations.splice(s,1),e.activeConversations.length===0&&e.addMessage({type:"system",content:_e("chat.session.closed")}));for(let n of e.panels)n.conversationId===t.conversationId&&(n.conversationId=null);e.saveOpenSessions()}function cd(e,t){let s=t.conversationId;if(s){delete e.processingConversations[s],Ce(e,s),e._closedAt||(e._closedAt={}),e._closedAt[s]=Date.now(),e._turnCompletedConvs||(e._turnCompletedConvs=new Set),e._turnCompletedConvs.add(s);let n=e.executionStatusMap[s];n&&(n.currentTool=null),e.finishStreamingForConversation(s),rs(e,s);let r=e.conversations.find(i=>i.id===s);r&&(t.claudeSessionId&&(r.claudeSessionId=t.claudeSessionId),t.workDir&&(r.workDir=t.workDir)),e.clearStatus?.conversationId===s&&e.clearStatus?.status==="clearing"&&(e.clearStatus={conversationId:s,status:"completed"},setTimeout(()=>{e.clearStatus?.conversationId===s&&e.clearStatus?.status==="completed"&&(e.clearStatus=null)},3e3)),e.saveOpenSessions()}}function dd(e,t){let s=t.conversationId;if(s){delete e.processingConversations[s],Ce(e,s),e._closedAt||(e._closedAt={}),e._closedAt[s]=Date.now(),e._turnCompletedConvs||(e._turnCompletedConvs=new Set),e._turnCompletedConvs.add(s);let n=e.executionStatusMap[s];n&&(n.currentTool=null),e.finishStreamingForConversation(s),rs(e,s);let r=e.conversations.find(i=>i.id===s);r&&(t.claudeSessionId&&(r.claudeSessionId=t.claudeSessionId),t.workDir&&(r.workDir=t.workDir)),e.saveOpenSessions()}}function ud(e,t){if(t.conversationId){if(t.isProcessing&&!Ss(e,t.conversationId)&&!e._turnCompletedConvs?.has(t.conversationId))e.processingConversations[t.conversationId]=!0;else if(e.processingConversations[t.conversationId]){delete e.processingConversations[t.conversationId],Ce(e,t.conversationId);let s=e.executionStatusMap[t.conversationId];s&&(s.currentTool=null),e.finishStreamingForConversation(t.conversationId)}}}function pd(e,t){let s=t.conversationId||e.currentConversation;if(s){delete e.processingConversations[s],Ce(e,s),e._closedAt||(e._closedAt={}),e._closedAt[s]=Date.now(),e._turnCompletedConvs||(e._turnCompletedConvs=new Set),e._turnCompletedConvs.add(s);let n=e.executionStatusMap[s];n&&(n.currentTool=null),e.finishStreamingForConversation(s),rs(e,s)}}function fd(e,t){if(!!t.requestId){if(e.chatHistoryRequestIdSupported=!0,!e.isCurrentChatHistoryResponse?.(t))return!1}else{let i=`chat:${t.conversationId}`,o=e.chatHistoryRequests?.[i];if(e.chatHistoryRequestIdSupported===!0||!o?.loading)return!1;t={...t,requestId:o.requestId,catalogKey:i,mode:o.mode||t.mode,...o.mode==="delta"?{afterMessageId:o.cursor}:{}}}e.messagesMap[t.conversationId]||(e.messagesMap[t.conversationId]=[]);let n=e.messagesMap[t.conversationId],r=t.mode==="delta"||typeof t.afterMessageId=="number"&&t.afterMessageId>0;if(t.conversationId&&e.activeConversations.includes(t.conversationId)){let i=od((t.messages||[]).map(a=>e.formatDbMessage(a)).flat().filter(Boolean));if(i.length>0){let a=n.find(l=>l.dbMessageId);if(a&&i[0].dbMessageId&&i[i.length-1].dbMessageId<a.dbMessageId){let l=n.indexOf(a);e.debug,n.splice(l,0,...i)}else{e.debug;for(let l of i)if(!(l.dbMessageId&&n.some(c=>c.dbMessageId===l.dbMessageId))){if(l.dbMessageId&&(l.type==="assistant"||l.type==="user")){let c=null;if(l.type==="user"?c=n.find(d=>!d.dbMessageId&&!d.isStreaming&&ei(d,l)):c=n.find(d=>!d.dbMessageId&&!d.isStreaming&&d.type==="assistant"&&d.content===l.content),c){c.dbMessageId=l.dbMessageId,c.id=l.id,l.timestamp&&(c.timestamp=l.timestamp),l.clientMessageId&&!c.clientMessageId&&(c.clientMessageId=l.clientMessageId);continue}}n.push(l)}}}r||(e.hasMoreMessages=t.hasMore??!1),At(e);let o=e.chatSessionState[t.conversationId]?.hasMoreOlder;e.chatSessionState[t.conversationId]={lastSeenDbId:ks(e.messagesMap[t.conversationId]),hasMoreOlder:r?!!o:!!t.hasMore}}return e.finishChatHistoryRequest?.(t)&&(e.currentConversation===t.conversationId&&(e.loadingMoreMessages=!1),e.setRefreshingSession(t.conversationId,!1)),!0}function gd(e,t){let s=t.sessionId??null,n=t.agentId||s&&e.yeaftSessionAgentById?.[s]||null,r=t.conversationId||n&&e.yeaftConversationIdsByAgent?.[n]||e.yeaftConversationId;if(!r||!s||!Array.isArray(t.messages))return null;e.messagesMap[r]||(e.messagesMap[r]=[]);let i=new Set(Array.isArray(t.sourceMessageIds)?t.sourceMessageIds:[]),o=new Set,a=new Set;for(let b of e.messagesMap[r]){if(ns(b)!==s)continue;let y=b?.persistedMessageId||b?.messageId||b?.id||null;y&&o.add(y),y&&(b?._historyWindowPrefetched===!0||b?._historyWindowDetached===!0)&&a.add(y),!(!t.entryId||!i.has(y))&&(b.historyEntryId=t.entryId,Number.isFinite(t.indexGeneration)&&(b.historyIndexGeneration=t.indexGeneration))}let l=t.messages.filter(b=>t.prefetch===!0||!o.has(b?.id)||a.has(b?.id)).map(b=>t.entryId&&i.has(b?.id)?{...b,historyEntryId:t.entryId,...t.prefetch===!0?{_historyWindowPrefetched:!0}:{},...Number.isFinite(t.indexGeneration)?{historyIndexGeneration:t.indexGeneration}:{}}:b),{formatted:c}=hd(l,s,"window",e.messagesMap[r],n),d=`history-window:${t.requestId||t.anchorMessageId||Date.now()}`;for(let b of c)b._historyWindowKey=d,b._historyWindowDetached=t.prefetch!==!0,b._historyWindowPrefetched=t.prefetch===!0;let u=xt(e),p=u.rows(r),f=new Set(t.messages.map(b=>b?.id).filter(Boolean)),g=[];if(t.prefetch!==!0){for(let y of p){if(ns(y)!==s)continue;let S=y?.persistedMessageId||y?.messageId||y?.id||null;f.has(S)&&(y._historyWindowPrefetched!==!0&&y._historyWindowDetached!==!0||(y._historyWindowKey=d,y._historyWindowDetached=!0,y._historyWindowPrefetched=!1,g.push(y)))}let b=p.filter(y=>ns(y)!==s||y._historyWindowDetached!==!0||y._historyWindowKey===d);b.length!==p.length&&u.replaceProjection(r,b)}u.commitDurable({conversationId:r,sessionId:s,rows:c,mode:"window"});let h=c.length>0?c:g,m=kt(e);return zo(e,{conversationId:r,agentId:n,sessionId:s,incomingRows:h,activeAgentId:m.agentId,activeSessionId:m.sessionId}),r}function rd(e){return e?.toolId?[ns(e)??"",e.vpId||e.speakerVpId||"",e.turnId||"",e.threadId||"main",e.toolId].join("\0"):null}function id(e,t,s){return e.toolName="AskUserQuestion",e.toolId=t.toolCallId,e.toolInput={questions:s},e.askQuestions=s,e.askRequestId=null,e.askPending=!1,e.pendingAnswers=null,e.askSubmitGeneration=null,e.hasResult=!0,e.isHistory=!0,t.status==="answered"?(e.askAnswered=!0,e.selectedAnswers=t.answers,e.askExpired=!1):(e.askAnswered=!1,e.selectedAnswers=null,e.askExpired=!0),e}function Um(e,t){return(e||[]).find(s=>s?.type==="tool-use"&&(s.toolName==="AskUser"||s.toolName==="AskUserQuestion")&&s.toolId===t.toolCallId&&ns(s)===t.sessionId&&(s.vpId||s.speakerVpId||"")===(t.vpId||"")&&(s.turnId||"")===(t.turnId||"")&&(s.threadId||"main")===(t.threadId||"main"))||null}function hd(e,t,s,n,r=null){let i=new Set((n||[]).map(c=>Om(Fm(c,r))).filter(Boolean)),o=new Set,a=[],l=0;for(let c of e){if(!c||c._reflection||c.internal||c.systemOnly||c.systemOnlyMessage||qm(c.content))continue;let d=c.id||c.messageId||null,u=c.clientMessageId||null,p=c.sessionId??c.groupId??t??null,f=Wn(r,p,d),g=u?es(r,p,u):f,h=c.historyEntryId?{historyEntryId:c.historyEntryId,...Number.isFinite(c.historyIndexGeneration)?{historyIndexGeneration:c.historyIndexGeneration}:{}}:{};if(!(f&&o.has(f))&&!(f&&s!=="recent"&&i.has(f))){if(f&&o.add(f),c.role==="user"){l+=1;let m=d||c.messageId||c.turnId||null;a.push({...d?{id:d,messageId:d}:{},...f?{stableKey:f}:{},...g?{uiKey:g}:{},...h,seq:Number.isFinite(c.seq)?c.seq:As(d),type:"user",content:c.content,timestamp:nd(c),sessionId:p,turnId:c.turnId||m,...u?{clientMessageId:u}:{},...Array.isArray(c.attachments)&&c.attachments.length>0?{attachments:c.attachments}:{},...c.quote?{quote:c.quote}:{},isStreaming:!1,isHistory:!0})}else if(c.role==="assistant"){l+=1;let m=d||c.messageId||c.turnId||null,b=Hm(c,p),y=nd(c),S=!!c.turnId,w=c.turnId||m,v=typeof c.content=="string"?c.content:c.content||"",k=Array.isArray(c.todos)?c.todos:$m(c.toolCalls),x=c.executionOrigin==="route_forward"?{executionOrigin:"route_forward"}:{};(typeof v!="string"||v.trim())&&a.push({...d?{id:d,messageId:d}:{},...f?{stableKey:f}:{},...g?{uiKey:g}:{},...h,seq:Number.isFinite(c.seq)?c.seq:As(d),...c.entryId?{entryId:c.entryId}:{},...Array.isArray(c.sourceMessageIds)?{sourceMessageIds:c.sourceMessageIds}:{},type:"assistant",content:v,timestamp:y,sessionId:p,turnId:w,_hasPersistedTurnId:S,...x,...b?{vpId:b,speakerVpId:b}:{},...c.responseKind==="progress"||c.responseKind==="result"?{responseKind:c.responseKind}:{},...c.incomplete===!0?{incomplete:!0}:{},...typeof c.stopReason=="string"&&c.stopReason?{stopReason:c.stopReason}:{},isStreaming:!1,isHistory:!0}),Array.isArray(k)&&k.length>0&&a.push({...d?{id:`${d}:todos`,messageId:`${d}:todos`}:{},...f?{stableKey:`${f}:todos`}:{},...h,seq:Number.isFinite(c.seq)?c.seq:As(d),type:"tool-use",toolName:"TodoWrite",toolInput:{todos:k},timestamp:y,startTime:y||0,sessionId:p,turnId:w,...x,...b?{vpId:b,speakerVpId:b}:{},isStreaming:!1,isHistory:!0,hasResult:!0});for(let[T,D]of(Array.isArray(c.toolCalls)?c.toolCalls:[]).entries()){if(!D||D.name==="TodoWrite")continue;let L=D.id||`index:${T}`,_=encodeURIComponent(String(L));a.push({...d?{id:`${d}:tool:${_}`,messageId:`${d}:tool:${_}`,persistedMessageId:d}:{},...f?{stableKey:`${f}:tool:${_}`}:{},...h,seq:Number.isFinite(c.seq)?c.seq:As(d),type:"tool-use",toolId:D.id||null,toolName:D.name||"unknown",toolInput:D.input||{},timestamp:y,startTime:y||0,sessionId:p,turnId:w,...x,...b?{vpId:b,speakerVpId:b}:{},isStreaming:!1,isHistory:!0,hasResult:!0})}for(let T of Array.isArray(c.images)?c.images:[])T?.assetId&&a.push({id:`${d||m||w}:image:${T.assetId}`,messageId:`${d||m||w}:image:${T.assetId}`,...f?{stableKey:`${f}:image:${T.assetId}`}:{},...h,seq:Number.isFinite(c.seq)?c.seq:As(d),type:"chat-image",...T,timestamp:y,sessionId:p,turnId:w,...x,...b?{vpId:b,speakerVpId:b}:{},isStreaming:!1,isHistory:!0});for(let T of Array.isArray(c.askUserResults)?c.askUserResults:[]){if(!T?.toolCallId||T.status!=="answered"&&T.status!=="expired")continue;let D=[{question:typeof T.question=="string"?T.question:"",options:(Array.isArray(T.options)?T.options:[]).filter(R=>typeof R=="string").map(R=>({label:R,description:""})),multiSelect:!1}],L={toolCallId:T.toolCallId,sessionId:p,vpId:b||"",turnId:w||"",threadId:c.threadId||"main"},_=Um(n,L);if(_){Object.assign(_,h),id(_,T,D);let R=a.findIndex(N=>N?.type==="tool-use"&&N.toolId===T.toolCallId&&(N.sessionId??N.groupId??null)===(_.sessionId??_.groupId??null)&&(N.turnId||"")===(_.turnId||""));R>=0&&a.splice(R,1);continue}let E=id({id:`${d||m||w}:ask:${T.toolCallId}`,messageId:`${d||m||w}:ask:${T.toolCallId}`,...f?{stableKey:`${f}:ask:${T.toolCallId}`}:{},...h,seq:Number.isFinite(c.seq)?c.seq:As(d),type:"tool-use",timestamp:y,sessionId:p,turnId:w,threadId:L.threadId,...x,...b?{vpId:b,speakerVpId:b}:{},isStreaming:!1},T,D),M=rd(E);(!M||!a.some(R=>rd(R)===M))&&a.push(E);let A=a.findIndex(R=>R!==E&&R?.type==="tool-use"&&R.toolId===T.toolCallId&&(R.sessionId??R.groupId??null)===(E.sessionId??E.groupId??null)&&(R.turnId||"")===(E.turnId||""));A>=0&&a.splice(A,1)}}}}return{formatted:a,acceptedHistoryMessages:l}}function md(e,t){let s=t.sessionId!=null?t.sessionId:t.groupId,n=t.agentId||s&&e.yeaftSessionAgentById?.[s]||null;if(tn(e,n,t.conversationId)){let j=e.yeaftConversationIdsByAgent?.[n]||null;if(!j||j===t.conversationId)return;Mt(e,t.conversationId,j,{removeSource:t.conversationId!==e.yeaftConversationId}),t={...t,conversationId:j}}if(t.requestId&&typeof e.isCurrentYeaftHistoryResponse=="function"&&!e.isCurrentYeaftHistoryResponse(t))return;let r=t.mode==="recent"||t.mode==="delta"?t.mode:"older",i=Array.isArray(t.messages)?t.messages:[],o=t.agentId||s&&e.yeaftSessionAgentById?.[s]||null,a=ye(o,s),l=e.yeaftSessionHistoryState?.[a]||null;typeof t.streamId=="string"&&typeof l?.streamId=="string"&&(t.streamId!==l.streamId||Number.isFinite(t.revision)&&Number.isFinite(l.revision)&&t.revision!==l.revision)&&(r="recent",typeof e.clearYeaftHistoryMemory=="function"&&e.clearYeaftHistoryMemory({agentId:o,sessionId:s,preserveLiveRows:!0,preserveSessionOwner:!0})),t.perfTraceId&&Ze(e,{traceId:t.perfTraceId,phase:"history.chunk_received",agentId:t.agentId||null,sessionId:s||null,messageType:t.type,bytes:(()=>{try{return JSON.stringify(t).length}catch{return null}})(),detail:{mode:r,rawCount:i.length}});let d=t.agentId||(s&&e.yeaftSessionAgentById?e.yeaftSessionAgentById[s]:null),u=d&&e.yeaftConversationIdsByAgent?e.yeaftConversationIdsByAgent[d]:null,p=t.conversationId||u||e.yeaftConversationId;if(!p){e.yeaftLoadingMoreHistory=!1;return}jm(e,t,s,p),e.messagesMap[p]||(e.messagesMap[p]=[]);let{formatted:f,acceptedHistoryMessages:g}=hd(i,s,r,e.messagesMap[p],d);zn(e,p,f);let h=xt(e),m=0,b=!1;if(r==="recent"){let j=Nm(h,p,f,s??null);m=j.insertedRows,b=j.preservedEmpty}else if(f.length>0&&(m=h.commitDurable({conversationId:p,sessionId:s??null,rows:f,mode:r}).insertedRows,r==="older"&&typeof e.expandYeaftMessageWindow=="function")){let te=e.yeaftActiveSessionFilter?s??null:null;e.expandYeaftMessageWindow(te,t.turns||10,d)}let y=kt(e);zo(e,{conversationId:p,agentId:d,sessionId:s,incomingRows:f,activeAgentId:y.agentId,activeSessionId:y.sessionId});let S=ye(t.agentId||null,s),w=e.yeaftHistoryCacheState?.[S]||null,v=e.yeaftSessionHistoryState?.[S]||{},k=Number.isFinite(v.serverOldestFetchedSeq)?v.serverOldestFetchedSeq:Number.isFinite(v.oldestSeq)?v.oldestSeq:null,x=Number.isFinite(t.nextBeforeSeq)?t.nextBeforeSeq:Number.isFinite(t.oldestSeq)?t.oldestSeq:b?k:null,T=b&&!Number.isFinite(t.nextBeforeSeq)&&!Number.isFinite(t.oldestSeq)?v.serverHasMore??v.hasMore??!1:t.hasMore,D=r==="delta"?v:sd(v,{mode:r,oldestSeq:x,hasMore:T,ranges:w?.ranges||[],pageKind:t.pageKind,stopAtSeq:t.gapStopAtSeq,cacheEpoch:w?.rangeEpoch??t.cacheEpoch??0}),L=typeof t.latestSeq=="number"?t.latestSeq:v.latestSeq??null,_={streamId:typeof t.streamId=="string"?t.streamId:v.streamId??null,revision:Number.isFinite(t.revision)?t.revision:v.revision??null},E=r==="delta"?{...v,..._,loaded:!0,loading:!1,latestSeq:L,syncingAfterSeq:null,count:(v.count||0)+m}:{...D,..._,loaded:!0,loading:!1,count:w?w.rowCount:r==="older"?(v.count||0)+m:b?v.count||0:g,latestSeq:b&&!Number.isFinite(t.latestSeq)?v.latestSeq??null:L,syncingAfterSeq:null};t.requestId&&typeof e.finishYeaftHistoryLoad=="function"?e.finishYeaftHistoryLoad(t,E,"chunk"):e.yeaftSessionHistoryState&&(e.yeaftSessionHistoryState={...e.yeaftSessionHistoryState,[S]:E}),r==="delta"&&t.hasMoreAfter===!0&&Number.isFinite(E.latestSeq)&&E.latestSeq>Number(t.afterSeq??-1)&&typeof e.continueYeaftHistoryDelta=="function"&&queueMicrotask(()=>e.continueYeaftHistoryDelta(s,d,E.latestSeq));let M=kt(e),A=M.sessionId===(s||null),R=!t.agentId||!M.agentId||t.agentId===M.agentId,N=A&&R,F=ye(null,M.sessionId);if(t.perfTraceId&&(Ze(e,{traceId:t.perfTraceId,phase:"history.chunk_applied",agentId:t.agentId||null,sessionId:s||null,messageType:t.type,detail:{mode:r,formattedCount:f.length,insertedRows:m,acceptedHistoryMessages:g,preservedEmptyRecent:b}}),ti(e,{traceId:t.perfTraceId,phase:"history.next_paint",agentId:t.agentId||null,sessionId:s||null,messageType:t.type,detail:{mode:r,insertedRows:m}})),N)e.yeaftHasMoreHistory=E.hasMore,e.yeaftOldestLoadedSeq=Number.isFinite(E.serverOldestFetchedSeq)?E.serverOldestFetchedSeq:Number.isFinite(E.oldestSeq)?E.oldestSeq:e.yeaftOldestLoadedSeq,e.yeaftLoadingMoreHistory=!1;else if(e.yeaftLoadingMoreHistory){let j=e.yeaftSessionHistoryState?.[M.sessionKey]||e.yeaftSessionHistoryState?.[F]||null;e.yeaftLoadingMoreHistory=!!j?.loading}}var si=O(()=>{ss();na();Xr();bs();ra();Yn();Bt();oa();Ur();Gs();Kr();aa();Un()});function vd(e,t,s=null){if(!s)return!1;if(e.promoteYeaftHistoryOutlineRow?.(t,s))return!0;let n=t?.sessionId??t?.groupId??e._currentYeaftSessionId??null;return n?!!e.invalidateYeaftHistoryOutline?.(n,s):!1}function Km(e){let t=e;if(typeof t=="string"){let s=t.trim();if(s.startsWith("[")&&s.endsWith("]")||s.startsWith("{")&&s.endsWith("}"))try{t=JSON.parse(s)}catch{t=e}}return Array.isArray(t)?t.map(s=>typeof s=="string"?s:!s||typeof s!="object"?"":s.type==="text"&&typeof s.text=="string"||s.type==="input_text"&&typeof s.text=="string"?s.text:"").join("").replace(/\n\n\[Uploaded files\][\s\S]*$/m,"").trim():t&&typeof t=="object"?typeof t.text=="string"?t.text.trim():typeof t.content=="string"?t.content.trim():"":typeof t=="string"?t.replace(/\n\n\[Uploaded files\][\s\S]*$/m,"").trim():""}function ca(e,t){return e.executionStatusMap[t]||(e.executionStatusMap[t]={currentTool:null,toolHistory:[],lastActivity:null}),e.executionStatusMap[t]}function yd(e,t,s,n=null){if(!t)return;let r=ca(e,t);if(r.lastActivity=Date.now(),Qr(e,t),s.type==="system"){if(s.subtype==="init"){let i=e.conversations.find(o=>o.id===t);i&&i.connecting&&(i.connecting=!1);return}s.message&&e.addMessageToConversation(t,{type:"system",content:typeof s.message=="string"?s.message:JSON.stringify(s.message,null,2)});return}if(s.type==="assistant"){let i=s.message?.content;if(!i)return;let o=e.messagesMap[t]||[];for(let a of o)a.type==="tool-use"&&!a.hasResult&&(a.hasResult=!0);for(let a of r.toolHistory)a.status==="running"&&(a.status="done");if(r.currentTool=null,typeof i=="string"){e.appendToAssistantMessageForConversation(t,i,{id:s.message?.id||s.message?.messageId||null,ts:s.ts||s.message?.ts||s.message?.time||null,sessionId:e._currentYeaftSessionId||null,vpId:e._currentYeaftVpId||null,turnId:e._currentYeaftTurnId||null,threadId:e._currentYeaftThreadId||null});return}if(!Array.isArray(i))return;if(i.length===0){e.finishStreamingForConversation(t);return}for(let a of i)a.type==="text"?e.appendToAssistantMessageForConversation(t,a.text,{id:s.message?.id||s.message?.messageId||null,ts:s.ts||s.message?.ts||s.message?.time||null,sessionId:e._currentYeaftSessionId||null,vpId:e._currentYeaftVpId||null,turnId:e._currentYeaftTurnId||null,threadId:e._currentYeaftThreadId||null}):a.type==="image_asset"&&a.image?e.addMessageToConversation(t,{type:"chat-image",...a.image,sessionId:e._currentYeaftSessionId||null,vpId:e._currentYeaftVpId||null,speakerVpId:e._currentYeaftVpId||null,turnId:e._currentYeaftTurnId||null,threadId:e._currentYeaftThreadId||null}):a.type==="tool_use"&&(e.finishStreamingForConversation(t,{completeLifecycle:!1}),r.currentTool={name:a.name,input:a.input,startTime:Date.now()},r.toolHistory.unshift({name:a.name,input:a.input,timestamp:Date.now(),status:"running"}),r.toolHistory.length>20&&r.toolHistory.pop(),e.addMessageToConversation(t,{type:"tool-use",toolId:a.id||a.tool_use_id||null,toolName:a.name,toolInput:a.input,startTime:Date.now(),isHistory:a.history===!0||s.history===!0||s.isHistory===!0,sessionId:e._currentYeaftSessionId||null,vpId:e._currentYeaftVpId||null,turnId:e._currentYeaftTurnId||null,threadId:e._currentYeaftThreadId||null}))}else if(s.type==="user"){let i=s.internal===!0||s.message?.internal===!0||s.userAuthored===!1||s.message?.userAuthored===!1,o=s.message?.content,a=Km(o);if(typeof a=="string"&&(a.includes("<local-command-caveat>")||a.includes("<command-name>")))return;if(typeof a=="string"&&a.includes("<local-command-stdout>")){let c=a.match(/<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/);if(c){e.appendToAssistantMessageForConversation(t,c[1].trim()),e.finishStreamingForConversation(t);return}}let l=[];if(s.tool_use_result)l=Array.isArray(s.tool_use_result)?s.tool_use_result:[s.tool_use_result];else if(s.message?.content){let c=s.message.content;l=(Array.isArray(c)?c:[]).filter(u=>u.type==="tool_result")}if(l.length>0){let c=e.messagesMap[t]||[];for(let d of l){if(r.toolHistory.length>0){let g=r.toolHistory.findIndex(h=>h.status==="running");g>=0&&(r.toolHistory[g].status="done")}let u=d.tool_use_id||d.toolUseId||d.tool_call_id||d.toolCallId||null,p=d.content||d,f=!1;if(u){for(let g=c.length-1;g>=0;g--)if(c[g].type==="tool-use"&&c[g].toolId===u){c[g].hasResult=!0,c[g].toolResult=d.is_update&&c[g].toolResult?`${c[g].toolResult}
2
2
 
3
3
  ${p}`:p,f=!0;break}}if(!f){for(let g=c.length-1;g>=0;g--)if(c[g].type==="tool-use"&&!c[g].hasResult){c[g].hasResult=!0,c[g].toolResult=p;break}}}r.currentTool=null}else if(!i&&(typeof a=="string"&&a.trim()||Array.isArray(s.message?.attachments)&&s.message.attachments.length>0)){let c=s.message?.clientMessageId||s.clientMessageId||null,d={type:"user",content:a,clientMessageId:c},u=e.messagesMap[t]||[];if(u.some(f=>ei(f,d))){if(c){for(let f=u.length-1;f>=0;f--)if(u[f].type==="user"&&u[f].clientMessageId===c){s.dbMessageId&&!u[f].dbMessageId&&(u[f].dbMessageId=s.dbMessageId),s.message?.id&&!u[f].messageId&&(u[f].id=s.message.id,u[f].messageId=s.message.id),s.ts&&!u[f].ts&&(u[f].ts=s.ts),vd(e,u[f],n);break}}}else{let f=e.addMessageToConversation(t,{...s.message?.id?{id:s.message.id,messageId:s.message.id}:{},...s.ts?{ts:s.ts}:{},type:"user",content:a,...s.message?.attachments?{attachments:s.message.attachments}:{},...s.message?.quote?{quote:s.message.quote}:{},...c?{clientMessageId:c}:{}});vd(e,f,n)}}}else if(s.type==="result"){delete e.processingConversations[t],Ce(e,t);let i=e.conversations.find(d=>d.id===t);i&&i.connecting&&(i.connecting=!1);let o=e._currentYeaftSessionId||null;if(e._currentYeaftTurnId){let d=Object.entries(e.activeVpTurns||{}).find(([,u])=>(u?.turnId===e._currentYeaftTurnId||!u?.turnId&&u===e.activeVpTurns[e._currentYeaftTurnId])&&(!e._currentYeaftAgentId||!u?.agentId||u.agentId===e._currentYeaftAgentId));if(d){let[u,p]=d,{[u]:f,...g}=e.activeVpTurns;!o&&p?.sessionId&&(o=p.sessionId),e.activeVpTurns=g}}if(o&&e._currentYeaftVpId&&e.vpStatuses){let d=e._currentYeaftTurnId||null,u={...e.vpStatuses||{}},p=!1;for(let[f,g]of Object.entries(u))!g||g.vpId!==e._currentYeaftVpId||e._currentYeaftAgentId&&g.agentId&&g.agentId!==e._currentYeaftAgentId||(g.sessionId||g.groupId||null)!==o||d&&g.turnId&&g.turnId!==d||(u[f]={...g,state:"idle",turnId:null,since:Date.now()},p=!0);p&&(e.vpStatuses=u)}o&&typeof e.clearYeaftSessionProcessingIfIdle=="function"&&e.clearYeaftSessionProcessingIfIdle(o,{agentId:e._currentYeaftAgentId||null}),e._closedAt||(e._closedAt={}),e._closedAt[t]=Date.now(),e._turnCompletedConvs||(e._turnCompletedConvs=new Set),e._turnCompletedConvs.add(t),r.currentTool=null,rs(e,t);let a=e.messagesMap[t]||[],l=s.result_text||"";if(typeof l=="string"&&l.trim()){let d=!1;for(let u=a.length-1;u>=0;u--){if(a[u].type==="assistant"){d=!0;break}if(a[u].type==="user")break}d||e.appendToAssistantMessageForConversation(t,l.trim())}e.finishStreamingForConversation(t),!(n&&e.promoteCompletedYeaftHistoryOutline?.(t,e._currentYeaftTurnId||null,n))&&o&&n&&e.invalidateYeaftHistoryOutline?.(o,n),e.sweepStaleStreamingForConversation(t),o&&n&&e.pruneConversationMessageRetention?.(t,o,n)}}var bd=O(()=>{ss();si();ra()});function xs(e){if(e==null)return e;try{return JSON.parse(JSON.stringify(e))}catch{return e}}function ni(e,t){if(!t)return e??null;if(Object.prototype.hasOwnProperty.call(t,"base"))return xs(t.base)??null;if(Object.prototype.hasOwnProperty.call(t,"replacement"))return xs(t.replacement)??null;let s=e&&typeof e=="object"&&!Array.isArray(e)?xs(e):{};if(t.set&&typeof t.set=="object")for(let[n,r]of Object.entries(t.set))s[n]=xs(r);if(t.body&&typeof t.body=="object"){let n=s.body&&typeof s.body=="object"&&!Array.isArray(s.body)?{...s.body}:{};for(let[i,o]of Object.entries(t.body))i==="messages"||i==="messagesFrom"||i==="messagesAppend"||i==="messagesKey"||(n[i]=xs(o));let r=t.body.messagesKey==="messages"||t.body.messagesKey==="input"?t.body.messagesKey:Array.isArray(n.messages)||Object.prototype.hasOwnProperty.call(t.body,"messages")?"messages":"input";if(Array.isArray(t.body.messages))n[r]=xs(t.body.messages)||[];else if(Array.isArray(t.body.messagesAppend)){let i=Array.isArray(n[r])?n[r]:[],o=Number.isFinite(Number(t.body.messagesFrom))?Number(t.body.messagesFrom):i.length;n[r]=i.slice(0,o).concat(xs(t.body.messagesAppend)||[])}s.body=n}return s}function wd(e,t){return!t||!Object.prototype.hasOwnProperty.call(t,"rawRequestDelta")?e??null:ni(e??null,t.rawRequestDelta)}function tr(e){if(!e)return 0;let t=typeof e=="string"?e:String(e),s=0,n=0;for(let r of t){let i=r.codePointAt(0)||0;i>=19968&&i<=40959||i>=12352&&i<=12447||i>=12448&&i<=12543||i>=44032&&i<=55215?s+=1:n+=1}return Math.ceil(s+n/4)}function Ym(e){let t=[],s=[];if(!e)return{messageText:t,toolText:s};let n=e.content;if(typeof n=="string")e.role==="tool"?s.push(n):t.push(n);else if(Array.isArray(n))for(let r of n){if(!r||typeof r!="object")continue;let i=r.type;if(i==="text"&&typeof r.text=="string")t.push(r.text);else if(i==="tool_use"){if(s.push(String(r.name||"")),r.input!==void 0)try{s.push(JSON.stringify(r.input))}catch{}}else if(i==="tool_result"){let o=r.content;if(typeof o=="string")s.push(o);else if(Array.isArray(o)){for(let a of o)if(a)if(typeof a=="string")s.push(a);else if(typeof a=="object"&&typeof a.text=="string")s.push(a.text);else try{s.push(JSON.stringify(a))}catch{}}else if(o!==void 0)try{s.push(JSON.stringify(o))}catch{}}else try{t.push(JSON.stringify(r))}catch{}}if(Array.isArray(e.toolCalls)){for(let r of e.toolCalls)if(r&&(s.push(String(r.name||"")),r.input!==void 0))try{s.push(JSON.stringify(r.input))}catch{}}return{messageText:t,toolText:s}}function kd(e){let t=0,s=0;if(e&&Array.isArray(e.messages))for(let i of e.messages){let{messageText:o,toolText:a}=Ym(i);for(let l of o)t+=tr(l);for(let l of a)s+=tr(l)}let n=0,r=0;if(e&&typeof e.response=="string"&&(n+=tr(e.response)),e&&Array.isArray(e.toolCalls)){for(let i of e.toolCalls)if(i&&(r+=tr(String(i.name||"")),i.input!==void 0))try{r+=tr(JSON.stringify(i.input))}catch{}}return{inputMessageTokens:t,inputToolTokens:s,outputMessageTokens:n,outputToolTokens:r,inputTotalEstimated:t+s,outputTotalEstimated:n+r}}function da(e,t,s){let n=Math.max(0,Math.floor(Number(e)||0)),r=Math.max(0,Number(t)||0),i=Math.max(0,Number(s)||0),o=r+i;if(n===0)return{message:0,tool:0};if(o===0)return{message:n,tool:0};let a=Math.round(r/o*n),l=Math.min(n,Math.max(0,a));return{message:l,tool:n-l}}function Sd(e){if(e==null||e==="")return"";let t;if(typeof e=="number")t=e;else if(typeof e=="string"){let o=Date.parse(e);if(Number.isNaN(o)){let a=Number(e);if(!Number.isFinite(a))return"";t=a}else t=o}else return"";if(!Number.isFinite(t))return"";let s=new Date(t),n=String(s.getHours()).padStart(2,"0"),r=String(s.getMinutes()).padStart(2,"0"),i=String(s.getSeconds()).padStart(2,"0");return`${n}:${r}:${i}`}var ua=O(()=>{});function St(e,t){return!e||!t?"":`${e}${t}`}function sr(e){let t=typeof e=="string"?e:String(e||"");if(!t)return{agentId:null,sessionId:null};let s=t.indexOf("");if(s<0)return{agentId:null,sessionId:t};let n=t.slice(0,s)||null,r=t.slice(s+1)||null;return{agentId:n,sessionId:r}}function pa(e){return e?`${e}`:""}function fa(e,t){return!e||!t?"":`${e}${t}`}var nr=O(()=>{});function Gm(e,t){if(!e||!!!t?.online)return!1;let n=!e.online,r=e.online&&e.version!=null&&t.version!=null&&e.version!==t.version;return n||r}function Id(e,t){let s=e.lastViewedConversation||localStorage.getItem("lastViewedConversation");if(!s)return!1;let n=e.conversations.find(i=>i.id===s);if(!n)return!1;let r=t?.agentId||e.currentAgent;return t&&(e.currentAgent=t.agentId,e.currentAgentInfo=t.agentInfo,e.sendWsMessage({type:"select_agent",agentId:t.agentId,silent:!0})),e.activeConversations=[s],e.currentWorkDir=n.workDir,e.messagesMap[s]=[],e.sendWsMessage({type:"select_conversation",conversationId:s}),e.requestChatHistory?.(s,{mode:"recent",turns:5}),e.sendWsMessage({type:"refresh_conversation",conversationId:s}),!0}function Cd(e,t){let s=Array.isArray(e.agents)?e.agents:[],n=e._hasHandledAgentList===!0,r=e.currentAgent||null,i=!!(r&&s.some(a=>a&&a.id===r&&a.online));e.agents=t.agents,e._hasHandledAgentList=!0;let o=e.currentAgent||null;if(o){let a=e._yeaftAgentSeen&&e._yeaftAgentSeen.id===o?e._yeaftAgentSeen:null,l=t.agents.find(d=>d.id===o)||null;(e.currentView==="yeaft"||e.workCenterOpen&&e.workCenterAgentId===o)&&Gm(a,l)&&(e._yeaftReconnectCatchUpPending=!0),l?e._yeaftAgentSeen={id:o,online:!!l.online,version:l.version!=null?l.version:null}:a?a.online&&(e._yeaftAgentSeen={id:o,online:!1,version:a.version}):e._yeaftAgentSeen={id:o,online:!1,version:null}}{let a=new Set(t.agents.map(l=>l.id));for(let l of t.agents)e.proxyPorts[l.id]=l.proxyPorts||[],l.yeaftStatus&&typeof e.cacheYeaftAgentStatus=="function"&&e.cacheYeaftAgentStatus(l.id,l.yeaftStatus);for(let l of Object.keys(e.proxyPorts))a.has(l)||delete e.proxyPorts[l]}if(e.currentAgent){let a=t.agents.find(l=>l.id===e.currentAgent);a&&(e.currentAgentInfo=a)}if(e.currentView==="yeaft"&&!e.currentAgent){let a=t.agents.find(l=>l.online);a&&(e.currentAgent=a.id,e.currentAgentInfo=a)}if(e.currentView==="yeaft"&&typeof e.loadOpenedYeaftSessionsForConnectedAgents=="function"){let a=t.agents.filter(l=>l&&l.online&&l.id).map(l=>l.id);e.loadOpenedYeaftSessionsForConnectedAgents(a)}{let a=[],l=new Set;for(let d of t.agents)for(let u of d.conversations||[])l.has(u.id)||(l.add(u.id),a.push({...u,type:u.type,agentId:d.id,agentName:d.name}),u.title&&(u.customTitle&&(e.customConversationTitles[u.id]=u.title),e.conversationTitles[u.id]||(e.conversationTitles[u.id]=u.title)));for(let d of a){d.agentOnline=!0;let u=e.conversations.find(p=>p.id===d.id);if(u)u.claudeSessionId=d.claudeSessionId||u.claudeSessionId,u.processing=d.processing,u.userId=d.userId,u.username=d.username,u.agentId=d.agentId,u.agentName=d.agentName,u.agentOnline=!0,d.type&&(u.type=d.type),d.name!==void 0&&(u.name=d.name);else{let p=e._recentlyDeletedSessions?.[d.id];if(p&&Date.now()-p<15e3)continue;e.conversations.push(d)}d.pinned&&!e.pinnedSessions.includes(d.id)&&e.pinnedSessions.push(d.id)}let c=new Set(t.agents.map(d=>d.id));e.conversations=e.conversations.filter(d=>{if(l.has(d.id)||e.activeConversations.includes(d.id))return!0;if(d.agentId&&c.has(d.agentId)){let u=e._recentlyDeletedSessions?.[d.id];return u&&Date.now()-u<15e3||(delete e.messagesMap[d.id],delete e.processingConversations[d.id],Ce(e,d.id),delete e.executionStatusMap[d.id]),!1}return d.agentId&&!c.has(d.agentId)&&(d.agentOnline=!1),!0});for(let d of a)if(d.processing&&!Ss(e,d.id)&&!e._turnCompletedConvs?.has(d.id))e.processingConversations[d.id]=!0;else if(e.processingConversations[d.id]){delete e.processingConversations[d.id],Ce(e,d.id);let u=e.executionStatusMap[d.id];u&&(u.currentTool=null),e.finishStreamingForConversation(d.id)}for(let d of Object.keys(e.processingConversations))if(!l.has(d)){if(d.startsWith("yeaft-"))continue;delete e.processingConversations[d],Ce(e,d);let u=e.executionStatusMap[d];u&&(u.currentTool=null),e.finishStreamingForConversation(d)}}if(localStorage.setItem("pinned-sessions",JSON.stringify(e.pinnedSessions)),e._closedAt){let a=Date.now();for(let l of Object.keys(e._closedAt))a-e._closedAt[l]>3e4&&(delete e._closedAt[l],e._turnCompletedConvs?.delete(l))}if(e.currentAgent){let a=t.agents.find(l=>l.id===e.currentAgent&&l.online);if(a){let l=!!e._yeaftReconnectCatchUpPending,d=l||n&&!i;if(e.currentAgentInfo=a,d&&(e._offlineConversationRestoreKey=null,e.sendWsMessage({type:"select_agent",agentId:e.currentAgent,silent:!0})),d&&e.workCenterOpen&&e.workCenterAgentId===e.currentAgent&&typeof e.listWorkItems=="function"){let u=e._workCenterListFiltersByAgent?.[e.workCenterAgentId]||{};e.listWorkItems(e.workCenterAgentId,u).catch(()=>{})}if(e._yeaftReconnectCatchUpPending=!1,e.currentView==="yeaft"&&typeof e.requestYeaftSessionBootstrap=="function"){let u=l||!e.yeaftSessionReady||!e.yeaftModel||!e.yeaftStatus;(u||l)&&e.requestYeaftSessionBootstrap({forceSessionReady:u,catchUpHistory:l})}if(!d)return;if(e.currentConversation){let u=e.conversations.find(g=>g.id===e.currentConversation);e.sendWsMessage({type:"select_conversation",conversationId:e.currentConversation});let p=e.messagesMap[e.currentConversation]||[],f=ks(p);f!=null?e.requestChatHistory?.(e.currentConversation,{mode:"delta",afterMessageId:f}):e.requestChatHistory?.(e.currentConversation,{mode:"recent",turns:5}),e.sendWsMessage({type:"refresh_conversation",conversationId:e.currentConversation})}else e.recoveryDismissed||Id(e);return}else{let l=`${e.currentAgent||""}:${e.currentConversation||""}`;e.currentConversation&&(!n||i||e._offlineConversationRestoreKey!==l)&&(e._offlineConversationRestoreKey=l,e.sendWsMessage({type:"select_conversation",conversationId:e.currentConversation}));return}}if(!e.currentConversation&&!e.currentAgent&&!e.recoveryDismissed){let a=e.lastViewedConversation||localStorage.getItem("lastViewedConversation"),l=e.lastUsedAgent;if(a){let c=e.conversations.find(d=>d.id===a);if(c){let d=t.agents.find(u=>u.id===c.agentId&&u.online);if(d){Id(e,{agentId:c.agentId,agentInfo:d});return}}}l&&(e.agents.find(d=>d.id===l&&d.online)?e.selectAgent(l):e.checkPendingRecovery())}}function Ad(e,t){let s=e.pendingAgentSelection||null;if(s){if(!(typeof t.requestId=="string"&&t.requestId?t.requestId===s.requestId:t.agentId===s.agentId))return!1;if(e.pendingAgentSelection=null,t.ok===!1)return e.agentSwitching=!1,!1}else{if(t.requestId)return!1;if(e.currentAgent&&t.agentId!==e.currentAgent)return!1}e.agentSwitching=!1;let n=e.currentAgent===t.agentId,r={id:t.agentId,name:t.agentName,workDir:t.workDir,capabilities:t.capabilities||["terminal","file_editor","background_tasks"],version:t.version||null};if(typeof e.activateYeaftAgent=="function"?e.activateYeaftAgent(t.agentId,r):(e.currentAgent=t.agentId,e.currentAgentInfo=r),Array.isArray(t.slashCommands)){let u=[...new Set(t.slashCommands)];e.slashCommandsMap[`agent:${t.agentId}`]=u}t.slashCommandDescriptions&&(e.slashCommandDescriptions={...e.slashCommandDescriptions,...t.slashCommandDescriptions});let i=t.conversations||[],o=new Set,a=i.filter(u=>o.has(u.id)?!1:(o.add(u.id),!0)).map(u=>({...u,agentId:t.agentId,agentName:t.agentName}));if(n&&e.currentConversation){let u=i.find(p=>p.id===e.currentConversation);u&&!a.find(p=>p.id===u.id)&&a.push({...u,agentId:t.agentId,agentName:t.agentName})}let l=new Set(a.map(u=>u.id)),c=e.conversations.filter(u=>!l.has(u.id));e.conversations=[...c,...a];for(let u of i)u.title&&(u.customTitle&&(e.customConversationTitles[u.id]=u.title),e.conversationTitles[u.id]||(e.conversationTitles[u.id]=u.title));let d=new Set(i.map(u=>u.id));for(let u of i)if(u.processing&&!Ss(e,u.id)&&!e._turnCompletedConvs?.has(u.id))e.processingConversations[u.id]=!0;else if(e.processingConversations[u.id]){delete e.processingConversations[u.id],Ce(e,u.id);let p=e.executionStatusMap[u.id];p&&(p.currentTool=null),e.finishStreamingForConversation(u.id)}for(let u of Object.keys(e.processingConversations))if(!d.has(u)){if(u.startsWith("yeaft-"))continue;if(!c.some(f=>f.id===u)){delete e.processingConversations[u],Ce(e,u);let f=e.executionStatusMap[u];f&&(f.currentTool=null),e.finishStreamingForConversation(u)}}if(e.currentView!=="yeaft"){if(n&&e.currentConversation){let u=e.conversations.find(p=>p.id===e.currentConversation);e.currentWorkDir=u?.workDir||e.currentWorkDir||t.workDir,At(e),e.sendWsMessage({type:"select_conversation",conversationId:e.currentConversation})}else{e.activeConversations=[],e.currentWorkDir=t.workDir;let u=e.lastViewedConversation||localStorage.getItem("lastViewedConversation");u&&e.conversations.find(p=>p.id===u)&&(e.autoRestoreConversation(u),e.pendingRecovery=null)}pc(e)}return!0}var xd=O(()=>{ss();bs();Yn()});function Qm(e={}){return{providers:e.providers||[],primaryModel:e.primaryModel||null,fastModel:e.fastModel||null,language:e.language||"en"}}function Td(){return window.Pinia?.useSessionsStore?.()||window.__useSessionsStore&&window.__useSessionsStore()}function ev(e,t){let s=t.agentId||null,n=Array.isArray(e.yeaftSessionHydrateSlices)?e.yeaftSessionHydrateSlices.filter(r=>r.agentId!==s):[];e.yeaftSessionHydrateSlices=[...n,{agentId:s,sessions:Array.isArray(t.sessions)?t.sessions:[]}]}function tv(e){let t=Td(),s=null;try{s=localStorage.getItem("lastViewedYeaftSession")||null}catch{}let n=sr(s),r=e.yeaftActiveSessionFilter||t?.activeSessionId||null;if(r){let i=t?.activeSessionKey?t.sessions?.[t.activeSessionKey]:null;return i?.id===r&&i.agentId?{sessionId:r,agentId:i.agentId}:n.sessionId===r&&n.agentId?n:{sessionId:r,agentId:null}}return n}function Md(e){let t=Td(),s=tv(e);typeof t?.beginInventoryCommit=="function"?t.beginInventoryCommit(s.sessionId,s.agentId):typeof t?.resetInventory=="function"&&t.resetInventory();let n=Array.isArray(e.yeaftSessionHydrateSlices)?e.yeaftSessionHydrateSlices:[],r=s.agentId?[...n.filter(i=>i.agentId===s.agentId),...n.filter(i=>i.agentId!==s.agentId)]:n;r.length===0&&t?.applySnapshot?.([],null),r.forEach((i,o)=>{t?.applySnapshot?.(i.sessions||[],i.agentId||null,{deferActivation:o<r.length-1})}),e.yeaftSessionHydrateSlices=[]}function sv(e){let t=e.yeaftSessionHydrateRequestId||null;e.yeaftSessionInventoryCompleteSupported!==!1||!t||(clearTimeout(e._legacyYeaftSessionHydrateTimer),e._legacyYeaftSessionHydrateTimer=setTimeout(()=>{e.yeaftSessionHydrateRequestId===t&&(e._legacyYeaftSessionHydrateTimer=null,Md(e),e._hasHandledYeaftSessionHydrate=!0,e.yeaftSessionHydrateRequestId=null,e.yeaftSessionHydrateError=null,e._yeaftSessionInventorySocketQuarantined=!0)},Jm))}function nv(e,t={}){let s=e||{systemPrompt:"",messages:[],rawRequest:null},n={systemPrompt:s.systemPrompt||"",messages:Array.isArray(s.messages)?[...s.messages]:[],rawRequest:s.rawRequest??null};if(t?.base){let r={systemPrompt:t.systemPrompt||"",messages:Array.isArray(t.messages)?t.messages:[],rawRequest:null};return Object.prototype.hasOwnProperty.call(t,"rawRequestDelta")&&(r.rawRequest=ni(null,t.rawRequestDelta)),r}if(typeof t?.systemPrompt=="string"&&(n.systemPrompt=t.systemPrompt),Array.isArray(t?.messages))n.messages=t.messages;else if(Array.isArray(t?.messagesAppend)){let r=Number.isFinite(Number(t.messagesFrom))?Number(t.messagesFrom):n.messages.length;n.messages=n.messages.slice(0,r).concat(t.messagesAppend)}return Object.prototype.hasOwnProperty.call(t||{},"rawRequestDelta")&&(n.rawRequest=ni(n.rawRequest,t.rawRequestDelta)),n}function rv(e=[]){let t=new Map;return e.map(s=>{if(!s||!s.requestDelta)return s;let n=s.turnId||"__unknown__",r=t.get(n)||s.requestBase||null,i=r?.rawRequest??null,o=nv(r,s.requestDelta);return t.set(n,o),{...s,systemPrompt:typeof s.systemPrompt=="string"&&s.systemPrompt?s.systemPrompt:o.systemPrompt,messages:Array.isArray(s.messages)&&s.messages.length>0?s.messages:o.messages,rawRequest:s.rawRequest??null,rawRequestBase:i}})}function Pd(e,t){let s=Re();switch(e._lastPongAt=Date.now(),t.type){case"work_center_response":{let n=t.requestId?e.workCenterPending[t.requestId]:null;if(!n)break;clearTimeout(n.timer),delete e.workCenterPending[t.requestId],t.ok?n.resolve(t.data):n.reject(new Error(t.error||"Work Center request failed"));break}case"work_center_event":e.applyWorkCenterEvent(t.agentId,t.event);break;case"auth_result":if(t.success){if(e.authenticated=!0,t.sessionKey&&(e.sessionKey=yt(t.sessionKey),s.setSessionKey(t.sessionKey)),t.acceptPlaintext===!0&&(e.serverEncryptionRequired=!1),e.yeaftSessionInventoryCompleteSupported=t.yeaftSessionInventoryComplete===!0,e.yeaftSessionHydrateSlices=[],e._hasHandledYeaftSessionHydrate=!1,e.yeaftSessionHydrateError=null,t.role&&(s.role=t.role),typeof e.requestYeaftSessionInventory=="function")e.requestYeaftSessionInventory();else{let n=e.conversations.map(r=>r.id).filter(Boolean);e.sendWsMessage({type:"get_agents",conversationIds:n.length>0?n:void 0})}e.checkPendingRecovery()}else e.addMessage({type:"error",content:t.error||_e("login.error.loginFailed")}),s.handleAuthFailure?.(void 0,t._wsAuthToken,t._wsAuthGeneration);break;case"agent_list":Cd(e,t);break;case"yeaft_session_hydrate":{if(e.yeaftSessionInventoryCompleteSupported===!0&&(!t.requestId||t.requestId!==e.yeaftSessionHydrateRequestId)||e.yeaftSessionInventoryCompleteSupported!==!0&&!e.yeaftSessionHydrateRequestId||t.requestId&&e.yeaftSessionHydrateRequestId&&t.requestId!==e.yeaftSessionHydrateRequestId)break;ev(e,t),e.yeaftSessionInventoryCompleteSupported!==!0&&sv(e);break}case"yeaft_session_hydrate_complete":if(e.yeaftSessionInventoryCompleteSupported===!0&&(!t.requestId||t.requestId!==e.yeaftSessionHydrateRequestId)||e.yeaftSessionHydrateRequestId&&!t.requestId||t.requestId&&e.yeaftSessionHydrateRequestId&&t.requestId!==e.yeaftSessionHydrateRequestId)break;clearTimeout(e._legacyYeaftSessionHydrateTimer),e._legacyYeaftSessionHydrateTimer=null,t.ok!==!1?Md(e):e.yeaftSessionHydrateSlices=[],e.yeaftSessionHydrateRequestId=null,e._hasHandledYeaftSessionHydrate=t.ok!==!1,e.yeaftSessionHydrateError=t.ok===!1?t.error||"session_inventory_failed":null;break;case"session_catalog_snapshot":e.applySessionCatalogSnapshot(t.catalog,t.projectsAuthoritative===!0?t.projects:null,t.hiddenCatalog);break;case"session_ui_metadata_updated":e.finishSessionCatalogMutation?.(t);break;case"session_catalog_reorder_result":e.finishSessionCatalogMutation?.(t);break;case"agent_selected":if(!Ad(e,t))break;e.workCenterOpen&&e.workCenterAgentId&&e.listWorkItems(e.workCenterAgentId).catch(()=>{});break;case"conversation_created":ad(e,t);break;case"conversation_resumed":ld(e,t);break;case"conversation_selected":if(e.currentConversation===t.conversationId)return;e.activeConversations=[t.conversationId];{let n=e.conversations.find(r=>r.id===t.conversationId);n&&(e.currentWorkDir=n.workDir)}e.messagesMap[t.conversationId]=[],e.saveOpenSessions();break;case"conversation_settings_updated":{let n=e.conversations.find(i=>i.id===t.conversationId);n&&t.disallowedTools!==void 0&&(n.disallowedTools=t.disallowedTools);let r=e.conversationMcpServers[t.conversationId];if(r&&t.disallowedTools){let i=new Set(t.disallowedTools),o=e.conversationMcpServerTools[t.conversationId]||{};for(let a of r){let l=o[a.name];l&&l.length>0?a.enabled=!l.some(c=>i.has(c)):a.enabled=!i.has(`mcp__${a.name}`)}}t.needRestart&&n&&(n.needRestart=!0);break}case"sync_messages_result":fd(e,t);break;case"conversation_deleted":la(e,t);break;case"conversation_delete_result":t.ok&&la(e,t);break;case"turn_completed":cd(e,t);break;case"conversation_closed":dd(e,t);break;case"claude_output":e.handleAssistantOutputFrame(t.conversationId,t.data);break;case"yeaft_output":case"yeaft_session_output":case"session_output":e.handleYeaftOutput(t);break;case"yeaft_asset_ready":{let n=t.conversationId||e.yeaftConversationIdsByAgent?.[t.agentId]||e.yeaftConversationId;if(!n||!t.image)break;e.messagesMap[n]||(e.messagesMap[n]=[]),e.messagesMap[n].some(i=>i?.type==="chat-image"&&i.assetId===t.image.assetId&&i.sessionId===t.sessionId&&i.turnId===t.turnId)||e.addMessageToConversation(n,{type:"chat-image",...t.image,sessionId:t.sessionId||null,vpId:t.vpId||null,speakerVpId:t.vpId||null,turnId:t.turnId||null,threadId:t.threadId||null});break}case"yeaft_history_chunk":md(e,t);break;case"yeaft_history_outline":e.handleYeaftHistoryOutline(t);break;case"yeaft_history_search_result":e.handleYeaftHistorySearchResult(t);break;case"yeaft_history_window":{let n=e.pendingYeaftHistoryWindow?.(t);if(!n||(n.pending?.prefetch===!0&&(t.prefetch=!0),e.pendingYeaftHistoryWindow?.(t)?.pending!==n.pending))break;let r=t.error?null:gd(e,t);e.handleYeaftHistoryWindow(t,r);break}case"yeaft_tool_stats":{e._fetchYeaftToolStatsTimer&&(clearTimeout(e._fetchYeaftToolStatsTimer),e._fetchYeaftToolStatsTimer=null);let n=t?.snapshot,r=n&&typeof n=="object"&&!Array.isArray(n)?n:{};e.yeaftToolStats={snapshot:r,registered:Array.isArray(t?.registered)?t.registered:[],unused:Array.isArray(t?.unused)?t.unused:[],error:typeof t?.error=="string"?t.error:null,notice:typeof t?.notice=="string"?t.notice:null,fetchedAt:Date.now()},e.yeaftToolStatsLoading=!1;break}case"yeaft_debug_history":{let n=e.yeaftDebugPanel?.agentId||null;if(n&&t?.agentId&&t.agentId!==n)break;let r=typeof t?.requestId=="string"?t.requestId:"",i=typeof t?.detailTurnId=="string"&&t.detailTurnId,o=i?e._yeaftDebugHistoryLatestDetailRequestId:e._yeaftDebugHistoryLatestListRequestId;if(o&&r!==o||!o&&r)break;e._fetchYeaftDebugHistoryTimer&&(clearTimeout(e._fetchYeaftDebugHistoryTimer),e._fetchYeaftDebugHistoryTimer=null),e._yeaftDebugHistoryInFlightKey=null;let a=Array.isArray(t?.turns)?t.turns:[],l=t?.search?Zm:Xm,c=i?a:a.slice(-l),d=new Set(c.map(x=>x?.turnId).filter(Boolean)),u=rv(Array.isArray(t?.loops)?t.loops:[]),p=i?u:u.filter(x=>!x?.turnId||d.has(x.turnId)),f=Array.isArray(t?.dreamEvents)?t.dreamEvents:[];e.yeaftDebugHistoryHasMore=!!t?.hasMore||!i&&a.length>c.length,!t?.detailTurnId&&Number.isFinite(t?.limit)&&t.limit>0&&(e.yeaftDebugHistoryLimit=Math.min(l,t.limit)),(!e.yeaftDebugTurnsById||typeof e.yeaftDebugTurnsById!="object")&&(e.yeaftDebugTurnsById={}),Array.isArray(e.yeaftDebugLoops)||(e.yeaftDebugLoops=[]),Array.isArray(e.yeaftDebugTurnOrder)||(e.yeaftDebugTurnOrder=[]);let g=i?{...e.yeaftDebugTurnsById}:{};for(let x of c){let T=x?.turnId;if(!T)continue;let D=g[T];if(D){let L=x?.detailsLoaded?{...D,...x}:{...x,...D};L.memoryLoaded==null&&D.memoryLoaded!=null&&(L.memoryLoaded=D.memoryLoaded),L.memoryAdjust==null&&D.memoryAdjust!=null&&(L.memoryAdjust=D.memoryAdjust),g[T]=L}else g[T]=x}e.yeaftDebugTurnsById=g;let h=x=>x?.loopInstanceId||`${x?.turnId||""}#${x?.loopNumber||0}`,m=e.yeaftDebugLoops,b=new Map;for(let x of m)x&&b.set(h(x),x);let y=new Set,S=[];for(let x of p){if(!x)continue;let T=h(x);y.add(T);let D=b.get(T);S.push(i?{...D||{},...x}:D||x)}if(i)for(let x of m)!x||y.has(h(x))||S.push(x);e.yeaftDebugLoops=S;let w=new Set,v=[],k=x=>{!x||w.has(x)||(w.add(x),v.push(x))};if(i){for(let x of e.yeaftDebugTurnOrder)k(x);for(let x of c)k(x?.turnId)}else for(let x of c)k(x?.turnId);e.yeaftDebugTurnOrder=i?v:v.slice(-l);for(let x of f){if(!x)continue;let T=null,D=x.sessionId||x.groupId;typeof x.target=="string"&&x.target.includes("/")?T=x.target:typeof D=="string"&&D?T=`group/${D}`:T="*",typeof e._appendDreamEvent=="function"&&e._appendDreamEvent(T,x),x.type==="dream_progress"&&typeof e.handleYeaftOutput=="function"&&e.handleYeaftOutput({event:x})}e.yeaftDebugHistoryLoading=!1,e.yeaftDebugHistoryError=typeof t?.error=="string"?t.error:null,e.yeaftDebugHistoryProjection=t?.projection&&typeof t.projection=="object"?t.projection:null,e.yeaftDebugHistoryFetchedAt=Date.now(),i&&e.yeaftDebugPanel&&e.yeaftDebugPanel.turnId===t.detailTurnId&&(e.yeaftDebugPanel={...e.yeaftDebugPanel,status:e.yeaftDebugHistoryError?"error":"ready",error:e.yeaftDebugHistoryError});break}case"chat_image":t.conversationId&&t.fileId&&e.addMessageToConversation(t.conversationId,{type:"chat-image",fileId:t.fileId,previewToken:t.previewToken,mimeType:t.mimeType});break;case"error":{let n=t.conversationId||e.currentConversation,r=["Permission denied","Agent not found","No conversation selected","Agent is still syncing","No agent available","Agent access denied"].some(c=>t.message?.includes(c));if((t.message?.includes("Agent is still syncing")||t.message?.includes("Agent not found"))&&At(e),["No conversation selected","Agent is still syncing","No agent available"].some(c=>t.message?.includes(c))&&n&&(delete e.processingConversations[n],Ce(e,n),e.finishStreamingForConversation(n)),r&&n){let c=e.messagesMap[n];if(c&&c.length>0)for(let d=c.length-1;d>=0&&d>=c.length-5;d--){let u=c[d];if(u&&u.type==="error"&&u._sysErrBaseContent!==void 0){if(u._sysErrBaseContent===t.message&&Date.now()-(u._sysErrFirstAt||0)<=3e3){u._sysErrCount=(u._sysErrCount||1)+1,u.content=`${u._sysErrBaseContent} (\xD7${u._sysErrCount})`,u._sysErrRemoveTimer&&(clearTimeout(u._sysErrRemoveTimer),u._sysErrRemoveTimer=setTimeout(()=>{let p=e.messagesMap[n];if(p){let f=p.findIndex(g=>g.id===u.id);f>=0&&p.splice(f,1)}},5e3));return}break}}}let o=Date.now().toString()+Math.random().toString(36).substr(2,9),a={type:"error",content:t.message,transient:r,dbMessageId:r?"err_"+o:void 0};r&&(a._sysErrBaseContent=t.message,a._sysErrCount=1,a._sysErrFirstAt=Date.now()),e.addMessageToConversation(n,a);let l=null;if(r&&n){let c=e.messagesMap[n];c&&c.length>0&&(l=c[c.length-1])}if(r&&n&&l){let c=n,d="err_"+o;l._sysErrRemoveTimer=setTimeout(()=>{let u=e.messagesMap[c];if(u){let p=u.findIndex(f=>f.id===d);p>=0&&u.splice(p,1)}},5e3)}!r&&n&&(delete e.processingConversations[n],Ce(e,n),e.finishStreamingForConversation(n));break}case"history_sessions_list":if(t.requestId&&e._historySessionsRequestId&&t.requestId!==e._historySessionsRequestId)break;e.historySessions=t.sessions||[],e.historySessionsLoading=!1;break;case"folders_list":if(t.requestId&&e._foldersRequestId&&t.requestId!==e._foldersRequestId)break;e.folders=t.folders||[],e.foldersLoading=!1,e._foldersResolve&&(e._foldersResolve(),e._foldersResolve=null);break;case"models_list":if(t.requestId&&e._modelsRequestId&&t.requestId!==e._modelsRequestId)break;e.providerModels=t.models||[],e.providerModelsLoading=!1,e._modelsTimeout&&(clearTimeout(e._modelsTimeout),e._modelsTimeout=null),e._modelsResolve&&(e._modelsResolve(e.providerModels),e._modelsResolve=null);break;case"conversation_refresh":ud(e,t);break;case"session_pinned":if(t.conversationId){let n=t.agentId?{agentId:t.agentId}:{};if(typeof e.setSessionPinned=="function")e.setSessionPinned(t.conversationId,!!t.pinned,n);else try{let r=window.Pinia?.useSessionsStore?.()||window.__useSessionsStore&&window.__useSessionsStore();r&&typeof r.applyPinState=="function"&&r.applyPinState(t.conversationId,!!t.pinned,t.agentId||e.yeaftSessionAgentById?.[t.conversationId]||e.currentAgent||null)}catch{}}break;case"execution_cancelled":pd(e,t);break;case"slash_commands_update":if(Array.isArray(t.slashCommands)){let n=[...new Set(t.slashCommands)];if(t.commandSet==="yeaft"){let r=t.conversationId&&t.conversationId!=="__preload__"?t.conversationId:null,i=t.agentId&&e.yeaftConversationIdsByAgent?.[t.agentId]||null,o=r||i;o&&(e.slashCommandsMap[o]=n);let a=e.yeaftConversationId||null,l=t.agentId?e.currentAgent===t.agentId&&(i===a||r===a):r===a;a&&l&&(e.slashCommandsMap[a]=n)}else t.conversationId&&(e.slashCommandsMap[t.conversationId]=n),t.agentId&&(e.slashCommandsMap[`agent:${t.agentId}`]=n)}t.slashCommandDescriptions&&(e.slashCommandDescriptions={...e.slashCommandDescriptions,...t.slashCommandDescriptions});break;case"compact_status":{let n=t.conversationId;e.compactStatus={conversationId:n,status:t.status,message:t.message},t.status==="completed"?setTimeout(()=>{e.compactStatus?.conversationId===n&&e.compactStatus?.status==="completed"&&(e.compactStatus=null)},3e3):t.status==="compacting"&&setTimeout(()=>{e.compactStatus?.conversationId===n&&e.compactStatus?.status==="compacting"&&(e.compactStatus=null)},3e4)}break;case"pong_session":{let n=t.conversationId;if(!n)break;if(e._pongTimeouts?.[n]&&(clearTimeout(e._pongTimeouts[n]),delete e._pongTimeouts[n]),t.status==="unsupported"){Ce(e,n),Zc(e,n);break}if(t.status==="ok")e.sessionHealth?.[n]&&delete e.sessionHealth[n],!t.isProcessing&&e.processingConversations[n]&&(delete e.processingConversations[n],Ce(e,n),e.finishStreamingForConversation(n));else if(e.sessionHealth||(e.sessionHealth={}),e.sessionHealth[n]={status:t.status},t.status==="session-lost"||t.status==="cli-exited"){if(e._autoRefreshed||(e._autoRefreshed={}),!e._autoRefreshed[n]){e._autoRefreshed[n]=!0;let r=e.conversations.find(i=>i.id===n);e.sendWsMessage({type:"refresh_conversation",conversationId:n,agentId:r?.agentId})}delete e.processingConversations[n],Ce(e,n),e.finishStreamingForConversation(n)}break}case"ask_user_question":if(t.conversationId){let n=()=>{let r=e.messagesMap[t.conversationId]||[];for(let i=r.length-1;i>=0;i--)if(r[i].type==="tool-use"&&r[i].toolName==="AskUserQuestion"&&!r[i].askRequestId)return r[i].askRequestId=t.requestId,r[i].askQuestions=t.questions,!0;return!1};if(!n()){let r=0,i=setInterval(()=>{r++,(n()||r>=10)&&clearInterval(i)},200)}}break;case"restart_agent_ack":window.dispatchEvent(new CustomEvent("agent-restart-ack",{detail:{agentId:t.agentId}}));break;case"upgrade_agent_ack":window.dispatchEvent(new CustomEvent("agent-upgrade-ack",{detail:{agentId:t.agentId,success:t.success,error:t.error,alreadyLatest:t.alreadyLatest,version:t.version,reason:t.reason,currentNode:t.currentNode,requiredNode:t.requiredNode,requiredCapability:t.requiredCapability}}));break;case"terminal_created":case"terminal_output":case"terminal_closed":case"terminal_error":case"file_content":case"file_saved":case"directory_listing":case"git_status_result":case"git_diff_result":case"git_op_result":case"file_op_result":case"file_search_result":t.type,t.type,window.dispatchEvent(new CustomEvent("workbench-message",{detail:t}));break;case"server_updating":e.connectionState="updating";break;case"context_usage":e.contextUsage={inputTokens:t.inputTokens,maxTokens:t.maxTokens,percentage:t.percentage,conversationId:t.conversationId};break;case"mcp_servers_list":case"mcp_config_updated":t.agentId&&t.servers&&(e.mcpServers[t.agentId]=t.servers);break;case"expert_roles_list":t.roles&&(e.expertRoleDefinitions=t.roles);break;case"llm_models_discovered":t.agentId&&(e.llmModelDiscovery=e.llmModelDiscovery||{},e.llmModelDiscovery[t.agentId]=t);break;case"llm_config":case"llm_config_updated":if(t.agentId){let n=t.agentConfig||Qm(t),r=t.effectiveConfig||n;e.llmConfig[t.agentId]={providers:t.providers||r.providers||[],primaryModel:t.primaryModel||r.primaryModel||null,fastModel:t.fastModel||r.fastModel||null,language:t.language||n.language||r.language||"en",needsSetup:t.needsSetup??r.needsSetup??!1,agentConfig:n,effectiveConfig:r,requestId:t.requestId||null,statusRefreshError:t.statusRefreshError||null,error:t.error||null,loaded:!0}}break;case"models_dev_registry":if(e.modelsDevRegistry={registry:t.registry||{},fetchedAt:t.fetchedAt||Date.now(),error:t.error||null,loaded:!0},e._modelsDevPending){let n=e._modelsDevPending;e._modelsDevPending=null,n.timer&&clearTimeout(n.timer);for(let r of n.resolvers)r(e.modelsDevRegistry)}break;case"yeaft_settings":case"yeaft_settings_updated":t.agentId&&(e.yeaftSettings[t.agentId]={maxConcurrentThreads:t.maxConcurrentThreads??6,autoArchiveIdleDays:t.autoArchiveIdleDays??30,error:t.error||null,loaded:!0,at:Date.now()});break;case"telemetry_settings":case"telemetry_settings_updated":{let n={enabled:t.enabled!==!1,retentionDays:t.retentionDays??3,flushIntervalMs:t.flushIntervalMs??1e3,maxQueueSize:t.maxQueueSize??5e3,rawExchangeMaxBytes:t.rawExchangeMaxBytes??524288,traceTextMaxBytes:t.traceTextMaxBytes??262144,error:t.error||null,loaded:!0,at:Date.now()};e.telemetrySettings=n;let r=e._telemetryPending,i=t.type==="telemetry_settings"?"load":"update";r&&r[i]&&(r[i](n),delete r[i]);break}case"search_settings":case"search_settings_updated":{let n={backend:t.backend||"tavily",tavilyKeyConfigured:!!t.tavilyKeyConfigured,tavilyKeyMasked:t.tavilyKeyMasked||null,disableHtmlFallback:!!t.disableHtmlFallback,error:t.error||null,loaded:!0,at:Date.now()};e.searchSettings=n;let r=e._searchPending,i=t.type==="search_settings"?"load":"update";r&&r[i]&&(r[i](n),delete r[i]);break}case"tavily_usage":{let n=t.error?{error:t.error}:{plan:t.plan,used:t.used,limit:t.limit,paygoUsed:t.paygoUsed,paygoLimit:t.paygoLimit};e.tavilyUsage=n,e.tavilyUsageLoading=!1;let r=e._searchPending;r&&r.usage&&(r.usage(n),delete r.usage);break}case"yeaft_mcp_list_result":case"yeaft_mcp_add_result":case"yeaft_mcp_remove_result":case"yeaft_mcp_reload_result":case"yeaft_mcp_updated":{if(Array.isArray(t.servers)&&(e.yeaftMcpServers=t.servers),t.runtime&&typeof t.runtime=="object"&&(e.yeaftMcpRuntime={connected:!!t.runtime.connected,toolCount:t.runtime.toolCount||0,perServer:Array.isArray(t.runtime.perServer)?t.runtime.perServer:[]}),e.yeaftMcpLoading=!1,e.yeaftMcpError=t.error||null,t.requestId){let n=e._mcpPending;n&&n[t.requestId]&&(n[t.requestId](t),delete n[t.requestId])}break}case"conversation_mcp_update":t.conversationId&&t.servers&&(e.conversationMcpServers[t.conversationId]=t.servers),t.conversationId&&t.serverTools&&(e.conversationMcpServerTools[t.conversationId]=t.serverTools);break;case"btw_stream":e.appendBtwDelta(t.delta);break;case"btw_done":e.btwLoading=!1,t.btwSessionId&&(e.btwSessionId=t.btwSessionId);break;case"btw_error":{let n=e.btwMessages[e.btwMessages.length-1];n&&n.role==="assistant"&&(n.content="Error: "+t.error),e.btwLoading=!1;break}case"background_task_started":case"background_task_output":break;case"subagent_started":t.conversationId&&t.subagentId&&e.addSubagent(t.conversationId,{id:t.subagentId,slug:t.slug,type:t.subagentType,description:t.description,parentToolUseId:t.parentToolUseId});break;case"subagent_message":t.conversationId&&t.subagentId&&t.message&&e.appendSubagentMessage(t.conversationId,t.subagentId,t.message);break;case"subagent_completed":t.conversationId&&t.subagentId&&e.completeSubagent(t.conversationId,t.subagentId);break}}var Xm,Zm,Jm,Rd=O(()=>{wt();Fr();Bt();ss();bs();ua();nr();xd();si();Xm=1,Zm=5,Jm=500});function Dd(){return Object.values(_d).sort((t,s)=>t.order-s.order).map(t=>({teamId:t.id,team:t,roles:Object.values(It).filter(s=>s.group===t.id)}))}function Ed(e){let t=[];for(let s of Object.values(It)){t.push({roleId:s.id,roleName:s.name,roleTitle:s.title,actionId:null,actionName:null,searchText:`${s.name} ${s.fullName} ${s.title} ${s.titleEn}`.toLowerCase(),displayText:s.name,group:s.group});for(let n of s.actions)t.push({roleId:s.id,roleName:s.name,roleTitle:s.title,actionId:n.id,actionName:n.name,searchText:`${s.name} ${s.fullName} ${s.title} ${n.name} ${n.nameEn}`.toLowerCase(),displayText:`${s.name}\xB7${n.name}`,group:s.group})}if(e&&e.length>0){for(let s of e)if(t.push({roleId:s.id,roleName:s.name,roleTitle:s.title,actionId:null,actionName:null,searchText:`${s.name} ${s.fullName||""} ${s.title} ${s.titleEn||""}`.toLowerCase(),displayText:s.name,group:"custom"}),s.actions)for(let n of s.actions)t.push({roleId:s.id,roleName:s.name,roleTitle:s.title,actionId:n.id,actionName:n.name,searchText:`${s.name} ${s.fullName||""} ${s.title} ${n.name} ${n.nameEn||""}`.toLowerCase(),displayText:`${s.name}\xB7${n.name}`,group:"custom"})}return t}function Ts(e,t){let s=It[e.role];if(s){if(e.action){let n=s.actions.find(r=>r.id===e.action);return n?`${s.name}\xB7${n.name}`:s.name}return s.name}if(t){let n=t.find(r=>r.id===e.role);if(n){if(e.action){let r=n.actions?.find(i=>i.id===e.action);return r?`${n.name}\xB7${r.name}`:n.name}return n.name}}return e.role}function ga(e,t,s,n="zh-CN"){if(!e||e.length===0||!t||t.length===0)return null;let r=n==="zh-CN";if(!e.some(l=>!It[l.role]&&t.some(c=>c.id===l.role)))return null;if(e.length===1){let{role:l,action:c}=e[0],d=t.find(p=>p.id===l);if(!d)return null;let u;if(c&&d.actions){let p=d.actions.find(f=>f.id===c);p?s?(u=(r?p.messageTemplate:p.messageTemplateEn)||"",u+=s):u=(r?p.defaultMessage:p.defaultMessageEn)||"":u=((r?d.messagePrefix:d.messagePrefixEn)||"")+(s||"")}else u=((r?d.messagePrefix:d.messagePrefixEn)||"")+(s||"");return{effectivePrompt:u}}let o=[];for(let{role:l,action:c}of e){let d=t.find(p=>p.id===l),u=It[l];if(d)if(c){let p=d.actions?.find(f=>f.id===c);p&&o.push((r?p.messageTemplate:p.messageTemplateEn)||"")}else o.push((r?d.messagePrefix:d.messagePrefixEn)||"");else if(u)return null}return o.length===0?null:{effectivePrompt:o.join(`
4
4
  ---
Binary file
@@ -16,6 +16,6 @@
16
16
  </head>
17
17
  <body>
18
18
  <div id="app"></div>
19
- <script type="module" src="app.bundle.js?v=2cebcb30"></script>
19
+ <script type="module" src="app.bundle.js?v=5efb333f"></script>
20
20
  </body>
21
21
  </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yeaft/webchat-agent",
3
- "version": "1.0.399",
3
+ "version": "1.0.400",
4
4
  "description": "Remote worker agent for Yeaft Web Code Agent — connects the native Yeaft engine, CLI providers, and workbench tools",
5
5
  "main": "index.js",
6
6
  "type": "module",