@yeaft/webchat-agent 1.0.369 → 1.0.370

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,11 +1,11 @@
1
1
  var N=(e,t,s)=>()=>{if(s)throw s[0];try{return e&&(t=e(e=0)),t}catch(n){throw s=[n],n}};var Mh=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(s){throw t=0,s}};function hc(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 vc(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 yc(e){return e&&typeof e=="object"&&typeof e.n=="string"&&typeof e.c=="string"}function yt(e){return nacl.util.decodeBase64(e)}var ei=N(()=>{});function Vt(){return globalThis.localStorage||null}function wc(){let e=si();for(let t of Ko)try{t(e)}catch{}}function Ph(){try{Vt()?.removeItem(Fn),Vt()?.removeItem(Bn)}catch{}}function Rh(e){return String(e||"").trim()||null}function bc(e,t){if(!Nn(t))return{};try{let s=JSON.parse(Vt()?.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)?(Vt()?.removeItem(e),{}):s.records}catch{try{Vt()?.removeItem(e)}catch{}return{}}}function kc(e,t,s){if(!Nn(s))return!1;try{return Vt()?.setItem(e,JSON.stringify({ownerId:s.ownerId,records:t||{}})),!0}catch{return!1}}function bt(e){let t=Rh(e);if(!t)return zo(),null;if(ws!==t){ws=t,ti+=1;for(let s of[Fn,Bn])try{let n=JSON.parse(Vt()?.getItem(s)||"null");(!n||n.ownerId!==t)&&Vt()?.removeItem(s)}catch{try{Vt()?.removeItem(s)}catch{}}wc()}return si()}function zo(){ws=null,ti+=1,Ph(),wc()}function si(){return ws?{ownerId:ws,epoch:ti}:null}function Nn(e){return!!e&&!!ws&&e.ownerId===ws&&e.epoch===ti}function Sc(e){return{drafts:bc(Fn,e),outbox:bc(Bn,e)}}function Yo(e,t){return kc(Fn,e,t)}function qn(e,t){return kc(Bn,e,t)}function Ic(e){return typeof e!="function"?()=>{}:(Ko.add(e),()=>Ko.delete(e))}var Fn,Bn,ws,ti,Ko,Kw,Go=N(()=>{Fn="yeaft-work-center-composer-drafts-v1",Bn="yeaft-work-center-message-outbox-v1",ws=null,ti=0,Ko=new Set;Kw=Object.freeze({drafts:Fn,outbox:Bn})});function ve(e,t){let s=t==null?"__all__":String(t);return e?`${e}${s}`:s}function Wn(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 jn(e,t,s){return typeof s!="string"||!s?null:`${ve(e,t)}message:${s}`}function ss(e,t,s){return typeof s!="string"||!s?null:`${ve(e,t)}client:${s}`}var sn=N(()=>{});function Qo(e){return typeof e=="string"&&e?e:null}function nn(e,t){return e?.yeaftSessionHistoryState?.[t]||null}function Ht(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:ve(s,t)}}function Ac(e,{agentId:t,sessionId:s,mode:n="recent",preserveLoaded:r=!1,latestSeq:i=null}={}){if(!t||!s)return null;let o=ve(t,s),a=nn(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,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},ks(e),{sessionKey:o,requestId:c,generation:l,state:d}}function Zo(e,t={}){let s=t.sessionId??t.groupId??null;if(!s)return!1;let n=t.agentId||e?.yeaftSessionAgentById?.[s]||null,r=ve(n,s),i=nn(e,r),o=Qo(t.requestId);if(!i)return o===null;let a=Qo(i.requestId);return o?o===a:a===null}function xc(e,t={},s={},n="chunk"){if(!Zo(e,t))return null;let r=t.sessionId??t.groupId??null,i=t.agentId||e?.yeaftSessionAgentById?.[r]||null,o=ve(i,r),a=nn(e,o)||{},l=Qo(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},ks(e),d}function Un(e,{agentId:t,sessionId:s,requestId:n,error:r="history_load_failed"}={}){if(!t||!s||!n)return!1;let i=ve(t,s),o=nn(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()}},ks(e),!0)}function ks(e){let{sessionKey:t}=Ht(e),s=t?nn(e,t):null;return e.yeaftLoadingMoreHistory=!!s?.loading,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 Xo(e){let{sessionKey:t}=Ht(e);return t?nn(e,t):null}var Cc,ni=N(()=>{sn();Cc=15e3});function ri(e){return e?.sessionId??e?.groupId??null}function Jo(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 wt(e){return e?.isStreaming||e?.status==="pending"?!1:Number.isFinite(e?.seq)||!!Jo(e)||e?.isHistory===!0&&!e?.clientMessageId}function ea(e){if(Number.isFinite(e?.seq))return Number(e.seq);let s=Jo(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 ta(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}function _h(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&&!Jo(e):!1}function Eh(e){let t=[],s=null;for(let n of e)(n?.type==="user"||!s)&&(s={rows:[],bytes:0,protected:!1},t.push(s)),s.rows.push(n),s.bytes+=ta(n),_h(n)&&(s.protected=!0);return t}function Mc(e,{conversationId:t,agentId:s=null,sessionId:n=null,limits:r=Tc}={}){let i=e?.messagesMap?.[t];if(!Array.isArray(i)||i.length===0||!s||!n)return{evictedRows:0,keptRows:0};let o=h=>ri(h)===n,a=i.filter(o),l=Eh(a);if(l.length===0)return{evictedRows:0,keptRows:0};let c=new Set(l.filter(h=>h.protected)),d=l.filter(h=>c.has(h)).reduce((h,y)=>h+y.rows.length,0),u=l.filter(h=>c.has(h)).reduce((h,y)=>h+y.bytes,0),f=!1;for(let h=l.length-1;h>=0;h-=1){let y=l[h];if(c.has(y))continue;let b=d+y.rows.length>r.maxRowsPerSession||u+y.bytes>r.maxBytesPerSession,M=d<r.recentRowsFloor;f&&b&&!M||(c.add(y),f=!0,d+=y.rows.length,u+=y.bytes)}let p=new Set(l.filter(h=>c.has(h)).flatMap(h=>h.rows)),g=a.filter(h=>!p.has(h));if(g.length===0)return{evictedRows:0,keptRows:p.size,keptBytes:u};e.messagesMap[t]=i.filter(h=>!o(h)||p.has(h));let m=ve(s,n),v=e.yeaftHistoryCacheState?.[m]||null,k=Pc(a.filter(h=>p.has(h))),I=JSON.stringify(v?.ranges||[])===JSON.stringify(k.ranges)?Number(v?.rangeEpoch)||0:(Number(v?.rangeEpoch)||0)+1;if(e.yeaftHistoryCacheState={...e.yeaftHistoryCacheState||{},[m]:{...v||{},agentId:s,sessionId:n,conversationId:t,lastAccessed:Date.now(),rangeEpoch:I,...k}},g.some(wt)){let h=k.ranges[0]?.startSeq??null,y=e.yeaftSessionHistoryState?.[m]||{};e.yeaftSessionHistoryState={...e.yeaftSessionHistoryState||{},[m]:{...y,serverOldestFetchedSeq:h,oldestSeq:h,serverHasMore:h!==null,hasMore:h!==null,gapTraversalInitialized:!1,gapQueue:[],requestedBeforeSeqs:[],completedHistoryWorkKeys:[],pendingPageKind:null,pendingPageBeforeSeq:null,pendingGapStopAtSeq:null,pendingCacheEpoch:null,pendingHistoryWorkKey:null,paginationError:null,count:k.rowCount}};let b=Ht(e);b.agentId===s&&b.sessionId===n&&ks(e)}return{evictedRows:g.length,keptRows:p.size,keptBytes:u}}function Kn(e){if(e?.historyEntryId)return`entry:${e.historyEntryId}`;let t=ea(e);return Number.isFinite(t)?`seq:${t}`:e?.stableKey||e?.uiKey||e?.id||e?.messageId||"legacy"}function Dh(e){let t=new Map;for(let s of e){if(!wt(s))continue;let n=Kn(s),r=t.get(n)||{key:n,rows:[],seq:ea(s),bytes:0,touchedAt:0};r.rows.push(s),r.bytes+=ta(s),r.touchedAt=Math.max(r.touchedAt,Number(s?._historyCacheTouchedAt)||0),t.set(n,r)}return Array.from(t.values())}function Lh(e,t,s=new Set){let n=e.slice().sort((u,f)=>(f.seq||-1)-(u.seq||-1)),r=new Set,i=0,o=0;for(let u of e)s.has(u.key)&&(r.add(u.key),i+=u.rows.length,o+=u.bytes);for(let u of n){if(r.has(u.key))continue;if(i>=t.recentRowsFloor)break;let f=i+u.rows.length,p=o+u.bytes;if(r.size>0&&(f>t.maxRowsPerSession||p>t.maxBytesPerSession))break;r.add(u.key),i=f,o=p}let a=e.slice().sort((u,f)=>f.touchedAt-u.touchedAt||(f.seq||-1)-(u.seq||-1)),l=new Set(r),c=e.filter(u=>r.has(u.key)).reduce((u,f)=>u+f.rows.length,0),d=e.filter(u=>r.has(u.key)).reduce((u,f)=>u+f.bytes,0);for(let u of a){if(l.has(u.key))continue;let f=c+u.rows.length,p=d+u.bytes;l.size>0&&(f>t.maxRowsPerSession||p>t.maxBytesPerSession)||(l.add(u.key),c=f,d=p)}return l}function $h(e){let t=Array.from(new Set(e.map(ea).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 Pc(e){let t=e.filter(wt);return{rowCount:t.length,byteCount:t.reduce((s,n)=>s+ta(n),0),ranges:$h(t)}}function Vh(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 Hh(e,{conversationId:t,agentId:s,sessionId:n,incomingRows:r,now:i,limits:o}){let a=e.messagesMap?.[t]||[],l=a.filter(I=>ri(I)===n);Vh(l,r,i);let c=new Set((r||[]).filter(I=>I?.historyEntryId).map(Kn)),d=Dh(l),u=Lh(d,o,c),f=l.filter(I=>!wt(I)||u.has(Kn(I))),p=new Set(f);e.messagesMap[t]=a.filter(I=>ri(I)!==n||p.has(I));let g=Pc(f),m=ve(s,n),v=e.yeaftHistoryCacheState?.[m]||null,w=JSON.stringify(v?.ranges||[])===JSON.stringify(g.ranges)?Number(v?.rangeEpoch)||0:(Number(v?.rangeEpoch)||0)+1;e.yeaftHistoryCacheState={...e.yeaftHistoryCacheState||{},[m]:{agentId:s,sessionId:n,conversationId:t,lastAccessed:i,rangeEpoch:w,...g}}}function Oh(e,t){let s=e.messagesMap?.[t.conversationId]||[];e.messagesMap[t.conversationId]=s.filter(n=>ri(n)!==t.sessionId||!wt(n))}function Fh(e,t,s){let n={...e.yeaftHistoryCacheState||{}},r=Object.entries(n).filter(([,a])=>a?.rowCount>0),i=()=>Object.values(n).reduce((a,l)=>({rows:a.rows+(Number(l?.rowCount)||0),bytes:a.bytes+(Number(l?.byteCount)||0),sessions:a.sessions+((Number(l?.rowCount)||0)>0?1:0)}),{rows:0,bytes:0,sessions:0}),o=r.filter(([a])=>a!==t).sort((a,l)=>(Number(a[1]?.lastAccessed)||0)-(Number(l[1]?.lastAccessed)||0));for(let[a,l]of o){let c=i();if(c.sessions<=s.maxSessions&&c.rows<=s.maxRowsTotal&&c.bytes<=s.maxBytesTotal)break;Oh(e,l),n[a]={...l,rowCount:0,byteCount:0,ranges:[]}}e.yeaftHistoryCacheState=n}function Rc(e,t,s,n=Date.now()){if(!t||!s)return;let r=ve(t,s),i=e.yeaftHistoryCacheState?.[r];i&&(e.yeaftHistoryCacheState={...e.yeaftHistoryCacheState||{},[r]:{...i,lastAccessed:n}})}function zn(e,{conversationId:t,agentId:s,sessionId:n,incomingRows:r=[],activeAgentId:i=null,activeSessionId:o=null,now:a=Date.now(),limits:l=Tc}={}){if(!e||!t||!s||!n)return;Hh(e,{conversationId:t,agentId:s,sessionId:n,incomingRows:r,now:a,limits:l});let c=i&&o?ve(i,o):null;Fh(e,c,l)}var Tc,ii=N(()=>{sn();ni();Tc=Object.freeze({maxSessions:8,maxRowsPerSession:600,maxBytesPerSession:4*1024*1024,maxRowsTotal:2400,maxBytesTotal:16*1024*1024,recentRowsFloor:100})});function Cs(e){return String(e||"").trim()||null}function na(e,t,s){return[e,t,s].map(n=>String(n||"")).join("")}function Ec(){return globalThis.indexedDB||null}function qh(){let e=Ec();return!!e&&typeof e.open=="function"}function Wh(){return typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function As(e){return new Promise((t,s)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>s(e.error||new Error("IndexedDB request failed"))})}function Ot(e){return new Promise((t,s)=>{e.oncomplete=()=>t(),e.onerror=()=>s(e.error||new Error("IndexedDB transaction failed")),e.onabort=()=>s(e.error||new Error("IndexedDB transaction aborted"))})}async function Xn(){return qh()?Yn||(Yn=new Promise((e,t)=>{let s=Ec().open(Bh,Nh);s.onupgradeneeded=()=>{let n=s.result;n.objectStoreNames.contains(et)?s.transaction.objectStore(et).clear():n.createObjectStore(et,{keyPath:"key"}).createIndex("ownerAccess",["ownerId","lastAccessed"]),n.objectStoreNames.contains(lt)||n.createObjectStore(lt,{keyPath:"key"})},s.onsuccess=()=>{s.result.onversionchange=()=>s.result.close(),e(s.result)},s.onerror=()=>t(s.error||new Error("Failed to open history cache")),s.onblocked=()=>t(new Error("History cache upgrade is blocked"))}).catch(e=>{throw Yn=null,e}),Yn):null}function ns(e){return!!e&&!!Qn&&e.ownerId===Qn&&e===Zn}function oi(e,t){return!!e&&!!t&&e.key===Is&&e.ownerId===t.ownerId&&e.generation===t.generation}function jh(e){try{return JSON.parse(JSON.stringify(e))}catch{return null}}function Uh(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}function Kh(e){let t=e?.stableKey||e?.uiKey;if(t)return String(t);let s=Kn(e),n=[e?.type||"",e?.toolName||"",e?.toolCallId||"",e?.speakerVpId||e?.vpId||"",e?.id||e?.messageId||""].join(":");return`${s}:projection:${n}`}function zh(e,t){let s=[],n=null;for(let[d,u]of(Array.isArray(e)?e:[]).entries()){let f=jh(u);if(!wt(f)||(f.type==="user"&&(n={firstIndex:d,entries:[],rowsByKey:new Map},s.push(n)),!n))continue;let p=Kh(f),g=n.rowsByKey.get(p);g?n.entries[g.entryIndex]={row:f,index:d}:(n.rowsByKey.set(p,{entryIndex:n.entries.length}),n.entries.push({row:f,index:d}))}let r=s.slice().reverse().map(d=>({...d,rowCount:d.entries.length,bytes:d.entries.reduce((u,f)=>u+Uh(f.row),0)})),i=[],o=0,a=0,l=Number.isFinite(t.maxTurnsPerSession)?Math.max(0,Math.floor(t.maxTurnsPerSession)):sa.maxTurnsPerSession;for(let d of r){let u=i.length>=l,f=o+d.rowCount>t.maxRowsPerSession||a+d.bytes>t.maxBytesPerSession;if(u||i.length>0&&f)break;i.push(d),o+=d.rowCount,a+=d.bytes}return{rows:i.flatMap(d=>d.entries).sort((d,u)=>d.index-u.index).map(d=>d.row),bytes:a,turns:i.length}}async function Yh(e){let t=await Xn(),s=Wh();if(!t)return e.generation=s,!0;let n=t.transaction([lt,et],"readwrite"),r=n.objectStore(lt),i=n.objectStore(et),o=await As(r.get(Is)),a=!Gn&&!!e.ownerId&&o?.ownerId===e.ownerId&&typeof o?.generation=="string",l=a?o.generation:s;return a||i.clear(),r.put({key:Is,ownerId:e.ownerId,generation:l}),await Ot(n),e.generation=l,!0}function Dc(e){return Ss=Ss.catch(()=>{if(!Gn)throw new Error("Browser history owner cleanup failed")}).then(()=>Yh(e)).then(s=>(Gn=!1,s),s=>{throw Gn=!0,s}),Ss.catch(()=>{}),Ss}async function Gh(e,t){let s=await Xn();if(!s)return;let n=s.transaction([lt,et],"readwrite"),r=await As(n.objectStore(lt).get(Is)),i=n.objectStore(et);if(!oi(r,e)){await Ot(n);return}let o=(await As(i.getAll())).filter(l=>l?.ownerId===e.ownerId).sort((l,c)=>(Number(c.lastAccessed)||0)-(Number(l.lastAccessed)||0)),a=Date.now()-t.maxAgeMs;o.forEach((l,c)=>{(c>=t.maxSessionsPerOwner||(Number(l.lastAccessed)||0)<a)&&i.delete(l.key)}),await Ot(n)}function Lc(e){let t=Cs(e);return t?((Qn!==t||Gn)&&(Qn=t,Zn={ownerId:t,generation:null},Dc(Zn)),rs()):(ra(),null)}function ra(){return Qn=null,Zn=null,Dc({ownerId:null,generation:null})}function rs(){return Zn}async function $c({fence:e,agentId:t,sessionId:s,limits:n=sa}={}){let r=Cs(t),i=Cs(s);if(!ns(e)||!r||!i)return null;try{await Ss;let o=await Xn();if(!o||!ns(e))return null;let a=na(e.ownerId,r,i),l=o.transaction([lt,et],"readwrite"),c=await As(l.objectStore(lt).get(Is)),d=l.objectStore(et);if(!oi(c,e))return await Ot(l),null;let u=await As(d.get(a)),f=Date.now()-n.maxAgeMs,p=!!u&&(Number(u.lastAccessed)||0)<f;return p&&d.delete(a),await Ot(l),p||!ns(e)||u?.schemaVersion!==_c||u.ownerId!==e.ownerId||u.agentId!==r||u.sessionId!==i||!Array.isArray(u.rows)?null:u}catch{return null}}async function Vc({fence:e,agentId:t,sessionId:s,rows:n,historyState:r=null,limits:i=sa}={}){let o=Cs(t),a=Cs(s);if(!ns(e)||!o||!a)return!1;let l=zh(n,i);if(l.rows.length===0)return!1;try{await Ss;let c=await Xn();if(!c||!ns(e))return!1;let d=Date.now(),u=c.transaction([lt,et],"readwrite"),f=await As(u.objectStore(lt).get(Is));return oi(f,e)?(u.objectStore(et).put({key:na(e.ownerId,o,a),schemaVersion:_c,ownerId:e.ownerId,agentId:o,sessionId:a,rows:l.rows,turnCount:l.turns,rowCount:l.rows.length,byteCount:l.bytes,latestSeq:Number.isFinite(r?.latestSeq)?r.latestSeq:null,streamId:typeof r?.streamId=="string"?r.streamId:null,revision:Number.isFinite(r?.revision)?r.revision:null,oldestSeq:Number.isFinite(r?.oldestSeq)?r.oldestSeq:null,hasMore:!!r?.hasMore,lastAccessed:d}),await Ot(u),ns(e)?(Gh(e,i).catch(()=>{}),!0):!1):(await Ot(u),!1)}catch{return!1}}async function ia({fence:e,agentId:t,sessionId:s}={}){let n=Cs(t),r=Cs(s);if(!ns(e)||!n||!r)return!1;await Ss;let i=await Xn();if(!i)return!0;if(!ns(e))return!1;let o=i.transaction([lt,et],"readwrite"),a=await As(o.objectStore(lt).get(Is));return oi(a,e)?(o.objectStore(et).delete(na(e.ownerId,n,r)),await Ot(o),!0):(await Ot(o),!0)}var Bh,Nh,et,lt,Is,_c,sa,Qn,Zn,Yn,Ss,Gn,oa=N(()=>{ii();Bh="yeaft-history-cache",Nh=4,et="sessions",lt="metadata",Is="active-owner",_c=3,sa=Object.freeze({maxSessionsPerOwner:12,maxTurnsPerSession:500,maxRowsPerSession:600,maxBytesPerSession:4*1024*1024,maxAgeMs:720*60*60*1e3}),Qn=null,Zn=null,Yn=null,Ss=Promise.resolve(!0),Gn=!1});function Zh(){try{globalThis.Pinia?.useChatStore?.()?.clearYeaftHistoryMemory?.()}catch{}}function Hc(e){return String(e||"").trim()||null}function Oc(e,t){let s=Hc(rs()?.ownerId),n=Hc(e);return s!==n&&Zh(),t(n)}function Ct(e){return Oc(e,Lc)}function Xh(){return Oc(null,()=>ra())}var Qh,Jh,De,kt=N(()=>{ei();Go();oa();({defineStore:Qh}=Pinia);Jh=1800*1e3,De=Qh("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),Ct(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),Ct(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),Ct(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),Ct(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),Ct(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),Ct(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),Ct(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),Ct(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");return i&&this.token===e&&(!o||o===e)&&(this.token=i,localStorage.setItem("authToken",i)),r?.role&&(this.role=r.role),this.userId=r?.userId||null,bt(this.userId),Ct(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).catch(r=>{}),!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),Ct(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(){zo();let e=Xh();return 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,e}}})});function Le(e,t){let s=Ft?.value||"zh-CN",r=(rn[s]||rn["zh-CN"]||{})[e];if(r===void 0&&s!=="zh-CN"&&(r=(rn["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 ev(){return Ft?.value||"zh-CN"}function Jn(e){rn[e]&&(Ft&&(Ft.value=e),localStorage.setItem("locale",e),document.documentElement.setAttribute("lang",e))}function tv(){let e=localStorage.getItem("locale");return e&&rn[e]?e:(navigator.language||navigator.userLanguage||"").startsWith("en")?"en":"zh-CN"}function Fc(e,t){return rn=t,Ft=Vue.ref(tv()),document.documentElement.setAttribute("lang",Ft.value),e.config.globalProperties.$t=Le,e.config.globalProperties.$locale=Ft,e.provide("t",Le),e.provide("locale",Ft),{t:Le,setLocale:Jn,getLocale:ev,locale:Ft}}var Ft,rn,Bt=N(()=>{Ft=null,rn={}});function ai(e){if(e==null||e==="")return"claude-code";if(sv.has(e))return e;throw new Error(`Unknown Chat runtime provider: ${e}`)}function is(e){if(typeof e!="string"||!e)throw new Error("Chat catalog key requires conversationId");return`chat:${e}`}function li(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 er(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 Bc(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 Nc(e,t,s="recent",n=null){let r=is(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 aa(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 sv,la=N(()=>{sv=new Set(["claude-code","copilot"])});function on(e,t,s=""){tr&&(clearTimeout(tr),tr=null),e.sessionLoading=t,e.sessionLoadingText=s,t&&(tr=setTimeout(()=>{e.sessionLoading&&(e.sessionLoading=!1,e.sessionLoadingText=""),tr=null},nv))}function At(e){on(e,!1)}function qc(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:ai(t.provider),catalogKey:t.catalogKey||null},e.recoveryDismissed=!1)}}function Wc(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:ai(r)}),e.pendingRecovery=null,e.recoveryDismissed=!1},500)}function jc(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]=[],on(e,!0,Le("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 Kc(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 xs(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=ai(t.provider),n={sessionId:t.claudeSessionId,workDir:t.workDir,agentId:t.agentId||e.currentAgent,provider:s,catalogKey:is(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 zc(e){return e.lastUsedSession}function Yc(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 Gc(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 Qc(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 Zc(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 Xc(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 Jc(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 ed(e,t=20){if(De().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 td(e,t){if(!De().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 ca(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 sd(e,t){let s=ca(e,t);return s&&s.online}var nv,tr,Ts=N(()=>{kt();Bt();la();nv=3e4,tr=null});function nd(e){return e?.code===1008&&String(e.reason||"").toLowerCase().includes("authentication")}function rd(e){let t=sr;sr=[];for(let{resolve:s,reject:n,timer:r}of t)clearTimeout(r),e?s():n(new Error("WebSocket reconnect failed"))}function id(e,t){if(!e.ws||e.ws.readyState!==WebSocket.OPEN)return!1;if(e.currentView==="yeaft"&&iv.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=hc(t,e.sessionKey);e.ws.send(JSON.stringify(s))}else e.ws.send(JSON.stringify(t));return!0}catch{return!1}}function nr(e,t=1e4){return e.ws&&e.ws.readyState===WebSocket.OPEN?Promise.resolve():new Promise((s,n)=>{let r=setTimeout(()=>{sr=sr.filter(i=>i.resolve!==s),n(new Error("WebSocket reconnect timeout"))},t);sr.push({resolve:s,reject:n,timer:r}),(!e.ws||e.ws.readyState!==WebSocket.CONNECTING)&&(e.reconnectAttempts=0,e.connect())})}function od(e,t){try{let s=JSON.parse(t);return e.sessionKey&&yc(s)?vc(s,e.sessionKey):s}catch{return null}}function ad(e){let t=De(),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{}rd(!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){nd(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),nd(l)){t.handleAuthFailure?.(void 0,n,r),e.reconnectAttempts=0,rd(!1);return}if(e._yeaftReconnectCatchUpPending=!0,c){e.reconnectAttempts=0,e.reconnectTimer=setTimeout(()=>{e.connect()},2e3);return}e.scheduleReconnect()},e.ws.onerror=l=>{}}function ld(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 cd(e){e.reconnectAttempts=0,e.connect()}function dd(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 ud(e){e.heartbeatTimer&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=null)}function pd(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 sr,iv,da=N(()=>{kt();ei();Ts();sr=[];iv=new Set(["sync_messages","refresh_conversation","select_conversation","cancel_execution","update_conversation_settings","ask_user_answer"])});function lv(e){return e?.type==="tool-use"}function ua(e){return e?.type==="tool-summary"}function pa(e){return lv(e)&&!av.has(e.toolName)}function md(e,t,s,n=s){let r=t==="history"&&(n?.dbMessageId||n?.id)||null;return{...r?{id:`tool_summary_${t}_${r}`,dbMessageId:n?.dbMessageId||null}:{},type:"tool-summary",count:e,omittedCount:e,source:t,isHistory:t!=="live",timestamp:s?.timestamp||s?.startTime||n?.timestamp||n?.startTime||null,sessionId:s?.sessionId??s?.groupId??null,turnId:s?.turnId||null,vpId:s?.vpId||null,speakerVpId:s?.speakerVpId||null}}function cv(e,t){return!ua(e)||!ua(t)?!1:(e.turnId||null)===(t.turnId||null)&&(e.sessionId||null)===(t.sessionId||null)&&(e.speakerVpId||e.vpId||null)===(t.speakerVpId||t.vpId||null)&&(e.source||null)===(t.source||null)}function dv(e,t){let s=(Number(e.count)||0)+(Number(t.count)||0);return e.count=s,e.omittedCount=s,!e.timestamp&&t.timestamp&&(e.timestamp=t.timestamp),Number(t.dbMessageId||0)>Number(e.dbMessageId||0)&&(e.dbMessageId=t.dbMessageId,t.id&&(e.id=t.id)),e}function fd(e){return[e?.sessionId||"",e?.turnId||"",e?.speakerVpId||e?.vpId||""].join("")}function gd(e,t,s,n,r=n){if(!t)return;let i=md(t,s,n,r),o=e[e.length-1];cv(o,i)?dv(o,i):e.push(i)}function fa(e=[]){let t=[],s=0,n=null,r=null;for(let i of e){if(pa(i)&&i.isHistory){s+=1,n||(n=i),r=i;continue}gd(t,s,"history",n,r),s=0,n=null,r=null,t.push(i)}return gd(t,s,"history",n,r),t}function hd(e=[],t={}){let s=Number.isFinite(t.maxDetailed)?Math.max(1,t.maxDetailed):100;if(!Array.isArray(e)||e.length<=s)return e;let n=e.length;for(let p=e.length-1;p>=0;p-=1){let g=e[p];if(g?.type==="user"||g?.type==="system"||g?.type==="error")break;n=p}let r=e.slice(n),i=new Map;for(let p of r){if(!pa(p)||p.isHistory)continue;let g=fd(p);i.set(g,(i.get(g)||0)+1)}let o=new Map;for(let[p,g]of i)g>s&&o.set(p,g-s);if(o.size===0)return e;let a=new Map,l=new Map,c=new Set,d=[],u=(p,g,m)=>{a.set(p,(a.get(p)||0)+g),!l.has(p)&&m&&l.set(p,m)},f=(p,g)=>{if(c.has(p))return;let m=a.get(p)||0;m<=0||(d.push(md(m,"live",l.get(p)||g)),c.add(p))};for(let p of r){let g=fd(p);if(ua(p)&&p.source==="live"&&o.has(g)){u(g,Number(p.count)||0,p);continue}if(pa(p)&&!p.isHistory&&o.has(g)){let m=o.get(g)||0;if(m>0){o.set(g,m-1),u(g,1,p);continue}}f(g,p),d.push(p)}for(let p of a.keys())f(p,l.get(p));return e.splice(n,e.length-n,...d),e}var av,ga=N(()=>{av=new Set(["TodoWrite","AskUserQuestion"])});function ma(e,t){return t?t===e.yeaftConversationId?!0:Object.values(e.yeaftConversationIdsByAgent||{}).includes(t):!1}function rr(e,t,s){s&&(s.type!=="assistant"&&s.type!=="tool-use"||ma(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 pv(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 ci(e){let t=e?.stableKey??e?.messageId??e?.dbMessageId??e?.id;return t==null||t===""?null:String(t)}function ha(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 Ms(e,t,s){for(let n of Array.isArray(s)?s:[])ha(e,t,n);return s}function va(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 ui(e=[],t=[]){let s=[],n=new Map,r=new Map;for(let i of[...e,...t]){if(!i)continue;let o=ci(i),a=i.type==="user"&&i.clientMessageId?String(i.clientMessageId):null;if(o&&n.has(o)){va(n.get(o),i);continue}if(a&&r.has(a)){let l=r.get(a);va(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 vd(e,t,s){return!e||e!==t?!1:!s?.loaded&&!s?.loading}function yd(e,t){return!!t&&!!e?.loaded&&!e?.loading&&Number.isFinite(e?.latestSeq)}function bd({sessionState:e,hasCachedSessionRows:t,force:s=!1}={}){return e?.loading?!1:s?!e?.loaded:e?.loaded?!1:!t}function fv(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"&&ci(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,rr(e,t,o),!0):!1}function di(e,t,s){if(!t)return;let n={...s};ha(e,t,n);let r={...n,id:s.dbMessageId||s.id||Date.now().toString()+Math.random().toString(36).substr(2,9),timestamp:pv(s)};if(ma(e,t)&&!r.sessionId&&(r.sessionId=e._currentYeaftSessionId||e.yeaftActiveSessionFilter||uv),ma(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?jn(o,r.sessionId,a):ss(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),rr(e,t,r)}e.messagesMap[t]||(e.messagesMap[t]=[]),ha(e,t,r);let i=ci(s);if(i){let o=e.messagesMap[t].find(a=>ci(a)===i);if(o)return va(o,r),t===e.yeaftConversationId&&e.messagesMap[t].sort((a,l)=>a.timestamp-l.timestamp),o}return e.messagesMap[t].push(r),hd(e.messagesMap[t]),t===e.yeaftConversationId&&e.messagesMap[t].sort((o,a)=>o.timestamp-a.timestamp),r}function wd(e,t,s,n={}){if(!t||!s)return;e.messagesMap[t]||(e.messagesMap[t]=[]);let r=e.messagesMap[t];if(fv(e,t,n,s))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(rr(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}di(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(rr(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 di(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 kd(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())),rr(e,t,o),o.type==="user")break}}function Sd(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 Id(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 Ps(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 Cd(e){return{id:e.id,dbMessageId:e.id,timestamp:e.created_at}}function Ad(e){return e?e.message_type==="tool_use"&&!gv.has(e.tool_name)?{...Cd(e),type:"tool-use",toolName:e.tool_name||"unknown",hasResult:!0,isHistory:!0,startTime:e.created_at||0}:ya(e):null}function ya(e){if(!e)return null;let t=Cd(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 uv,gv,ir=N(()=>{ga();sn();uv="grp_default";gv=new Set(["TodoWrite","AskUserQuestion"])});function Rs(e,t){return e._closedAt?.[t]?Date.now()-e._closedAt[t]<3e4:!1}function an(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 pi(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)?cn(e,t):an(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 or(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 ln(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]&&cn(e,t)))}function xd(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 cn(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 os=N(()=>{});function ba(e,t){return t&&Array.isArray(e?._yeaftRetiredConversationIdsByAgent?.[t])?e._yeaftRetiredConversationIdsByAgent[t]:[]}function dn(e,t,s){return!t||!s?!1:ba(e,t).includes(s)}function wa(e,t){let s=e?._yeaftRetiredConversationTargetsByAgent?.[t];return s&&typeof s=="object"?s:{}}function Td(e,t,s){if(!t||!s)return null;let n=wa(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 ar(e,t,s,n=null){if(!t||!s)return;let r=ba(e,t).filter(a=>a!==s).concat(s).slice(-8);e._yeaftRetiredConversationIdsByAgent={...e._yeaftRetiredConversationIdsByAgent||{},[t]:r};let i=wa(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 ka(e,t,s){if(!t||!s||!e?._yeaftRetiredConversationIdsByAgent)return;let n=ba(e,t).filter(i=>i!==s);e._yeaftRetiredConversationIdsByAgent={...e._yeaftRetiredConversationIdsByAgent,[t]:n};let r={...wa(e,t)};delete r[s],e._yeaftRetiredConversationTargetsByAgent={...e._yeaftRetiredConversationTargetsByAgent||{},[t]:r}}var fi=N(()=>{});function vv(e,t,s){let n=e.messagesMap?.[t]||[],r=e.messagesMap?.[s]||[];e.messagesMap||(e.messagesMap={}),Ms(e,t,n),Ms(e,s,r),e.messagesMap[s]=ui(r,n).sort((i,o)=>{let a=Number.isFinite(i?.seq)?i.seq:null,l=Number.isFinite(o?.seq)?o.seq:null;return a!==null&&l!==null&&a!==l?a-l:a!==null&&l===null?-1:a===null&&l!==null?1:(i?.timestamp||0)-(o?.timestamp||0)})}function yv(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 gi(e,t){return!!e&&Object.prototype.hasOwnProperty.call(e,t)}function un(e,t,s,{removeSource:n}){gi(e,t)&&(gi(e,s)||(e[s]=n?e[t]:yv(e[t])),n&&delete e[t])}function xt(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 mi(e,t,s,n){return!t||!s||!n||s===n?!1:(e._yeaftPendingConversationPromotions={...e._yeaftPendingConversationPromotions||{},[t]:{sourceConversationId:s,targetConversationId:n}},!0)}function lr(e,t,s=null){let n=xt(e,t,s);if(!n)return null;let r={...e._yeaftPendingConversationPromotions||{}};return delete r[t],e._yeaftPendingConversationPromotions=r,n}function cr(e,t,s){let n=xt(e,t);return!n||!s||n.targetConversationId===s?null:(Tt(e,n.targetConversationId,s,{removeSource:!0}),ar(e,t,n.targetConversationId,s),mi(e,t,n.sourceConversationId,s),n)}function Tt(e,t,s,{removeSource:n=!0}={}){if(!t||!s||t===s)return!1;vv(e,t,s),e.yeaftHistoryCacheState&&(e.yeaftHistoryCacheState=Object.fromEntries(Object.entries(e.yeaftHistoryCacheState).map(([c,d])=>[c,d?.conversationId===t?{...d,conversationId:s}:d]))),un(e.processingConversations,t,s,{removeSource:n}),un(e.executionStatusMap,t,s,{removeSource:n}),un(e.refreshingSessionMap,t,s,{removeSource:n}),un(e._closedAt,t,s,{removeSource:n}),un(e._autoRefreshed,t,s,{removeSource:n}),un(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=gi(e.sessionHealth,s),d=e.sessionHealth?.[s],u=gi(e._autoRefreshed,s),f=e._autoRefreshed?.[s];cn(e,s),c&&(e.sessionHealth||(e.sessionHealth={}),e.sessionHealth[s]=d),u&&(e._autoRefreshed||(e._autoRefreshed={}),e._autoRefreshed[s]=f)}return n&&e.messagesMap&&delete e.messagesMap[t],!0}var Sa=N(()=>{ir();fi();os()});function hi(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 Ia=N(()=>{});function Ca(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function bv(){return Date.now()}function wv(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`pt_${crypto.randomUUID()}`:`pt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}function kv(e,t=160){return typeof e!="string"?e:e.length>t?`${e.slice(0,t)}...[truncated]`:e}function Sv(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"?kv(n):n);return t}function _s(){return wv()}function Ge(e,t={}){!e||!t.traceId||(Array.isArray(e._perfTraceQueue)||(e._perfTraceQueue=[]),e._perfTraceQueue.push({traceId:t.traceId,source:"web",phase:t.phase||"unknown",at:bv(),monotonicMs:Ca(),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:Sv(t.detail)}),e._perfTraceQueue.length>200&&e._perfTraceQueue.splice(0,e._perfTraceQueue.length-200),Iv(e))}function Iv(e){!e||e._perfTraceFlushTimer||(e._perfTraceFlushTimer=setTimeout(()=>Cv(e),250))}function Cv(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 vi(e,t={}){if(typeof requestAnimationFrame!="function")return;let s=Ca();requestAnimationFrame(()=>{requestAnimationFrame(()=>{Ge(e,{...t,phase:t.phase||"render.next_paint",durationMs:Ca()-s})})})}var Aa=N(()=>{});function Mt(e){return Number.isFinite(e)?Number(e):null}function Av(e){return(Array.isArray(e)?e:[]).map(t=>({startSeq:Mt(t?.startSeq),endSeq:Mt(t?.endSeq)})).filter(t=>t.startSeq!==null&&t.endSeq!==null&&t.startSeq<=t.endSeq).sort((t,s)=>t.startSeq-s.startSeq)}function dr(e){return Number.isFinite(e)&&e>=0?Math.floor(e):0}function Es(e){let t=Mt(e?.beforeSeq);if(t===null)return null;if(e?.kind==="gap"){let s=Mt(e.stopAtSeq);return s===null?null:`gap:${dr(e.cacheEpoch)}:${s}:${t}`}return`server:${t}`}function ur(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 xv(e,t){let s=Es(t);if(!s)return e.completedHistoryWorkKeys||[];let n=ur(e);return n.add(s),Array.from(n).slice(-256)}function Tv(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 Mv(e,t={},s=0){let n=Av(e),r=dr(s),i=ur(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=Es(d),i.has(d.workKey)||o.push(d)}return o.sort((a,l)=>l.beforeSeq-a.beforeSeq)}function Md(e,t,s){let n=Mv(e,t,s),r=Mt(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=Es(o),ur(t).has(o.workKey)?[]:[o]}function Pd(e={},t=[],s=0){let n=dr(s),r=ur(e),i=e.serverHasMore!==!1,o=Mt(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=Es(u),r.has(u.workKey)?(i=!1,d="history_cursor_repeated"):c=u}return!c&&!i&&(a||(l=Md(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 Rd(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=dr(a),c=Mt(s),d=Mt(e.pendingPageBeforeSeq),u=i||e.pendingPageKind||(t==="older"?"server":null),f=Mt(o??e.pendingGapStopAtSeq),p=dr(e.pendingCacheEpoch??l),g={kind:u,beforeSeq:d,stopAtSeq:f,cacheEpoch:p},m=Mt(e.serverOldestFetchedSeq??e.oldestSeq),v=e.serverHasMore!==!1,k=Number(e.noProgressCount)||0,w=null,I=e.requestedBeforeSeqs||[],h=e.completedHistoryWorkKeys||[],y=e.gapTraversalInitialized===!0,b=Array.isArray(e.gapQueue)?e.gapQueue.slice():[];if(t==="recent")m=c,v=!!n,k=0,I=[],h=[],y=!1,b=[];else if(d===null)c!==null&&(m=m===null?c:Math.min(m,c)),v=!!n,k=0;else{I=Tv(e,d),h=xv(e,g);let x=c!==null&&c<d;if(u==="server")x?(m=m===null?c:Math.min(m,c),v=!!n,k=0):(v=!1,k+=1,w="history_cursor_no_progress");else if(u==="gap"){let D=Es(g);b=b.filter(E=>Es(E)!==D);let V=f!==null&&c!==null&&c<=f;if(x||V||n===!1){if(k=0,!V&&n!==!1&&c!==null&&f!==null){let E={kind:"gap",beforeSeq:c,stopAtSeq:f,cacheEpoch:p};E.workKey=Es(E),ur({completedHistoryWorkKeys:h}).has(E.workKey)||b.unshift(E)}}else k+=1,w="history_cursor_no_progress"}}t==="older"&&!v&&!y&&(b=Md(r,{...e,serverOldestFetchedSeq:m,completedHistoryWorkKeys:h},l),y=!0);let M={...e,serverOldestFetchedSeq:m,serverHasMore:v,requestedBeforeSeqs:I,completedHistoryWorkKeys:h,gapTraversalInitialized:y,gapQueue:b,noProgressCount:k,oldestSeq:m,paginationError:w};return delete M.pendingPageKind,delete M.pendingPageBeforeSeq,delete M.pendingGapStopAtSeq,delete M.pendingCacheEpoch,delete M.pendingHistoryWorkKey,{...M,hasMore:v||b.length>0}}var xa=N(()=>{});function $d(e){return e.filter(t=>!(t.type==="user"&&(!t.content||!t.content.trim())))}function Ds(e){let t=typeof e=="string"?e.match(/^m(\d+)$/):null,s=t?Number(t[1]):null;return Number.isFinite(s)?s:null}function _d(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 Pv(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 Rv(e){return Array.isArray(e?.toolCalls)?e.toolCalls.filter(t=>t?.name!=="TodoWrite").length:Number(e?.toolSummaryCount||0)||0}function _v(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 Ev(e,t){return e.speakerVpId||e.vpId||e.vp_id||e.authorVpId||e.authorVP||_v(t)}function yi(e){return e?.stableKey||(e&&(e.messageId||e.id)?e.messageId||e.id:null)}function Dv(e,t=null){if(!e||e.stableKey)return e;let s=pr(e),n=e.messageId||e.id||null,r=e.type==="user"&&e.clientMessageId||null;return e.stableKey=r&&n===r?ss(t,s,r):jn(t,s,n),Number.isFinite(e.seq)||(e.seq=Ds(n)),e.uiKey||(e.uiKey=e.stableKey||null),e}function Lv(e){return!e||e.isHistory===!0?!1:e.isStreaming||Vd(e)?!0:!Number.isFinite(e.seq)&&Number.isFinite(e.timestamp)}function Ed(e){let t=Lv(e),s=Number.isFinite(e?.seq)?e.seq:null,n=Number.isFinite(e?.timestamp)?e.timestamp:0;return t?[2,n,s??0]:[1,n,s??-1]}function $v(e){e.sort((t,s)=>{let n=Ed(t),r=Ed(s);for(let i=0;i<n.length;i+=1)if(n[i]!==r[i])return n[i]-r[i];return 0})}function Vv(e,t){if(!e||!t||e.type!=="assistant"||t.type!=="assistant"||(e.sessionId??null)!==(t.sessionId??null))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||!(e.isStreaming||e.isHistory!==!0)||t._hasPersistedTurnId!==!0)return!1;let a=e.turnId||"",l=t.turnId||"";if(!a||!l||a!==l)return!1;let c=typeof e.content=="string"?e.content:"",d=typeof t.content=="string"?t.content:"";return!!c&&!!d&&(d.startsWith(c)||c.startsWith(d))}function Ta(e,t){let s=new Map,n=new Map;e.forEach((i,o)=>{let a=yi(i);a&&s.set(a,o),i?.type==="user"&&i.clientMessageId&&n.set(i.clientMessageId,o)});let r=0;for(let i of t){let o=yi(i),a=o&&s.has(o)?s.get(o):null;if(a===null&&i?.type==="user"&&i.clientMessageId&&n.has(i.clientMessageId)&&(a=n.get(i.clientMessageId)),a===null&&i?.type==="assistant"&&(a=e.findIndex(l=>Vv(l,i))),a!==null&&a>=0){let l=yi(e[a]),c=e[a]?.uiKey||null;e[a]={...e[a],...i,...c?{uiKey:c}:{}},o&&s.set(o,a),l&&l!==o&&s.get(l)===a&&s.delete(l),i?.type==="user"&&i.clientMessageId&&n.set(i.clientMessageId,a)}else o&&s.set(o,e.length),i?.type==="user"&&i.clientMessageId&&n.set(i.clientMessageId,e.length),e.push(i),r+=1}return $v(e),r}function pr(e){return e?e.sessionId??e.groupId??null:null}function Vd(e){return!e||e.type!=="user"||!e.clientMessageId?!1:(e.messageId||e.id||null)===e.clientMessageId}function Hv(e,t,s){let n=e.some(a=>a&&(s==null||pr(a)===s));if(t.length===0&&n)return{insertedRows:0,preservedEmpty:!0};let r=t.reduce((a,l)=>Math.max(a,l?.timestamp||0),0),i=e.filter(a=>a?s!=null&&pr(a)!==s||wt(a)||a.isStreaming||a.type==="tool-use"&&a.toolName==="AskUserQuestion"&&(a.askAnswered||a.askPending||a.askExpired)||Vd(a)?!0:r>0&&(a.timestamp||0)>r:!1);return e.splice(0,e.length,...i),{insertedRows:Ta(e,t),preservedEmpty:!1}}function Ov(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 Fv(e,t){let s=typeof e.yeaftConversationId=="string"?e.yeaftConversationId:"";return s.startsWith(`yeaft-local-${t}-`)||/^yeaft-local-\d/.test(s)?s:null}function Bv(e,t,s,n){let r=t.agentId||s&&e.yeaftSessionAgentById?.[s]||null;if(!r||!n||e.currentView!=="yeaft")return;let i=Ht(e);if(i.sessionId!==(s||null)||i.agentId&&i.agentId!==r)return;let o=e.yeaftConversationId||null;if(dn(e,r,n)){let d=e.yeaftConversationIdsByAgent?.[r]||null;d&&d!==n&&Tt(e,n,d,{removeSource:n!==e.yeaftConversationId});return}let a=xt(e,r);a&&a.targetConversationId!==n&&cr(e,r,n);let l=xt(e,r,n);if(l&&(Tt(e,l.sourceConversationId,n,{removeSource:!0}),lr(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=Fv(e,r);c&&(Tt(e,c,n,{removeSource:!0}),e.yeaftConversationIdsByAgent={...e.yeaftConversationIdsByAgent||{},[r]:n},e.yeaftConversationId=n,e.activeConversations=[n])}function as(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 Hd(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:Le("store.convCreated",{agent:s?.name||t.agentId,workDir:t.workDir})}),e.saveOpenSessions()}function Od(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:Le("store.convResumed",{agent:s?.name||t.agentId,sessionId:t.claudeSessionId?t.claudeSessionId.slice(0,8)+"...":""})}),t.dbMessages&&t.dbMessages.length>0){let n=$d(t.dbMessages.map(o=>e.formatDbMessageForHistoryHydration(o)).flat().filter(Boolean)),r=fa(n),i=e.messagesMap[t.conversationId]||[];for(let o of r)i.push(o)}e.hasMoreMessages=!!t.hasMoreMessages,e.chatSessionState[t.conversationId]={lastSeenDbId:Ps(e.messagesMap[t.conversationId]),hasMoreOlder:!!t.hasMoreMessages},e.saveOpenSessions()}function Ma(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:Le("chat.session.closed")}));for(let n of e.panels)n.conversationId===t.conversationId&&(n.conversationId=null);e.saveOpenSessions()}function Fd(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),as(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 Bd(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),as(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 Nd(e,t){if(t.conversationId){if(t.isProcessing&&!Rs(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 qd(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),as(e,s)}}function Wd(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=fa($d((t.messages||[]).map(a=>e.formatDbMessageForHistoryHydration(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&&hi(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:Ps(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 jd(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:[]);for(let c of e.messagesMap[r]){let d=c?.persistedMessageId||c?.messageId||c?.id||null;!t.entryId||!i.has(d)||(c.historyEntryId=t.entryId,Number.isFinite(t.indexGeneration)&&(c.historyIndexGeneration=t.indexGeneration))}let o=t.messages.map(c=>t.entryId&&i.has(c?.id)?{...c,historyEntryId:t.entryId,...t.prefetch===!0?{_historyWindowPrefetched:!0}:{},...Number.isFinite(t.indexGeneration)?{historyIndexGeneration:t.indexGeneration}:{}}:c),{formatted:a}=Ud(o,s,"window",e.messagesMap[r],n);if(t.prefetch===!0)for(let c of a)c._historyWindowPrefetched=!0;Ta(e.messagesMap[r],a);let l=Ht(e);return zn(e,{conversationId:r,agentId:n,sessionId:s,incomingRows:a,activeAgentId:l.agentId,activeSessionId:l.sessionId}),r}function Dd(e){return e?.toolId?[pr(e)??"",e.vpId||e.speakerVpId||"",e.turnId||"",e.threadId||"main",e.toolId].join("\0"):null}function Ld(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 Nv(e,t){return(e||[]).find(s=>s?.type==="tool-use"&&(s.toolName==="AskUser"||s.toolName==="AskUserQuestion")&&s.toolId===t.toolCallId&&pr(s)===t.sessionId&&(s.vpId||s.speakerVpId||"")===(t.vpId||"")&&(s.turnId||"")===(t.turnId||"")&&(s.threadId||"main")===(t.threadId||"main"))||null}function Ud(e,t,s,n,r=null){let i=new Set((n||[]).map(c=>yi(Dv(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||Ov(c.content))continue;let d=c.id||c.messageId||null,u=c.clientMessageId||null,f=c.sessionId??c.groupId??t??null,p=jn(r,f,d),g=u?ss(r,f,u):p,m=c.historyEntryId?{historyEntryId:c.historyEntryId,...Number.isFinite(c.historyIndexGeneration)?{historyIndexGeneration:c.historyIndexGeneration}:{}}:{};if(!(p&&o.has(p))&&!(p&&s!=="recent"&&i.has(p))){if(p&&o.add(p),c.role==="user"){l+=1;let v=d||c.messageId||c.turnId||null;a.push({...d?{id:d,messageId:d}:{},...p?{stableKey:p}:{},...g?{uiKey:g}:{},...m,seq:Number.isFinite(c.seq)?c.seq:Ds(d),type:"user",content:c.content,timestamp:_d(c),sessionId:f,turnId:c.turnId||v,...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 v=d||c.messageId||c.turnId||null,k=Ev(c,f),w=_d(c),I=!!c.turnId,h=c.turnId||v,y=typeof c.content=="string"?c.content:c.content||"",b=Array.isArray(c.todos)?c.todos:Pv(c.toolCalls),M=c.executionOrigin==="route_forward"?{executionOrigin:"route_forward"}:{};(typeof y!="string"||y.trim())&&a.push({...d?{id:d,messageId:d}:{},...p?{stableKey:p}:{},...g?{uiKey:g}:{},...m,seq:Number.isFinite(c.seq)?c.seq:Ds(d),...c.entryId?{entryId:c.entryId}:{},...Array.isArray(c.sourceMessageIds)?{sourceMessageIds:c.sourceMessageIds}:{},type:"assistant",content:y,timestamp:w,sessionId:f,turnId:h,_hasPersistedTurnId:I,...M,...k?{vpId:k,speakerVpId:k}:{},...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(b)&&b.length>0&&a.push({...d?{id:`${d}:todos`,messageId:`${d}:todos`}:{},...p?{stableKey:`${p}:todos`}:{},...m,seq:Number.isFinite(c.seq)?c.seq:Ds(d),type:"tool-use",toolName:"TodoWrite",toolInput:{todos:b},timestamp:w,sessionId:f,turnId:h,...M,...k?{vpId:k,speakerVpId:k}:{},isStreaming:!1,isHistory:!0,hasResult:!0});for(let D of Array.isArray(c.images)?c.images:[])D?.assetId&&a.push({id:`${d||v||h}:image:${D.assetId}`,messageId:`${d||v||h}:image:${D.assetId}`,...p?{stableKey:`${p}:image:${D.assetId}`}:{},...m,seq:Number.isFinite(c.seq)?c.seq:Ds(d),type:"chat-image",...D,timestamp:w,sessionId:f,turnId:h,...M,...k?{vpId:k,speakerVpId:k}:{},isStreaming:!1,isHistory:!0});for(let D of Array.isArray(c.askUserResults)?c.askUserResults:[]){if(!D?.toolCallId||D.status!=="answered"&&D.status!=="expired")continue;let V=[{question:typeof D.question=="string"?D.question:"",options:(Array.isArray(D.options)?D.options:[]).filter(R=>typeof R=="string").map(R=>({label:R,description:""})),multiSelect:!1}],E={toolCallId:D.toolCallId,sessionId:f,vpId:k||"",turnId:h||"",threadId:c.threadId||"main"},_=Nv(n,E);if(_){Object.assign(_,m),Ld(_,D,V);continue}let T=Ld({id:`${d||v||h}:ask:${D.toolCallId}`,messageId:`${d||v||h}:ask:${D.toolCallId}`,...p?{stableKey:`${p}:ask:${D.toolCallId}`}:{},...m,seq:Number.isFinite(c.seq)?c.seq:Ds(d),type:"tool-use",timestamp:w,sessionId:f,turnId:h,threadId:E.threadId,...M,...k?{vpId:k,speakerVpId:k}:{},isStreaming:!1},D,V),A=Dd(T);(!A||!a.some(R=>Dd(R)===A))&&a.push(T)}let x=Rv(c);x>0&&a.push({...d?{id:`${d}:tool-summary`,messageId:`${d}:tool-summary`,persistedMessageId:d}:{},...p?{stableKey:`${p}:tool-summary`}:{},...m,seq:Number.isFinite(c.seq)?c.seq:Ds(d),type:"tool-summary",count:x,omittedCount:x,source:"history",timestamp:w,sessionId:f,turnId:h,...M,...k?{vpId:k,speakerVpId:k}:{},isStreaming:!1,isHistory:!0})}}}return{formatted:a,acceptedHistoryMessages:l}}function Kd(e,t){let s=t.sessionId!=null?t.sessionId:t.groupId,n=t.agentId||s&&e.yeaftSessionAgentById?.[s]||null;if(dn(e,n,t.conversationId)){let F=e.yeaftConversationIdsByAgent?.[n]||null;if(!F||F===t.conversationId)return;Tt(e,t.conversationId,F,{removeSource:t.conversationId!==e.yeaftConversationId}),t={...t,conversationId:F}}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=ve(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}),typeof e.removeYeaftHistoryBrowserCache=="function"&&e.removeYeaftHistoryBrowserCache(o,s)),t.perfTraceId&&Ge(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,f=t.conversationId||u||e.yeaftConversationId;if(!f){e.yeaftLoadingMoreHistory=!1;return}Bv(e,t,s,f),e.messagesMap[f]||(e.messagesMap[f]=[]);let{formatted:p,acceptedHistoryMessages:g}=Ud(i,s,r,e.messagesMap[f],d);Ms(e,f,p);let m=0,v=!1;if(r==="recent"){let F=Hv(e.messagesMap[f],p,s??null);m=F.insertedRows,v=F.preservedEmpty}else if(p.length>0)if(r==="older"){if(e.messagesMap[f].splice(0,0,...p),m=p.length,typeof e.expandYeaftMessageWindow=="function"){let F=e.yeaftActiveSessionFilter?s??null:null;e.expandYeaftMessageWindow(F,t.turns||10,d)}}else m=Ta(e.messagesMap[f],p);let k=Ht(e);zn(e,{conversationId:f,agentId:d,sessionId:s,incomingRows:p,activeAgentId:k.agentId,activeSessionId:k.sessionId});let w=ve(t.agentId||null,s),I=e.yeaftHistoryCacheState?.[w]||null,h=e.yeaftSessionHistoryState?.[w]||{},y=Number.isFinite(h.serverOldestFetchedSeq)?h.serverOldestFetchedSeq:Number.isFinite(h.oldestSeq)?h.oldestSeq:null,b=Number.isFinite(t.nextBeforeSeq)?t.nextBeforeSeq:Number.isFinite(t.oldestSeq)?t.oldestSeq:v?y:null,M=v&&!Number.isFinite(t.nextBeforeSeq)&&!Number.isFinite(t.oldestSeq)?h.serverHasMore??h.hasMore??!1:t.hasMore,x=r==="delta"?h:Rd(h,{mode:r,oldestSeq:b,hasMore:M,ranges:I?.ranges||[],pageKind:t.pageKind,stopAtSeq:t.gapStopAtSeq,cacheEpoch:I?.rangeEpoch??t.cacheEpoch??0}),D=typeof t.latestSeq=="number"?t.latestSeq:h.latestSeq??null,V={streamId:typeof t.streamId=="string"?t.streamId:h.streamId??null,revision:Number.isFinite(t.revision)?t.revision:h.revision??null},E=r==="delta"?{...h,...V,loaded:!0,loading:!1,latestSeq:D,syncingAfterSeq:null,count:(h.count||0)+m}:{...x,...V,loaded:!0,loading:!1,count:I?I.rowCount:r==="older"?(h.count||0)+m:v?h.count||0:g,latestSeq:v&&!Number.isFinite(t.latestSeq)?h.latestSeq??null:D,syncingAfterSeq:null};t.requestId&&typeof e.finishYeaftHistoryLoad=="function"?e.finishYeaftHistoryLoad(t,E,"chunk"):e.yeaftSessionHistoryState&&(e.yeaftSessionHistoryState={...e.yeaftSessionHistoryState,[w]:E}),typeof e.persistYeaftHistoryBrowserCache=="function"&&e.persistYeaftHistoryBrowserCache(s,d,f),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 _=Ht(e),T=_.sessionId===(s||null),A=!t.agentId||!_.agentId||t.agentId===_.agentId,R=T&&A,j=ve(null,_.sessionId);if(t.perfTraceId&&(Ge(e,{traceId:t.perfTraceId,phase:"history.chunk_applied",agentId:t.agentId||null,sessionId:s||null,messageType:t.type,detail:{mode:r,formattedCount:p.length,insertedRows:m,acceptedHistoryMessages:g,preservedEmptyRecent:v}}),vi(e,{traceId:t.perfTraceId,phase:"history.next_paint",agentId:t.agentId||null,sessionId:s||null,messageType:t.type,detail:{mode:r,insertedRows:m}})),R)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 F=e.yeaftSessionHistoryState?.[_.sessionKey]||e.yeaftSessionHistoryState?.[j]||null;e.yeaftLoadingMoreHistory=!!F?.loading}}var bi=N(()=>{os();Sa();fi();Ts();Ia();ir();ga();Bt();Aa();ni();sn();ii();xa()});function zd(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 qv(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 Pa(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=Pa(e,t);if(r.lastActivity=Date.now(),pi(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_summary"?e.addMessageToConversation(t,{type:"tool-summary",count:Number(a.count||a.omittedCount||0)||0,omittedCount:Number(a.omittedCount||a.count||0)||0,source:a.source||"history",isHistory:a.source!=="live",sessionId:e._currentYeaftSessionId||null,vpId: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(),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=qv(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(m=>m.status==="running");g>=0&&(r.toolHistory[g].status="done")}let u=d.tool_use_id||d.toolUseId||d.tool_call_id||d.toolCallId||null,f=d.content||d,p=!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
- ${f}`:f,p=!0;break}}if(!p){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=f;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(p=>hi(p,d))){if(c){for(let p=u.length-1;p>=0;p--)if(u[p].type==="user"&&u[p].clientMessageId===c){s.dbMessageId&&!u[p].dbMessageId&&(u[p].dbMessageId=s.dbMessageId),s.message?.id&&!u[p].messageId&&(u[p].id=s.message.id,u[p].messageId=s.message.id),s.ts&&!u[p].ts&&(u[p].ts=s.ts),zd(e,u[p],n);break}}}else{let p=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}:{}});zd(e,p,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,f]=d,{[u]:p,...g}=e.activeVpTurns;!o&&f?.sessionId&&(o=f.sessionId),e.activeVpTurns=g}}if(o&&e._currentYeaftVpId&&e.vpStatuses){let d=e._currentYeaftTurnId||null,u={...e.vpStatuses||{}},f=!1;for(let[p,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[p]={...g,state:"idle",turnId:null,since:Date.now()},f=!0);f&&(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,as(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 Gd=N(()=>{os();bi();Ia()});function Ls(e){if(e==null)return e;try{return JSON.parse(JSON.stringify(e))}catch{return e}}function wi(e,t){if(!t)return e??null;if(Object.prototype.hasOwnProperty.call(t,"base"))return Ls(t.base)??null;if(Object.prototype.hasOwnProperty.call(t,"replacement"))return Ls(t.replacement)??null;let s=e&&typeof e=="object"&&!Array.isArray(e)?Ls(e):{};if(t.set&&typeof t.set=="object")for(let[n,r]of Object.entries(t.set))s[n]=Ls(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]=Ls(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]=Ls(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(Ls(t.body.messagesAppend)||[])}s.body=n}return s}function Qd(e,t){return!t||!Object.prototype.hasOwnProperty.call(t,"rawRequestDelta")?e??null:wi(e??null,t.rawRequestDelta)}function fr(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 jv(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 Zd(e){let t=0,s=0;if(e&&Array.isArray(e.messages))for(let i of e.messages){let{messageText:o,toolText:a}=jv(i);for(let l of o)t+=fr(l);for(let l of a)s+=fr(l)}let n=0,r=0;if(e&&typeof e.response=="string"&&(n+=fr(e.response)),e&&Array.isArray(e.toolCalls)){for(let i of e.toolCalls)if(i&&(r+=fr(String(i.name||"")),i.input!==void 0))try{r+=fr(JSON.stringify(i.input))}catch{}}return{inputMessageTokens:t,inputToolTokens:s,outputMessageTokens:n,outputToolTokens:r,inputTotalEstimated:t+s,outputTotalEstimated:n+r}}function Ra(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 Xd(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 _a=N(()=>{});function St(e,t){return!e||!t?"":`${e}${t}`}function gr(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 Ea(e){return e?`${e}`:""}function Da(e,t){return!e||!t?"":`${e}${t}`}var mr=N(()=>{});function Uv(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 Jd(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 eu(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(c=>c.id===o)||null;e.currentView==="yeaft"&&Uv(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(f=>f.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 f=e._recentlyDeletedSessions?.[d.id];if(f&&Date.now()-f<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&&!Rs(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})),e.currentView==="yeaft"&&typeof e.requestYeaftSessionBootstrap=="function"){e._yeaftReconnectCatchUpPending=!1;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 f=e.messagesMap[e.currentConversation]||[],p=Ps(f);p!=null?e.requestChatHistory?.(e.currentConversation,{mode:"delta",afterMessageId:p}):e.requestChatHistory?.(e.currentConversation,{mode:"recent",turns:5}),e.sendWsMessage({type:"refresh_conversation",conversationId:e.currentConversation})}else e.recoveryDismissed||Jd(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){Jd(e,{agentId:c.agentId,agentInfo:d});return}}}l&&(e.agents.find(d=>d.id===l&&d.online)?e.selectAgent(l):e.checkPendingRecovery())}}function tu(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(f=>f.id===e.currentConversation);u&&!a.find(f=>f.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&&!Rs(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 f=e.executionStatusMap[u.id];f&&(f.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(p=>p.id===u)){delete e.processingConversations[u],Ce(e,u);let p=e.executionStatusMap[u];p&&(p.currentTool=null),e.finishStreamingForConversation(u)}}if(e.currentView!=="yeaft"){if(n&&e.currentConversation){let u=e.conversations.find(f=>f.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(f=>f.id===u)&&(e.autoRestoreConversation(u),e.pendingRecovery=null)}Kc(e)}return!0}var su=N(()=>{os();Ts();ir()});function Kv(e={}){return{providers:e.providers||[],primaryModel:e.primaryModel||null,fastModel:e.fastModel||null,language:e.language||"en"}}function nu(){return window.Pinia?.useSessionsStore?.()||window.__useSessionsStore&&window.__useSessionsStore()}function Qv(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 Zv(e){let t=nu(),s=null;try{s=localStorage.getItem("lastViewedYeaftSession")||null}catch{}let n=gr(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 ru(e){let t=nu(),s=Zv(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 Xv(e){let t=e.yeaftSessionHydrateRequestId||null;e.yeaftSessionInventoryCompleteSupported!==!1||!t||(clearTimeout(e._legacyYeaftSessionHydrateTimer),e._legacyYeaftSessionHydrateTimer=setTimeout(()=>{e.yeaftSessionHydrateRequestId===t&&(e._legacyYeaftSessionHydrateTimer=null,ru(e),e._hasHandledYeaftSessionHydrate=!0,e.yeaftSessionHydrateRequestId=null,e.yeaftSessionHydrateError=null,e._yeaftSessionInventorySocketQuarantined=!0)},Gv))}function Jv(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=wi(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=wi(n.rawRequest,t.rawRequestDelta)),n}function ey(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=Jv(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 iu(e,t){let s=De();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||Le("login.error.loginFailed")}),s.handleAuthFailure?.(void 0,t._wsAuthToken,t._wsAuthGeneration);break;case"agent_list":eu(e,t),e.workCenterOpen&&e.workCenterAgentId&&e.listWorkItems(e.workCenterAgentId).catch(()=>{});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;Qv(e,t),e.yeaftSessionInventoryCompleteSupported!==!0&&Xv(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?ru(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(!tu(e,t))break;e.workCenterOpen&&e.workCenterAgentId&&e.listWorkItems(e.workCenterAgentId).catch(()=>{});break;case"conversation_created":Hd(e,t);break;case"conversation_resumed":Od(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":Wd(e,t);break;case"conversation_deleted":Ma(e,t);break;case"conversation_delete_result":t.ok&&Ma(e,t);break;case"turn_completed":Fd(e,t);break;case"conversation_closed":Bd(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":Kd(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:jd(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=typeof t?.requestId=="string"?t.requestId:"",r=typeof t?.detailTurnId=="string"&&t.detailTurnId,i=r?e._yeaftDebugHistoryLatestDetailRequestId:e._yeaftDebugHistoryLatestListRequestId;if(i&&n!==i||!i&&n)break;e._fetchYeaftDebugHistoryTimer&&(clearTimeout(e._fetchYeaftDebugHistoryTimer),e._fetchYeaftDebugHistoryTimer=null),e._yeaftDebugHistoryInFlightKey=null;let o=Array.isArray(t?.turns)?t.turns:[],a=t?.search?Yv:zv,l=r?o:o.slice(-a),c=new Set(l.map(b=>b?.turnId).filter(Boolean)),d=ey(Array.isArray(t?.loops)?t.loops:[]),u=r?d:d.filter(b=>!b?.turnId||c.has(b.turnId)),f=Array.isArray(t?.dreamEvents)?t.dreamEvents:[];e.yeaftDebugHistoryHasMore=!!t?.hasMore||!r&&o.length>l.length,!t?.detailTurnId&&Number.isFinite(t?.limit)&&t.limit>0&&(e.yeaftDebugHistoryLimit=Math.min(a,t.limit)),(!e.yeaftDebugTurnsById||typeof e.yeaftDebugTurnsById!="object")&&(e.yeaftDebugTurnsById={}),Array.isArray(e.yeaftDebugLoops)||(e.yeaftDebugLoops=[]),Array.isArray(e.yeaftDebugTurnOrder)||(e.yeaftDebugTurnOrder=[]);let p=r?{...e.yeaftDebugTurnsById}:{};for(let b of l){let M=b?.turnId;if(!M)continue;let x=p[M];if(x){let D=b?.detailsLoaded?{...x,...b}:{...b,...x};D.memoryLoaded==null&&x.memoryLoaded!=null&&(D.memoryLoaded=x.memoryLoaded),D.memoryAdjust==null&&x.memoryAdjust!=null&&(D.memoryAdjust=x.memoryAdjust),p[M]=D}else p[M]=b}e.yeaftDebugTurnsById=p;let g=b=>b?.loopInstanceId||`${b?.turnId||""}#${b?.loopNumber||0}`,m=e.yeaftDebugLoops,v=new Map;for(let b of m)b&&v.set(g(b),b);let k=new Set,w=[];for(let b of u){if(!b)continue;let M=g(b);k.add(M),w.push(v.get(M)||b)}if(r)for(let b of m)!b||k.has(g(b))||w.push(b);e.yeaftDebugLoops=w;let I=new Set,h=[],y=b=>{!b||I.has(b)||(I.add(b),h.push(b))};if(r){for(let b of e.yeaftDebugTurnOrder)y(b);for(let b of l)y(b?.turnId)}else for(let b of l)y(b?.turnId);e.yeaftDebugTurnOrder=r?h:h.slice(-a);for(let b of f){if(!b)continue;let M=null,x=b.sessionId||b.groupId;typeof b.target=="string"&&b.target.includes("/")?M=b.target:typeof x=="string"&&x?M=`group/${x}`:M="*",typeof e._appendDreamEvent=="function"&&e._appendDreamEvent(M,b),b.type==="dream_progress"&&typeof e.handleYeaftOutput=="function"&&e.handleYeaftOutput({event:b})}e.yeaftDebugHistoryLoading=!1,e.yeaftDebugHistoryError=typeof t?.error=="string"?t.error:null,e.yeaftDebugHistoryFetchedAt=Date.now(),r&&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 f=e.messagesMap[n];if(f){let p=f.findIndex(g=>g.id===u.id);p>=0&&f.splice(p,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 f=u.findIndex(p=>p.id===d);f>=0&&u.splice(f,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":Nd(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":qd(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),xd(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,minimumVersion:t.minimumVersion}}));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||Kv(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 zv,Yv,Gv,ou=N(()=>{kt();ei();Bt();os();Ts();_a();mr();su();bi();zv=1,Yv=5,Gv=500});function lu(){return Object.values(au).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 cu(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 $s(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 La(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(f=>f.id===l);if(!d)return null;let u;if(c&&d.actions){let f=d.actions.find(p=>p.id===c);f?s?(u=(r?f.messageTemplate:f.messageTemplateEn)||"",u+=s):u=(r?f.defaultMessage:f.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(f=>f.id===l),u=It[l];if(d)if(c){let f=d.actions?.find(p=>p.id===c);f&&o.push((r?f.messageTemplate:f.messageTemplateEn)||"")}else o.push((r?d.messagePrefix:d.messagePrefixEn)||"");else if(u)return null}return o.length===0?null:{effectivePrompt:o.join(`
3
+ ${f}`:f,p=!0;break}}if(!p){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=f;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(p=>hi(p,d))){if(c){for(let p=u.length-1;p>=0;p--)if(u[p].type==="user"&&u[p].clientMessageId===c){s.dbMessageId&&!u[p].dbMessageId&&(u[p].dbMessageId=s.dbMessageId),s.message?.id&&!u[p].messageId&&(u[p].id=s.message.id,u[p].messageId=s.message.id),s.ts&&!u[p].ts&&(u[p].ts=s.ts),zd(e,u[p],n);break}}}else{let p=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}:{}});zd(e,p,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,f]=d,{[u]:p,...g}=e.activeVpTurns;!o&&f?.sessionId&&(o=f.sessionId),e.activeVpTurns=g}}if(o&&e._currentYeaftVpId&&e.vpStatuses){let d=e._currentYeaftTurnId||null,u={...e.vpStatuses||{}},f=!1;for(let[p,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[p]={...g,state:"idle",turnId:null,since:Date.now()},f=!0);f&&(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,as(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 Gd=N(()=>{os();bi();Ia()});function Ls(e){if(e==null)return e;try{return JSON.parse(JSON.stringify(e))}catch{return e}}function wi(e,t){if(!t)return e??null;if(Object.prototype.hasOwnProperty.call(t,"base"))return Ls(t.base)??null;if(Object.prototype.hasOwnProperty.call(t,"replacement"))return Ls(t.replacement)??null;let s=e&&typeof e=="object"&&!Array.isArray(e)?Ls(e):{};if(t.set&&typeof t.set=="object")for(let[n,r]of Object.entries(t.set))s[n]=Ls(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]=Ls(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]=Ls(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(Ls(t.body.messagesAppend)||[])}s.body=n}return s}function Qd(e,t){return!t||!Object.prototype.hasOwnProperty.call(t,"rawRequestDelta")?e??null:wi(e??null,t.rawRequestDelta)}function fr(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 jv(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 Zd(e){let t=0,s=0;if(e&&Array.isArray(e.messages))for(let i of e.messages){let{messageText:o,toolText:a}=jv(i);for(let l of o)t+=fr(l);for(let l of a)s+=fr(l)}let n=0,r=0;if(e&&typeof e.response=="string"&&(n+=fr(e.response)),e&&Array.isArray(e.toolCalls)){for(let i of e.toolCalls)if(i&&(r+=fr(String(i.name||"")),i.input!==void 0))try{r+=fr(JSON.stringify(i.input))}catch{}}return{inputMessageTokens:t,inputToolTokens:s,outputMessageTokens:n,outputToolTokens:r,inputTotalEstimated:t+s,outputTotalEstimated:n+r}}function Ra(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 Xd(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 _a=N(()=>{});function St(e,t){return!e||!t?"":`${e}${t}`}function gr(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 Ea(e){return e?`${e}`:""}function Da(e,t){return!e||!t?"":`${e}${t}`}var mr=N(()=>{});function Uv(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 Jd(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 eu(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(c=>c.id===o)||null;e.currentView==="yeaft"&&Uv(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(f=>f.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 f=e._recentlyDeletedSessions?.[d.id];if(f&&Date.now()-f<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&&!Rs(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})),e.currentView==="yeaft"&&typeof e.requestYeaftSessionBootstrap=="function"){e._yeaftReconnectCatchUpPending=!1;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 f=e.messagesMap[e.currentConversation]||[],p=Ps(f);p!=null?e.requestChatHistory?.(e.currentConversation,{mode:"delta",afterMessageId:p}):e.requestChatHistory?.(e.currentConversation,{mode:"recent",turns:5}),e.sendWsMessage({type:"refresh_conversation",conversationId:e.currentConversation})}else e.recoveryDismissed||Jd(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){Jd(e,{agentId:c.agentId,agentInfo:d});return}}}l&&(e.agents.find(d=>d.id===l&&d.online)?e.selectAgent(l):e.checkPendingRecovery())}}function tu(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(f=>f.id===e.currentConversation);u&&!a.find(f=>f.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&&!Rs(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 f=e.executionStatusMap[u.id];f&&(f.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(p=>p.id===u)){delete e.processingConversations[u],Ce(e,u);let p=e.executionStatusMap[u];p&&(p.currentTool=null),e.finishStreamingForConversation(u)}}if(e.currentView!=="yeaft"){if(n&&e.currentConversation){let u=e.conversations.find(f=>f.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(f=>f.id===u)&&(e.autoRestoreConversation(u),e.pendingRecovery=null)}Kc(e)}return!0}var su=N(()=>{os();Ts();ir()});function Kv(e={}){return{providers:e.providers||[],primaryModel:e.primaryModel||null,fastModel:e.fastModel||null,language:e.language||"en"}}function nu(){return window.Pinia?.useSessionsStore?.()||window.__useSessionsStore&&window.__useSessionsStore()}function Qv(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 Zv(e){let t=nu(),s=null;try{s=localStorage.getItem("lastViewedYeaftSession")||null}catch{}let n=gr(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 ru(e){let t=nu(),s=Zv(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 Xv(e){let t=e.yeaftSessionHydrateRequestId||null;e.yeaftSessionInventoryCompleteSupported!==!1||!t||(clearTimeout(e._legacyYeaftSessionHydrateTimer),e._legacyYeaftSessionHydrateTimer=setTimeout(()=>{e.yeaftSessionHydrateRequestId===t&&(e._legacyYeaftSessionHydrateTimer=null,ru(e),e._hasHandledYeaftSessionHydrate=!0,e.yeaftSessionHydrateRequestId=null,e.yeaftSessionHydrateError=null,e._yeaftSessionInventorySocketQuarantined=!0)},Gv))}function Jv(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=wi(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=wi(n.rawRequest,t.rawRequestDelta)),n}function ey(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=Jv(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 iu(e,t){let s=De();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||Le("login.error.loginFailed")}),s.handleAuthFailure?.(void 0,t._wsAuthToken,t._wsAuthGeneration);break;case"agent_list":eu(e,t),e.workCenterOpen&&e.workCenterAgentId&&e.listWorkItems(e.workCenterAgentId).catch(()=>{});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;Qv(e,t),e.yeaftSessionInventoryCompleteSupported!==!0&&Xv(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?ru(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(!tu(e,t))break;e.workCenterOpen&&e.workCenterAgentId&&e.listWorkItems(e.workCenterAgentId).catch(()=>{});break;case"conversation_created":Hd(e,t);break;case"conversation_resumed":Od(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":Wd(e,t);break;case"conversation_deleted":Ma(e,t);break;case"conversation_delete_result":t.ok&&Ma(e,t);break;case"turn_completed":Fd(e,t);break;case"conversation_closed":Bd(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":Kd(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:jd(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=typeof t?.requestId=="string"?t.requestId:"",r=typeof t?.detailTurnId=="string"&&t.detailTurnId,i=r?e._yeaftDebugHistoryLatestDetailRequestId:e._yeaftDebugHistoryLatestListRequestId;if(i&&n!==i||!i&&n)break;e._fetchYeaftDebugHistoryTimer&&(clearTimeout(e._fetchYeaftDebugHistoryTimer),e._fetchYeaftDebugHistoryTimer=null),e._yeaftDebugHistoryInFlightKey=null;let o=Array.isArray(t?.turns)?t.turns:[],a=t?.search?Yv:zv,l=r?o:o.slice(-a),c=new Set(l.map(b=>b?.turnId).filter(Boolean)),d=ey(Array.isArray(t?.loops)?t.loops:[]),u=r?d:d.filter(b=>!b?.turnId||c.has(b.turnId)),f=Array.isArray(t?.dreamEvents)?t.dreamEvents:[];e.yeaftDebugHistoryHasMore=!!t?.hasMore||!r&&o.length>l.length,!t?.detailTurnId&&Number.isFinite(t?.limit)&&t.limit>0&&(e.yeaftDebugHistoryLimit=Math.min(a,t.limit)),(!e.yeaftDebugTurnsById||typeof e.yeaftDebugTurnsById!="object")&&(e.yeaftDebugTurnsById={}),Array.isArray(e.yeaftDebugLoops)||(e.yeaftDebugLoops=[]),Array.isArray(e.yeaftDebugTurnOrder)||(e.yeaftDebugTurnOrder=[]);let p=r?{...e.yeaftDebugTurnsById}:{};for(let b of l){let M=b?.turnId;if(!M)continue;let x=p[M];if(x){let D=b?.detailsLoaded?{...x,...b}:{...b,...x};D.memoryLoaded==null&&x.memoryLoaded!=null&&(D.memoryLoaded=x.memoryLoaded),D.memoryAdjust==null&&x.memoryAdjust!=null&&(D.memoryAdjust=x.memoryAdjust),p[M]=D}else p[M]=b}e.yeaftDebugTurnsById=p;let g=b=>b?.loopInstanceId||`${b?.turnId||""}#${b?.loopNumber||0}`,m=e.yeaftDebugLoops,v=new Map;for(let b of m)b&&v.set(g(b),b);let k=new Set,w=[];for(let b of u){if(!b)continue;let M=g(b);k.add(M);let x=v.get(M);w.push(r?{...x||{},...b}:x||b)}if(r)for(let b of m)!b||k.has(g(b))||w.push(b);e.yeaftDebugLoops=w;let I=new Set,h=[],y=b=>{!b||I.has(b)||(I.add(b),h.push(b))};if(r){for(let b of e.yeaftDebugTurnOrder)y(b);for(let b of l)y(b?.turnId)}else for(let b of l)y(b?.turnId);e.yeaftDebugTurnOrder=r?h:h.slice(-a);for(let b of f){if(!b)continue;let M=null,x=b.sessionId||b.groupId;typeof b.target=="string"&&b.target.includes("/")?M=b.target:typeof x=="string"&&x?M=`group/${x}`:M="*",typeof e._appendDreamEvent=="function"&&e._appendDreamEvent(M,b),b.type==="dream_progress"&&typeof e.handleYeaftOutput=="function"&&e.handleYeaftOutput({event:b})}e.yeaftDebugHistoryLoading=!1,e.yeaftDebugHistoryError=typeof t?.error=="string"?t.error:null,e.yeaftDebugHistoryFetchedAt=Date.now(),r&&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 f=e.messagesMap[n];if(f){let p=f.findIndex(g=>g.id===u.id);p>=0&&f.splice(p,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 f=u.findIndex(p=>p.id===d);f>=0&&u.splice(f,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":Nd(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":qd(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),xd(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,minimumVersion:t.minimumVersion}}));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||Kv(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 zv,Yv,Gv,ou=N(()=>{kt();ei();Bt();os();Ts();_a();mr();su();bi();zv=1,Yv=5,Gv=500});function lu(){return Object.values(au).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 cu(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 $s(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 La(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(f=>f.id===l);if(!d)return null;let u;if(c&&d.actions){let f=d.actions.find(p=>p.id===c);f?s?(u=(r?f.messageTemplate:f.messageTemplateEn)||"",u+=s):u=(r?f.defaultMessage:f.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(f=>f.id===l),u=It[l];if(d)if(c){let f=d.actions?.find(p=>p.id===c);f&&o.push((r?f.messageTemplate:f.messageTemplateEn)||"")}else o.push((r?d.messagePrefix:d.messagePrefixEn)||"");else if(u)return null}return o.length===0?null:{effectivePrompt:o.join(`
4
4
  ---
5
5
 
6
6
  `)+(s||"")}}function uu(e){return Object.values(au).filter(t=>e||!t.adminOnly).sort((t,s)=>t.order-s.order)}var au,It,du,Vs,hr=N(()=>{au={dev:{id:"dev",name:"\u8F6F\u4EF6\u5F00\u53D1",nameEn:"Software Dev",icon:"\u{1F5A5}\uFE0F",order:0},trading:{id:"trading",name:"\u4EA4\u6613",nameEn:"Trading",icon:"\u{1F4C8}",order:1,adminOnly:!0},writing:{id:"writing",name:"\u5199\u4F5C",nameEn:"Writing",icon:"\u270D\uFE0F",order:2,adminOnly:!0},video:{id:"video",name:"\u89C6\u9891",nameEn:"Video",icon:"\u{1F3AC}",order:3,adminOnly:!0}},It={jobs:{id:"jobs",name:"Jobs",fullName:"Steve Jobs",title:"\u4EA7\u54C1\u7ECF\u7406",titleEn:"Product Manager",group:"dev",actions:[{id:"product-analysis",name:"\u4EA7\u54C1\u5206\u6790",nameEn:"Product Analysis"},{id:"design-review",name:"\u8BBE\u8BA1\u5BA1\u67E5",nameEn:"Design Review"},{id:"requirements",name:"\u9700\u6C42\u62C6\u89E3",nameEn:"Requirements"}]},fowler:{id:"fowler",name:"Fowler",fullName:"Martin Fowler",title:"\u8F6F\u4EF6\u67B6\u6784\u5E08",titleEn:"Software Architect",group:"dev",actions:[{id:"architecture",name:"\u67B6\u6784\u5BA1\u67E5",nameEn:"Architecture Review"},{id:"refactoring",name:"\u91CD\u6784\u5206\u6790",nameEn:"Refactoring"},{id:"code-review",name:"\u4EE3\u7801\u5BA1\u67E5",nameEn:"Code Review"}]},torvalds:{id:"torvalds",name:"Torvalds",fullName:"Linus Torvalds",title:"\u7CFB\u7EDF\u5F00\u53D1\u5DE5\u7A0B\u5E08",titleEn:"Systems Engineer",group:"dev",actions:[{id:"system-design",name:"\u7CFB\u7EDF\u8BBE\u8BA1",nameEn:"System Design"},{id:"performance",name:"\u6027\u80FD\u4F18\u5316",nameEn:"Performance"},{id:"code-style",name:"\u4EE3\u7801\u98CE\u683C",nameEn:"Code Style"},{id:"implementation",name:"\u4EE3\u7801\u5B9E\u73B0",nameEn:"Implementation"}]},beck:{id:"beck",name:"Beck",fullName:"Kent Beck",title:"\u6D4B\u8BD5\u5DE5\u7A0B\u5E08",titleEn:"Test Engineer",group:"dev",actions:[{id:"test-strategy",name:"\u6D4B\u8BD5\u7B56\u7565",nameEn:"Test Strategy"},{id:"tdd-guide",name:"TDD \u6307\u5BFC",nameEn:"TDD Guide"},{id:"quality-check",name:"\u8D28\u91CF\u8BC4\u4F30",nameEn:"Quality Check"}]},schneier:{id:"schneier",name:"Schneier",fullName:"Bruce Schneier",title:"\u5B89\u5168\u5DE5\u7A0B\u5E08",titleEn:"Security Engineer",group:"dev",actions:[{id:"security-audit",name:"\u5B89\u5168\u5BA1\u8BA1",nameEn:"Security Audit"},{id:"threat-model",name:"\u5A01\u80C1\u5EFA\u6A21",nameEn:"Threat Model"},{id:"auth-review",name:"\u8BA4\u8BC1\u5BA1\u67E5",nameEn:"Auth Review"}]},rams:{id:"rams",name:"Rams",fullName:"Dieter Rams",title:"UI/UX \u8BBE\u8BA1\u5E08",titleEn:"UI/UX Designer",group:"dev",actions:[{id:"ui-review",name:"\u754C\u9762\u5BA1\u67E5",nameEn:"UI Review"},{id:"interaction",name:"\u4EA4\u4E92\u8BBE\u8BA1",nameEn:"Interaction Design"},{id:"layout",name:"\u5E03\u5C40\u4F18\u5316",nameEn:"Layout Optimization"}]},graham:{id:"graham",name:"Graham",fullName:"Paul Graham",title:"\u6280\u672F\u5199\u4F5C / \u65B9\u6848\u8BC4\u4F30\u5E08",titleEn:"Tech Writer / Evaluator",group:"dev",actions:[{id:"writing",name:"\u6280\u672F\u5199\u4F5C",nameEn:"Tech Writing"},{id:"proposal-review",name:"\u65B9\u6848\u8BC4\u4F30",nameEn:"Proposal Review"},{id:"explain",name:"\u6982\u5FF5\u89E3\u91CA",nameEn:"Explain"}]},hightower:{id:"hightower",name:"Hightower",fullName:"Kelsey Hightower",title:"DevOps / \u8FD0\u7EF4\u5DE5\u7A0B\u5E08",titleEn:"DevOps Engineer",group:"dev",actions:[{id:"deployment",name:"\u90E8\u7F72\u5BA1\u67E5",nameEn:"Deployment Review"},{id:"cicd",name:"CI/CD \u8BC4\u4F30",nameEn:"CI/CD Review"},{id:"infra",name:"\u57FA\u7840\u8BBE\u65BD",nameEn:"Infrastructure"}]},gregg:{id:"gregg",name:"Gregg",fullName:"Brendan Gregg",title:"\u6027\u80FD\u5DE5\u7A0B\u5E08",titleEn:"Performance Engineer",group:"dev",actions:[{id:"perf-analysis",name:"\u6027\u80FD\u5206\u6790",nameEn:"Perf Analysis"},{id:"tuning",name:"\u7CFB\u7EDF\u8C03\u4F18",nameEn:"Tuning"},{id:"benchmark",name:"\u57FA\u51C6\u6D4B\u8BD5",nameEn:"Benchmark"}]},codd:{id:"codd",name:"Codd",fullName:"Edgar Codd",title:"\u6570\u636E\u5E93 / SQL \u4E13\u5BB6",titleEn:"Database / SQL Expert",group:"dev",actions:[{id:"sql-optimization",name:"SQL \u4F18\u5316",nameEn:"SQL Optimization"},{id:"schema-design",name:"Schema \u8BBE\u8BA1",nameEn:"Schema Design"},{id:"data-modeling",name:"\u6570\u636E\u5EFA\u6A21",nameEn:"Data Modeling"}]},knuth:{id:"knuth",name:"Knuth",fullName:"Donald Knuth",title:"\u7B97\u6CD5 / \u6570\u636E\u5904\u7406\u4E13\u5BB6",titleEn:"Algorithm Expert",group:"dev",actions:[{id:"algorithm-design",name:"\u7B97\u6CD5\u8BBE\u8BA1",nameEn:"Algorithm Design"},{id:"data-processing",name:"\u6570\u636E\u5904\u7406",nameEn:"Data Processing"},{id:"optimization",name:"\u4F18\u5316",nameEn:"Optimization"}]},thomas:{id:"thomas",name:"Thomas",fullName:"Dave Thomas",title:"\u6280\u672F\u6587\u6863\u5DE5\u7A0B\u5E08",titleEn:"Tech Doc Engineer",group:"dev",actions:[{id:"api-docs",name:"API \u6587\u6863",nameEn:"API Docs"},{id:"readme",name:"README",nameEn:"README"},{id:"comment-review",name:"\u6CE8\u91CA\u5BA1\u67E5",nameEn:"Comment Review"}]},soros:{id:"soros",name:"Soros",fullName:"George Soros",title:"\u5B8F\u89C2\u7B56\u7565\u5E08",titleEn:"Macro Strategist",group:"trading",actions:[{id:"macro-analysis",name:"\u5B8F\u89C2\u5206\u6790",nameEn:"Macro Analysis"},{id:"risk-assessment",name:"\u98CE\u9669\u8BC4\u4F30",nameEn:"Risk Assessment"},{id:"thesis-review",name:"\u8BBA\u70B9\u5BA1\u67E5",nameEn:"Thesis Review"}]},livermore:{id:"livermore",name:"Livermore",fullName:"Jesse Livermore",title:"\u6280\u672F\u5206\u6790\u5E08",titleEn:"Technical Analyst",group:"trading",actions:[{id:"price-action",name:"\u4EF7\u683C\u884C\u4E3A",nameEn:"Price Action"},{id:"pattern-recognition",name:"\u56FE\u5F62\u8BC6\u522B",nameEn:"Pattern Recognition"},{id:"trade-plan",name:"\u4EA4\u6613\u8BA1\u5212",nameEn:"Trade Plan"}]},dalio:{id:"dalio",name:"Dalio",fullName:"Ray Dalio",title:"\u7814\u7A76\u5458 / \u7ECF\u6D4E\u5206\u6790\u5E08",titleEn:"Research / Economist",group:"trading",actions:[{id:"economic-analysis",name:"\u7ECF\u6D4E\u5206\u6790",nameEn:"Economic Analysis"},{id:"portfolio-review",name:"\u7EC4\u5408\u5BA1\u67E5",nameEn:"Portfolio Review"},{id:"research-report",name:"\u7814\u7A76\u62A5\u544A",nameEn:"Research Report"}]},taleb:{id:"taleb",name:"Taleb",fullName:"Nassim Taleb",title:"\u98CE\u63A7\u5B98",titleEn:"Risk Manager",group:"trading",actions:[{id:"risk-audit",name:"\u98CE\u9669\u5BA1\u8BA1",nameEn:"Risk Audit"},{id:"antifragile",name:"\u53CD\u8106\u5F31\u8BC4\u4F30",nameEn:"Antifragile Assessment"},{id:"stress-test",name:"\u538B\u529B\u6D4B\u8BD5",nameEn:"Stress Test"}]},jones:{id:"jones",name:"Jones",fullName:"Paul Tudor Jones",title:"\u4EA4\u6613\u6267\u884C\u5458",titleEn:"Trade Executor",group:"trading",actions:[{id:"execution",name:"\u6267\u884C\u8BA1\u5212",nameEn:"Execution Plan"},{id:"position-sizing",name:"\u4ED3\u4F4D\u8BA1\u7B97",nameEn:"Position Sizing"},{id:"trade-review",name:"\u4EA4\u6613\u590D\u76D8",nameEn:"Trade Review"}]},simons:{id:"simons",name:"Simons",fullName:"Jim Simons",title:"\u91CF\u5316\u5206\u6790\u5E08",titleEn:"Quant Analyst",group:"trading",actions:[{id:"quant-signal",name:"\u91CF\u5316\u4FE1\u53F7",nameEn:"Quant Signal"},{id:"backtest-review",name:"\u56DE\u6D4B\u5BA1\u67E5",nameEn:"Backtest Review"},{id:"model-design",name:"\u6A21\u578B\u8BBE\u8BA1",nameEn:"Model Design"}]},jinyong:{id:"jinyong",name:"\u91D1\u5EB8",fullName:"\u91D1\u5EB8\uFF08Louis Cha\uFF09",title:"\u6B66\u4FA0\u5927\u5E08",titleEn:"Wuxia Master",group:"writing",actions:[{id:"world-building",name:"\u6B66\u4FA0\u4E16\u754C\u89C2",nameEn:"Wuxia World Building"},{id:"character-design",name:"\u4EBA\u7269\u5851\u9020",nameEn:"Character Design"},{id:"plot-design",name:"\u60C5\u8282\u7F16\u6392",nameEn:"Plot Design"}]},zhouzi:{id:"zhouzi",name:"\u8098\u5B50",fullName:"\u4F1A\u8BF4\u8BDD\u7684\u8098\u5B50",title:"\u7F51\u6587\u5929\u738B",titleEn:"Web Novel King",group:"writing",actions:[{id:"cool-factor",name:"\u723D\u611F\u8BBE\u8BA1",nameEn:"Cool Factor Design"},{id:"pacing",name:"\u8282\u594F\u628A\u63A7",nameEn:"Pacing Control"},{id:"cheat-design",name:"\u91D1\u624B\u6307\u8BBE\u8BA1",nameEn:"Cheat System Design"}]},qiongyao:{id:"qiongyao",name:"\u743C\u7476",fullName:"\u743C\u7476\uFF08Chiung Yao\uFF09",title:"\u8A00\u60C5\u5B97\u5E08",titleEn:"Romance Master",group:"writing",actions:[{id:"emotion-writing",name:"\u60C5\u611F\u63CF\u5199",nameEn:"Emotion Writing"},{id:"dialogue-design",name:"\u5BF9\u8BDD\u8BBE\u8BA1",nameEn:"Dialogue Design"},{id:"romance-arc",name:"\u8650\u604B\u67B6\u6784",nameEn:"Romance Arc"}]},luxun:{id:"luxun",name:"\u9C81\u8FC5",fullName:"\u9C81\u8FC5\uFF08Lu Xun\uFF09",title:"\u6587\u5B66\u5DE8\u5320",titleEn:"Literary Giant",group:"writing",actions:[{id:"satire",name:"\u8BBD\u523A\u5199\u4F5C",nameEn:"Satirical Writing"},{id:"character-sketch",name:"\u4EBA\u7269\u523B\u753B",nameEn:"Character Sketch"},{id:"prose-craft",name:"\u6587\u7B14\u9524\u70BC",nameEn:"Prose Craft"}]},kubrick:{id:"kubrick",name:"Kubrick",fullName:"Stanley Kubrick",title:"\u5BFC\u6F14 / \u89C6\u89C9\u603B\u76D1",titleEn:"Director / Visual Director",group:"video",actions:[{id:"narrative-pacing",name:"\u53D9\u4E8B\u8282\u594F",nameEn:"Narrative Pacing"},{id:"visual-concept",name:"\u89C6\u89C9\u6982\u5FF5",nameEn:"Visual Concept"},{id:"scene-breakdown",name:"\u573A\u666F\u62C6\u89E3",nameEn:"Scene Breakdown"}]},kaufman:{id:"kaufman",name:"Kaufman",fullName:"Charlie Kaufman",title:"\u7F16\u5267",titleEn:"Screenwriter",group:"video",actions:[{id:"script-writing",name:"\u811A\u672C\u5199\u4F5C",nameEn:"Script Writing"},{id:"character-design",name:"\u89D2\u8272\u8BBE\u8BA1",nameEn:"Character Design"},{id:"narrative-structure",name:"\u53D9\u4E8B\u7ED3\u6784",nameEn:"Narrative Structure"}]},spielberg:{id:"spielberg",name:"Spielberg",fullName:"Steven Spielberg",title:"\u5206\u955C / \u89C6\u89C9\u53D9\u4E8B\u5E08",titleEn:"Storyboard / Visual Storyteller",group:"video",actions:[{id:"storyboard",name:"\u5206\u955C\u8BBE\u8BA1",nameEn:"Storyboard"},{id:"shot-design",name:"\u955C\u5934\u65B9\u6848",nameEn:"Shot Design"},{id:"visual-storytelling",name:"\u89C6\u89C9\u53D9\u4E8B",nameEn:"Visual Storytelling"}]},schoonmaker:{id:"schoonmaker",name:"Schoonmaker",fullName:"Thelma Schoonmaker",title:"\u526A\u8F91\u5E08",titleEn:"Editor",group:"video",actions:[{id:"editing-rhythm",name:"\u526A\u8F91\u8282\u594F",nameEn:"Editing Rhythm"},{id:"sequence-design",name:"\u5E8F\u5217\u8BBE\u8BA1",nameEn:"Sequence Design"},{id:"final-cut",name:"\u6700\u7EC8\u5BA1\u7247",nameEn:"Final Cut"}]}};du="dev",Vs=3});function ry(e,t){return!t||!e?.yeaftConversationIdsByAgent?[]:Object.entries(e.yeaftConversationIdsByAgent).filter(([,s])=>s===t).map(([s])=>s).filter(Boolean)}function pu(){return`cm_${crypto.randomUUID()}`}function fu(e,t){if(t===e.currentAgent&&!e.pendingAgentSelection)return;let s=`agent_select_${crypto.randomUUID()}`;return e.agentSwitching=!0,e.pendingAgentSelection={agentId:t,requestId:s},e.sendWsMessage({type:"select_agent",agentId:t,requestId:s})===!1?(e.pendingAgentSelection=null,e.agentSwitching=!1,null):s}function gu(e,t,s=null,n=null,r={}){let i=s||e.currentAgent;if(!i){e.addMessage({type:"error",content:Le("chat.agent.selectFirst")});return}on(e,!0,Le("chat.session.creating"));let o={type:"create_conversation",agentId:i,workDir:t||e.currentAgentWorkDir};n!==null&&(o.disallowedTools=n),r&&typeof r.provider=="string"&&(o.provider=r.provider),r&&r.providerOptions&&typeof r.providerOptions=="object"&&(o.providerOptions=r.providerOptions),e.sendWsMessage(o)}function mu(e,t,s,n=null,r=null,i=null){let o=n||e.currentAgent;if(!o){e.addMessage({type:"error",content:Le("chat.agent.selectFirst")});return}let a=null,l={};r&&typeof r=="object"&&!Array.isArray(r)?l=r:(a=r,i&&typeof i=="object"&&(l=i)),on(e,!0,Le("chat.session.loadingHistory"));let c={type:"resume_conversation",agentId:o,claudeSessionId:t,workDir:s||e.currentAgentWorkDir};a!==null&&(c.disallowedTools=a),typeof l.provider=="string"&&(c.provider=l.provider),l.providerOptions&&typeof l.providerOptions=="object"&&(c.providerOptions=l.providerOptions),e.sendWsMessage(c)}function hu(e,t,s,{refresh:n=!1}={}){if(e.panels.length>1){let a=e.activePanelId||e.panels[0]?.id;a&&e.setPanelConversation(a,t,{refresh:n});return}if(t===e.currentConversation){n&&(e.syncChatConversationHistory?.(t),xs(e));return}let r=e.conversations.find(a=>a.id===t&&a.type!=="yeaft");if(r&&r.agentId&&r.agentId!==e.currentAgent){let a=e.agents.find(l=>l.id===r.agentId);a&&(e.currentAgent=r.agentId,e.currentAgentInfo=a,e.sendWsMessage({type:"select_agent",agentId:r.agentId,silent:!0}))}e.sendWsMessage({type:"select_conversation",conversationId:t}),e.panels.length>1?e.activeConversations.includes(t)||e.activeConversations.push(t):e.activeConversations=[t],r&&(e.currentWorkDir=r.workDir);let i=e.messagesMap[t];(!i||i.length===0)&&(e.messagesMap[t]=[],on(e,!0,Le("chat.session.loadingHistory"))),e.syncChatConversationHistory?.(t),e.loadingMoreMessages=!1;let o=e.chatSessionState[t];e.hasMoreMessages=!!o?.hasMoreOlder,xs(e)}function $a(e,t,s){t&&e.sendWsMessage({type:"update_conversation_settings",conversationId:t,...s})}function vu(e,t,s){let n=e.currentConversation;if(!n)return;let r=e.conversationMcpServers[n];if(r){let f=r.find(p=>p.name===t);f&&(f.enabled=s)}let i=e.conversationMcpServers[n]||[],o=e.conversationMcpServerTools[n]||{},a=[];for(let f of i)if(!f.enabled){let p=o[f.name];p&&p.length>0?a.push(...p):a.push(`mcp__${f.name}`)}let u=[...(e.conversations.find(f=>f.id===n)?.disallowedTools||[]).filter(f=>!f.startsWith("mcp__")),...a];$a(e,n,{disallowedTools:u})}function yu(e,t,s){return t?e.sendWsMessage({type:"delete_conversation",requestId:`delete_${crypto.randomUUID()}`,conversationId:t,...s?{agentId:s}:{}}):!1}function bu(e,t,s){e._recentlyDeletedSessions||(e._recentlyDeletedSessions={}),e._recentlyDeletedSessions[t]=Date.now(),e.conversations=e.conversations.filter(i=>i.id!==t);let n=e.activeConversations.indexOf(t);n>=0&&(e.activeConversations.splice(n,1),e.activeConversations.length===0&&(localStorage.removeItem("lastViewedConversation"),e.lastViewedConversation=null));for(let i of e.panels)i.conversationId===t&&(i.conversationId=null);let r=e.pinnedSessions.indexOf(t);r>=0&&(e.pinnedSessions.splice(r,1),localStorage.setItem("pinned-sessions",JSON.stringify(e.pinnedSessions))),e.sendWsMessage({type:"delete_conversation",requestId:`delete_${crypto.randomUUID()}`,conversationId:t,...s?{agentId:s}:{}})}function wu(e,t,s=[],n={}){let r=n.expertSelections&&n.expertSelections.length>0;if(!t.trim()&&s.length===0&&!r||!e.currentAgent||!e.currentConversation)return;let i=pu();if(e.addMessage({type:"user",content:t,clientMessageId:i,attachments:s.length>0?s:void 0,expertSelections:r?n.expertSelections:void 0}),t.trim()){let c=t.trim().substring(0,100);e.conversationTitles[e.currentConversation]=c}else if(r){let c=n.expertSelections[0],d=`@${c.role}${c.action?"\xB7"+c.action:""}`;e.conversationTitles[e.currentConversation]=d}let o=e.conversations.find(c=>c.id===e.currentConversation);o&&(o.lastMessageAt=Date.now()),e.processingConversations[e.currentConversation]||(e.processingConversations[e.currentConversation]=!0,e._closedAt?.[e.currentConversation]&&delete e._closedAt[e.currentConversation],e._turnCompletedConvs?.delete(e.currentConversation),e.getOrCreateExecutionStatus(e.currentConversation),an(e,e.currentConversation));let a=s.map(c=>c.fileId),l={type:"chat",conversationId:e.currentConversation,prompt:t,fileIds:a,workDir:e.currentWorkDir,clientMessageId:i};if(n.targetRole&&(l.targetRole=n.targetRole),r){l.expertSelections=n.expertSelections;let c=La(n.expertSelections,e.customExpertRoles,t,e.language||"zh-CN");c&&(l.expertMessage=c.effectivePrompt)}e.sendWsMessage(l)||nr(e).then(()=>{e.sendWsMessage(l)}).catch(()=>{e.addMessage({type:"system",content:Le("chat.connection.reconnectFailed")}),delete e.processingConversations[e.currentConversation],Ce(e,e.currentConversation)})}function ku(e){if(!e.currentConversation||!e.processingConversations[e.currentConversation])return;let t=e.currentConversation;e.sendWsMessage({type:"cancel_execution",conversationId:t}),delete e.processingConversations[t],Ce(e,t),e._closedAt||(e._closedAt={}),e._closedAt[t]=Date.now();let s=e.executionStatusMap[t];s&&(s.currentTool=null),e.finishStreamingForConversation(t),as(e,t),e.addMessage({type:"system",content:Le("chat.execution.cancelled")})}function Su(e,t,s,n){let r=n||e.currentConversation,o=(e.messagesMap[r]||[]).find(g=>g.type==="tool-use"&&g.toolName==="AskUserQuestion"&&g.askRequestId===t),a=e.currentView==="yeaft"||!!o?.sessionId;if(a&&o?.askPending)return;let l=o?.sessionId||e.yeaftActiveSessionFilter||null,c=typeof o?.agentId=="string"&&o.agentId?o.agentId:null,d=a?ry(e,r):[],u=d.length===1?d[0]:null;if(c&&u&&c!==u)return!1;let f=a&&!c&&!u&&typeof e.agentIdForSession=="function"?e.agentIdForSession(l):null,p=e.sendWsMessage(a?{type:"yeaft_ask_user_answer",agentId:c||u||f||e.yeaftAgentId||e.currentAgent||null,conversationId:r,requestId:t,toolCallId:o?.toolId||null,answers:s,sessionId:l,vpId:o?.vpId||o?.speakerVpId||null,turnId:o?.turnId||null,threadId:o?.threadId||"main"}:{type:"ask_user_answer",conversationId:r,requestId:t,answers:s});if(o&&!a)o.askAnswered=!0,o.selectedAnswers=s;else if(o&&p!==!1){let g=++ny;o.askPending=!0,o.pendingAnswers=s,o.askSubmitGeneration=g;let m=setTimeout(()=>{o.askSubmitGeneration!==g||o.askPending!==!0||(o.askPending=!1,o.pendingAnswers=null,o.askSubmitGeneration=null)},sy);typeof m?.unref=="function"&&m.unref()}p!==!1&&r&&!e.processingConversations[r]&&(e.processingConversations[r]=!0,e._closedAt?.[r]&&delete e._closedAt[r],e.getOrCreateExecutionStatus(r))}function Iu(e,t){t&&(e.activeConversations.includes(t)||e.activeConversations.length>=3||(e.activeConversations.push(t),e.messagesMap[t]||(e.messagesMap[t]=[],e.requestChatHistory?.(t,{mode:"recent",turns:5})),xs(e)))}function Cu(e,t){let s=e.activeConversations.indexOf(t);s<0||(e.activeConversations.splice(s,1),e.activeConversations.length===0&&(localStorage.removeItem("lastViewedConversation"),e.lastViewedConversation=null),xs(e))}function Au(e,t,s,n=[],r={}){let i=r.expertSelections&&r.expertSelections.length>0;if(!s.trim()&&n.length===0&&!i||!e.currentAgent||!t)return;let o=pu();if(e.addMessageToConversation(t,{type:"user",content:s,clientMessageId:o,attachments:n.length>0?n:void 0,expertSelections:i?r.expertSelections:void 0}),s.trim()){let d=s.trim().substring(0,100);e.conversationTitles[t]=d}else if(i){let d=r.expertSelections[0],u=`@${d.role}${d.action?"\xB7"+d.action:""}`;e.conversationTitles[t]=u}let a=e.conversations.find(d=>d.id===t);a&&(a.lastMessageAt=Date.now()),e.processingConversations[t]||(e.processingConversations[t]=!0,e._closedAt?.[t]&&delete e._closedAt[t],e._turnCompletedConvs?.delete(t),e.getOrCreateExecutionStatus(t),an(e,t));let l=n.map(d=>d.fileId),c={type:"chat",conversationId:t,prompt:s,fileIds:l,workDir:a?.workDir||e.currentWorkDir,clientMessageId:o};if(r.targetRole&&(c.targetRole=r.targetRole),i){c.expertSelections=r.expertSelections;let d=La(r.expertSelections,e.customExpertRoles,s,e.language||"zh-CN");d&&(c.expertMessage=d.effectivePrompt)}e.sendWsMessage(c)||nr(e).then(()=>{e.sendWsMessage(c)}).catch(()=>{e.addMessageToConversation(t,{type:"system",content:Le("chat.connection.reconnectFailed")}),delete e.processingConversations[t],Ce(e,t)})}function xu(e,t){if(!t||!e.processingConversations[t])return;e.sendWsMessage({type:"cancel_execution",conversationId:t}),delete e.processingConversations[t],Ce(e,t),e._closedAt||(e._closedAt={}),e._closedAt[t]=Date.now();let s=e.executionStatusMap[t];s&&(s.currentTool=null),e.finishStreamingForConversation(t),as(e,t),e.addMessageToConversation(t,{type:"system",content:Le("chat.execution.cancelled")})}function Tu(e){e.ws&&e.ws.readyState===WebSocket.OPEN&&(typeof e.requestYeaftSessionInventory=="function"?e.requestYeaftSessionInventory():e.sendWsMessage({type:"get_agents"}))}function Mu(e){!e.currentAgent||!e.currentConversation||e.sendWsMessage({type:"refresh_conversation",conversationId:e.currentConversation})}function Pu(e,t){t&&e.sendWsMessage({type:"restart_agent",agentId:t})}function Ru(e,t){t&&e.sendWsMessage({type:"upgrade_agent",agentId:t})}var sy,ny,_u=N(()=>{os();Ts();da();bi();Bt();hr();sy=1e4,ny=0});function oy(e=globalThis.localStorage){try{return e?.getItem(Du)==="yeaft"?"yeaft":Eu}catch{return Eu}}function Va(e,t=globalThis.localStorage){if(e!=="chat"&&e!=="yeaft")return!1;try{return t?.setItem(Du,e),!!t}catch{return!1}}function Lu(e=globalThis.localStorage){let t=oy(e);if(t!=="yeaft")return{currentView:t,_yeaftTransitionActive:!1,_savedActiveConversations:null,_savedChatIdentity:null,_pendingChatRestoreConversationId:null};let s=null;try{s=e?.getItem("lastViewedConversation")||null}catch{}let n=s&&!s.startsWith("yeaft-")?s:null;return{currentView:t,_yeaftTransitionActive:!0,_savedActiveConversations:null,_savedChatIdentity:null,_pendingChatRestoreConversationId:n}}function Ha(e){return e._yeaftTransitionActive?!1:(e._savedActiveConversations=[...e.activeConversations],e._savedChatIdentity={agentId:e.currentAgent||null,agentInfo:e.currentAgentInfo?{...e.currentAgentInfo}:null,workDir:e.currentWorkDir||null},e._yeaftTransitionActive=!0,!0)}function $u(e){let t=Ha(e);return e.activeConversations=[e.yeaftConversationId],t}function Vu(e){if(!e._yeaftTransitionActive)return null;let t=e._savedChatIdentity||null;return e.activeConversations=e._savedActiveConversations||[],t&&(e.currentAgent=t.agentId,e.currentAgentInfo=t.agentInfo,e.currentWorkDir=t.workDir),e._savedActiveConversations=null,e._savedChatIdentity=null,e._yeaftTransitionActive=!1,t}var Du,Eu,Hu=N(()=>{Du="yeaft-preferred-conversation-view",Eu="chat"});function Ou(e,t,s){let n={...e||{}},r={...n[t]||{}};return r[s]=(r[s]||0)+1,n[t]=r,n}function Fu(e,t,s){let n={...e||{}},r={...n[t]||{}},i=(r[s]||0)-1;return i<=0?delete r[s]:r[s]=i,Object.keys(r).length===0?delete n[t]:n[t]=r,n}var Bu=N(()=>{});function Oa(e){return e.currentView==="yeaft"?e.yeaftConversationId||null:e.activeConversations[0]||null}var Nu=N(()=>{});function qu({loops:e,turnsById:t,turnOrder:s,maxLoops:n}){if(!Array.isArray(e)||e.length<=n)return{loops:e,turnsById:t,turnOrder:s};let r=e.length-n,i=e.slice(r),o=new Set;for(let c of i)c&&c.turnId&&o.add(c.turnId);for(let c of s){let d=t[c];d&&d.closedAt==null&&o.add(c)}let a={};for(let c of Object.keys(t))o.has(c)&&(a[c]=t[c]);let l=s.filter(c=>o.has(c));return{loops:i,turnsById:a,turnOrder:l}}var Wu=N(()=>{});function Ee(e){let t=Number(e);return Number.isFinite(t)?t:null}function fn(e){let t=Ee(e);return Number.isInteger(t)&&t>0?t:null}function Fa(e){let t=Ee(e);return Number.isInteger(t)&&t>=0?t:null}function ju(e){return cy.has(e)?1:0}function dy(e,t){if(!e)return t||null;if(!t)return e;let s=Ee(e.progressRevision),n=Ee(t.progressRevision);if(s!=null||n!=null){if(s==null)return t;if(n==null)return e;if(s!==n)return n>s?t:e}let r=ju(e.status),i=ju(t.status);if(r!==i)return i>r?t:e;let o=Ee(e.updatedAt)??Ee(e.createdAt)??0;return(Ee(t.updatedAt)??Ee(t.createdAt)??0)>o?t:e}function pn(e){return Math.max(0,Number(e)||0)}function Uu(e){return typeof e?.id=="string"&&e.id.startsWith("event:")?e.id.slice(6):null}function uy(e,t){if(/^\d+$/.test(e)&&/^\d+$/.test(t)){let s=BigInt(e),n=BigInt(t);return s<n?-1:s>n?1:0}return e.localeCompare(t)}function py(e,t){let s=pn(e?.createdAt)-pn(t?.createdAt);if(s)return s;let n=Uu(e),r=Uu(t);if(n!=null&&r!=null)return uy(n,r);let i=e?.role==="user"?0:1,o=t?.role==="user"?0:1;if(i!==o)return i-o;let a=pn(e?.generation)-pn(t?.generation);return a||pn(e?.attempt)-pn(t?.attempt)||String(e?.id||"").localeCompare(String(t?.id||""))}function vr(...e){let t=new Map;for(let s of e){let n=Array.isArray(s)?s:[s];for(let r of n)r?.id&&t.set(r.id,dy(t.get(r.id),r))}return[...t.values()].sort(py)}function ct(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:1}function gn(e,t,s,n){return`${e}:${t}:${s}:${ct(n)}`}function Ba(e,t,s,n){return`${e}:${t}:${s}:${ct(n)}`}function mn(e,t){if(!e||!t||e.id!==t.id)return!1;let s=Ee(e.revision),n=Ee(t.revision);if(s!=null&&n!=null&&s!==n)return s<n;let r=Ee(e.coordinatorRevision),i=Ee(t.coordinatorRevision);if(r!=null&&i!=null&&r!==i)return r<i;let o=Ee(e.updatedAt),a=Ee(t.updatedAt);return o!=null&&a!=null&&o<a}function Ku(e,t){if(mn(e,t))return!0;if(!e||!t||e.id!==t.id)return!1;let s=Ee(e.revision),n=Ee(t.revision);return e.currentActionId!==t.currentActionId&&s!=null&&n!=null&&s<=n}function Na(e,t){let s=fn(e?.generation),n=fn(t?.generation);if(s!=null&&n!=null&&s!==n)return n<s;let r=Fa(e?.attempt),i=Fa(t?.attempt);if(r!=null&&i!=null&&r!==i)return i<r;let o=Ee(e?.progressRevision),a=Ee(t?.progressRevision);return o!=null&&a!=null&&a<o}function qa(e,t){if(!e||e.id!==t?.id||mn(t,e))return null;let s=Array.isArray(e.actions)?e.actions:[],n=Array.isArray(t.actionStats)?t.actionStats:[],r=e.currentActionId||null,i=Object.prototype.hasOwnProperty.call(t,"currentActionId")?t.currentActionId||null:r,o=typeof t.eventActionId=="string"&&n.some(g=>g?.id===t.eventActionId)?t.eventActionId:null,a=o||r!==i&&r||i;if(!a)return null;let l=s.find(g=>g?.id===a)||null,c=n.find(g=>g?.id===a)||(t.currentAction?.id===a?t.currentAction:null);if(l&&c&&Na(l,c))return null;let d=fn(l?.generation),u=fn(c?.generation),f=Fa(c?.attempt),p={actionId:a,generation:u||d||1,...f==null?{}:{attempt:f}};return o||r!==i||!l||d!=null&&u!=null&&u>d||l?.status==="running"&&c?.status&&c.status!=="running"?p:null}function zu(e,t){if(!e||e.id!==t?.id||mn(t,e))return!1;let s=Ee(t.coordinatorRevision),n=Ee(e.coordinatorRevision)??0;return s!=null&&s>n?!0:qa(e,t)!=null}function Yu(e,t){if(!e||e.id!==t?.id||mn(t,e))return e;let s={...e},n=!Array.isArray(e.actions)||!Array.isArray(t.actionStats);if(Array.isArray(e.actions)&&Array.isArray(t.actionStats)){let r=new Map(t.actionStats.map(o=>[o?.id,o])),i=!1;n=!0,s.actions=e.actions.map(o=>{let a=r.get(o?.id);if(!a)return o;if(i=!0,Na(o,a))return n=!1,o;if(Ee(a?.progressRevision)==null){let{response:u,messages:f,...p}=a;return{...o,...p}}let c=fn(o?.generation),d=fn(a?.generation);if(c!=null&&d!=null&&d>c){let{messages:u,thread:f,liveMessage:p,response:g,failure:m,messageCursor:v,messageCount:k,failureReason:w,...I}=o;return{...I,...a}}return{...o,...a}}),i||(n=!1)}for(let r of ly)!n&&fy.has(r)||Object.prototype.hasOwnProperty.call(t,r)&&(s[r]=t[r]);return s}function Gu(e,t){if(!Array.isArray(e)||!Array.isArray(t))return!1;let s=new Map(e.map(n=>[n?.id,n]));return t.some(n=>{let r=s.get(n?.id);return r?Na(r,n):!1})}function Qu(e,t){return Ee(e?.revision)===Ee(t?.revision)&&Ee(e?.coordinatorRevision)===Ee(t?.coordinatorRevision)&&Ee(e?.updatedAt)===Ee(t?.updatedAt)}function Zu(e,t){return!e||!t||e.id!==t.id?!1:mn(e,t)?!0:Qu(t,e)&&Gu(t.actions,e.actions)}function ki(e,t){let s=Array.isArray(e)?e:[],n=s.find(i=>i.id===t?.id)||null,r=n&&mn(t,n)?n:t;return n&&r===t&&Qu(n,t)&&Gu(n.actionStats,t.actionStats)&&(r=n),r?.id?[r,...s.filter(i=>i.id!==r.id)].sort((i,o)=>Number(o.updatedAt||0)-Number(i.updatedAt||0)):s}var ly,cy,fy,Wa=N(()=>{ly=Object.freeze(["revision","planRevision","ledgerRevision","coordinatorRevision","title","goal","workItemType","planningMode","status","lifecycle","attentionState","activeActionIds","attentionActionIds","currentActionId","currentAction","executionStats","failureReason","origin","linkedSessionIds","createdAt","updatedAt"]);cy=new Set(["completed","failed","cancelled","superseded","interrupted"]);fy=new Set(["status","lifecycle","attentionState","activeActionIds","attentionActionIds","currentActionId","currentAction","executionStats","failureReason"])});function Hs(e){return typeof e=="string"?e.trim():""}function Xu(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e;if(typeof e=="string"&&e.trim()){let t=Date.parse(e);if(Number.isFinite(t))return t}return null}function Pt(e){let t=Xu(e);if(!t)return"";try{return new Intl.DateTimeFormat(void 0,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}catch{return""}}function gy(e){return Array.isArray(e)?e.slice(0,100).map(t=>({content:Hs(t?.content).slice(0,2e3),status:["pending","in_progress","completed"].includes(t?.status)?t.status:"pending",...Hs(t?.activeForm)?{activeForm:Hs(t.activeForm).slice(0,2e3)}:{}})).filter(t=>t.content):[]}function Qe(e){if(!e||typeof e!="object")return null;let t=Hs(e.content).slice(0,1e5),s=gy(e.todos);if(!t&&s.length===0)return null;let n=e.role==="assistant"?"assistant":"user",r=Xu(e.timestamp);return{id:Hs(e.id).slice(0,256)||null,role:n,author:Hs(e.author).slice(0,256)||(n==="assistant"?"Assistant":"User"),content:t,...r?{timestamp:r}:{},...s.length>0?{todos:s}:{}}}function Ju(e,t){return Qe({id:e?.messageId||e?.id||null,role:"user",author:t,content:e?.content||"",timestamp:e?.timestamp||e?.createdAt||e?.ts||e?.time||null})}function ep(e,t){let s=e?.todoMsg?.toolInput?.todos,n=Array.isArray(e?.toolMsgs)?e.toolMsgs.map(o=>Hs(o?.toolName)).filter(Boolean):[],r=Number(e?.toolSummaryCount||0)||0,i=n.length>0?`Tool actions: ${n.join(", ")}`:r>0?`Tool actions: ${r}`:"";return Qe({id:e?.atMessageId||e?.messageId||e?.id||e?.turnId||null,role:"assistant",author:t,content:e?.textContent||i,timestamp:e?.timestamp||e?.createdAt||e?.speakerTimestamp||null,todos:s})}var ls=N(()=>{});function tp(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:t?.type==="text"&&typeof t.text=="string"?t.text:"").join(""):e==null?"":String(e)}function my(e,t){if(!e||e.type!=="assistant")return!1;let s=e.sessionId??e.groupId??null,n=e.speakerVpId||e.vpId||null;return!(t.sessionId&&s!==t.sessionId||t.vpId&&n!==t.vpId||t.turnId&&e.turnId!==t.turnId)}function sp(e,t={}){if(!Array.isArray(e)||!t.turnId)return!1;let s=e.filter(n=>my(n,t));if(s.length===0)return!1;for(let n of s)n.responseKind="progress";if(t.reason==="end_turn"){for(let n=s.length-1;n>=0;n-=1)if(tp(s[n].content).trim()){s[n].responseKind="result";break}}return!0}function Si(e,t){if(!e||!t)return;let s=tp(t.content);s&&(Array.isArray(e.textSegments)||(e.textSegments=[]),e.textSegments.push({key:t.messageId||t.id||`response-${e.textSegments.length}`,content:s,kind:t.responseKind==="result"?"result":"progress",explicitKind:t.responseKind==="progress"||t.responseKind==="result",isStreaming:t.isStreaming===!0}),e.textContent=e.textSegments.map(n=>n.content).join(`
7
7
 
8
- `))}function Ii(e){let t=Array.isArray(e?.textSegments)?e.textSegments:[];if(t.length===0)return;let s=Array.isArray(e?.messages)?e.messages:[],n=e?.isActive===!0||e?.isStreaming===!0||t.some(l=>l.isStreaming===!0)||s.some(l=>l?.isStreaming===!0||l?.status==="pending"),r=s.some(l=>l?.incomplete===!0||ja.has(l?.status)||ja.has(l?.turnEndReason)||ja.has(l?.stopReason));if(n||r){for(let l of t)l.kind="progress";return}if(t.some(l=>l.kind==="result"))return;let i=s.some(l=>l?.turnEndReason==="end_turn"),o=t.some(l=>l.explicitKind),a=t.length===1&&!o;(i||a||e.isHistory&&!o)&&(t[t.length-1].kind="result")}var ja,Ci=N(()=>{ja=new Set(["aborted","errored","error","cancelled","canceled"])});function Ua(e){return e?.type==="user"&&typeof e.content=="string"&&e.content.trim()}function Ka(e){return e?.type==="assistant"||e?.type==="thinking"||e?.type==="tool_use"||e?.type==="tool-use"||e?.type==="tool_result"||e?.type==="tool-result"}function za(e,t){if(!e||e.kind!=="assistant")return!0;let s=e.turnId||e.lastTurnId||"",n=t?.turnId||"";if(s&&n&&s!==n)return!0;let r=e.speakerVpId||"",i=t?.speakerVpId||t?.vpId||"";return!!(r&&i&&r!==i)}function np(e=[]){let t=[],s=null,n=r=>{s&&(t.push({start:s.start,end:r,kind:s.kind}),s=null)};for(let r=0;r<e.length;r++){let i=e[r];if(i){if(Ua(i)||i.type==="system"||i.type==="error"){n(r),s={start:r,kind:i.type};continue}if(!Ka(i)){s||(s={start:r,kind:"other"});continue}(!s||s.kind==="assistant"&&za(s,i))&&(n(r),s={start:r,kind:"assistant",turnId:i.turnId||"",speakerVpId:i.speakerVpId||i.vpId||""}),s.lastTurnId=i.turnId||s.lastTurnId||"",s.speakerVpId=s.speakerVpId||i.speakerVpId||i.vpId||""}}return n(e.length),t}function rp(e,t){return!e||e._historyWindowPrefetched===!0?!1:t?(e.sessionId??e.groupId)===t:!0}function Ya(e=[],t=null,s=yr){let n=Math.max(1,Number.isFinite(s)?Math.floor(s):yr),r=[],i=[],o=null,a=c=>{o&&(i.push({start:o.start,end:c,kind:o.kind}),o=null)};for(let c of e){if(!rp(c,t))continue;let d=r.length;if(r.push(c),Ua(c)||c.type==="system"||c.type==="error"){a(d),o={start:d,kind:c.type};continue}if(!Ka(c)){o||(o={start:d,kind:"other"});continue}(!o||o.kind==="assistant"&&za(o,c))&&(a(d),o={start:d,kind:"assistant",turnId:c.turnId||"",speakerVpId:c.speakerVpId||c.vpId||""}),o.lastTurnId=c.turnId||o.lastTurnId||"",o.speakerVpId=o.speakerVpId||c.speakerVpId||c.vpId||""}if(a(r.length),i.length<=n)return r;let l=i[i.length-n];return r.slice(l.start)}function ip(e=[],t=null,s=yr){let n=Math.max(1,s||yr),r=0,i=null,o=()=>i?(i=null,r+=1,r>n):!1;for(let a of e)if(rp(a,t)){if(Ua(a)||a.type==="system"||a.type==="error"){if(o())return!0;i={kind:a.type};continue}if(!Ka(a)){i||(i={kind:"other"});continue}if(!i||i.kind==="assistant"&&za(i,a)){if(o())return!0;i={kind:"assistant",turnId:a.turnId||"",speakerVpId:a.speakerVpId||a.vpId||""}}i.lastTurnId=a.turnId||i.lastTurnId||"",i.speakerVpId=i.speakerVpId||a.speakerVpId||a.vpId||""}return o(),r>n}function Os(){return yr}function br(){return hy}var yr,hy,op=N(()=>{yr=Number.POSITIVE_INFINITY,hy=20});function yy(e,t){let s=new Set;if(!t)return s;for(let n of e?.sessionCatalog||[])n?.runtimeProvider!=="yeaft"||n?.routeRef?.sessionId!==t||n.routeRef.agentId&&s.add(n.routeRef.agentId);if(s.size===0){let n=cs();for(let r of n?.sessionList||[])r?.id===t&&r?.agentId&&s.add(r.agentId)}return s}function Ip(e,t){let s=yy(e,t);return s.size===1?s.values().next().value:null}function Mi(e,t,s){return!!s&&Ip(e,t)===s}function st(e,t,s){return!e||e.sessionId!==t?!1:s?e.agentId===s:!e.agentId}function ap(e,t,s=null){if(!t)return!1;let n=s||be(e,t),r=St(n,t);if(r&&e.yeaftProcessingSessions?.[r]||e.yeaftProcessingSessions?.[t]&&Mi(e,t,n))return!0;for(let i of Object.values(e.activeVpTurns||{}))if(st(i,t,n))return!0;for(let i of Object.values(e.vpStatuses||{}))if(st(i,t,n)&&kr.has(i?.state))return!0;return!1}function by(e,t,s,n=null){let r={...e.yeaftProcessingSessions||{}};if(t){let i=Ea(t);if(r=Object.fromEntries(Object.entries(r).filter(([o])=>n?o!==St(t,n):!o.startsWith(i))),n)Mi(e,n,t)&&delete r[n];else for(let o of Object.keys(r))Mi(e,o,t)&&delete r[o]}else n?delete r[n]:r={};for(let i of s||[]){let o=i?.sessionId||i?.groupId||null;if(!o||!kr.has(i?.state))continue;let a=St(t,o)||o;r[a]=!0}return r}function hn(e,t,s){let n=Da(t,s);return n&&e?.activeVpTurns?.[n]?n:e?.activeVpTurns?.[s]&&(!t||!e.activeVpTurns[s]?.agentId||e.activeVpTurns[s].agentId===t)?s:n||s||""}function lp(e,t){if(!t){e.activeVpTurns={},e.stoppingVpTurnIds={},e.vpStatuses={},e.yeaftProcessingSessions={};return}e.activeVpTurns=Object.fromEntries(Object.entries(e.activeVpTurns||{}).filter(([,n])=>n?.agentId&&n.agentId!==t)),e.stoppingVpTurnIds=Object.fromEntries(Object.entries(e.stoppingVpTurnIds||{}).filter(([n])=>e.activeVpTurns?.[n])),e.vpStatuses=Object.fromEntries(Object.entries(e.vpStatuses||{}).filter(([,n])=>n?.agentId&&n.agentId!==t));let s=Ea(t);e.yeaftProcessingSessions=Object.fromEntries(Object.entries(e.yeaftProcessingSessions||{}).filter(([n])=>!n.startsWith(s)))}function Nt(e,t){return`${e||""}:${t||""}`}function Cy(e){return e?.kind==="action"&&typeof e.actionId=="string"&&Number.isInteger(Number(e.generation))&&Number(e.generation)>0?{kind:"action",actionId:e.actionId,generation:Number(e.generation)}:{kind:"coordinator"}}function Ay(e){return typeof e=="string"?e:e?.kind==="action"&&typeof e.actionId=="string"?{kind:"action",actionId:e.actionId,generation:Number.isInteger(Number(e.generation))?Number(e.generation):0}:{kind:"coordinator"}}function xy(e={}){let t=Qe(e.quote);return{agentId:e.agentId||"",workItemId:e.workItemId||"",target:Cy(e.target),text:String(e.text||""),...t?{quote:t}:{},attachments:Array.isArray(e.attachments)?e.attachments.map(s=>({fileId:s?.fileId||"",name:s?.name||"",mimeType:s?.mimeType||"",size:Math.max(0,Number(s?.size)||0)})):[],revision:Number(e.revision)||0,planRevision:Number(e.planRevision)||0,ledgerRevision:Number(e.ledgerRevision)||0,coordinatorRevision:Number(e.coordinatorRevision)||0}}function fp(e,t,s){return{conversationId:s||null,agentId:e?.agentId||t?.agentId||null,requestId:t?.requestId||null,toolCallId:t?.toolCallId||null,sessionId:e?.sessionId||t?.sessionId||null,vpId:e?.vpId||t?.vpId||null,turnId:e?.turnId||t?.turnId||null,threadId:e?.threadId||t?.threadId||null}}function gp(e,t){return{conversationId:t||null,agentId:e?.agentId||null,requestId:e?.askRequestId||null,toolCallId:e?.toolId||null,sessionId:e?.sessionId||e?.groupId||null,vpId:e?.vpId||e?.speakerVpId||null,turnId:e?.turnId||null,threadId:e?.threadId||null}}function Ty(e,t){return el.every(s=>!t[s]||e[s]===t[s])}function Cp(e,t){return el.every(s=>!e[s]||!t[s]||e[s]===t[s])}function mp(e,t,s){let n=(e||[]).filter(o=>o?.type==="tool-use"&&(o.toolName==="AskUser"||o.toolName==="AskUserQuestion")&&(!t.requestId||!o.askRequestId||o.askRequestId===t.requestId)&&(!t.toolCallId||!o.toolId||o.toolId===t.toolCallId)),r=n.filter(o=>Ty(gp(o,s),t));if(r.length===1)return r[0];let i=n.filter(o=>Cp(gp(o,s),t));return i.length===1?i[0]:null}function Ap(e){return el.map(t=>e[t]||"").join("\0")}function My(e,t,s){let n=Ap(t),r={...e._yeaftAskTerminalEvents||{},[n]:{identity:t,event:s,receivedAt:Date.now()}},i=Object.keys(r);if(i.length>pp){i.sort((o,a)=>r[o].receivedAt-r[a].receivedAt);for(let o of i.slice(0,i.length-pp))delete r[o]}e._yeaftAskTerminalEvents=r}function hp(e,t){let s=e._yeaftAskTerminalEvents||{},n=Ap(t),r=s[n]?n:null;if(!r){let l=Object.entries(s).filter(([,c])=>Cp(c.identity||{},t));l.length===1&&(r=l[0][0])}if(!r)return null;let i=s[r],{[r]:o,...a}=s;return e._yeaftAskTerminalEvents=a,i?.event||null}function Py(e,t,s){return(e.messagesMap?.[t]||[]).some(n=>n?.type==="tool-use"&&n.sessionId===s&&n.hasResult===!1)}function Ga(e,t){t.type==="ask_user_answered"?(e.askAnswered=!0,e.selectedAnswers=t.answers||{},e.askExpired=!1):(e.isHistory=!0,e.askExpired=!0,e.askAnswered=!1,e.selectedAnswers=null),e.askPending=!1,e.pendingAnswers=null,e.askSubmitGeneration=null,e.askRequestId=null}function Ry(e){if(!e||typeof e!="string")return null;let t=e.match(/^(\d+)/);if(!t)return null;let s=Number(t[1]);return Number.isFinite(s)?s:null}function _y(e){if(!e||typeof e!="string")return null;let t=e.match(/^m(\d+)$/);if(!t)return null;let s=Number(t[1]);return Number.isFinite(s)?s:null}function wr(e){return Wn(e)}function Qa(e,t,s){return`${St(e,t)}::${s||""}`}function Za(e){return Object.fromEntries(Object.entries(e||{}).filter(([,t])=>t?.status==="running"))}function cs(){try{return typeof window>"u"?null:window.Pinia?.useSessionsStore?.()||window.__useSessionsStore&&window.__useSessionsStore()||null}catch{return null}}function vp(e){let t=cs();if(!t?.reorderSessionsGlobally)return;let s=(Array.isArray(e)?e:[]).filter(n=>n?.runtimeProvider==="yeaft").map(n=>`${n.routeRef?.agentId||""}${n.routeRef?.sessionId||""}`).filter(n=>!n.startsWith(""));t.reorderSessionsGlobally(s)}function be(e,t,s=null){if(s)return s;if(t){let n=cs(),r=n?.activeSessionKey?n.sessions?.[n.activeSessionKey]:null;if(r?.id===t&&r.agentId)return r.agentId;let i=n&&typeof n.sessionById=="function"?n.sessionById(t,e?.currentAgent||null):null;if(i&&i.agentId)return i.agentId;let o=e?.yeaftSessionAgentById?e.yeaftSessionAgentById[t]:null;if(o)return o}return e?.currentAgent||null}function Ey(e,t){let s=i=>String(i||"").replace(/^v/,"").split(".").slice(0,3).map(o=>Number.parseInt(o,10)),n=s(e),r=s(t);if(n.length<3||r.length<3||[...n,...r].some(i=>!Number.isFinite(i)))return!1;for(let i=0;i<3;i+=1)if(n[i]!==r[i])return n[i]>r[i];return!0}function yp(e,t,s){if(!t||!s)return!1;let n=Array.isArray(e?.agents)?e.agents.find(o=>o?.id===t):null,r=e?.currentAgentInfo?.id===t?e.currentAgentInfo:null;return(n?.capabilities||r?.capabilities||[]).includes(s)?!0:s==="session_history_search"&&Ey(n?.version||r?.version,"1.0.166")}function Fs(e,{fallbackDefault:t=!1}={}){if(e?.yeaftActiveSessionFilter)return e.yeaftActiveSessionFilter;let s=cs();return s?.activeSessionId?s.activeSessionId:t?"grp_default":null}function Ti(e){let t=e.yeaftDebugSessionFilter;if(t==="__all__")return null;if(t)return t;let s=Fs(e);return s||(cs()?.sessions?.grp_default?"grp_default":null)}function Xa(e,t="session"){return[e?.vpId||e?.ownerVpId||"vp",e?.threadId||"thread",e?.turnId||t].join(":")}function qt(e,t,s=null){return s||t&&e?.yeaftConversationIdsByAgent?.[t]||e?.yeaftConversationId||null}function tt(e,t=null,s=null){let n=t||e?.yeaftActiveSessionFilter||null,r=s||be(e,n);return(r&&e?.yeaftConversationIdsByAgent?e.yeaftConversationIdsByAgent[r]:null)||e?.yeaftConversationId||null}function bp(e,t,s){if(e?.currentView!=="yeaft")return!1;let n=e?.yeaftActiveSessionFilter||null;if(n&&t!==n)return!1;let r=be(e,n);return!r||!s||r===s}var vy,$e,Ai,xi,cp,dp,wy,up,ky,kr,Sy,Iy,pp,el,wp,Ja,kp,Sp,Bs,Pi=N(()=>{kt();Go();Bt();da();ir();Gd();ou();_u();Ts();os();Hu();Sa();fi();Bu();Nu();Wu();la();Wa();Aa();ls();Ci();sn();ni();mr();op();ii();oa();xa();({defineStore:vy}=Pinia),$e=Object.freeze([]),Ai=(e,t,s)=>`${e||""}::${t||""}::${s}`;xi=5,cp=100,dp=512*1024,wy=15e3,up=Object.freeze([150,300,600,1e3]),ky=new Set(["index_building","stale_result"]),kr=new Set(["typing","thinking","retrying","streaming","tool"]),Sy=Object.freeze(["model","availableModels","refreshedAt","catalogRefreshedAt","catalogEpoch","catalogRevision","catalogDigest","refreshStartedAt","refreshReason","refreshError","refreshing"]),Iy=8,pp=64;el=Object.freeze(["conversationId","agentId","requestId","toolCallId","sessionId","vpId","turnId","threadId"]);wp=1e3,Ja=1,kp=5,Sp=200,Bs=vy("chat",{state:()=>({ws:null,authenticated:!1,_hasHandledAgentList:!1,_hasHandledYeaftSessionHydrate:!1,yeaftSessionInventoryCompleteSupported:null,yeaftSessionHydrateRequestId:null,yeaftSessionHydrateSlices:[],yeaftSessionHydrateError:null,_yeaftSessionInventorySocketQuarantined:!1,sessionKey:null,serverEncryptionRequired:!0,connectionState:"disconnected",reconnectAttempts:0,maxReconnectAttempts:10,reconnectTimer:null,agents:[],currentAgent:null,currentAgentInfo:null,conversations:[],activeConversations:[],currentWorkDir:null,messagesMap:{},_messageUiKeySequence:0,chatSessionState:{},panels:[],activePanelId:null,_pendingPaneId:null,conversationTitles:{},customConversationTitles:{},processingConversations:{},yeaftProcessingSessions:{},yeaftUnreadSessionKeys:{},theme:localStorage.getItem("theme")||(typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),themeFollowSystem:!localStorage.getItem("theme"),locale:localStorage.getItem("locale")||"zh-CN",executionStatusMap:{},sessionHealth:{},historySessions:[],historySessionsLoading:!1,folders:[],foldersLoading:!1,providerModels:[],providerModelsLoading:!1,contextUsage:null,lastUsedAgent:localStorage.getItem("lastUsedAgent")||null,lastUsedSession:JSON.parse(localStorage.getItem("lastUsedSession")||"null"),lastViewedConversation:localStorage.getItem("lastViewedConversation")||null,pendingRecovery:null,recoveryDismissed:!1,sessionLoading:!1,sessionLoadingText:"",agentSwitching:!1,pendingAgentSelection:null,_pendingSessionTitle:null,workbenchExpanded:!1,workbenchMaximized:!1,sidebarCollapsed:!1,sessionSidebarOpen:!1,compactStatus:null,clearStatus:null,refreshingSession:!1,refreshingSessionMap:{},proxyPorts:{},hasMoreMessages:!1,loadingMoreMessages:!1,chatHistoryRequests:{},chatHistoryRequestIdSupported:null,chatHistoryConnectionGeneration:0,sessionCatalog:[],hiddenSessionCatalog:[],sessionProjects:[],sessionCatalogLoaded:!1,sessionCatalogMutationRequests:{},projectMutationRequests:{},activeCatalogKey:null,openUnifiedSessionCreate:!1,openUnifiedChatCreate:!1,pendingUnifiedSessionSettings:null,yeaftHasMoreHistory:!1,yeaftLoadingMoreHistory:!1,yeaftOldestLoadedSeq:null,yeaftHistoryLoadError:null,yeaftSessionHistoryState:{},yeaftMessageWindowState:{},yeaftHistoryCacheState:{},_yeaftHistoryBrowserHydrationBySession:{},yeaftBootstrapMetaLoadingKey:null,yeaftHistoryPerfTraceBySession:{},yeaftHistorySearchState:{requestId:null,agentId:null,sessionId:null,query:"",senderKey:"",loading:!1,results:[],hasMore:!1,nextBeforeSeq:null,nextCursor:null,error:null},yeaftHistoryOutlineBySession:{},_yeaftHistoryOutlineTimeouts:{},_yeaftHistorySearchTimeout:null,_yeaftHistoryWindowPendingByKey:{},_yeaftHistoryRevealLeases:{},_yeaftHistoryRevealSequence:0,_yeaftReconnectCatchUpPending:!1,_yeaftOpenedSessionsLoadedAgents:{},_yeaftAgentSeen:null,slashCommandsMap:{},slashCommandDescriptions:{},inputDrafts:{},mcpServers:{},expertRoleDefinitions:null,llmConfig:{},llmModelDiscovery:{},llmGithubDevice:null,modelsDevRegistry:{registry:{},fetchedAt:0,error:null,loaded:!1},_modelsDevPending:null,yeaftSettings:{},searchSettings:null,telemetrySettings:null,tavilyUsage:null,tavilyUsageLoading:!1,_perfTraceQueue:[],_perfTraceFlushTimer:null,yeaftPerfTraceByMessageId:{},yeaftPerfTraceByTurnId:{},yeaftMcpServers:[],yeaftMcpRuntime:{connected:!1,toolCount:0,perServer:[]},yeaftMcpLoading:!1,yeaftMcpError:null,btwMode:!1,btwMessages:[],btwLoading:!1,btwSessionId:null,conversationMcpServers:{},conversationMcpServerTools:{},mcpPanelOpen:!1,expertSelections:[],customExpertRoles:[],subagents:{},activeSubagentId:null,activeRightPanel:null,pinnedSessions:JSON.parse(localStorage.getItem("pinned-sessions")||"[]"),...Lu(),workCenterOpen:!1,workCenterAgentId:null,workCenterItemsByAgent:{},workCenterListPageByAgent:{},workCenterListMoreLoadingByAgent:{},_workCenterListGenerationByAgent:{},_workCenterListQueryByAgent:{},_workCenterListFiltersByAgent:{},_workCenterListMoreRequestsByAgent:{},_workCenterListEventGenerationByAgent:{},_workCenterListEventsByAgent:{},_workCenterDeletedIdsByAgent:{},workCenterDetailByAgent:{},workCenterActionMessages:{},workCenterActionMessagesLoading:{},workCenterActionMessagesError:{},workCenterActionRequests:{},workCenterActionRequestDetails:{},workCenterActionRequestsLoading:{},workCenterActionRequestsError:{},workCenterActionRequestDetailsLoading:{},workCenterActionRequestDetailsError:{},workCenterLoadedByAgent:{},workCenterLoadingByAgent:{},workCenterErrorByAgent:{},workCenterWatcherByAgent:{},workCenterSettingsByAgent:{},workCenterRuntimeByAgent:{},workCenterSettingsLoadingByAgent:{},workCenterSettingsErrorByAgent:{},_workCenterSettingsGenerationByAgent:{},_workCenterDetailRequestGenerationByAgent:{},_workCenterDetailEventRefreshByAgent:{},_workCenterActionInputGenerationByAgent:{},_workCenterActionMessageRequests:{},_workCenterActionMessageGenerationByKey:{},_workCenterActionRequestsGeneration:{},_workCenterActionRequestDetailsGeneration:{},workCenterPending:{},workCenterComposerDrafts:{},workCenterMessageOutbox:{},_workCenterBrowserFence:null,_workCenterBrowserUnsubscribe:null,workCenterCreateDraft:null,yeaftConversationId:null,yeaftConversationIdsByAgent:{},_yeaftPendingConversationPromotions:{},_yeaftRetiredConversationIdsByAgent:{},_yeaftRetiredConversationTargetsByAgent:{},yeaftSessionAgentById:{},yeaftModel:null,yeaftModelEffort:null,yeaftSessionReady:!1,yeaftStatus:null,yeaftAvailableModels:[],yeaftStatusByAgent:{},_yeaftRetiredCatalogEpochsByAgent:{},yeaftModelsRefreshing:!1,yeaftModelRefreshError:null,yeaftYeaftDir:null,yeaftActiveTasksBySession:{},yeaftStoppingTasksById:{},yeaftToolStats:null,yeaftToolStatsLoading:!1,yeaftDebugLoops:[],yeaftDebugTurnsById:{},yeaftDebugTurnOrder:[],yeaftDebugHistoryLoading:!1,yeaftDebugHistoryError:null,yeaftDebugHistoryFetchedAt:0,yeaftDebugHistoryLimit:Ja,yeaftDebugHistoryHasMore:!1,yeaftDebugPanel:{open:!1,status:"idle",requestId:null,agentId:null,sessionId:null,turnId:null,error:null},yeaftDebugSearch:"",yeaftDebugSessionFilter:null,yeaftDreamLatest:{},yeaftDreamSnapshots:{},yeaftDreamPromptLoads:{},yeaftDreamEvents:{},yeaftReflectionCards:{},yeaftSubAgentCards:{},yeaftSidebarV2Enabled:!0,yeaftActiveSessionFilter:null,_currentYeaftSessionId:null,_currentYeaftVpId:null,_currentYeaftTurnId:null,_currentYeaftThreadId:null,_yeaftAskTerminalEvents:{},activeVpTurns:{},vpStatuses:{},stoppingVpTurnIds:{},yeaftVpTyping:{},_vpCrudPending:null}),getters:{currentConversation:e=>e.activeConversations[0]||null,activeConversationId:e=>Oa(e),activeSessionRoute(e){if(e.currentView==="yeaft"){let n=Fs(e);return n?{runtimeProvider:"yeaft",agentId:be(e,n),sessionId:n}:null}let t=Oa(e);if(!t)return null;let s=e.conversations.find(n=>n?.id===t&&n.type!=="yeaft");return s?{runtimeProvider:s.provider==="copilot"?"copilot":"claude-code",agentId:s.agentId||e.currentAgent||null,sessionId:t}:null},messages(e){let t=this.activeConversationId,s=t&&e.messagesMap[t]||$e;if(e.currentView==="yeaft"){let n=e.yeaftActiveSessionFilter||null,r=ve(be(e,n),n),i=e.yeaftMessageWindowState[r]?.visibleTurns||Os();return Ya(s,e.yeaftActiveSessionFilter||null,i)}return s},yeaftAllMessages:e=>{let t=tt(e);return t&&e.messagesMap[t]||$e},yeaftVisibleMessages(e){let t=tt(e),s=t&&e.messagesMap[t]||$e,n=e.yeaftActiveSessionFilter||null,r=ve(be(e,n),n),i=e.yeaftMessageWindowState[r]?.visibleTurns||Os();return Ya(s,e.yeaftActiveSessionFilter||null,i)},hasHiddenYeaftMessages(e){if(e.currentView!=="yeaft")return!1;let t=tt(e),s=t&&e.messagesMap[t]||$e,n=e.yeaftActiveSessionFilter||null,r=ve(be(e,n),n),i=e.yeaftMessageWindowState[r]?.visibleTurns||Os();return ip(s,e.yeaftActiveSessionFilter||null,i)},activeYeaftHistoryState(e){return Xo(e)},yeaftInitialHistoryLoading(e){let t=Xo(e);return e.currentView==="yeaft"&&!!e.yeaftActiveSessionFilter&&!!t?.loading&&!t?.loaded&&this.yeaftVisibleMessages.length===0},vpsTypingInCurrentConv(e){let t=this.activeConversationId;if(!t)return $e;let s=(e.yeaftVpTyping||{})[t];if(!s)return $e;let n=Object.keys(s).filter(r=>(s[r]||0)>0);return n.length===0?$e:n},isVpTypingInCurrentConv(e){return t=>{if(!t)return!1;let s=this.activeConversationId;if(!s)return!1;let n=(e.yeaftVpTyping||{})[s];return n?(n[t]||0)>0:!1}},yeaftDreamLatestForActiveSession(e){let t=Ti(e);if(!t)return null;let s=`sessions/${t}`;return e.yeaftDreamLatest?.[s]||null},yeaftDreamSnapshotForActiveSession(e){let t=Ti(e);if(!t)return null;let s=`sessions/${t}`;return e.yeaftDreamSnapshots?.[s]||null},yeaftDreamPromptLoadForActiveSession(e){let t=Ti(e);if(!t)return null;let s=`sessions/${t}`;return e.yeaftDreamPromptLoads?.[s]||null},yeaftDreamEventsForActiveSession(e){let t=Ti(e);if(!t)return[];let s=`sessions/${t}`,n=Array.isArray(e.yeaftDreamEvents?.[s])?e.yeaftDreamEvents[s]:[],r=Array.isArray(e.yeaftDreamEvents?.["*"])?e.yeaftDreamEvents["*"]:[];return r.length===0?n:n.length===0?r:[...n,...r].sort((i,o)=>(i.at||0)-(o.at||0))},yeaftDebugTurnsForActiveSession:e=>{let t=e.yeaftDebugTurnOrder||$e,s=e.yeaftDebugTurnsById||{},n=e.yeaftDebugLoops||$e,r=e.yeaftReflectionCards||{},i=e.yeaftDebugSessionFilter,o;i==="__all__"?o=null:i?o=i:o=null;let a={};for(let d of n)!d||!d.turnId||(a[d.turnId]||(a[d.turnId]=[]),a[d.turnId].push(d));let l={};for(let d of Object.keys(r)){let u=r[d];!u||!u.turnId||(l[u.turnId]||(l[u.turnId]=[]),l[u.turnId].push(u))}let c=[];for(let d=t.length-1;d>=0;d--){let u=t[d],f=s[u];if(!f||o&&f.sessionId&&f.sessionId!==o)continue;let p=a[u]||$e,g=l[u]||$e,m=p.length,v=0,k=0;for(let h of p){let y=h&&h.usage;y&&Number.isFinite(y.totalTokens)?v+=y.totalTokens:y&&(v+=(y.totalInputTokens||(y.inputTokens||0)+(y.cacheReadTokens||0)+(y.cacheWriteTokens||0))+(y.outputTokens||0)),h&&Number.isFinite(h.latencyMs)&&(k+=h.latencyMs)}let w=!f.closedAt,I={...f,loopCount:w||!f.loopCount?m:f.loopCount,totalTokens:w||!f.totalTokens?v:f.totalTokens,totalMs:w||!f.totalMs?k:f.totalMs,loops:p,reflections:g};c.push(I)}return c},yeaftDebugAvailableSessions:e=>{let t=new Set;for(let s of e.yeaftDebugTurnOrder||$e){let n=e.yeaftDebugTurnsById[s];n&&n.sessionId&&t.add(n.sessionId)}return Array.from(t).sort()},yeaftDebugTurnTotal:e=>(e.yeaftDebugTurnOrder||$e).length,messagesCache:e=>e.messagesMap,isMultiColumn:e=>e.activeConversations.length>1,isSplitMode:e=>e.panels.length>1,isProcessing:e=>{if(e.currentView==="yeaft"){let t=Fs(e);return t?ap(e,t,be(e,t)):!1}return e.currentConversation?!!e.processingConversations[e.currentConversation]:!1},canSend:e=>!(!e.currentAgent||!e.currentConversation),currentAgentName:e=>e.currentAgentInfo?.name||"\u9009\u62E9 Agent",currentAgentWorkDir:e=>e.currentAgentInfo?.workDir||"",effectiveWorkDir:e=>e.currentView==="yeaft"?cs()?.activeSession?.workDir||e.yeaftYeaftDir||e.currentAgentInfo?.workDir||"":e.currentWorkDir||e.currentAgentInfo?.workDir||"",currentAgentCapabilities:e=>e.currentAgentInfo?.capabilities||["terminal","file_editor","background_tasks"],hasCapability:e=>t=>(e.currentAgentInfo?.capabilities||["terminal","file_editor","background_tasks"]).includes(t),getConversationTitle:e=>t=>e.customConversationTitles[t]||e.conversationTitles[t]||null,executionStatus:e=>e.currentConversation?e.executionStatusMap[e.currentConversation]||{currentTool:null,toolHistory:[],lastActivity:null}:{currentTool:null,toolHistory:[],lastActivity:null},isConversationProcessing:e=>t=>!!e.processingConversations[t],isConversationConnecting:e=>t=>t?!!e.conversations.find(n=>n.id===t)?.connecting:!1,isConversationCompacting:e=>t=>t?e.compactStatus?.conversationId===t&&e.compactStatus?.status==="compacting":!1,isYeaftSessionProcessing:e=>(t,s=null)=>ap(e,t,s),isSessionHistorySyncing:e=>t=>{let s=t?.sessionId||null;return s?t.runtimeProvider==="yeaft"?!!e.yeaftSessionHistoryState?.[ve(t.agentId||null,s)]?.loading:!!e.chatHistoryRequests?.[is(s)]?.loading:!1},isYeaftSessionUnread:e=>(t,s=null)=>{if(!t)return!1;let n=be(e,t,s);return n?!!e.yeaftUnreadSessionKeys?.[li(n,t)]:!1},showRecoveryBanner:e=>e.pendingRecovery&&!e.recoveryDismissed&&!e.currentConversation,currentSubagents:e=>{if(!e.currentConversation)return $e;let t=e.subagents[e.currentConversation];return t?Object.values(t):$e},hasRunningSubagents:e=>{if(!e.currentConversation)return!1;let t=e.subagents[e.currentConversation];return t?Object.values(t).some(s=>s.status==="running"):!1},runningSubagentCount:e=>{if(!e.currentConversation)return 0;let t=e.subagents[e.currentConversation];return t?Object.values(t).filter(s=>s.status==="running").length:0},activeSubagentMessages:e=>{if(!e.currentConversation||!e.activeSubagentId)return $e;let t=e.subagents[e.currentConversation];if(!t)return $e;let s=t[e.activeSubagentId];return(Array.isArray(s?.messages)?s.messages:$e).filter(r=>r?.type==="text")},selectedTaskInfo:()=>null,currentMcpServers:e=>e.currentConversation&&e.conversationMcpServers[e.currentConversation]||$e},actions:{activateChatView({persistPreference:e=!1}={}){let t=this._pendingChatRestoreConversationId;this._pendingChatRestoreConversationId=null;let s=t?this.conversations.find(o=>o.id===t):null,n=s?.agentId?this.agents.find(o=>o.id===s.agentId&&o.online):null;!this._savedChatIdentity&&s&&n&&(this._savedChatIdentity={agentId:n.id,agentInfo:{...n},workDir:s.workDir||n.workDir||null}),this.currentView="chat",e&&Va("chat");let r=this._savedChatIdentity||null,i=this.pendingAgentSelection&&this.pendingAgentSelection.agentId!==r?.agentId;r?.agentId&&(this.currentAgent!==r.agentId||i)&&this.selectAgent(r.agentId),Vu(this),t&&s&&n&&(this.autoRestoreConversation(t),this.sendWsMessage({type:"refresh_conversation",conversationId:t}))},enterWorkCenter(e=null){if(!this.hydrateWorkCenterBrowserState())return!1;let t=this.agents.filter(n=>n?.online&&Array.isArray(n.capabilities)&&n.capabilities.includes("work_center")),s=t.some(n=>n.id===e)?e:t[0]?.id||null;if(!s)return this.workCenterOpen=!1,this.workCenterAgentId=null,!1;if(this.currentAgent!==s){this.selectAgent(s),this.currentAgent=s;let n=this.agents.find(r=>r.id===s);n&&(this.currentAgentInfo=n)}return this.workCenterAgentId=s,this.workCenterOpen=!0,this.listWorkItems(s).catch(()=>{}),!0},leaveWorkCenter(){this.workCenterOpen=!1},enterWorkCenterFromSession(e,t=""){if(!e?.id)return;let s=e.agentId||be(this,e.id),n=String(t||e.title||e.name||"").trim();this.workCenterCreateDraft={sourceAgentId:s,requirement:n,workDir:String(e.workDir||"").trim(),origin:{sessionId:e.id,messageId:null,createdBy:"user"},linkedSessionIds:[e.id]},this.enterWorkCenter(s)},hydrateWorkCenterBrowserState(){this._workCenterBrowserUnsubscribe||(this._workCenterBrowserUnsubscribe=Ic(()=>{Nn(this._workCenterBrowserFence)||this.clearWorkCenterBrowserState()}));let e=si();if(!e)return this._workCenterBrowserFence=null,this.workCenterComposerDrafts={},this.workCenterMessageOutbox={},!1;if(!Nn(this._workCenterBrowserFence)){let t=Sc(e);this._workCenterBrowserFence=e,this.workCenterComposerDrafts=t.drafts,this.workCenterMessageOutbox=t.outbox}return!0},clearWorkCenterBrowserState(){this._workCenterBrowserFence=null,this.workCenterComposerDrafts={},this.workCenterMessageOutbox={}},workCenterComposerKey(e,t){return Nt(e,t)},saveWorkCenterComposerDraft(e,t,s={}){let n=Nt(e,t);if(!e||!t)return;let r=Qe(s.quote),i={...this.workCenterComposerDrafts||{},[n]:{text:String(s.text||""),...r?{quote:r}:{},attachments:Array.isArray(s.attachments)?s.attachments:[],target:Ay(s.target),error:String(s.error||"")}};return Yo(i,this._workCenterBrowserFence)?(this.workCenterComposerDrafts=i,!0):!1},loadWorkCenterComposerDraft(e,t){return this.workCenterComposerDrafts?.[Nt(e,t)]||null},removeWorkCenterComposerDraft(e,t){let s=Nt(e,t),n={...this.workCenterComposerDrafts||{}};return delete n[s],Yo(n,this._workCenterBrowserFence)?(this.workCenterComposerDrafts=n,!0):!1},prepareWorkCenterMessageEnvelope(e={}){let t=xy(e),s=Nt(t.agentId,t.workItemId),n=this.workCenterMessageOutbox?.[s]||null;if(n)return n;let r={...t,clientMessageId:globalThis.crypto?.randomUUID?.()||`${Date.now()}-${Math.random()}`,createdAt:Date.now()},i={...this.workCenterMessageOutbox||{},[s]:r};return qn(i,this._workCenterBrowserFence)?(this.workCenterMessageOutbox=i,r):null},loadWorkCenterMessageEnvelope(e,t){return this.workCenterMessageOutbox?.[Nt(e,t)]||null},replaceWorkCenterMessageEnvelopeAttachments(e,t,s=[]){let n=Nt(e,t),r=this.workCenterMessageOutbox?.[n];if(!r)return null;let i={...r,attachments:Array.isArray(s)?s.map(a=>({fileId:a?.fileId||"",name:a?.name||"",mimeType:a?.mimeType||"",size:Math.max(0,Number(a?.size)||0)})):[]},o={...this.workCenterMessageOutbox||{},[n]:i};return qn(o,this._workCenterBrowserFence)?(this.workCenterMessageOutbox=o,i):null},discardWorkCenterMessageEnvelope(e,t){let s=Nt(e,t),n={...this.workCenterMessageOutbox||{}};return delete n[s],qn(n,this._workCenterBrowserFence)?(this.workCenterMessageOutbox=n,!0):!1},confirmWorkCenterMessageEnvelope(e,t,s){let n=Nt(e,t),r=this.workCenterMessageOutbox?.[n];if(!r||r.clientMessageId!==s)return!1;let i={...this.workCenterMessageOutbox||{}};return delete i[n],qn(i,this._workCenterBrowserFence)?(this.workCenterMessageOutbox=i,this.removeWorkCenterComposerDraft(e,t),!0):!1},workCenterRequest(e,t={},s=null){let n=s||this.workCenterAgentId||this.currentAgent;if(!n)return Promise.reject(new Error("No Agent selected"));let r=`work-center-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise((i,o)=>{let a=setTimeout(()=>{delete this.workCenterPending[r],o(new Error("Work Center request timed out"))},3e4);this.workCenterPending[r]={resolve:i,reject:o,timer:a,agentId:n,op:e,clientMessageId:typeof t.clientMessageId=="string"?t.clientMessageId:null},this.sendWsMessage({type:"work_center_request",agentId:n,requestId:r,op:e,payload:t})})},workItemMatchesBoardQuery(e,t={}){if(!e||t.lane&&e.boardLane!==t.lane||t.vpId&&!(e.executors||[]).some(n=>n?.id===t.vpId)||t.workItemType&&e.workItemType!==t.workItemType||t.updatedFrom&&Number(e.updatedAt)<Number(t.updatedFrom)||t.updatedTo&&Number(e.updatedAt)>Number(t.updatedTo))return!1;let s=String(t.keyword||"").trim().toLowerCase();return!s||String(e.title||"").toLowerCase().includes(s)||String(e.goal||"").toLowerCase().includes(s)},applyWorkItemBoardSummary(e,t,s={}){let n=ki(e,t),r=n.find(i=>i?.id===t?.id)||null;return!r||this.workItemMatchesBoardQuery(r,s)?n:n.filter(i=>i.id!==r.id)},async listWorkItems(e=null,t={}){let s=e||this.workCenterAgentId||this.currentAgent;if(!s)return[];let n={lane:["needs_attention","active","closed"].includes(t.lane)?t.lane:null,keyword:String(t.keyword||t.search||"").trim(),vpId:String(t.vpId||"").trim(),workItemType:String(t.workItemType||"").trim(),createdFrom:Number(t.createdFrom)||null,createdTo:Number(t.createdTo)||null,updatedFrom:Number(t.updatedFrom)||null,updatedTo:Number(t.updatedTo)||null,limit:Math.min(Math.max(Number(t.limit)||100,1),200)},r=JSON.stringify(n),i=Number(this._workCenterListGenerationByAgent[s]||0)+1,o=Number(this._workCenterListEventGenerationByAgent[s]||0);this._workCenterListGenerationByAgent={...this._workCenterListGenerationByAgent,[s]:i},this._workCenterListQueryByAgent={...this._workCenterListQueryByAgent,[s]:r},this._workCenterListFiltersByAgent={...this._workCenterListFiltersByAgent,[s]:n},this.workCenterLoadingByAgent={...this.workCenterLoadingByAgent,[s]:!0},this.workCenterErrorByAgent={...this.workCenterErrorByAgent,[s]:null};try{let a=await this.workCenterRequest("list",n,s),l=(Array.isArray(a?.items)?a.items:[]).filter(d=>!this.workItemDeleted(s,d?.id));if(this._workCenterListGenerationByAgent[s]===i&&this._workCenterListQueryByAgent[s]===r&&this.workCenterAgentId===s){let d=l,u=this._workCenterListEventsByAgent[s]||{};for(let f of Object.values(u))Number(f?.generation)<=o||f?.queryKey!==r||(d=this.applyWorkItemBoardSummary(d,f.summary,n));this.workCenterItemsByAgent={...this.workCenterItemsByAgent,[s]:d},this.workCenterListPageByAgent={...this.workCenterListPageByAgent,[s]:{nextCursor:a?.nextCursor||null,queryKey:r}},this.workCenterWatcherByAgent={...this.workCenterWatcherByAgent,[s]:a?.watcher||null},this.workCenterLoadedByAgent={...this.workCenterLoadedByAgent,[s]:!0}}return l}catch(a){throw this._workCenterListGenerationByAgent[s]===i&&this._workCenterListQueryByAgent[s]===r&&(this.workCenterErrorByAgent={...this.workCenterErrorByAgent,[s]:a?.message||String(a)}),a}finally{this._workCenterListGenerationByAgent[s]===i&&this._workCenterListQueryByAgent[s]===r&&(this.workCenterLoadingByAgent={...this.workCenterLoadingByAgent,[s]:!1})}},async loadMoreWorkItems(e=null){let t=e||this.workCenterAgentId||this.currentAgent,s=this.workCenterListPageByAgent[t],n=this._workCenterListFiltersByAgent[t];if(!t||!s?.nextCursor||!n)return[];let r=s.queryKey,i=this._workCenterListGenerationByAgent[t],o=Number(this._workCenterListEventGenerationByAgent[t]||0),a=s.nextCursor,l=`${i}:${r}:${a}`;if(this._workCenterListMoreRequestsByAgent[t]?.key===l)return this._workCenterListMoreRequestsByAgent[t].request;this.workCenterListMoreLoadingByAgent={...this.workCenterListMoreLoadingByAgent,[t]:!0};let c=(async()=>{try{let d=await this.workCenterRequest("list",{...n,cursor:a},t),u=this.workCenterListPageByAgent[t];if(this._workCenterListGenerationByAgent[t]!==i||this._workCenterListQueryByAgent[t]!==r||u?.queryKey!==r||u?.nextCursor!==a||this.workCenterAgentId!==t)return[];let f=[...this.workCenterItemsByAgent[t]||[]];for(let g of Array.isArray(d?.items)?d.items:[]){if(this.workItemDeleted(t,g?.id))continue;let m=f.findIndex(v=>v.id===g.id);m<0?f.push(g):f[m]=ki([f[m]],g)[0]}let p=this._workCenterListEventsByAgent[t]||{};for(let g of Object.values(p))Number(g?.generation)<=o||g?.queryKey!==r||(f=this.applyWorkItemBoardSummary(f,g.summary,n));return this.workCenterItemsByAgent={...this.workCenterItemsByAgent,[t]:f},this.workCenterListPageByAgent={...this.workCenterListPageByAgent,[t]:{nextCursor:d?.nextCursor||null,queryKey:r}},d?.items||[]}finally{if(this._workCenterListMoreRequestsByAgent[t]?.key===l){let d={...this._workCenterListMoreRequestsByAgent};delete d[t],this._workCenterListMoreRequestsByAgent=d,this.workCenterListMoreLoadingByAgent={...this.workCenterListMoreLoadingByAgent,[t]:!1}}}})();return this._workCenterListMoreRequestsByAgent={...this._workCenterListMoreRequestsByAgent,[t]:{key:l,request:c}},c},workItemDeleted(e,t){return!!this._workCenterDeletedIdsByAgent[e]?.[t]},removeWorkItemState(e,t){this._workCenterDeletedIdsByAgent={...this._workCenterDeletedIdsByAgent,[e]:{...this._workCenterDeletedIdsByAgent[e]||{},[t]:!0}},this.beginWorkCenterDetailWrite(e),this.workCenterItemsByAgent={...this.workCenterItemsByAgent,[e]:(this.workCenterItemsByAgent[e]||[]).filter(n=>n.id!==t)},this.workCenterDetailByAgent[e]?.id===t&&(this.workCenterDetailByAgent={...this.workCenterDetailByAgent,[e]:null});let s=`${e}:${t}:`;for(let n of["workCenterActionMessages","workCenterActionMessagesLoading","workCenterActionMessagesError","workCenterActionRequests","workCenterActionRequestsLoading","workCenterActionRequestsError","workCenterActionRequestDetails","workCenterActionRequestDetailsLoading","workCenterActionRequestDetailsError","_workCenterActionMessageRequests","_workCenterActionMessageGenerationByKey","_workCenterActionRequestsGeneration","_workCenterActionRequestDetailsGeneration"]){let r={};for(let[i,o]of Object.entries(this[n]||{}))i.startsWith(s)||(r[i]=o);this[n]=r}},beginWorkCenterDetailWrite(e){let t=Number(this._workCenterDetailRequestGenerationByAgent[e]||0)+1;return this._workCenterDetailRequestGenerationByAgent={...this._workCenterDetailRequestGenerationByAgent,[e]:t},t},commitWorkCenterDetail(e,t,s){if(t?.id&&this.workItemDeleted(e,t.id)||s!=null&&Number(this._workCenterDetailRequestGenerationByAgent[e]||0)!==s)return!1;let n=this.workCenterDetailByAgent[e];return n?.id===t?.id&&Zu(t,n)?!1:(this.workCenterDetailByAgent={...this.workCenterDetailByAgent,[e]:t},!0)},async getWorkItem(e,t=null){let s=t||this.workCenterAgentId||this.currentAgent,n=this.beginWorkCenterDetailWrite(s),r=await this.workCenterRequest("get",{id:e},s);return this.commitWorkCenterDetail(s,r,n),this.workCenterDetailByAgent[s]||r},invalidateWorkItemActionMessages(e,t,s,n){if(!e||!t||!s)return null;let r=ct(n),i=gn(e,t,s,r);this._workCenterActionMessageGenerationByKey={...this._workCenterActionMessageGenerationByKey,[i]:Number(this._workCenterActionMessageGenerationByKey[i]||0)+1};for(let a of["workCenterActionMessages","workCenterActionMessagesLoading","workCenterActionMessagesError"]){let l={...this[a]};delete l[i],this[a]=l}let o={...this._workCenterActionMessageRequests};for(let a of Object.keys(o))a.startsWith(`${i}:`)&&delete o[a];return this._workCenterActionMessageRequests=o,i},async loadWorkItemActionMessages(e,t,s,n,r=null){let i=r||this.workCenterAgentId||this.currentAgent,o=ct(s),a=gn(i,e,t,o),l=Number(this._workCenterActionMessageGenerationByKey[a]||0),c=`${a}:${n==null?"latest":String(n)}`;if(this._workCenterActionMessageRequests[c])return this._workCenterActionMessageRequests[c];this.workCenterActionMessagesLoading={...this.workCenterActionMessagesLoading,[a]:!0},this.workCenterActionMessagesError={...this.workCenterActionMessagesError,[a]:null};let d=(async()=>{try{let u=await this.workCenterRequest("get_action_messages",{id:e,actionId:t,generation:o,cursor:n,limit:20},i);if(this.workItemDeleted(i,e)||ct(u?.generation)!==o||Number(this._workCenterActionMessageGenerationByKey[a]||0)!==l)return u;let f=this.workCenterActionMessages[a]?.messages||[],p=vr(f,u?.messages||[]),g=this.workCenterActionMessages[a],m=g?.nextCursor,v=n==null?null:Number(n),k=m==null?null:Number(m),w=!g||v==null||k!=null&&v===k;return this.workCenterActionMessages={...this.workCenterActionMessages,[a]:{generation:o,messages:p,nextCursor:w?u?.nextCursor??null:m,total:Math.max(Number(u?.total)||0,Number(g?.total)||0,p.length)}},u}catch(u){throw Number(this._workCenterActionMessageGenerationByKey[a]||0)===l&&(this.workCenterActionMessagesError={...this.workCenterActionMessagesError,[a]:u?.message||String(u)}),u}finally{if(this._workCenterActionMessageRequests[c]===d){let u={...this._workCenterActionMessageRequests};delete u[c],this._workCenterActionMessageRequests=u;let f=Object.keys(u).some(p=>p.startsWith(`${a}:`));this.workCenterActionMessagesLoading={...this.workCenterActionMessagesLoading,[a]:f}}}})();return this._workCenterActionMessageRequests={...this._workCenterActionMessageRequests,[c]:d},d},async loadWorkItemActionRequests(e,t,s,n=null){let r=n||this.workCenterAgentId||this.currentAgent,i=ct(s),o=Ba(r,e,t,i),a=Number(this._workCenterActionRequestsGeneration[o]||0)+1;this._workCenterActionRequestsGeneration={...this._workCenterActionRequestsGeneration,[o]:a},this.workCenterActionRequestsLoading={...this.workCenterActionRequestsLoading,[o]:!0},this.workCenterActionRequestsError={...this.workCenterActionRequestsError,[o]:null};try{let l=await this.workCenterRequest("get_action_requests",{id:e,actionId:t,generation:i},r),c=!this.workItemDeleted(r,e)&&ct(l?.generation)===i&&this._workCenterActionRequestsGeneration[o]===a;return c&&(this.workCenterActionRequests={...this.workCenterActionRequests,[o]:l?.requests||[]}),c?l?.requests||[]:this.workCenterActionRequests[o]||[]}catch(l){throw this._workCenterActionRequestsGeneration[o]===a&&(this.workCenterActionRequestsError={...this.workCenterActionRequestsError,[o]:l?.message||String(l)}),l}finally{this._workCenterActionRequestsGeneration[o]===a&&(this.workCenterActionRequestsLoading={...this.workCenterActionRequestsLoading,[o]:!1})}},async loadWorkItemActionRequest(e,t,s,n,r,i=null){let o=i||this.workCenterAgentId||this.currentAgent,a=ct(s),c=`${Ba(o,e,t,a)}:${n}:${r}`,d=Number(this._workCenterActionRequestDetailsGeneration[c]||0)+1;this._workCenterActionRequestDetailsGeneration={...this._workCenterActionRequestDetailsGeneration,[c]:d},this.workCenterActionRequestDetailsLoading={...this.workCenterActionRequestDetailsLoading,[c]:!0},this.workCenterActionRequestDetailsError={...this.workCenterActionRequestDetailsError,[c]:null};try{let u=await this.workCenterRequest("get_action_request",{id:e,actionId:t,generation:a,runId:n,requestId:r},o),f=!this.workItemDeleted(o,e)&&ct(u?.generation)===a&&this._workCenterActionRequestDetailsGeneration[c]===d;return f&&(this.workCenterActionRequestDetails={...this.workCenterActionRequestDetails,[c]:u?.request||null}),f?u?.request||null:this.workCenterActionRequestDetails[c]||null}catch(u){throw this._workCenterActionRequestDetailsGeneration[c]===d&&(this.workCenterActionRequestDetailsError={...this.workCenterActionRequestDetailsError,[c]:u?.message||String(u)}),u}finally{this._workCenterActionRequestDetailsGeneration[c]===d&&(this.workCenterActionRequestDetailsLoading={...this.workCenterActionRequestDetailsLoading,[c]:!1})}},async loadWorkCenterSettings(e=null){let t=e||this.workCenterAgentId||this.currentAgent;if(!t)throw new Error("No Agent selected");let s=Number(this._workCenterSettingsGenerationByAgent[t]||0)+1;this._workCenterSettingsGenerationByAgent={...this._workCenterSettingsGenerationByAgent,[t]:s},this.workCenterSettingsLoadingByAgent={...this.workCenterSettingsLoadingByAgent,[t]:!0},this.workCenterSettingsErrorByAgent={...this.workCenterSettingsErrorByAgent,[t]:null};try{let n=await this.workCenterRequest("get_settings",{},t);return this._workCenterSettingsGenerationByAgent[t]===s&&(this.workCenterSettingsByAgent={...this.workCenterSettingsByAgent,[t]:n?.settings||null},this.workCenterRuntimeByAgent={...this.workCenterRuntimeByAgent,[t]:n?.runtime||null}),n}catch(n){throw this._workCenterSettingsGenerationByAgent[t]===s&&(this.workCenterSettingsErrorByAgent={...this.workCenterSettingsErrorByAgent,[t]:n?.message||String(n)}),n}finally{this._workCenterSettingsGenerationByAgent[t]===s&&(this.workCenterSettingsLoadingByAgent={...this.workCenterSettingsLoadingByAgent,[t]:!1})}},async refreshWorkCenterRuntime(e=null){let t=e||this.workCenterAgentId||this.currentAgent;if(!t)throw new Error("No Agent selected");let s=Number(this._workCenterSettingsGenerationByAgent[t]||0)+1;this._workCenterSettingsGenerationByAgent={...this._workCenterSettingsGenerationByAgent,[t]:s},this.workCenterSettingsLoadingByAgent={...this.workCenterSettingsLoadingByAgent,[t]:!0},this.workCenterSettingsErrorByAgent={...this.workCenterSettingsErrorByAgent,[t]:null};try{let n=await this.workCenterRequest("refresh_runtime",{},t);return this._workCenterSettingsGenerationByAgent[t]===s&&(this.workCenterSettingsByAgent={...this.workCenterSettingsByAgent,[t]:n?.settings||null},this.workCenterRuntimeByAgent={...this.workCenterRuntimeByAgent,[t]:n?.runtime||null}),n}catch(n){throw this._workCenterSettingsGenerationByAgent[t]===s&&(this.workCenterSettingsErrorByAgent={...this.workCenterSettingsErrorByAgent,[t]:n?.message||String(n)}),n}finally{this._workCenterSettingsGenerationByAgent[t]===s&&(this.workCenterSettingsLoadingByAgent={...this.workCenterSettingsLoadingByAgent,[t]:!1})}},async saveWorkCenterSettings(e,t=null){let s=t||this.workCenterAgentId||this.currentAgent;if(!s)throw new Error("No Agent selected");let n=Number(this._workCenterSettingsGenerationByAgent[s]||0)+1;this._workCenterSettingsGenerationByAgent={...this._workCenterSettingsGenerationByAgent,[s]:n};let r=await this.workCenterRequest("update_settings",{settings:e},s);return this._workCenterSettingsGenerationByAgent[s]===n&&(this.workCenterSettingsByAgent={...this.workCenterSettingsByAgent,[s]:r?.settings||null},this.workCenterRuntimeByAgent={...this.workCenterRuntimeByAgent,[s]:r?.runtime||null},this.workCenterSettingsErrorByAgent={...this.workCenterSettingsErrorByAgent,[s]:null}),r},previewWorkCenterPlan(e={},t=null){let s=t||this.workCenterAgentId||this.currentAgent;return this.workCenterRequest("preview",e,s)},async createWorkItem(e,t=null){let s=t||this.workCenterAgentId||this.currentAgent,n=this.beginWorkCenterDetailWrite(s),r=await this.workCenterRequest("create",e,s);return await this.listWorkItems(s,this._workCenterListFiltersByAgent[s]||{}),this.commitWorkCenterDetail(s,r,n),r},async updateWorkItem(e,t,s=null){let n=s||this.workCenterAgentId||this.currentAgent,r=this.beginWorkCenterDetailWrite(n),i=await this.workCenterRequest("update",{id:e,patch:t},n);return await this.listWorkItems(n,this._workCenterListFiltersByAgent[n]||{}),this.commitWorkCenterDetail(n,i,r),i},async startWorkItem(e,t=null){let s=t||this.workCenterAgentId||this.currentAgent,n=this.beginWorkCenterDetailWrite(s),r=await this.workCenterRequest("start",{id:e},s);return await this.listWorkItems(s,this._workCenterListFiltersByAgent[s]||{}),this.commitWorkCenterDetail(s,r,n),r},async cancelWorkItem(e,t=null){let s=t||this.workCenterAgentId||this.currentAgent,n=this.beginWorkCenterDetailWrite(s),r=await this.workCenterRequest("cancel",{id:e},s);return await this.listWorkItems(s,this._workCenterListFiltersByAgent[s]||{}),this.commitWorkCenterDetail(s,r,n),r},async resumeWorkItem(e,t,s=null){let n=s||this.workCenterAgentId||this.currentAgent,r=this.beginWorkCenterDetailWrite(n),i=await this.workCenterRequest("resume",{id:e,revision:t},n);return await this.listWorkItems(n,this._workCenterListFiltersByAgent[n]||{}),this.commitWorkCenterDetail(n,i,r),i},async deleteWorkItem(e,t,s=null){let n=s||this.workCenterAgentId||this.currentAgent,r=await this.workCenterRequest("delete",{id:e,revision:t},n);return this.removeWorkItemState(n,e),r},async postWorkItemMessage(e,t,s,n,r=[],i=null,o={},a=null){if(!this.hydrateWorkCenterBrowserState())throw new Error("Work Center browser owner is unavailable; sign in again and retry");let l=i||this.workCenterAgentId||this.currentAgent,c=this.prepareWorkCenterMessageEnvelope({agentId:l,workItemId:e,target:s,text:t,quote:a,attachments:r,revision:n,planRevision:o.planRevision,ledgerRevision:o.ledgerRevision,coordinatorRevision:o.coordinatorRevision});if(!c)throw new Error("Work Center browser owner changed; reopen Work Center and try again");let d=c.clientMessageId,u=this.workCenterDetailByAgent[l]?.id===e?this.workCenterDetailByAgent[l]:null,f=await this.workCenterRequest("post_work_item_message",{id:c.workItemId,clientMessageId:d,text:c.text,target:c.target,revision:c.revision,planRevision:c.planRevision||Number(u?.planRevision)||0,ledgerRevision:c.ledgerRevision||Number(u?.ledgerRevision)||0,coordinatorRevision:Number.isInteger(Number(c.coordinatorRevision))?Number(c.coordinatorRevision):Number(u?.coordinatorRevision)||0,...c.quote?{quote:c.quote}:{},attachments:c.attachments},l);if(c.target.kind==="coordinator"){if(!f?.accepted)throw new Error("Work Center Coordinator did not accept the message");return this.confirmWorkCenterMessageEnvelope(l,e,d),f}return await this.listWorkItems(l,this._workCenterListFiltersByAgent[l]||{}),this.confirmWorkCenterMessageEnvelope(l,e,d),f},async sendWorkItemMessage(e,t,s,n=[],r=null,i={},o=null){let a=r||this.workCenterAgentId||this.currentAgent,l=this.workCenterDetailByAgent[a]?.id===e?this.workCenterDetailByAgent[a]:null,c=await this.workCenterRequest("work_item_message",{id:e,text:t,revision:s,planRevision:Number.isInteger(Number(i.planRevision))?Number(i.planRevision):Number(l?.planRevision)||0,ledgerRevision:Number.isInteger(Number(i.ledgerRevision))?Number(i.ledgerRevision):Number(l?.ledgerRevision)||0,coordinatorRevision:Number.isInteger(Number(i.coordinatorRevision))?Number(i.coordinatorRevision):Number(l?.coordinatorRevision)||0,...Qe(o)?{quote:Qe(o)}:{},attachments:Array.isArray(n)?n:[]},a);if(!c?.accepted)throw new Error("Work Center Coordinator did not accept the message");return c},async retryWorkItemAction(e,t,s,n,r=null){let i=r||this.workCenterAgentId||this.currentAgent,o=this.beginWorkCenterDetailWrite(i),a=await this.workCenterRequest("retry_action",{id:e,actionId:t,revision:s,generation:n},i);return await this.listWorkItems(i,this._workCenterListFiltersByAgent[i]||{}),this.commitWorkCenterDetail(i,a,o),a},async sendWorkItemActionInput(e,t,s,n,r,i=[],o=null,a=null){let l=o||this.workCenterAgentId||this.currentAgent,c=Number(this._workCenterActionInputGenerationByAgent[l]||0)+1;this._workCenterActionInputGenerationByAgent={...this._workCenterActionInputGenerationByAgent,[l]:c};let d=Qe(a),u=await this.workCenterRequest("action_input",{id:e,text:t,actionId:s,revision:n,generation:r,attachments:i,...d?{quote:d}:{}},l);await this.listWorkItems(l,this._workCenterListFiltersByAgent[l]||{});let f=this.workCenterDetailByAgent[l],p=f?.actions?.find(m=>m?.id===s),g=f?.id===e&&Number(f.revision)===Number(n)&&p&&Number(p.generation)===Number(r);return this._workCenterActionInputGenerationByAgent[l]===c&&g&&!Ku(u,f)?(this.workCenterDetailByAgent={...this.workCenterDetailByAgent,[l]:u},u):f?.id===e?f:u},async guideWorkItemAction(e,t,s,n,r,i=[],o=null){let a=o||this.workCenterAgentId||this.currentAgent,l=this.beginWorkCenterDetailWrite(a),c=await this.workCenterRequest("guide",{id:e,guidance:t,actionId:s,revision:n,generation:r,attachments:i},a);return await this.listWorkItems(a,this._workCenterListFiltersByAgent[a]||{}),this.commitWorkCenterDetail(a,c,l),c},previewWorkItemAttachment(e,t,s=null){let n=s||this.workCenterAgentId||this.currentAgent;return this.workCenterRequest("preview_attachment",{id:e,attachmentId:t},n)},applyWorkCenterEvent(e,t){if(!e||!t?.workItem)return;let s=t.workItem;if(t.clientMessageId){this.confirmWorkCenterMessageEnvelope(e,s.id,t.clientMessageId);let u=Object.entries(this.workCenterPending||{}).find(([,f])=>f?.agentId===e&&f.clientMessageId===t.clientMessageId);if(u){let[f,p]=u;clearTimeout(p.timer),delete this.workCenterPending[f],p.resolve(t.type==="coordinator.turn_started"?{accepted:!0,turnId:null,receipt:!0}:t.workItem)}}let n=this.workCenterItemsByAgent[e]||[];if(t.type==="work_item.deleted"){this.removeWorkItemState(e,s.id);return}if(this.workItemDeleted(e,s.id))return;let r=this._workCenterListFiltersByAgent[e]||{},i=this._workCenterListEventsByAgent[e]?.[s.id]?.summary||null,o=n.some(u=>u?.id===s.id)?n:i?[i]:[],a=ki(o,s).find(u=>u?.id===s.id)||s,l=Number(this._workCenterListEventGenerationByAgent[e]||0)+1;this._workCenterListEventGenerationByAgent={...this._workCenterListEventGenerationByAgent,[e]:l},this._workCenterListEventsByAgent={...this._workCenterListEventsByAgent,[e]:{...this._workCenterListEventsByAgent[e]||{},[s.id]:{generation:l,queryKey:this._workCenterListQueryByAgent[e]||null,summary:a}}};let c=this.applyWorkItemBoardSummary(n,a,r);this.workCenterItemsByAgent={...this.workCenterItemsByAgent,[e]:c};let d=this.workCenterDetailByAgent[e];if(d?.id===s.id){let u=t.type==="run.finished"&&t.actionId&&Array.isArray(s.actionStats)&&s.actionStats.some(k=>k?.id===t.actionId)?{...s,eventActionId:t.actionId}:s,f=qa(d,u),p=Number(s.coordinatorRevision),g=Number(d.coordinatorRevision)||0,m=Number.isInteger(p)&&p>g,v=zu(d,u);this.workCenterDetailByAgent={...this.workCenterDetailByAgent,[e]:Yu(d,s)},v&&this.refreshWorkItemDetailAfterActionChange(e,s,m?null:f)}},async refreshWorkItemDetailAfterActionChange(e,t,s=null){let n=s?(Array.isArray(t.actionStats)?t.actionStats:[]).find(m=>m?.id===s.actionId):(Array.isArray(t.actionStats)?t.actionStats:[]).find(m=>m?.id===t.currentActionId)||t.currentAction,r=s?.actionId||t.currentActionId||null,i=Number(s?.generation??n?.generation),o=Number.isInteger(i)&&i>0?i:null,a=Number(t.coordinatorRevision),l=!s&&Number.isInteger(a)&&a>=0?a:null,c=Number(s?.attempt),d=Number.isInteger(c)&&c>=0?c:null,u=l!=null?`${t.id}:coordinator:${l}`:`${t.id}:${r}${o==null?"":`:${o}`}${d==null?"":`:${d}`}`;if(this._workCenterDetailEventRefreshByAgent[e]?.key===u)return;let f=this.beginWorkCenterDetailWrite(e),p={key:u,generation:f};this._workCenterDetailEventRefreshByAgent={...this._workCenterDetailEventRefreshByAgent,[e]:p},s&&this.invalidateWorkItemActionMessages(e,t.id,s.actionId,s.generation);let g=r&&o!=null?this.loadWorkItemActionMessages(t.id,r,o,null,e).catch(()=>null):null;try{let m=await this.workCenterRequest("get",{id:t.id},e),v=this.workCenterDetailByAgent[e],k=v?.actions?.find(M=>M?.id===r),w=m?.actions?.find(M=>M?.id===r),I=o==null||ct(k?.generation)===o,h=o==null||ct(w?.generation)>=o,y=l==null||Number(m?.coordinatorRevision)===l,b=l!=null||I&&h&&(t.currentActionId==null?m?.currentActionId==null:v?.currentActionId===t.currentActionId&&m?.currentActionId===t.currentActionId);v?.id===t.id&&y&&b&&this.commitWorkCenterDetail(e,m,f)&&g&&await g}catch{}finally{if(this._workCenterDetailEventRefreshByAgent[e]===p){let m={...this._workCenterDetailEventRefreshByAgent};delete m[e],this._workCenterDetailEventRefreshByAgent=m}}},cacheYeaftAgentStatus(e,t,{allowBootstrapCatalog:s=!1}={}){if(!e||!t)return;let n=this.yeaftStatusByAgent[e]||{},r=Number(n.catalogRevision)||0,i=Number(t.catalogRevision)||0,o=typeof n.catalogEpoch=="string"?n.catalogEpoch:"",a=typeof t.catalogEpoch=="string"?t.catalogEpoch:"",l=Number(n.catalogRefreshedAt)||0,c=Number(t.catalogRefreshedAt)||0,d=Array.isArray(t.availableModels),u=t.type==="yeaft_status"&&d&&(i>0||c>0),f=Array.isArray(this._yeaftRetiredCatalogEpochsByAgent?.[e])?this._yeaftRetiredCatalogEpochsByAgent[e]:[],p=!!a&&f.includes(a),g=!!a&&a===o,m=i>0?g&&i===r:c>0&&c===l,v=i>0?!!a&&(a!==o||i>r):r===0&&c>l,k=i>0?!!t.catalogDigest&&!!n.catalogDigest&&t.catalogDigest===n.catalogDigest:t.catalogDigest===n.catalogDigest,w=u&&!p&&(v||m&&k),h=w||s&&r===0&&l===0&&!u&&d,y={...t};if(!h)for(let M of Sy)delete y[M];let b={...n,...y};if(h){if(w&&o&&a&&o!==a){let M=[...f.filter(x=>x!==o),o].slice(-Iy);this._yeaftRetiredCatalogEpochsByAgent={...this._yeaftRetiredCatalogEpochsByAgent||{},[e]:M}}b.availableModels=t.availableModels,b.catalogRefreshedAt=w?c:null,b.catalogEpoch=w&&a||null,b.catalogRevision=w&&i||null,b.catalogDigest=w&&t.catalogDigest||null}this.yeaftStatusByAgent={...this.yeaftStatusByAgent,[e]:b},this.currentAgent===e&&this.applyCachedYeaftStatus(e)},applyCachedYeaftStatus(e=this.currentAgent){let t=e?this.yeaftStatusByAgent[e]:null;return t?(this.yeaftModel=t.model||null,this.yeaftModelEffort=t.modelEffort||null,this.yeaftAvailableModels=Array.isArray(t.availableModels)?t.availableModels:[],this.yeaftModelsRefreshing=!!t.refreshing,this.yeaftModelRefreshError=t.refreshError||null,this.yeaftYeaftDir=t.yeaftDir||null,this.yeaftStatus={skills:t.skills,mcpServers:t.mcpServers,tools:t.tools,multiVp:!!t.multiVp},!0):!1},activateYeaftAgentCatalog(e,t=this.currentAgent){let s=e?this.yeaftStatusByAgent[e]:null;return s&&this.applyCachedYeaftStatus(e),Array.isArray(s?.availableModels)?!0:(this.yeaftModel=null,this.yeaftModelEffort=null,this.yeaftAvailableModels=[],s||(this.yeaftStatus=null),this.yeaftModelsRefreshing=!!e&&!s?.refreshError,this.yeaftModelRefreshError=s?.refreshError||null,t!==e&&(this.yeaftYeaftDir=null),!1)},activateYeaftAgent(e,t=null){if(!e)return!1;let s=this.currentAgent;return this.currentAgent=e,t&&(this.currentAgentInfo=t),this.activateYeaftAgentCatalog(e,s)},resolveYeaftSessionAgentId(e){return be(this,e)},requestYeaftSessionInventory(){if(this.yeaftSessionInventoryCompleteSupported===!1&&this.yeaftSessionHydrateRequestId)return this.yeaftSessionHydrateRequestId;if(this._yeaftSessionInventorySocketQuarantined)return this.manualReconnect(),null;clearTimeout(this._legacyYeaftSessionHydrateTimer),this._legacyYeaftSessionHydrateTimer=null;let e=`session_inventory_${crypto.randomUUID()}`;this.yeaftSessionHydrateRequestId=e,this.yeaftSessionHydrateSlices=[],this._hasHandledAgentList=!1,this._hasHandledYeaftSessionHydrate=!1,this.yeaftSessionHydrateError=null;let t=this.conversations.map(n=>n.id).filter(Boolean);return this.sendWsMessage({type:"get_agents",requestId:e,conversationIds:t.length>0?t:void 0})?(setTimeout(()=>{this.yeaftSessionHydrateRequestId===e&&(this.yeaftSessionHydrateRequestId=null,this.yeaftSessionHydrateSlices=[],this.yeaftSessionHydrateError="session_inventory_timeout",this.yeaftSessionInventoryCompleteSupported!==!0&&(this._yeaftSessionInventorySocketQuarantined=!0))},wy),e):(this.yeaftSessionHydrateRequestId=null,this.yeaftSessionHydrateSlices=[],this.yeaftSessionHydrateError="session_inventory_send_failed",null)},beginYeaftHistoryLoad(e){let t=Ac(this,e);if(!t)return null;let{agentId:s,sessionId:n}=e||{};return setTimeout(()=>{Un(this,{agentId:s,sessionId:n,requestId:t.requestId,error:"history_load_timeout"})},Cc),t},finishYeaftHistoryLoad(e,t={},s="chunk"){return xc(this,e,t,s)},isCurrentYeaftHistoryResponse(e){return Zo(this,e)},syncActiveYeaftHistoryLoad(){return ks(this)},enterYeaft(e=null,{deferBootstrap:t=!1}={}){let s=this.currentAgent;Ha(this);let n=Fs(this),r=!e&&n?be(this,n):null,i=e||r||this.currentAgent||null;if(!i){let a=this.agents.find(l=>l.online);a&&(i=a.id)}if(i&&this.currentAgent!==i){this.selectAgent(i),this.currentAgent=i;let a=this.agents.find(l=>l.id===i);a&&(this.currentAgentInfo=a)}if(!this.applyCachedYeaftStatus(i)&&s&&s!==i&&(this.yeaftAvailableModels=[],this.yeaftStatus=null,this.yeaftModelsRefreshing=!0,this.yeaftModelRefreshError=null),i){let a=this.yeaftConversationIdsByAgent?.[i]||null;a||(a=`yeaft-local-${i}-${Date.now()}`,this.yeaftConversationIdsByAgent={...this.yeaftConversationIdsByAgent||{},[i]:a}),this.yeaftConversationId=a}else this.yeaftConversationId||(this.yeaftConversationId=`yeaft-local-${Date.now()}`);this.messagesMap[this.yeaftConversationId]||(this.messagesMap[this.yeaftConversationId]=[]),$u(this),this.currentView="yeaft",Va("yeaft"),this.hasMoreMessages=!1,this.loadingMoreMessages=!1,this.yeaftHasMoreHistory=!1,this.yeaftLoadingMoreHistory=!1,this.yeaftOldestLoadedSeq=null,this._yeaftReconnectCatchUpPending=!1,this.loadOpenedYeaftSessionsForConnectedAgents(null,{force:!0}),t||this.requestYeaftSessionBootstrap({forceSessionReady:!0,catchUpHistory:!0,forceHistoryReplay:!0})},loadOpenedYeaftSessionsForConnectedAgents(e=null,{force:t=!1}={}){let s=Array.isArray(e)?e.filter(Boolean):Array.isArray(this.agents)?this.agents.filter(i=>i&&i.online&&i.id).map(i=>i.id):[],n=[...new Set(s)];(!this._yeaftOpenedSessionsLoadedAgents||typeof this._yeaftOpenedSessionsLoadedAgents!="object")&&(this._yeaftOpenedSessionsLoadedAgents={});let r=[];for(let i of n)!t&&this._yeaftOpenedSessionsLoadedAgents[i]||(this._yeaftOpenedSessionsLoadedAgents[i]=Date.now(),r.push(i),this.sessionCrudRequest("list",{},{agentId:i}).catch(o=>{delete this._yeaftOpenedSessionsLoadedAgents[i]}));return r},requestYeaftSessionBootstrap({forceSessionReady:e=!1,catchUpHistory:t=!1,forceHistoryReplay:s=!1}={}){if(!this.currentAgent)return;let n=Fs(this),r=n?be(this,n):this.currentAgent,i=ve(r,n),o=n?this.yeaftSessionHistoryState[i]:null,a=e||!this.yeaftSessionReady||!this.yeaftModel||!this.yeaftStatus,l=Number.isFinite(o?.latestSeq)?o.latestSeq:null,c=!!n&&!!this.yeaftConversationId&&Array.isArray(this.messagesMap?.[this.yeaftConversationId])&&this.messagesMap[this.yeaftConversationId].some(I=>I&&(I.sessionId??I.groupId??null)===n),d=!!this._yeaftHistoryBrowserHydrationBySession?.[i];n&&r&&!o?.loaded&&!o?.loading&&!c&&!d&&(d=!0,this.hydrateYeaftHistoryBrowserCache(n,r,{revalidate:!0}));let u=!!n&&!d&&bd({sessionState:o,hasCachedSessionRows:c,force:!!s}),f=!!n&&!d&&!u&&yd(o,t);if(!a&&!u&&!f)return!1;let p=`${r}:${n||"__none__"}`,g=a&&!u&&!f;if(g&&this.yeaftBootstrapMetaLoadingKey===p)return!1;g&&(this.yeaftBootstrapMetaLoadingKey=p);let m=null;n&&u?m=this.beginYeaftHistoryLoad({agentId:r,sessionId:n,mode:"recent",preserveLoaded:!1}):n&&c&&!o?.loaded?(this.yeaftSessionHistoryState={...this.yeaftSessionHistoryState,[i]:{...o||{},loaded:!0,loading:!1,hasMore:!!o?.hasMore,oldestSeq:Number.isFinite(o?.oldestSeq)?o.oldestSeq:null,count:o?.count||0,latestSeq:l}},this.yeaftLoadingMoreHistory=!1):n&&f&&(m=this.beginYeaftHistoryLoad({agentId:r,sessionId:n,mode:"delta",preserveLoaded:!0,latestSeq:l}));let v={type:"yeaft_load_history",agentId:r,sessionId:n,...m?{requestId:m.requestId}:{}};f?v.afterSeq=l:v.limit=u?xi:0;let k=_s();v.perfTraceId=k;let w=f?"delta":u?"recent":"metadata";return n&&(this.yeaftHistoryPerfTraceBySession={...this.yeaftHistoryPerfTraceBySession||{},[i]:k}),Ge(this,{traceId:k,phase:"history.request_send",agentId:r,sessionId:n,messageType:v.type,bytes:JSON.stringify(v).length,detail:{mode:w,limit:v.limit??null,afterSeq:v.afterSeq??null,hasCachedSessionRows:c,needSessionReady:a}}),this.sendWsMessage(v),!0},leaveYeaft(){this.activateChatView({persistPreference:!0})},fetchYeaftToolStats(){this.currentAgent&&(this.yeaftToolStatsLoading=!0,this.sendWsMessage({type:"yeaft_fetch_tool_stats",agentId:this.currentAgent}),this._fetchYeaftToolStatsTimer&&clearTimeout(this._fetchYeaftToolStatsTimer),this._fetchYeaftToolStatsTimer=setTimeout(()=>{this.yeaftToolStatsLoading&&(this.yeaftToolStatsLoading=!1,this.yeaftToolStats={...this.yeaftToolStats||{snapshot:{},registered:[],unused:[]},error:null,notice:"Tool stats are unavailable right now. Try again after the agent reconnects.",fetchedAt:Date.now()}),this._fetchYeaftToolStatsTimer=null},1e4))},loadYeaftDebugHistory({groupId:e,limit:t,dreamLimit:s,indexOnly:n=!1,detailTurnId:r=null,search:i=void 0}={}){if(!this.currentAgent)return;let o=typeof i=="string"?i.trim():(this.yeaftDebugSearch||"").trim(),a=typeof r=="string"&&r,l=o&&!a?kp:Ja,c=Number.isFinite(t)&&t>0?t:this.yeaftDebugHistoryLimit||l,d=Math.max(1,Math.min(l,c)),u=a?"detail":"list",f=`dbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,p=JSON.stringify({agentId:this.currentAgent,groupId:e||null,limit:d,dreamLimit:Number.isFinite(s)&&s>0?s:5,indexOnly:!!n,detailTurnId:r||null,search:a?"":o});if(this._yeaftDebugHistoryInFlightKey===p)return;this._yeaftDebugHistoryInFlightKey=p,a?this._yeaftDebugHistoryLatestDetailRequestId=f:this._yeaftDebugHistoryLatestListRequestId=f,this.yeaftDebugHistoryLimit=d,this.yeaftDebugHistoryLoading=!0,this.yeaftDebugHistoryError=null;let g={type:"yeaft_fetch_debug_history",agentId:this.currentAgent,requestId:f,requestKind:u,limit:d,dreamLimit:Number.isFinite(s)&&s>0?s:5};n&&(g.indexOnly=!0),typeof r=="string"&&r?g.detailTurnId=r:o&&(g.search=o),typeof e=="string"&&e&&(g.sessionId=e),this.sendWsMessage(g),this._fetchYeaftDebugHistoryTimer&&clearTimeout(this._fetchYeaftDebugHistoryTimer),this._fetchYeaftDebugHistoryTimer=setTimeout(()=>{this.yeaftDebugHistoryLoading&&(this.yeaftDebugHistoryLoading=!1,this.yeaftDebugHistoryError="Debug history is unavailable right now. Try again after the agent reconnects.",this.yeaftDebugPanel?.status==="loading"&&(this.yeaftDebugPanel={...this.yeaftDebugPanel,status:"error",error:this.yeaftDebugHistoryError})),this._yeaftDebugHistoryInFlightKey=null,this._fetchYeaftDebugHistoryTimer=null},1e4)},openYeaftTurnDebug({sessionId:e=null,turnId:t=null}={}){if(!this.currentAgent)return;let s=`dbgpanel_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,n=t?"loading":"idle";this.yeaftDebugPanel={open:!0,status:n,requestId:s,agentId:this.currentAgent,sessionId:e||null,turnId:t||null,error:null},t&&this.loadYeaftDebugHistory({groupId:e||void 0,limit:1,dreamLimit:5,detailTurnId:t})},closeYeaftDebugPanel(){let t=(this.yeaftDebugPanel||{}).turnId||null;if(this.yeaftDebugPanel={open:!1,status:"idle",requestId:null,agentId:null,sessionId:null,turnId:null,error:null},t&&this.yeaftDebugTurnsById&&this.yeaftDebugTurnsById[t]){let s={...this.yeaftDebugTurnsById};delete s[t],this.yeaftDebugTurnsById=s,this.yeaftDebugTurnOrder=(this.yeaftDebugTurnOrder||[]).filter(n=>n!==t),this.yeaftDebugLoops=(this.yeaftDebugLoops||[]).filter(n=>!n||n.turnId!==t)}},agentIdForSession(e){return be(this,e)},sendYeaftSessionMessage({groupId:e,text:t,mentions:s,attachments:n,quote:r}){let i=be(this,e);if(!e||!i)return;let o=Array.isArray(n)?n.filter(g=>g&&g.fileId):[],a=Qe(r),l=o.length>0;if(!t?.trim()&&!l)return;let c=t?.trim()?t:"(attached files)",d=`u_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,u=_s();this.yeaftPerfTraceByMessageId={...this.yeaftPerfTraceByMessageId||{},[d]:u},Ge(this,{traceId:u,phase:"send.prepare",agentId:i,sessionId:e,turnId:d,messageType:"yeaft_session_send",detail:{mentionCount:Array.isArray(s)?s.length:0,attachmentCount:o.length,quoted:!!a}});let f=tt(this,e);if(f){let g={id:d,messageId:d,clientMessageId:d,stableKey:ss(i,e,d),uiKey:ss(i,e,d),type:"user",content:c,sessionId:e,turnId:d,...a?{quote:a}:{}};if(o.length>0&&(g.attachments=o.map(m=>({fileId:m.fileId,name:m.name,preview:m.preview,isImage:!!m.isImage,mimeType:m.mimeType||""}))),this.addMessageToConversation(f,g),this.processingConversations[f]=!0,e){let m=St(i,e);this.yeaftProcessingSessions={...this.yeaftProcessingSessions,...m?{[m]:!0}:{}}}this._turnCompletedConvs?.delete(f),this._closedAt?.[f]&&delete this._closedAt[f],this.getOrCreateExecutionStatus(f),cn(this,f)}let p={type:"yeaft_session_send",agentId:i,id:d,sessionId:e,text:c,mentions:Array.isArray(s)?s:[],perfTraceId:u,...a?{quote:a}:{}};o.length>0&&(p.attachments=o.map(g=>({fileId:g.fileId,isImage:!!g.isImage}))),Ge(this,{traceId:u,phase:"send.websocket_send",agentId:i,sessionId:e,turnId:d,messageType:p.type,bytes:JSON.stringify(p).length}),this.sendWsMessage(p)},cancelYeaftTask({agentId:e=null,sessionId:t,taskId:s}){let n=typeof t=="string"?t.trim():"",r=typeof s=="string"?s.trim():"",i=be(this,n,e);return!i||!n||!r?!1:(this.yeaftStoppingTasksById={...this.yeaftStoppingTasksById,[Qa(i,n,r)]:!0},this.sendWsMessage({type:"yeaft_task_cancel",agentId:i,sessionId:n,taskId:r,clientRequestId:`task_cancel_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}),!0)},hydrateYeaftHistoryBrowserCache(e,t=null,{revalidate:s=!1}={}){let n=e||null,r=be(this,n,t),i=rs();if(!i||!r||!n)return s&&this.revalidateYeaftHistoryBrowserCache(n,r),Promise.resolve(!1);let o=ve(r,n),a=`${i.epoch}:${crypto.randomUUID()}`;return this._yeaftHistoryBrowserHydrationBySession={...this._yeaftHistoryBrowserHydrationBySession||{},[o]:a},$c({fence:i,agentId:r,sessionId:n}).then(l=>{if(!l||this._yeaftHistoryBrowserHydrationBySession?.[o]!==a)return!1;let c=tt(this,n,r);if(!c)return!1;let d=this.messagesMap[c]||[];Ms(this,c,l.rows),this.messagesMap[c]=ui(d,l.rows).sort((p,g)=>{let m=Number.isFinite(p?.seq)?p.seq:null,v=Number.isFinite(g?.seq)?g.seq:null;return m!==null&&v!==null&&m!==v?m-v:m!==null&&v===null?-1:m===null&&v!==null?1:(p?.timestamp||0)-(g?.timestamp||0)});let u=this.yeaftSessionHistoryState[o]||{},f=Math.max(Number.isFinite(u.latestSeq)?u.latestSeq:-1,Number.isFinite(l.latestSeq)?l.latestSeq:-1);return this.yeaftSessionHistoryState={...this.yeaftSessionHistoryState,[o]:{...u,loaded:!0,loading:!!u.loading,latestSeq:f>=0?f:null,streamId:l.streamId||null,revision:Number.isFinite(l.revision)?l.revision:null,oldestSeq:Number.isFinite(u.oldestSeq)?u.oldestSeq:l.oldestSeq,hasMore:u.loaded?!!u.hasMore:!!l.hasMore,count:Math.max(Number(u.count)||0,Number(l.rowCount)||0),browserCached:!0}},zn(this,{conversationId:c,agentId:r,sessionId:n,incomingRows:l.rows,activeAgentId:r,activeSessionId:n}),this.syncActiveYeaftHistoryLoad(),s&&this.revalidateYeaftHistoryBrowserCache(n,r),!0}).catch(()=>(s&&this.revalidateYeaftHistoryBrowserCache(n,r),!1)).finally(()=>{if(this._yeaftHistoryBrowserHydrationBySession?.[o]!==a)return;let{[o]:l,...c}=this._yeaftHistoryBrowserHydrationBySession;this._yeaftHistoryBrowserHydrationBySession=c})},revalidateYeaftHistoryBrowserCache(e,t=null){let s=e||null,n=be(this,s,t);if(!n||!s||this.currentView!=="yeaft")return!1;let r=ve(n,s),i=this.yeaftSessionHistoryState?.[r]||null;if(i?.loading)return!1;let o=Number.isFinite(i?.latestSeq)?i.latestSeq:null,a=o===null?"recent":"delta",l=this.beginYeaftHistoryLoad({agentId:n,sessionId:s,mode:a,preserveLoaded:o!==null,latestSeq:o});if(!l)return!1;let c={type:"yeaft_load_history",agentId:n,sessionId:s,requestId:l.requestId,...o===null?{limit:xi}:{afterSeq:o,maxRows:cp,maxBytes:dp,...typeof i?.streamId=="string"?{streamId:i.streamId}:{},...Number.isFinite(i?.revision)?{revision:i.revision}:{}}};return o!==null&&(this.yeaftSessionHistoryState={...this.yeaftSessionHistoryState,[r]:{...this.yeaftSessionHistoryState[r],syncingAfterSeq:o}}),this.sendWsMessage(c)?!0:(Un(this,{agentId:n,sessionId:s,requestId:l.requestId,error:"history_load_send_failed"}),!1)},continueYeaftHistoryDelta(e,t=null,s=null){let n=e||null,r=be(this,n,t);if(!r||!n||!Number.isFinite(s))return!1;let i=ve(r,n),o=this.yeaftSessionHistoryState?.[i]||null;if(o?.loading)return!1;let a=this.beginYeaftHistoryLoad({agentId:r,sessionId:n,mode:"delta",preserveLoaded:!0,latestSeq:s});if(!a)return!1;this.yeaftSessionHistoryState={...this.yeaftSessionHistoryState,[i]:{...this.yeaftSessionHistoryState[i],syncingAfterSeq:s}};let l={type:"yeaft_load_history",agentId:r,sessionId:n,requestId:a.requestId,afterSeq:s,maxRows:cp,maxBytes:dp,...typeof o?.streamId=="string"?{streamId:o.streamId}:{},...Number.isFinite(o?.revision)?{revision:o.revision}:{}};return this.sendWsMessage(l)?!0:(Un(this,{agentId:r,sessionId:n,requestId:a.requestId,error:"history_load_send_failed"}),!1)},persistYeaftHistoryBrowserCache(e,t=null,s=null){let n=e||null,r=be(this,n,t),i=rs(),o=s||tt(this,n,r);if(!i||!r||!n||!o)return Promise.resolve(!1);let a=ve(r,n),l=(this.messagesMap[o]||[]).filter(c=>(c?.sessionId??c?.groupId??null)===n);return Vc({fence:i,agentId:r,sessionId:n,rows:l,historyState:this.yeaftSessionHistoryState[a]||null})},removeYeaftHistoryBrowserCache(e,t){let s=rs();return!s||!e||!t?Promise.resolve(!0):ia({fence:s,agentId:e,sessionId:t}).catch(()=>!1)},clearYeaftHistoryMemory({agentId:e=null,sessionId:t=null,preserveLiveRows:s=!1,preserveSessionOwner:n=!1}={}){let r=e||null,i=t||null,o=r&&i?ve(r,i):null,a={};for(let[p,g]of Object.entries(this._yeaftHistoryWindowPendingByKey||{})){if(!(!o||g?.agentId===r&&g?.sessionId===i)){a[p]=g;continue}clearTimeout(g?.timeout),g?.resolve?.(!1)}this._yeaftHistoryWindowPendingByKey=a;let l=r&&this.yeaftConversationIdsByAgent?.[r]||null,c=o?new Set([l].filter(Boolean)):new Set(Object.values(this.yeaftConversationIdsByAgent||{}).filter(Boolean));!o&&this.yeaftConversationId&&c.add(this.yeaftConversationId);let d={...this.messagesMap||{}};for(let p of c)Array.isArray(d[p])&&(d[p]=o?d[p].filter(g=>(g?.sessionId??g?.groupId??null)!==i?!0:s&&!wt(g)):[]);this.messagesMap=d;let u=p=>{if(!o)return{};let{[o]:g,...m}=p||{};return m};if(this.yeaftSessionHistoryState=u(this.yeaftSessionHistoryState),this.yeaftHistoryCacheState=u(this.yeaftHistoryCacheState),this.yeaftMessageWindowState=u(this.yeaftMessageWindowState),this._yeaftHistoryBrowserHydrationBySession=u(this._yeaftHistoryBrowserHydrationBySession),this.yeaftHistoryOutlineBySession=u(this.yeaftHistoryOutlineBySession),o){let p=this._yeaftHistoryOutlineTimeouts?.[o];p&&clearTimeout(p),this._yeaftHistoryOutlineTimeouts=u(this._yeaftHistoryOutlineTimeouts)}else{for(let p of Object.values(this._yeaftHistoryOutlineTimeouts||{}))p&&clearTimeout(p);this._yeaftHistoryOutlineTimeouts={}}if((!o||this.yeaftHistorySearchState?.agentId===r&&this.yeaftHistorySearchState?.sessionId===i)&&(this._yeaftHistorySearchTimeout&&clearTimeout(this._yeaftHistorySearchTimeout),this._yeaftHistorySearchTimeout=null,this.yeaftHistorySearchState={requestId:null,agentId:null,sessionId:null,query:"",senderKey:"",loading:!1,results:[],hasMore:!1,nextBeforeSeq:null,nextCursor:null,error:null}),this._yeaftHistoryRevealLeases=o?Object.fromEntries(Object.entries(this._yeaftHistoryRevealLeases||{}).filter(([,p])=>p?.sessionKey!==o)):{},o||(this.yeaftHasMoreHistory=!1,this.yeaftLoadingMoreHistory=!1,this.yeaftOldestLoadedSeq=null),!n&&i&&this.yeaftSessionAgentById?.[i]===r){let{[i]:p,...g}=this.yeaftSessionAgentById;this.yeaftSessionAgentById=g}this.syncActiveYeaftHistoryLoad()},getYeaftMessageWindowKey(e=null,t=null){let s=e||this.yeaftActiveSessionFilter||null,n=be(this,s,t);return ve(n,s)},pruneYeaftMessageWindow(e=null,t=null){if(this.currentView!=="yeaft")return;let s=this.getYeaftMessageWindowKey(e,t);Object.values(this._yeaftHistoryRevealLeases||{}).some(r=>r?.sessionKey===s)||(this.yeaftMessageWindowState={...this.yeaftMessageWindowState,[s]:{visibleTurns:Os()}})},expandYeaftMessageWindow(e=null,t=br(),s=null){if(this.currentView!=="yeaft")return;let n=this.getYeaftMessageWindowKey(e,s),i=(this.yeaftMessageWindowState[n]?.visibleTurns||Os())+Math.max(1,Number.isFinite(t)?Math.floor(t):br());this.yeaftMessageWindowState={...this.yeaftMessageWindowState,[n]:{visibleTurns:i}}},isYeaftMessageCached(e,t,s=null,n=null){let r=e||this.yeaftActiveSessionFilter||null,i=s||tt(this,r,n);return!i||!t?!1:(this.messagesMap[i]||[]).some(o=>(!r||(o?.sessionId??o?.groupId??null)===r)&&((o?.id||o?.messageId)===t||o?.persistedMessageId===t))},revealYeaftMessage(e,t,s=null,n=null){let r=e||this.yeaftActiveSessionFilter||null,i=be(this,r,n),o=s||tt(this,r,i);if(!o||!t)return!1;let a=(this.messagesMap[o]||[]).filter(g=>g?._historyWindowPrefetched===!0?!1:r?(g?.sessionId??g?.groupId??null)===r:!0),c=a.findIndex(g=>(g?.id||g?.messageId)===t||g?.persistedMessageId===t);if(c<0){let g=(this.messagesMap[o]||[]).find(m=>m?._historyWindowPrefetched===!0&&(m?.sessionId??m?.groupId??null)===r&&((m?.id||m?.messageId)===t||m?.persistedMessageId===t));if(!g)return!1;g._historyWindowPrefetched=!1,a.push(g),a.sort((m,v)=>{let k=Number.isFinite(m?.seq)?m.seq:null,w=Number.isFinite(v?.seq)?v.seq:null;return k!==null&&w!==null&&k!==w?k-w:k!==null&&w===null?-1:k===null&&w!==null?1:(m?.timestamp||0)-(v?.timestamp||0)}),c=a.indexOf(g)}let d=np(a),u=d.findIndex(g=>c>=g.start&&c<g.end);if(u<0)return!1;a[c]._historyWindowPrefetched=!1;let f=Math.max(Os(),d.length-u),p=this.getYeaftMessageWindowKey(r,i);return this.yeaftMessageWindowState={...this.yeaftMessageWindowState,[p]:{visibleTurns:f}},!0},getYeaftHistoryOutlineState(e=null,t=null){let s=e||this.yeaftActiveSessionFilter||null,n=be(this,s,t),r=ve(n,s),i=this.yeaftHistoryOutlineBySession[r]||{requestId:null,agentId:n,sessionId:s,loading:!1,results:[],hasMore:!1,nextBeforeSeq:null,nextCursor:null,totalCount:null,loaded:!1,retryAttempt:0,error:null},o=tt(this,s,n),a=o?this.messagesMap[o]||[]:[],l=new Map((i.results||[]).map(f=>[wr(f),f])),c=0;for(let f of a){if((f?.sessionId??f?.groupId??null)!==s)continue;let p=f.messageId||f.id;if(!p)continue;let g=f.type==="user"&&!!f.clientMessageId&&p===f.clientMessageId,m=f.type==="assistant"&&f.isStreaming===!0;if(!g&&!m)continue;let v=f.type,k=f.turnId||f.threadId||p,w=f.speakerVpId||f.vpId||null,I=wr({role:v,messageId:p,clientMessageId:f.clientMessageId,turnId:k,speakerVpId:w}),h=l.get(I),b=(typeof f.content=="string"?f.content:"").replace(/\s+/g," ").trim();l.set(I,{...h,agentId:n,sessionId:s,messageId:Number.isFinite(h?.seq)?h.messageId:p,...f.clientMessageId?{clientMessageId:f.clientMessageId}:{},turnId:k,role:v,speakerVpId:w||h?.speakerVpId||null,timestamp:f.timestamp||f.ts||h?.timestamp||null,snippet:b.length>180?`${b.slice(0,180).trimEnd()}\u2026`:b||h?.snippet||""}),h||(c+=1)}let d=f=>{let p=typeof f=="number"?f:Date.parse(f||"");return Number.isFinite(p)?p:0},u=Array.from(l.values()).sort((f,p)=>Number.isFinite(f.seq)&&Number.isFinite(p.seq)?f.seq-p.seq:d(f.timestamp)-d(p.timestamp));return{...i,results:u,totalCount:Number.isFinite(i.totalCount)?i.totalCount+c:i.totalCount}},promoteYeaftHistoryOutlineRow(e,t=null){let s=e?.sessionId??e?.groupId??null,n=ve(t,s),r=this.yeaftHistoryOutlineBySession[n];if(!s||!t||!r?.loaded||r.loading)return!1;let i=e?.type;if(i!=="user"&&i!=="assistant")return!1;let o=e.dbMessageId||e.messageId||e.id||null,a=_y(o);if(!o||!Number.isFinite(a))return!1;let l=e.turnId||e.threadId||o,c=e.speakerVpId||e.vpId||null,u=(typeof e.content=="string"?e.content:"").replace(/\s+/g," ").trim(),f=wr({role:i,messageId:o,clientMessageId:e.clientMessageId,turnId:l,speakerVpId:c}),p=new Map((r.results||[]).map(I=>[wr(I),I])),g=p.get(f);p.set(f,{...g,agentId:t,sessionId:s,messageId:o,...e.clientMessageId?{clientMessageId:e.clientMessageId}:{},turnId:l,seq:a,role:i,speakerVpId:c,timestamp:e.timestamp||e.ts||g?.timestamp||null,snippet:u.length>180?`${u.slice(0,180).trimEnd()}\u2026`:u||g?.snippet||""});let m=50,v=Array.from(p.values()).sort((I,h)=>(I.seq||0)-(h.seq||0)),k=v.length>m,w=v.slice(-m);return this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[n]:{...r,results:w,hasMore:r.hasMore||k,nextBeforeSeq:k&&Number.isFinite(w[0]?.seq)?w[0].seq:r.nextBeforeSeq,totalCount:Number.isFinite(r.totalCount)&&!g?r.totalCount+1:r.totalCount}},!0},promoteCompletedYeaftHistoryOutline(e,t=null,s=null){let n=this.messagesMap[e]||[],r=null,i=[];for(let o=n.length-1;o>=0;o--){let a=n[o];if(a?.type==="user")break;if(t&&a?.turnId&&a.turnId!==t||a?.type!=="assistant")continue;let l=typeof a.content=="string"?a.content.replace(/\s+/g," ").trim():"";r?!String(r.content||"").trim()&&l&&(r=a):r=a,l&&i.unshift(l)}return r?this.promoteYeaftHistoryOutlineRow({...r,content:i.join(" ")},s):!1},invalidateYeaftHistoryOutline(e,t=null){let s=ve(t,e),n=this.yeaftHistoryOutlineBySession[s];if(!e||!t||!n)return!1;if(n.loading)return this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[s]:{...n,refreshPending:!0}},!0;this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[s]:{...n,loaded:!1,refreshPending:!1}};let r=be(this,e);return this.currentView==="yeaft"&&this.yeaftActiveSessionFilter===e&&r===t?this.loadYeaftHistoryOutline({force:!0,targetSessionId:e,targetAgentId:t}):!0},loadYeaftHistoryOutline({append:e=!1,force:t=!1,targetSessionId:s=null,targetAgentId:n=null,retryAttempt:r=0}={}){if(this.currentView!=="yeaft"&&!s)return!1;let i=s||this.yeaftActiveSessionFilter||null,o=n||be(this,i);if(!i||!o)return!1;let a=ve(o,i),l=this.getYeaftHistoryOutlineState(i,o);if(!e&&l.loaded&&!t)return!0;if(e&&(!l.hasMore||!Number.isFinite(l.nextBeforeSeq))||l.loading)return!1;if(!yp(this,o,"session_history_outline"))return this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[a]:{...l,error:"unsupported",loading:!1}},!1;let c=`history_outline_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,d={...l,requestId:c,agentId:o,sessionId:i,loading:!0,requestAppend:e,refreshPending:!1,retryAttempt:r,error:null};this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[a]:d};let u=this._yeaftHistoryOutlineTimeouts[a];u&&clearTimeout(u);let f=setTimeout(()=>{let m=this.yeaftHistoryOutlineBySession[a];if(m?.requestId!==c)return;let v={...this._yeaftHistoryOutlineTimeouts};delete v[a],this._yeaftHistoryOutlineTimeouts=v;let k=m.refreshPending===!0;this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[a]:{...m,requestId:null,loading:!1,requestAppend:!1,loaded:k?!1:m.loaded,refreshPending:!1,error:k?null:"timeout"}},k&&this.loadYeaftHistoryOutline({force:!0,targetSessionId:i,targetAgentId:o})},1e4);this._yeaftHistoryOutlineTimeouts={...this._yeaftHistoryOutlineTimeouts,[a]:f};let p=_s(),g={type:"yeaft_load_history_outline",agentId:o,sessionId:i,requestId:c,perfTraceId:p,limit:50,...e&&l.nextCursor?{cursor:l.nextCursor}:{},...e&&!l.nextCursor&&Number.isFinite(l.nextBeforeSeq)?{beforeSeq:l.nextBeforeSeq}:{}};return Ge(this,{traceId:p,phase:"history_outline.request_send",agentId:o,sessionId:i,messageType:g.type,bytes:JSON.stringify(g).length,detail:{append:e,limit:g.limit}}),this.sendWsMessage(g),!0},handleYeaftHistoryOutline(e){if(!e?.agentId||!e?.sessionId)return!1;let t=ve(e.agentId,e.sessionId),s=this.yeaftHistoryOutlineBySession[t];if(!s||e.requestId!==s.requestId)return!1;let n=this._yeaftHistoryOutlineTimeouts[t];n&&clearTimeout(n);let r={...this._yeaftHistoryOutlineTimeouts};delete r[t],this._yeaftHistoryOutlineTimeouts=r;let i=Number.isInteger(s.retryAttempt)?s.retryAttempt:0;if(ky.has(e.error)&&i<up.length){let u=up[i],f=setTimeout(()=>{let p=this.yeaftHistoryOutlineBySession[t];if(p?.requestId!==e.requestId||p.loading!==!0)return;let g={...this._yeaftHistoryOutlineTimeouts};delete g[t],this._yeaftHistoryOutlineTimeouts=g;let m=p.refreshPending===!0;this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[t]:{...p,requestId:null,loading:!1,refreshPending:!1}},this.loadYeaftHistoryOutline({append:m?!1:s.requestAppend===!0,force:!0,targetSessionId:e.sessionId,targetAgentId:e.agentId,retryAttempt:i+1})},u);return this._yeaftHistoryOutlineTimeouts={...this._yeaftHistoryOutlineTimeouts,[t]:f},!0}let o=Array.isArray(e.results)?e.results.map(u=>({...u,agentId:e.agentId,sessionId:e.sessionId})):[],a=s.requestAppend?[...s.results||[],...o]:o,l=new Map(a.filter(u=>u?.messageId).map(u=>[wr(u),u])),c=Array.from(l.values()).sort((u,f)=>(u.seq||0)-(f.seq||0)),d=s.refreshPending===!0;return this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[t]:{...s,requestId:null,loading:!1,requestAppend:!1,refreshPending:!1,loaded:d?!1:!e.error,results:c,hasMore:!!e.hasMore,nextBeforeSeq:Number.isFinite(e.nextBeforeSeq)?e.nextBeforeSeq:null,nextCursor:e.nextCursor&&typeof e.nextCursor=="object"?e.nextCursor:null,totalCount:Number.isFinite(e.totalCount)?e.totalCount:s.totalCount,error:d?null:e.error||null}},d&&this.loadYeaftHistoryOutline({force:!0,targetSessionId:e.sessionId,targetAgentId:e.agentId}),!0},searchYeaftHistory(e,{append:t=!1,senderKey:s=""}={}){if(this.currentView!=="yeaft")return!1;let n=typeof e=="string"?e.trim():"",r=typeof s=="string"&&(s==="user"||s.startsWith("vp:"))?s.slice(0,103):"",i=this.yeaftActiveSessionFilter||null,o=be(this,i);if(this._yeaftHistorySearchTimeout&&(clearTimeout(this._yeaftHistorySearchTimeout),this._yeaftHistorySearchTimeout=null),!i||!o||Array.from(n).length<1&&!r)return this.yeaftHistorySearchState={requestId:null,agentId:o,sessionId:i,query:n,senderKey:r,loading:!1,results:[],hasMore:!1,nextBeforeSeq:null,nextCursor:null,error:null},!1;let a=this.yeaftHistorySearchState||{};if(!yp(this,o,"session_history_search"))return this.yeaftHistorySearchState={requestId:null,agentId:o,sessionId:i,query:n,senderKey:r,loading:!1,results:[],hasMore:!1,nextBeforeSeq:null,nextCursor:null,error:"unsupported"},!1;let l=`history_search_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;this.yeaftHistorySearchState={requestId:l,agentId:o,sessionId:i,query:n,senderKey:r,loading:!0,results:t&&a.query===n&&a.senderKey===r?a.results:[],hasMore:!1,nextBeforeSeq:t&&a.query===n&&a.senderKey===r?a.nextBeforeSeq:null,nextCursor:t&&a.query===n&&a.senderKey===r&&a.nextCursor||null,error:null},this._yeaftHistorySearchTimeout=setTimeout(()=>{this.yeaftHistorySearchState?.requestId===l&&(this._yeaftHistorySearchTimeout=null,this.yeaftHistorySearchState={...this.yeaftHistorySearchState,loading:!1,error:"timeout"})},1e4);let c=_s(),d={type:"yeaft_search_history",agentId:o,sessionId:i,requestId:l,perfTraceId:c,query:n,senderKey:r,limit:20,...t&&a.query===n&&a.senderKey===r&&a.nextCursor?{cursor:a.nextCursor}:{},...t&&a.query===n&&a.senderKey===r&&!a.nextCursor&&Number.isFinite(a.nextBeforeSeq)?{beforeSeq:a.nextBeforeSeq}:{}};return Ge(this,{traceId:c,phase:"history_search.request_send",agentId:o,sessionId:i,messageType:d.type,bytes:JSON.stringify(d).length,detail:{append:t,limit:d.limit,queryLength:Array.from(n).length,senderFilter:!!r}}),this.sendWsMessage(d),!0},handleYeaftHistorySearchResult(e){let t=this.yeaftHistorySearchState||{};if(!e||e.requestId!==t.requestId||e.agentId!==t.agentId||e.sessionId!==t.sessionId||e.query!==t.query||(e.senderKey||"")!==t.senderKey)return!1;this._yeaftHistorySearchTimeout&&(clearTimeout(this._yeaftHistorySearchTimeout),this._yeaftHistorySearchTimeout=null);let s=Array.isArray(e.results)?e.results.map(r=>({...r,agentId:e.agentId,sessionId:e.sessionId})):[],n=new Map((t.results||[]).map(r=>[Wn(r),r]));for(let r of s)(r?.entryId||r?.messageId)&&n.set(Wn(r),r);return this.yeaftHistorySearchState={...t,loading:!1,results:Array.from(n.values()),hasMore:!!e.hasMore,nextBeforeSeq:Number.isFinite(e.nextBeforeSeq)?e.nextBeforeSeq:null,nextCursor:e.nextCursor&&typeof e.nextCursor=="object"?e.nextCursor:null,error:e.error||null},!0},loadYeaftHistoryWindow(e,{validateCached:t=!1}={}){let s=e?.sessionId||this.yeaftActiveSessionFilter||null,n=e?.agentId||be(this,s),r=Wn(e);if(!s||!n||!e?.entryId||!Number.isFinite(e.indexGeneration)||!Number.isFinite(e.entryStartSeq)||!e?.messageId||!Number.isFinite(e.seq))return Promise.resolve(!1);let i=tt(this,s,n);if((this.messagesMap[i]||[]).some(p=>(p?.sessionId??p?.groupId??null)===s&&p?.historyEntryId===e.entryId&&p?.historyIndexGeneration===e.indexGeneration)&&!t)return Promise.resolve(!0);let a=ve(n,`${s}:${r}:generation:${e.indexGeneration}`),l=this._yeaftHistoryWindowPendingByKey||{};if(l[a]?.promise)return l[a].promise;let c=`history_window_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,d=null,u=new Promise(p=>{d=p}),f=setTimeout(()=>{if(this._yeaftHistoryWindowPendingByKey?.[a]?.requestId!==c)return;let{[a]:g,...m}=this._yeaftHistoryWindowPendingByKey;this._yeaftHistoryWindowPendingByKey=m,d(!1)},1e4);return this._yeaftHistoryWindowPendingByKey={...l,[a]:{requestId:c,agentId:n,sessionId:s,entryId:e.entryId||null,indexGeneration:Number.isFinite(e.indexGeneration)?e.indexGeneration:null,entryStartSeq:Number.isFinite(e.entryStartSeq)?e.entryStartSeq:null,resultId:r,messageId:e.messageId,prefetch:!t,resolve:d,timeout:f,promise:u}},this.sendWsMessage({type:"yeaft_load_history_window",agentId:n,sessionId:s,requestId:c,prefetch:!t,...e.entryId?{entryId:e.entryId}:{},...Number.isFinite(e.indexGeneration)?{indexGeneration:e.indexGeneration}:{},...Number.isFinite(e.entryStartSeq)?{entryStartSeq:e.entryStartSeq}:{},anchorMessageId:e.messageId,anchorSeq:e.seq,beforeTurns:5,afterTurns:5,maxRows:200,maxBytes:512*1024}),u},beginYeaftHistoryReveal(e){let t=e?.sessionId||null,s=e?.agentId||null,n=tt(this,t,s);if(!t||!s||!n)return null;let r=ve(s,t),i=`${r}${n}`,o=++this._yeaftHistoryRevealSequence,a={key:i,token:o,sessionKey:r,agentId:s,sessionId:t,conversationId:n};return this._yeaftHistoryRevealLeases={...this._yeaftHistoryRevealLeases||{},[i]:a},a},finishYeaftHistoryReveal(e){if(!e?.key||!Number.isFinite(e.token)||this._yeaftHistoryRevealLeases?.[e.key]?.token!==e.token)return!1;let{[e.key]:s,...n}=this._yeaftHistoryRevealLeases;return this._yeaftHistoryRevealLeases=n,!0},async revealYeaftHistoryResult(e,t=null){let s=!t,n=t||this.beginYeaftHistoryReveal(e),r=e?.sessionId||null,i=e?.agentId||null,o=tt(this,r,i);if(!n||!r||!i||!o||!e?.messageId)return this.finishYeaftHistoryReveal(n),!1;if(!await this.loadYeaftHistoryWindow(e,{validateCached:!0}))return this.finishYeaftHistoryReveal(n),!1;if(this.currentView!=="yeaft"||this.yeaftActiveSessionFilter!==r||be(this,r)!==i||tt(this,r,i)!==o)return this.finishYeaftHistoryReveal(n),!1;let l=this.revealYeaftMessage(r,e.messageId,o,i);return(!l||s)&&this.finishYeaftHistoryReveal(n),l},pendingYeaftHistoryWindow(e){let s=Object.entries(this._yeaftHistoryWindowPendingByKey||{}).find(([,i])=>i?.requestId===e?.requestId);if(!s)return null;let[n,r]=s;return e.agentId!==r.agentId||e.sessionId!==r.sessionId||e.entryId&&r.entryId&&e.entryId!==r.entryId||Number.isFinite(e.indexGeneration)&&Number.isFinite(r.indexGeneration)&&e.indexGeneration!==r.indexGeneration?null:{pendingKey:n,pending:r}},handleYeaftHistoryWindow(e,t=null){let s=this.pendingYeaftHistoryWindow(e);if(!s)return!1;let{pendingKey:n,pending:r}=s;r.prefetch===!0&&e.prefetch!==!0&&(e.prefetch=!0),clearTimeout(r.timeout);let{[n]:i,...o}=this._yeaftHistoryWindowPendingByKey;this._yeaftHistoryWindowPendingByKey=o;let a=!e.error&&!!t&&this.isYeaftMessageCached(r.sessionId,r.messageId,t,r.agentId);return r.resolve(!!a),!!a},createYeaftSession({displayName:e,vpIds:t,defaultVpId:s,workDir:n,agentId:r}={}){let i=Array.isArray(t)?t.slice():[],o=s&&i.includes(s)?s:i[0]||null,a=(e||"").trim(),l=(n||"").trim(),c={roster:i,defaultVpId:o};return a&&(c.name=a),l&&(c.workDir=l),this.sessionCrudRequest("create",c,{agentId:r})},handleYeaftOutput(e){if(!e)return;let t=e.agentId||this.yeaftAgentId||this.currentAgent||null,s=e.conversationId||e.event?.conversationId||null,n=dn(this,t,s);if(e.data&&n){if(e.data.type!=="result")return;let a=Td(this,t,s);if(!a)return;let l=e.turnId?hn(this,t,e.turnId):"",c=!!(l&&this.activeVpTurns?.[l])||(this.messagesMap?.[a]||[]).some(d=>d?.turnId===e.turnId&&(d.isStreaming||d.status==="pending"));if(!e.turnId||!c)return;e={...e,conversationId:a}}if(e.perfTraceId&&(Ge(this,{traceId:e.perfTraceId,phase:"receive.yeaft_output",agentId:e.agentId||null,sessionId:e.sessionId||null,vpId:e.vpId||null,turnId:e.turnId||null,threadId:e.threadId||null,messageType:e.data?.type||e.event?.type||e.type}),e.turnId&&(this.yeaftPerfTraceByTurnId={...this.yeaftPerfTraceByTurnId||{},[e.turnId]:e.perfTraceId})),e.data){let a=e.agentId||null,l=qt(this,a,e.conversationId);if(l){let d=Xa(e,e.turnId||"session");for(let u of["retry","retrying","thinking"])ln(this,l,`${u}:${d}`);e.data?.tool_use_result&&ln(this,l,`tool:${d}`)}let c=e.turnId?hn(this,e.agentId||null,e.turnId):"";if(c&&this.activeVpTurns?.[c]?.retryAttempt){let{retryAttempt:d,retryMax:u,retryDelayMs:f,retryReason:p,retryRecoveryMode:g,...m}=this.activeVpTurns[c];this.activeVpTurns={...this.activeVpTurns,[c]:m}}if(l){let d=e.sessionId??e.groupId??null,u=bp(this,d,a),f=a&&this.yeaftConversationIdsByAgent?this.yeaftConversationIdsByAgent[a]:null,p=xt(this,a);p&&p.targetConversationId!==l?cr(this,a,l):!p&&f&&f!==l&&!String(f).startsWith("yeaft-local-")&&(Tt(this,f,l,{removeSource:f!==this.yeaftConversationId}),ar(this,a,f,l)),ka(this,a,l);let g=xt(this,a,l),m=g?.sourceConversationId||f,v=!u&&m===this.yeaftConversationId;if(this.currentView==="yeaft"&&a&&m&&m!==l){let b=!v&&(!!g||String(m).startsWith("yeaft-local-"));Tt(this,m,l,{removeSource:b}),v?mi(this,a,m,l):b&&lr(this,a,l)}a&&(this.yeaftConversationIdsByAgent={...this.yeaftConversationIdsByAgent||{},[a]:l}),(u||!this.yeaftConversationId)&&(this.yeaftConversationId=l),u&&(this.activeConversations=[l]),this.messagesMap[l]||(this.messagesMap[l]=[]);let k=this._currentYeaftAgentId,w=this._currentYeaftSessionId,I=this._currentYeaftVpId,h=this._currentYeaftTurnId,y=this._currentYeaftThreadId;a&&(this._currentYeaftAgentId=a),d!=null&&(this._currentYeaftSessionId=d),e.vpId&&(this._currentYeaftVpId=e.vpId),e.turnId&&(this._currentYeaftTurnId=e.turnId),e.threadId&&(this._currentYeaftThreadId=e.threadId);try{let b=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.handleAssistantOutputFrame(l,e.data,a),e.perfTraceId){let T=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();Ge(this,{traceId:e.perfTraceId,phase:"store.apply_output",agentId:e.agentId||null,sessionId:d||null,vpId:e.vpId||null,turnId:e.turnId||null,threadId:e.threadId||null,messageType:e.data?.type||null,durationMs:T-b}),vi(this,{traceId:e.perfTraceId,agentId:e.agentId||null,sessionId:d||null,vpId:e.vpId||null,turnId:e.turnId||null,threadId:e.threadId||null,messageType:e.data?.type||null})}let M=e.data,x=M?.message?.id||M?.id||null,D=Ry(x),V=Array.isArray(M?.message?.content)?M.message.content:[],E=V.some(T=>T?.type==="tool_use"),_=!!M?.tool_use_result||V.some(T=>T?.type==="tool_result");if(d){let T=!_&&!Py(this,l,d)&&(M?.type==="user"||M?.type==="assistant"&&!E)?D:null,A=ve(e.agentId||null,d),R=this.yeaftSessionHistoryState[A]||{},j=Number.isFinite(R.latestSeq)?R.latestSeq:-1;T!==null&&T>j&&(this.yeaftSessionHistoryState={...this.yeaftSessionHistoryState,[A]:{...R,latestSeq:T}})}}finally{this._currentYeaftAgentId=k,this._currentYeaftSessionId=w,this._currentYeaftVpId=I,this._currentYeaftTurnId=h,this._currentYeaftThreadId=y}}return}let r=e.event;if(!r)return;let i={...r,vpId:r.vpId||e.vpId||null,threadId:r.threadId||e.threadId||null,turnId:r.turnId||e.turnId||null},o=qt(this,e.agentId||null,e.conversationId);if(o){let a=Xa(i);r.type==="tool_start"?or(this,o,`tool:${a}`):r.type==="tool_end"?ln(this,o,`tool:${a}`):r.type==="llm_retry"?or(this,o,`retry:${a}`):r.type==="vp_async_task_wait_start"?or(this,o,`async-wait:${a}`):r.type==="vp_async_task_wait_end"&&ln(this,o,`async-wait:${a}`)}switch(r.type){case"project_mutation_result":r.projectsAuthoritative===!0?this.finishProjectMutation(r):this.finishLegacyProjectMutation(r,e.agentId||null);break;case"ask_user_question":{let a=qt(this,e.agentId||null,e.conversationId);if(!a||!r.requestId)break;let l=fp(e,r,a),c=()=>{let d=this.messagesMap[a]||[],u=mp(d,l,a);if(u){if(u.askAnswered||u.askExpired)return!0;u.toolName="AskUserQuestion",r.toolCallId&&!u.toolId&&(u.toolId=r.toolCallId),u.agentId=l.agentId||u.agentId||null,u.askRequestId=r.requestId,u.askQuestions=r.questions||[],u.askCreatedAt=r.createdAt||null,u.askExpiresAt=r.expiresAt||null,r.replay&&(u.askPending=!1,u.pendingAnswers=null,u.askSubmitGeneration=null),u.isHistory=!1;let g=hp(this,l);return g&&Ga(u,g),this.messagesMap={...this.messagesMap,[a]:d.slice()},!0}if(!r.replay)return!1;let f={id:`ask-card-${r.requestId}`,type:"tool-use",toolName:"AskUserQuestion",toolId:r.toolCallId||null,toolInput:{questions:r.questions||[]},askRequestId:r.requestId,askQuestions:r.questions||[],askCreatedAt:r.createdAt||null,askExpiresAt:r.expiresAt||null,agentId:l.agentId,sessionId:l.sessionId,vpId:l.vpId,speakerVpId:l.vpId,turnId:l.turnId,threadId:l.threadId||"main",hasResult:!1,isHistory:!1,timestamp:r.createdAt||Date.now()},p=hp(this,l);return p&&Ga(f,p),d.push(f),this.messagesMap={...this.messagesMap,[a]:d.slice()},!0};if(!c()){let d=0,u=setInterval(()=>{d+=1,(c()||d>=10)&&clearInterval(u)},200)}break}case"ask_user_answered":case"ask_user_expired":{let a=qt(this,e.agentId||null,e.conversationId);if(!a||!r.requestId)break;let l=this.messagesMap[a]||[],c=fp(e,r,a),d=mp(l,c,a);if(!d){My(this,c,r);break}Ga(d,r),this.messagesMap={...this.messagesMap,[a]:l.slice()};break}case"session_ready":{let a=r.conversationId,l=e.agentId||this.currentAgent;if(dn(this,l,a))break;let c=l&&this.yeaftConversationIdsByAgent?this.yeaftConversationIdsByAgent[l]:null,d=this.yeaftConversationId?String(this.yeaftConversationId):"",u=d.startsWith("yeaft-local-")&&(!l||d.startsWith(`yeaft-local-${l}-`)||/^yeaft-local-\d/.test(d))?this.yeaftConversationId:null,f=c||u,p=r.sessionId||e.sessionId||null,g=bp(this,p,l),m=xt(this,l);m&&m.targetConversationId!==a?cr(this,l,a):!m&&c&&c!==a&&!String(c).startsWith("yeaft-local-")&&ar(this,l,c,a),ka(this,l,a);let k=xt(this,l,a)?.sourceConversationId||f,w=!g&&k===this.yeaftConversationId;if(k&&k!==a){let M=!w;Tt(this,k,a,{removeSource:M}),w?mi(this,l,k,a):M&&lr(this,l,a)}else this.messagesMap[a]||(this.messagesMap[a]=[]);l&&(this.yeaftConversationIdsByAgent={...this.yeaftConversationIdsByAgent||{},[l]:a},this.cacheYeaftAgentStatus(l,r,{allowBootstrapCatalog:g})),g&&(this.yeaftModel=r.model,this.yeaftModelEffort=r.modelEffort||null,this.yeaftSessionReady=!0,this.yeaftBootstrapMetaLoadingKey=null,l?this.applyCachedYeaftStatus(l):this.yeaftAvailableModels=r.availableModels||[]);let I=Array.isArray(r.tasks)?r.tasks:[],h={};for(let[M,x]of Object.entries(this.yeaftActiveTasksBySession||{})){let D=Object.fromEntries(Object.entries(x||{}).filter(([,E])=>E?.id&&E.status==="running"&&E.agentId&&E.agentId!==l)),V=Za(D);Object.keys(V).length>0&&(h[M]=V)}for(let M of I){if(!M?.id||!M.sessionId||M.status!=="running")continue;let x=ve(l,M.sessionId);h[x]={...h[x]||{},[M.id]:{...M,agentId:l}}}this.yeaftActiveTasksBySession=h,g&&(r.yeaftDir&&(this.yeaftYeaftDir=r.yeaftDir),this.yeaftStatus={skills:r.skills,mcpServers:r.mcpServers,tools:r.tools,multiVp:!!r.multiVp}),(g||!this.yeaftConversationId)&&(this.yeaftConversationId=a),g&&(this.activeConversations=[a]);let y=e.agentId||this.currentAgent||null,b=y||"__current__";this._yeaftVpSubscribedAgentKey!==b&&(this._yeaftVpSubscribedAgentKey=b,this.sendWsMessage(y?{type:"yeaft_vp_subscribe",agentId:y}:{type:"yeaft_vp_subscribe"}));break}case"yeaft_status":{let a=e.agentId||this.currentAgent;a&&this.cacheYeaftAgentStatus(a,r);break}case"context_usage":break;case"turn_open":{if(!r.turnId)break;let a={turnId:r.turnId,userPrompt:r.userPrompt||"",vpId:r.vpId||e.vpId||null,sessionId:r.sessionId||e.sessionId||null,openedAt:r.at||Date.now(),closedAt:null,totalMs:0,totalTokens:0,loopCount:0,memoryLoaded:null,memoryLoadedMeta:null,memoryAdjust:null,tools:[],detailsLoaded:!0};this.yeaftDebugTurnsById={...this.yeaftDebugTurnsById,[r.turnId]:a},this.yeaftDebugTurnOrder.includes(r.turnId)||(this.yeaftDebugTurnOrder=[...this.yeaftDebugTurnOrder,r.turnId]);break}case"turn_close":{if(!r.turnId)break;let a=this.yeaftDebugTurnsById[r.turnId];if(!a)break;this.yeaftDebugTurnsById={...this.yeaftDebugTurnsById,[r.turnId]:{...a,closedAt:Date.now(),totalMs:r.totalMs||0,totalTokens:r.totalTokens||0,loopCount:r.loopCount||a.loopCount||0}};break}case"memory_used":{if(!r.turnId)break;let a=this.yeaftDebugTurnsById[r.turnId];if(!a)break;this.yeaftDebugTurnsById={...this.yeaftDebugTurnsById,[r.turnId]:{...a,memoryLoaded:Array.isArray(r.loaded)?r.loaded:[],memoryLoadedMeta:r.meta||null}};break}case"dream_memory_loaded":{let a=Array.isArray(r.resident)?r.resident:[];if(r.turnId){let c=this.yeaftDebugTurnsById[r.turnId];c&&(this.yeaftDebugTurnsById={...this.yeaftDebugTurnsById,[r.turnId]:{...c,dreamMemoryLoaded:a,dreamMemoryLoadedInto:r.loadedInto||"system_prompt.memory"}})}let l={};for(let c of a){let d=c&&typeof c.scope=="string"?c.scope:null,u=d&&/^sessions\/[^/]+$/.test(d)?d:d&&/^group\/[^/]+$/.test(d)?`sessions/${d.slice(6)}`:null;u&&(l[u]={scope:u,sourceScope:d,sessionId:u.slice(9),turnId:r.turnId||null,vpId:r.vpId||null,loadedInto:r.loadedInto||"system_prompt.memory",summary:c.summary||"",truncated:!!c.truncated,receivedAt:Date.now()})}Object.keys(l).length>0&&(this.yeaftDreamPromptLoads={...this.yeaftDreamPromptLoads,...l});break}case"memory_adjust":{if(!r.turnId)break;let a=this.yeaftDebugTurnsById[r.turnId];if(!a)break;this.yeaftDebugTurnsById={...this.yeaftDebugTurnsById,[r.turnId]:{...a,memoryAdjust:{sessionKey:r.sessionKey||null,added:r.added||0,evicted:r.evicted||0,skipped:r.skipped||0,reason:r.reason||""}}};break}case"tool_exec":{if(!r.turnId)break;let a=this.yeaftDebugTurnsById[r.turnId];if(!a)break;let l=[...a.tools||[],{loopNumber:r.loopNumber||0,callId:r.callId||null,name:r.name||"?",durationMs:r.durationMs||0,isError:!!r.isError,toolOutput:r.toolOutput==null?null:String(r.toolOutput)}];this.yeaftDebugTurnsById={...this.yeaftDebugTurnsById,[r.turnId]:{...a,tools:l}};break}case"loop":{if(this.yeaftDebugLoops.push({turnId:r.turnId||null,loopNumber:r.loopNumber||0,model:r.model,systemPrompt:r.systemPrompt,messages:r.messages,response:r.response,toolCalls:r.toolCalls,usage:r.usage||{inputTokens:0,outputTokens:0,totalTokens:0},latencyMs:r.latencyMs,ttfbMs:r.ttfbMs,stopReason:r.stopReason,at:typeof r.at=="number"?r.at:null,rawRequest:r.rawRequest||null,rawResponse:r.rawResponse||null,sessionId:e.sessionId||null,vpId:e.vpId||r.vpId||null}),this.yeaftDebugLoops.length>wp){let a=qu({loops:this.yeaftDebugLoops,turnsById:this.yeaftDebugTurnsById,turnOrder:this.yeaftDebugTurnOrder,maxLoops:Math.max(wp,this.yeaftDebugHistoryLimit||0)});this.yeaftDebugLoops=a.loops,this.yeaftDebugTurnsById=a.turnsById,this.yeaftDebugTurnOrder=a.turnOrder}break}case"llm_retry":{if(!e.turnId)break;let a=hn(this,e.agentId||null,e.turnId),l=this.activeVpTurns?.[a];if(!l)break;let c=r.reason==="stream_idle_timeout"?"stream_idle_timeout":"transient_error";this.activeVpTurns={...this.activeVpTurns,[a]:{...l,retryAttempt:r.attempt||0,retryMax:r.maxRetries||0,retryDelayMs:r.delayMs||0,retryReason:c,retryRecoveryMode:r.recoveryMode||"restart"}};break}case"recall":case"consolidate":case"fallback":case"thinking_delta":break;case"reflection":{let a=qt(this,e.agentId||null,e.conversationId)||"unknown",l=Array.isArray(r.loopRange)?r.loopRange:[0,0],c=`${a}:${r.trigger}:${l[0]}-${l[1]}`,d=this.yeaftReflectionCards[c],u=this.messagesMap[a]||[],f=d?d.anchorMsgId:u.length>0&&u[u.length-1].id||null,p=d?d.anchorOrder:u.length;this.yeaftReflectionCards={...this.yeaftReflectionCards,[c]:{key:c,conversationId:a,turnId:r.turnId||d&&d.turnId||null,loopNumber:r.loopNumber||d&&d.loopNumber||null,trigger:r.trigger,status:r.status,loopRange:l,toolCount:r.toolCount||0,content:r.content||"",durationMs:r.durationMs||0,error:r.error||null,sessionId:e.sessionId||null,anchorMsgId:f,anchorOrder:p,updatedAt:Date.now()}};break}case"model_switched":this.yeaftModel=r.model,this.yeaftModelEffort=r.modelEffort||null;break;case"yeaft_task_event":{let a=r.task;if(!a?.id||!a.sessionId)break;let l=e.agentId||be(this,a.sessionId),c=ve(l,a.sessionId),d={...a,agentId:l},u={...this.yeaftActiveTasksBySession},f={...u[c]||{}};a.status==="running"?f[a.id]=d:delete f[a.id];let p=Za(f);if(Object.keys(p).length>0?u[c]=p:delete u[c],this.yeaftActiveTasksBySession=u,a.status!=="running"){let{[Qa(l,a.sessionId,a.id)]:g,...m}=this.yeaftStoppingTasksById||{};this.yeaftStoppingTasksById=m}break}case"yeaft_task_cancel_result":{let a=r.taskId||r.task?.id||null,l=r.task?.sessionId||r.sessionId||e.sessionId||null,c=e.agentId||be(this,l);if(a&&l&&r.success===!1){let{[Qa(c,l,a)]:u,...f}=this.yeaftStoppingTasksById||{};this.yeaftStoppingTasksById=f}let d=r.task;if(d?.id&&d.sessionId){let u=ve(c,d.sessionId),f={...this.yeaftActiveTasksBySession},p={...f[u]||{}};d.status==="running"?p[d.id]={...d,agentId:c}:delete p[d.id];let g=Za(p);Object.keys(g).length>0?f[u]=g:delete f[u],this.yeaftActiveTasksBySession=f}break}case"sub_agent_event":{let a=qt(this,e.agentId||null,e.conversationId)||"unknown",l=r.agentId;if(!l)break;let c=r.payload||{},d=`${a}:${l}`,u=this.yeaftSubAgentCards[d],f=this.messagesMap[a]||[],p=u?u.anchorMsgId:f.length>0&&f[f.length-1].id||null,g=u?u.anchorOrder:f.length,m=u?{...u}:{key:d,conversationId:a,agentId:l,agentName:c.agentName||"sub-agent",status:"running",text:"",toolCallCount:0,turns:0,error:null,expanded:!1,anchorMsgId:p,anchorOrder:g,updatedAt:Date.now(),sessionId:e.sessionId||null};switch(c.agentName&&!m.agentName&&(m.agentName=c.agentName),c.type){case"sub_agent_status":m.status=c.status||m.status,c.error&&(m.error=c.error);break;case"text_delta":break;case"tool_use":case"tool_call":m.toolCallCount=Number(m.toolCallCount||0)+1;break;case"tool_start":break;case"tool_result":case"tool_end":break;case"sub_agent_turn_end":{m.turns+=1;let v=typeof c.content=="string"?c.content.trim():"";v&&(m.text=m.text?`${m.text}
8
+ `))}function Ii(e){let t=Array.isArray(e?.textSegments)?e.textSegments:[];if(t.length===0)return;let s=Array.isArray(e?.messages)?e.messages:[],n=e?.isActive===!0||e?.isStreaming===!0||t.some(l=>l.isStreaming===!0)||s.some(l=>l?.isStreaming===!0||l?.status==="pending"),r=s.some(l=>l?.incomplete===!0||ja.has(l?.status)||ja.has(l?.turnEndReason)||ja.has(l?.stopReason));if(n||r){for(let l of t)l.kind="progress";return}if(t.some(l=>l.kind==="result"))return;let i=s.some(l=>l?.turnEndReason==="end_turn"),o=t.some(l=>l.explicitKind),a=t.length===1&&!o;(i||a||e.isHistory&&!o)&&(t[t.length-1].kind="result")}var ja,Ci=N(()=>{ja=new Set(["aborted","errored","error","cancelled","canceled"])});function Ua(e){return e?.type==="user"&&typeof e.content=="string"&&e.content.trim()}function Ka(e){return e?.type==="assistant"||e?.type==="thinking"||e?.type==="tool_use"||e?.type==="tool-use"||e?.type==="tool_result"||e?.type==="tool-result"}function za(e,t){if(!e||e.kind!=="assistant")return!0;let s=e.turnId||e.lastTurnId||"",n=t?.turnId||"";if(s&&n&&s!==n)return!0;let r=e.speakerVpId||"",i=t?.speakerVpId||t?.vpId||"";return!!(r&&i&&r!==i)}function np(e=[]){let t=[],s=null,n=r=>{s&&(t.push({start:s.start,end:r,kind:s.kind}),s=null)};for(let r=0;r<e.length;r++){let i=e[r];if(i){if(Ua(i)||i.type==="system"||i.type==="error"){n(r),s={start:r,kind:i.type};continue}if(!Ka(i)){s||(s={start:r,kind:"other"});continue}(!s||s.kind==="assistant"&&za(s,i))&&(n(r),s={start:r,kind:"assistant",turnId:i.turnId||"",speakerVpId:i.speakerVpId||i.vpId||""}),s.lastTurnId=i.turnId||s.lastTurnId||"",s.speakerVpId=s.speakerVpId||i.speakerVpId||i.vpId||""}}return n(e.length),t}function rp(e,t){return!e||e._historyWindowPrefetched===!0?!1:t?(e.sessionId??e.groupId)===t:!0}function Ya(e=[],t=null,s=yr){let n=Math.max(1,Number.isFinite(s)?Math.floor(s):yr),r=[],i=[],o=null,a=c=>{o&&(i.push({start:o.start,end:c,kind:o.kind}),o=null)};for(let c of e){if(!rp(c,t))continue;let d=r.length;if(r.push(c),Ua(c)||c.type==="system"||c.type==="error"){a(d),o={start:d,kind:c.type};continue}if(!Ka(c)){o||(o={start:d,kind:"other"});continue}(!o||o.kind==="assistant"&&za(o,c))&&(a(d),o={start:d,kind:"assistant",turnId:c.turnId||"",speakerVpId:c.speakerVpId||c.vpId||""}),o.lastTurnId=c.turnId||o.lastTurnId||"",o.speakerVpId=o.speakerVpId||c.speakerVpId||c.vpId||""}if(a(r.length),i.length<=n)return r;let l=i[i.length-n];return r.slice(l.start)}function ip(e=[],t=null,s=yr){let n=Math.max(1,s||yr),r=0,i=null,o=()=>i?(i=null,r+=1,r>n):!1;for(let a of e)if(rp(a,t)){if(Ua(a)||a.type==="system"||a.type==="error"){if(o())return!0;i={kind:a.type};continue}if(!Ka(a)){i||(i={kind:"other"});continue}if(!i||i.kind==="assistant"&&za(i,a)){if(o())return!0;i={kind:"assistant",turnId:a.turnId||"",speakerVpId:a.speakerVpId||a.vpId||""}}i.lastTurnId=a.turnId||i.lastTurnId||"",i.speakerVpId=i.speakerVpId||a.speakerVpId||a.vpId||""}return o(),r>n}function Os(){return yr}function br(){return hy}var yr,hy,op=N(()=>{yr=Number.POSITIVE_INFINITY,hy=20});function yy(e,t){let s=new Set;if(!t)return s;for(let n of e?.sessionCatalog||[])n?.runtimeProvider!=="yeaft"||n?.routeRef?.sessionId!==t||n.routeRef.agentId&&s.add(n.routeRef.agentId);if(s.size===0){let n=cs();for(let r of n?.sessionList||[])r?.id===t&&r?.agentId&&s.add(r.agentId)}return s}function Ip(e,t){let s=yy(e,t);return s.size===1?s.values().next().value:null}function Mi(e,t,s){return!!s&&Ip(e,t)===s}function st(e,t,s){return!e||e.sessionId!==t?!1:s?e.agentId===s:!e.agentId}function ap(e,t,s=null){if(!t)return!1;let n=s||be(e,t),r=St(n,t);if(r&&e.yeaftProcessingSessions?.[r]||e.yeaftProcessingSessions?.[t]&&Mi(e,t,n))return!0;for(let i of Object.values(e.activeVpTurns||{}))if(st(i,t,n))return!0;for(let i of Object.values(e.vpStatuses||{}))if(st(i,t,n)&&kr.has(i?.state))return!0;return!1}function by(e,t,s,n=null){let r={...e.yeaftProcessingSessions||{}};if(t){let i=Ea(t);if(r=Object.fromEntries(Object.entries(r).filter(([o])=>n?o!==St(t,n):!o.startsWith(i))),n)Mi(e,n,t)&&delete r[n];else for(let o of Object.keys(r))Mi(e,o,t)&&delete r[o]}else n?delete r[n]:r={};for(let i of s||[]){let o=i?.sessionId||i?.groupId||null;if(!o||!kr.has(i?.state))continue;let a=St(t,o)||o;r[a]=!0}return r}function hn(e,t,s){let n=Da(t,s);return n&&e?.activeVpTurns?.[n]?n:e?.activeVpTurns?.[s]&&(!t||!e.activeVpTurns[s]?.agentId||e.activeVpTurns[s].agentId===t)?s:n||s||""}function lp(e,t){if(!t){e.activeVpTurns={},e.stoppingVpTurnIds={},e.vpStatuses={},e.yeaftProcessingSessions={};return}e.activeVpTurns=Object.fromEntries(Object.entries(e.activeVpTurns||{}).filter(([,n])=>n?.agentId&&n.agentId!==t)),e.stoppingVpTurnIds=Object.fromEntries(Object.entries(e.stoppingVpTurnIds||{}).filter(([n])=>e.activeVpTurns?.[n])),e.vpStatuses=Object.fromEntries(Object.entries(e.vpStatuses||{}).filter(([,n])=>n?.agentId&&n.agentId!==t));let s=Ea(t);e.yeaftProcessingSessions=Object.fromEntries(Object.entries(e.yeaftProcessingSessions||{}).filter(([n])=>!n.startsWith(s)))}function Nt(e,t){return`${e||""}:${t||""}`}function Cy(e){return e?.kind==="action"&&typeof e.actionId=="string"&&Number.isInteger(Number(e.generation))&&Number(e.generation)>0?{kind:"action",actionId:e.actionId,generation:Number(e.generation)}:{kind:"coordinator"}}function Ay(e){return typeof e=="string"?e:e?.kind==="action"&&typeof e.actionId=="string"?{kind:"action",actionId:e.actionId,generation:Number.isInteger(Number(e.generation))?Number(e.generation):0}:{kind:"coordinator"}}function xy(e={}){let t=Qe(e.quote);return{agentId:e.agentId||"",workItemId:e.workItemId||"",target:Cy(e.target),text:String(e.text||""),...t?{quote:t}:{},attachments:Array.isArray(e.attachments)?e.attachments.map(s=>({fileId:s?.fileId||"",name:s?.name||"",mimeType:s?.mimeType||"",size:Math.max(0,Number(s?.size)||0)})):[],revision:Number(e.revision)||0,planRevision:Number(e.planRevision)||0,ledgerRevision:Number(e.ledgerRevision)||0,coordinatorRevision:Number(e.coordinatorRevision)||0}}function fp(e,t,s){return{conversationId:s||null,agentId:e?.agentId||t?.agentId||null,requestId:t?.requestId||null,toolCallId:t?.toolCallId||null,sessionId:e?.sessionId||t?.sessionId||null,vpId:e?.vpId||t?.vpId||null,turnId:e?.turnId||t?.turnId||null,threadId:e?.threadId||t?.threadId||null}}function gp(e,t){return{conversationId:t||null,agentId:e?.agentId||null,requestId:e?.askRequestId||null,toolCallId:e?.toolId||null,sessionId:e?.sessionId||e?.groupId||null,vpId:e?.vpId||e?.speakerVpId||null,turnId:e?.turnId||null,threadId:e?.threadId||null}}function Ty(e,t){return el.every(s=>!t[s]||e[s]===t[s])}function Cp(e,t){return el.every(s=>!e[s]||!t[s]||e[s]===t[s])}function mp(e,t,s){let n=(e||[]).filter(o=>o?.type==="tool-use"&&(o.toolName==="AskUser"||o.toolName==="AskUserQuestion")&&(!t.requestId||!o.askRequestId||o.askRequestId===t.requestId)&&(!t.toolCallId||!o.toolId||o.toolId===t.toolCallId)),r=n.filter(o=>Ty(gp(o,s),t));if(r.length===1)return r[0];let i=n.filter(o=>Cp(gp(o,s),t));return i.length===1?i[0]:null}function Ap(e){return el.map(t=>e[t]||"").join("\0")}function My(e,t,s){let n=Ap(t),r={...e._yeaftAskTerminalEvents||{},[n]:{identity:t,event:s,receivedAt:Date.now()}},i=Object.keys(r);if(i.length>pp){i.sort((o,a)=>r[o].receivedAt-r[a].receivedAt);for(let o of i.slice(0,i.length-pp))delete r[o]}e._yeaftAskTerminalEvents=r}function hp(e,t){let s=e._yeaftAskTerminalEvents||{},n=Ap(t),r=s[n]?n:null;if(!r){let l=Object.entries(s).filter(([,c])=>Cp(c.identity||{},t));l.length===1&&(r=l[0][0])}if(!r)return null;let i=s[r],{[r]:o,...a}=s;return e._yeaftAskTerminalEvents=a,i?.event||null}function Py(e,t,s){return(e.messagesMap?.[t]||[]).some(n=>n?.type==="tool-use"&&n.sessionId===s&&n.hasResult===!1)}function Ga(e,t){t.type==="ask_user_answered"?(e.askAnswered=!0,e.selectedAnswers=t.answers||{},e.askExpired=!1):(e.isHistory=!0,e.askExpired=!0,e.askAnswered=!1,e.selectedAnswers=null),e.askPending=!1,e.pendingAnswers=null,e.askSubmitGeneration=null,e.askRequestId=null}function Ry(e){if(!e||typeof e!="string")return null;let t=e.match(/^(\d+)/);if(!t)return null;let s=Number(t[1]);return Number.isFinite(s)?s:null}function _y(e){if(!e||typeof e!="string")return null;let t=e.match(/^m(\d+)$/);if(!t)return null;let s=Number(t[1]);return Number.isFinite(s)?s:null}function wr(e){return Wn(e)}function Qa(e,t,s){return`${St(e,t)}::${s||""}`}function Za(e){return Object.fromEntries(Object.entries(e||{}).filter(([,t])=>t?.status==="running"))}function cs(){try{return typeof window>"u"?null:window.Pinia?.useSessionsStore?.()||window.__useSessionsStore&&window.__useSessionsStore()||null}catch{return null}}function vp(e){let t=cs();if(!t?.reorderSessionsGlobally)return;let s=(Array.isArray(e)?e:[]).filter(n=>n?.runtimeProvider==="yeaft").map(n=>`${n.routeRef?.agentId||""}${n.routeRef?.sessionId||""}`).filter(n=>!n.startsWith(""));t.reorderSessionsGlobally(s)}function be(e,t,s=null){if(s)return s;if(t){let n=cs(),r=n?.activeSessionKey?n.sessions?.[n.activeSessionKey]:null;if(r?.id===t&&r.agentId)return r.agentId;let i=n&&typeof n.sessionById=="function"?n.sessionById(t,e?.currentAgent||null):null;if(i&&i.agentId)return i.agentId;let o=e?.yeaftSessionAgentById?e.yeaftSessionAgentById[t]:null;if(o)return o}return e?.currentAgent||null}function Ey(e,t){let s=i=>String(i||"").replace(/^v/,"").split(".").slice(0,3).map(o=>Number.parseInt(o,10)),n=s(e),r=s(t);if(n.length<3||r.length<3||[...n,...r].some(i=>!Number.isFinite(i)))return!1;for(let i=0;i<3;i+=1)if(n[i]!==r[i])return n[i]>r[i];return!0}function yp(e,t,s){if(!t||!s)return!1;let n=Array.isArray(e?.agents)?e.agents.find(o=>o?.id===t):null,r=e?.currentAgentInfo?.id===t?e.currentAgentInfo:null;return(n?.capabilities||r?.capabilities||[]).includes(s)?!0:s==="session_history_search"&&Ey(n?.version||r?.version,"1.0.166")}function Fs(e,{fallbackDefault:t=!1}={}){if(e?.yeaftActiveSessionFilter)return e.yeaftActiveSessionFilter;let s=cs();return s?.activeSessionId?s.activeSessionId:t?"grp_default":null}function Ti(e){let t=e.yeaftDebugSessionFilter;if(t==="__all__")return null;if(t)return t;let s=Fs(e);return s||(cs()?.sessions?.grp_default?"grp_default":null)}function Xa(e,t="session"){return[e?.vpId||e?.ownerVpId||"vp",e?.threadId||"thread",e?.turnId||t].join(":")}function qt(e,t,s=null){return s||t&&e?.yeaftConversationIdsByAgent?.[t]||e?.yeaftConversationId||null}function tt(e,t=null,s=null){let n=t||e?.yeaftActiveSessionFilter||null,r=s||be(e,n);return(r&&e?.yeaftConversationIdsByAgent?e.yeaftConversationIdsByAgent[r]:null)||e?.yeaftConversationId||null}function bp(e,t,s){if(e?.currentView!=="yeaft")return!1;let n=e?.yeaftActiveSessionFilter||null;if(n&&t!==n)return!1;let r=be(e,n);return!r||!s||r===s}var vy,$e,Ai,xi,cp,dp,wy,up,ky,kr,Sy,Iy,pp,el,wp,Ja,kp,Sp,Bs,Pi=N(()=>{kt();Go();Bt();da();ir();Gd();ou();_u();Ts();os();Hu();Sa();fi();Bu();Nu();Wu();la();Wa();Aa();ls();Ci();sn();ni();mr();op();ii();oa();xa();({defineStore:vy}=Pinia),$e=Object.freeze([]),Ai=(e,t,s)=>`${e||""}::${t||""}::${s}`;xi=5,cp=100,dp=512*1024,wy=15e3,up=Object.freeze([150,300,600,1e3]),ky=new Set(["index_building","stale_result"]),kr=new Set(["typing","thinking","retrying","streaming","tool"]),Sy=Object.freeze(["model","availableModels","refreshedAt","catalogRefreshedAt","catalogEpoch","catalogRevision","catalogDigest","refreshStartedAt","refreshReason","refreshError","refreshing"]),Iy=8,pp=64;el=Object.freeze(["conversationId","agentId","requestId","toolCallId","sessionId","vpId","turnId","threadId"]);wp=1e3,Ja=1,kp=5,Sp=200,Bs=vy("chat",{state:()=>({ws:null,authenticated:!1,_hasHandledAgentList:!1,_hasHandledYeaftSessionHydrate:!1,yeaftSessionInventoryCompleteSupported:null,yeaftSessionHydrateRequestId:null,yeaftSessionHydrateSlices:[],yeaftSessionHydrateError:null,_yeaftSessionInventorySocketQuarantined:!1,sessionKey:null,serverEncryptionRequired:!0,connectionState:"disconnected",reconnectAttempts:0,maxReconnectAttempts:10,reconnectTimer:null,agents:[],currentAgent:null,currentAgentInfo:null,conversations:[],activeConversations:[],currentWorkDir:null,messagesMap:{},_messageUiKeySequence:0,chatSessionState:{},panels:[],activePanelId:null,_pendingPaneId:null,conversationTitles:{},customConversationTitles:{},processingConversations:{},yeaftProcessingSessions:{},yeaftUnreadSessionKeys:{},theme:localStorage.getItem("theme")||(typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),themeFollowSystem:!localStorage.getItem("theme"),locale:localStorage.getItem("locale")||"zh-CN",executionStatusMap:{},sessionHealth:{},historySessions:[],historySessionsLoading:!1,folders:[],foldersLoading:!1,providerModels:[],providerModelsLoading:!1,contextUsage:null,lastUsedAgent:localStorage.getItem("lastUsedAgent")||null,lastUsedSession:JSON.parse(localStorage.getItem("lastUsedSession")||"null"),lastViewedConversation:localStorage.getItem("lastViewedConversation")||null,pendingRecovery:null,recoveryDismissed:!1,sessionLoading:!1,sessionLoadingText:"",agentSwitching:!1,pendingAgentSelection:null,_pendingSessionTitle:null,workbenchExpanded:!1,workbenchMaximized:!1,sidebarCollapsed:!1,sessionSidebarOpen:!1,compactStatus:null,clearStatus:null,refreshingSession:!1,refreshingSessionMap:{},proxyPorts:{},hasMoreMessages:!1,loadingMoreMessages:!1,chatHistoryRequests:{},chatHistoryRequestIdSupported:null,chatHistoryConnectionGeneration:0,sessionCatalog:[],hiddenSessionCatalog:[],sessionProjects:[],sessionCatalogLoaded:!1,sessionCatalogMutationRequests:{},projectMutationRequests:{},activeCatalogKey:null,openUnifiedSessionCreate:!1,openUnifiedChatCreate:!1,pendingUnifiedSessionSettings:null,yeaftHasMoreHistory:!1,yeaftLoadingMoreHistory:!1,yeaftOldestLoadedSeq:null,yeaftHistoryLoadError:null,yeaftSessionHistoryState:{},yeaftMessageWindowState:{},yeaftHistoryCacheState:{},_yeaftHistoryBrowserHydrationBySession:{},yeaftBootstrapMetaLoadingKey:null,yeaftHistoryPerfTraceBySession:{},yeaftHistorySearchState:{requestId:null,agentId:null,sessionId:null,query:"",senderKey:"",loading:!1,results:[],hasMore:!1,nextBeforeSeq:null,nextCursor:null,error:null},yeaftHistoryOutlineBySession:{},_yeaftHistoryOutlineTimeouts:{},_yeaftHistorySearchTimeout:null,_yeaftHistoryWindowPendingByKey:{},_yeaftHistoryRevealLeases:{},_yeaftHistoryRevealSequence:0,_yeaftReconnectCatchUpPending:!1,_yeaftOpenedSessionsLoadedAgents:{},_yeaftAgentSeen:null,slashCommandsMap:{},slashCommandDescriptions:{},inputDrafts:{},mcpServers:{},expertRoleDefinitions:null,llmConfig:{},llmModelDiscovery:{},llmGithubDevice:null,modelsDevRegistry:{registry:{},fetchedAt:0,error:null,loaded:!1},_modelsDevPending:null,yeaftSettings:{},searchSettings:null,telemetrySettings:null,tavilyUsage:null,tavilyUsageLoading:!1,_perfTraceQueue:[],_perfTraceFlushTimer:null,yeaftPerfTraceByMessageId:{},yeaftPerfTraceByTurnId:{},yeaftMcpServers:[],yeaftMcpRuntime:{connected:!1,toolCount:0,perServer:[]},yeaftMcpLoading:!1,yeaftMcpError:null,btwMode:!1,btwMessages:[],btwLoading:!1,btwSessionId:null,conversationMcpServers:{},conversationMcpServerTools:{},mcpPanelOpen:!1,expertSelections:[],customExpertRoles:[],subagents:{},activeSubagentId:null,activeRightPanel:null,pinnedSessions:JSON.parse(localStorage.getItem("pinned-sessions")||"[]"),...Lu(),workCenterOpen:!1,workCenterAgentId:null,workCenterItemsByAgent:{},workCenterListPageByAgent:{},workCenterListMoreLoadingByAgent:{},_workCenterListGenerationByAgent:{},_workCenterListQueryByAgent:{},_workCenterListFiltersByAgent:{},_workCenterListMoreRequestsByAgent:{},_workCenterListEventGenerationByAgent:{},_workCenterListEventsByAgent:{},_workCenterDeletedIdsByAgent:{},workCenterDetailByAgent:{},workCenterActionMessages:{},workCenterActionMessagesLoading:{},workCenterActionMessagesError:{},workCenterActionRequests:{},workCenterActionRequestDetails:{},workCenterActionRequestsLoading:{},workCenterActionRequestsError:{},workCenterActionRequestDetailsLoading:{},workCenterActionRequestDetailsError:{},workCenterLoadedByAgent:{},workCenterLoadingByAgent:{},workCenterErrorByAgent:{},workCenterWatcherByAgent:{},workCenterSettingsByAgent:{},workCenterRuntimeByAgent:{},workCenterSettingsLoadingByAgent:{},workCenterSettingsErrorByAgent:{},_workCenterSettingsGenerationByAgent:{},_workCenterDetailRequestGenerationByAgent:{},_workCenterDetailEventRefreshByAgent:{},_workCenterActionInputGenerationByAgent:{},_workCenterActionMessageRequests:{},_workCenterActionMessageGenerationByKey:{},_workCenterActionRequestsGeneration:{},_workCenterActionRequestDetailsGeneration:{},workCenterPending:{},workCenterComposerDrafts:{},workCenterMessageOutbox:{},_workCenterBrowserFence:null,_workCenterBrowserUnsubscribe:null,workCenterCreateDraft:null,yeaftConversationId:null,yeaftConversationIdsByAgent:{},_yeaftPendingConversationPromotions:{},_yeaftRetiredConversationIdsByAgent:{},_yeaftRetiredConversationTargetsByAgent:{},yeaftSessionAgentById:{},yeaftModel:null,yeaftModelEffort:null,yeaftSessionReady:!1,yeaftStatus:null,yeaftAvailableModels:[],yeaftStatusByAgent:{},_yeaftRetiredCatalogEpochsByAgent:{},yeaftModelsRefreshing:!1,yeaftModelRefreshError:null,yeaftYeaftDir:null,yeaftActiveTasksBySession:{},yeaftStoppingTasksById:{},yeaftToolStats:null,yeaftToolStatsLoading:!1,yeaftDebugLoops:[],yeaftDebugTurnsById:{},yeaftDebugTurnOrder:[],yeaftDebugHistoryLoading:!1,yeaftDebugHistoryError:null,yeaftDebugHistoryFetchedAt:0,yeaftDebugHistoryLimit:Ja,yeaftDebugHistoryHasMore:!1,yeaftDebugPanel:{open:!1,status:"idle",requestId:null,agentId:null,sessionId:null,turnId:null,error:null},yeaftDebugSearch:"",yeaftDebugSessionFilter:null,yeaftDreamLatest:{},yeaftDreamSnapshots:{},yeaftDreamPromptLoads:{},yeaftDreamEvents:{},yeaftReflectionCards:{},yeaftSubAgentCards:{},yeaftSidebarV2Enabled:!0,yeaftActiveSessionFilter:null,_currentYeaftSessionId:null,_currentYeaftVpId:null,_currentYeaftTurnId:null,_currentYeaftThreadId:null,_yeaftAskTerminalEvents:{},activeVpTurns:{},vpStatuses:{},stoppingVpTurnIds:{},yeaftVpTyping:{},_vpCrudPending:null}),getters:{currentConversation:e=>e.activeConversations[0]||null,activeConversationId:e=>Oa(e),activeSessionRoute(e){if(e.currentView==="yeaft"){let n=Fs(e);return n?{runtimeProvider:"yeaft",agentId:be(e,n),sessionId:n}:null}let t=Oa(e);if(!t)return null;let s=e.conversations.find(n=>n?.id===t&&n.type!=="yeaft");return s?{runtimeProvider:s.provider==="copilot"?"copilot":"claude-code",agentId:s.agentId||e.currentAgent||null,sessionId:t}:null},messages(e){let t=this.activeConversationId,s=t&&e.messagesMap[t]||$e;if(e.currentView==="yeaft"){let n=e.yeaftActiveSessionFilter||null,r=ve(be(e,n),n),i=e.yeaftMessageWindowState[r]?.visibleTurns||Os();return Ya(s,e.yeaftActiveSessionFilter||null,i)}return s},yeaftAllMessages:e=>{let t=tt(e);return t&&e.messagesMap[t]||$e},yeaftVisibleMessages(e){let t=tt(e),s=t&&e.messagesMap[t]||$e,n=e.yeaftActiveSessionFilter||null,r=ve(be(e,n),n),i=e.yeaftMessageWindowState[r]?.visibleTurns||Os();return Ya(s,e.yeaftActiveSessionFilter||null,i)},hasHiddenYeaftMessages(e){if(e.currentView!=="yeaft")return!1;let t=tt(e),s=t&&e.messagesMap[t]||$e,n=e.yeaftActiveSessionFilter||null,r=ve(be(e,n),n),i=e.yeaftMessageWindowState[r]?.visibleTurns||Os();return ip(s,e.yeaftActiveSessionFilter||null,i)},activeYeaftHistoryState(e){return Xo(e)},yeaftInitialHistoryLoading(e){let t=Xo(e);return e.currentView==="yeaft"&&!!e.yeaftActiveSessionFilter&&!!t?.loading&&!t?.loaded&&this.yeaftVisibleMessages.length===0},vpsTypingInCurrentConv(e){let t=this.activeConversationId;if(!t)return $e;let s=(e.yeaftVpTyping||{})[t];if(!s)return $e;let n=Object.keys(s).filter(r=>(s[r]||0)>0);return n.length===0?$e:n},isVpTypingInCurrentConv(e){return t=>{if(!t)return!1;let s=this.activeConversationId;if(!s)return!1;let n=(e.yeaftVpTyping||{})[s];return n?(n[t]||0)>0:!1}},yeaftDreamLatestForActiveSession(e){let t=Ti(e);if(!t)return null;let s=`sessions/${t}`;return e.yeaftDreamLatest?.[s]||null},yeaftDreamSnapshotForActiveSession(e){let t=Ti(e);if(!t)return null;let s=`sessions/${t}`;return e.yeaftDreamSnapshots?.[s]||null},yeaftDreamPromptLoadForActiveSession(e){let t=Ti(e);if(!t)return null;let s=`sessions/${t}`;return e.yeaftDreamPromptLoads?.[s]||null},yeaftDreamEventsForActiveSession(e){let t=Ti(e);if(!t)return[];let s=`sessions/${t}`,n=Array.isArray(e.yeaftDreamEvents?.[s])?e.yeaftDreamEvents[s]:[],r=Array.isArray(e.yeaftDreamEvents?.["*"])?e.yeaftDreamEvents["*"]:[];return r.length===0?n:n.length===0?r:[...n,...r].sort((i,o)=>(i.at||0)-(o.at||0))},yeaftDebugTurnsForActiveSession:e=>{let t=e.yeaftDebugTurnOrder||$e,s=e.yeaftDebugTurnsById||{},n=e.yeaftDebugLoops||$e,r=e.yeaftReflectionCards||{},i=e.yeaftDebugSessionFilter,o;i==="__all__"?o=null:i?o=i:o=null;let a={};for(let d of n)!d||!d.turnId||(a[d.turnId]||(a[d.turnId]=[]),a[d.turnId].push(d));let l={};for(let d of Object.keys(r)){let u=r[d];!u||!u.turnId||(l[u.turnId]||(l[u.turnId]=[]),l[u.turnId].push(u))}let c=[];for(let d=t.length-1;d>=0;d--){let u=t[d],f=s[u];if(!f||o&&f.sessionId&&f.sessionId!==o)continue;let p=a[u]||$e,g=l[u]||$e,m=p.length,v=0,k=0;for(let h of p){let y=h&&h.usage;y&&Number.isFinite(y.totalTokens)?v+=y.totalTokens:y&&(v+=(y.totalInputTokens||(y.inputTokens||0)+(y.cacheReadTokens||0)+(y.cacheWriteTokens||0))+(y.outputTokens||0)),h&&Number.isFinite(h.latencyMs)&&(k+=h.latencyMs)}let w=!f.closedAt,I={...f,loopCount:w||!f.loopCount?m:f.loopCount,totalTokens:w||!f.totalTokens?v:f.totalTokens,totalMs:w||!f.totalMs?k:f.totalMs,loops:p,reflections:g};c.push(I)}return c},yeaftDebugAvailableSessions:e=>{let t=new Set;for(let s of e.yeaftDebugTurnOrder||$e){let n=e.yeaftDebugTurnsById[s];n&&n.sessionId&&t.add(n.sessionId)}return Array.from(t).sort()},yeaftDebugTurnTotal:e=>(e.yeaftDebugTurnOrder||$e).length,messagesCache:e=>e.messagesMap,isMultiColumn:e=>e.activeConversations.length>1,isSplitMode:e=>e.panels.length>1,isProcessing:e=>{if(e.currentView==="yeaft"){let t=Fs(e);return t?ap(e,t,be(e,t)):!1}return e.currentConversation?!!e.processingConversations[e.currentConversation]:!1},canSend:e=>!(!e.currentAgent||!e.currentConversation),currentAgentName:e=>e.currentAgentInfo?.name||"\u9009\u62E9 Agent",currentAgentWorkDir:e=>e.currentAgentInfo?.workDir||"",effectiveWorkDir:e=>e.currentView==="yeaft"?cs()?.activeSession?.workDir||e.yeaftYeaftDir||e.currentAgentInfo?.workDir||"":e.currentWorkDir||e.currentAgentInfo?.workDir||"",currentAgentCapabilities:e=>e.currentAgentInfo?.capabilities||["terminal","file_editor","background_tasks"],hasCapability:e=>t=>(e.currentAgentInfo?.capabilities||["terminal","file_editor","background_tasks"]).includes(t),getConversationTitle:e=>t=>e.customConversationTitles[t]||e.conversationTitles[t]||null,executionStatus:e=>e.currentConversation?e.executionStatusMap[e.currentConversation]||{currentTool:null,toolHistory:[],lastActivity:null}:{currentTool:null,toolHistory:[],lastActivity:null},isConversationProcessing:e=>t=>!!e.processingConversations[t],isConversationConnecting:e=>t=>t?!!e.conversations.find(n=>n.id===t)?.connecting:!1,isConversationCompacting:e=>t=>t?e.compactStatus?.conversationId===t&&e.compactStatus?.status==="compacting":!1,isYeaftSessionProcessing:e=>(t,s=null)=>ap(e,t,s),isSessionHistorySyncing:e=>t=>{let s=t?.sessionId||null;return s?t.runtimeProvider==="yeaft"?!!e.yeaftSessionHistoryState?.[ve(t.agentId||null,s)]?.loading:!!e.chatHistoryRequests?.[is(s)]?.loading:!1},isYeaftSessionUnread:e=>(t,s=null)=>{if(!t)return!1;let n=be(e,t,s);return n?!!e.yeaftUnreadSessionKeys?.[li(n,t)]:!1},showRecoveryBanner:e=>e.pendingRecovery&&!e.recoveryDismissed&&!e.currentConversation,currentSubagents:e=>{if(!e.currentConversation)return $e;let t=e.subagents[e.currentConversation];return t?Object.values(t):$e},hasRunningSubagents:e=>{if(!e.currentConversation)return!1;let t=e.subagents[e.currentConversation];return t?Object.values(t).some(s=>s.status==="running"):!1},runningSubagentCount:e=>{if(!e.currentConversation)return 0;let t=e.subagents[e.currentConversation];return t?Object.values(t).filter(s=>s.status==="running").length:0},activeSubagentMessages:e=>{if(!e.currentConversation||!e.activeSubagentId)return $e;let t=e.subagents[e.currentConversation];if(!t)return $e;let s=t[e.activeSubagentId];return(Array.isArray(s?.messages)?s.messages:$e).filter(r=>r?.type==="text")},selectedTaskInfo:()=>null,currentMcpServers:e=>e.currentConversation&&e.conversationMcpServers[e.currentConversation]||$e},actions:{activateChatView({persistPreference:e=!1}={}){let t=this._pendingChatRestoreConversationId;this._pendingChatRestoreConversationId=null;let s=t?this.conversations.find(o=>o.id===t):null,n=s?.agentId?this.agents.find(o=>o.id===s.agentId&&o.online):null;!this._savedChatIdentity&&s&&n&&(this._savedChatIdentity={agentId:n.id,agentInfo:{...n},workDir:s.workDir||n.workDir||null}),this.currentView="chat",e&&Va("chat");let r=this._savedChatIdentity||null,i=this.pendingAgentSelection&&this.pendingAgentSelection.agentId!==r?.agentId;r?.agentId&&(this.currentAgent!==r.agentId||i)&&this.selectAgent(r.agentId),Vu(this),t&&s&&n&&(this.autoRestoreConversation(t),this.sendWsMessage({type:"refresh_conversation",conversationId:t}))},enterWorkCenter(e=null){if(!this.hydrateWorkCenterBrowserState())return!1;let t=this.agents.filter(n=>n?.online&&Array.isArray(n.capabilities)&&n.capabilities.includes("work_center")),s=t.some(n=>n.id===e)?e:t[0]?.id||null;if(!s)return this.workCenterOpen=!1,this.workCenterAgentId=null,!1;if(this.currentAgent!==s){this.selectAgent(s),this.currentAgent=s;let n=this.agents.find(r=>r.id===s);n&&(this.currentAgentInfo=n)}return this.workCenterAgentId=s,this.workCenterOpen=!0,this.listWorkItems(s).catch(()=>{}),!0},leaveWorkCenter(){this.workCenterOpen=!1},enterWorkCenterFromSession(e,t=""){if(!e?.id)return;let s=e.agentId||be(this,e.id),n=String(t||e.title||e.name||"").trim();this.workCenterCreateDraft={sourceAgentId:s,requirement:n,workDir:String(e.workDir||"").trim(),origin:{sessionId:e.id,messageId:null,createdBy:"user"},linkedSessionIds:[e.id]},this.enterWorkCenter(s)},hydrateWorkCenterBrowserState(){this._workCenterBrowserUnsubscribe||(this._workCenterBrowserUnsubscribe=Ic(()=>{Nn(this._workCenterBrowserFence)||this.clearWorkCenterBrowserState()}));let e=si();if(!e)return this._workCenterBrowserFence=null,this.workCenterComposerDrafts={},this.workCenterMessageOutbox={},!1;if(!Nn(this._workCenterBrowserFence)){let t=Sc(e);this._workCenterBrowserFence=e,this.workCenterComposerDrafts=t.drafts,this.workCenterMessageOutbox=t.outbox}return!0},clearWorkCenterBrowserState(){this._workCenterBrowserFence=null,this.workCenterComposerDrafts={},this.workCenterMessageOutbox={}},workCenterComposerKey(e,t){return Nt(e,t)},saveWorkCenterComposerDraft(e,t,s={}){let n=Nt(e,t);if(!e||!t)return;let r=Qe(s.quote),i={...this.workCenterComposerDrafts||{},[n]:{text:String(s.text||""),...r?{quote:r}:{},attachments:Array.isArray(s.attachments)?s.attachments:[],target:Ay(s.target),error:String(s.error||"")}};return Yo(i,this._workCenterBrowserFence)?(this.workCenterComposerDrafts=i,!0):!1},loadWorkCenterComposerDraft(e,t){return this.workCenterComposerDrafts?.[Nt(e,t)]||null},removeWorkCenterComposerDraft(e,t){let s=Nt(e,t),n={...this.workCenterComposerDrafts||{}};return delete n[s],Yo(n,this._workCenterBrowserFence)?(this.workCenterComposerDrafts=n,!0):!1},prepareWorkCenterMessageEnvelope(e={}){let t=xy(e),s=Nt(t.agentId,t.workItemId),n=this.workCenterMessageOutbox?.[s]||null;if(n)return n;let r={...t,clientMessageId:globalThis.crypto?.randomUUID?.()||`${Date.now()}-${Math.random()}`,createdAt:Date.now()},i={...this.workCenterMessageOutbox||{},[s]:r};return qn(i,this._workCenterBrowserFence)?(this.workCenterMessageOutbox=i,r):null},loadWorkCenterMessageEnvelope(e,t){return this.workCenterMessageOutbox?.[Nt(e,t)]||null},replaceWorkCenterMessageEnvelopeAttachments(e,t,s=[]){let n=Nt(e,t),r=this.workCenterMessageOutbox?.[n];if(!r)return null;let i={...r,attachments:Array.isArray(s)?s.map(a=>({fileId:a?.fileId||"",name:a?.name||"",mimeType:a?.mimeType||"",size:Math.max(0,Number(a?.size)||0)})):[]},o={...this.workCenterMessageOutbox||{},[n]:i};return qn(o,this._workCenterBrowserFence)?(this.workCenterMessageOutbox=o,i):null},discardWorkCenterMessageEnvelope(e,t){let s=Nt(e,t),n={...this.workCenterMessageOutbox||{}};return delete n[s],qn(n,this._workCenterBrowserFence)?(this.workCenterMessageOutbox=n,!0):!1},confirmWorkCenterMessageEnvelope(e,t,s){let n=Nt(e,t),r=this.workCenterMessageOutbox?.[n];if(!r||r.clientMessageId!==s)return!1;let i={...this.workCenterMessageOutbox||{}};return delete i[n],qn(i,this._workCenterBrowserFence)?(this.workCenterMessageOutbox=i,this.removeWorkCenterComposerDraft(e,t),!0):!1},workCenterRequest(e,t={},s=null){let n=s||this.workCenterAgentId||this.currentAgent;if(!n)return Promise.reject(new Error("No Agent selected"));let r=`work-center-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise((i,o)=>{let a=setTimeout(()=>{delete this.workCenterPending[r],o(new Error("Work Center request timed out"))},3e4);this.workCenterPending[r]={resolve:i,reject:o,timer:a,agentId:n,op:e,clientMessageId:typeof t.clientMessageId=="string"?t.clientMessageId:null},this.sendWsMessage({type:"work_center_request",agentId:n,requestId:r,op:e,payload:t})})},workItemMatchesBoardQuery(e,t={}){if(!e||t.lane&&e.boardLane!==t.lane||t.vpId&&!(e.executors||[]).some(n=>n?.id===t.vpId)||t.workItemType&&e.workItemType!==t.workItemType||t.updatedFrom&&Number(e.updatedAt)<Number(t.updatedFrom)||t.updatedTo&&Number(e.updatedAt)>Number(t.updatedTo))return!1;let s=String(t.keyword||"").trim().toLowerCase();return!s||String(e.title||"").toLowerCase().includes(s)||String(e.goal||"").toLowerCase().includes(s)},applyWorkItemBoardSummary(e,t,s={}){let n=ki(e,t),r=n.find(i=>i?.id===t?.id)||null;return!r||this.workItemMatchesBoardQuery(r,s)?n:n.filter(i=>i.id!==r.id)},async listWorkItems(e=null,t={}){let s=e||this.workCenterAgentId||this.currentAgent;if(!s)return[];let n={lane:["needs_attention","active","closed"].includes(t.lane)?t.lane:null,keyword:String(t.keyword||t.search||"").trim(),vpId:String(t.vpId||"").trim(),workItemType:String(t.workItemType||"").trim(),createdFrom:Number(t.createdFrom)||null,createdTo:Number(t.createdTo)||null,updatedFrom:Number(t.updatedFrom)||null,updatedTo:Number(t.updatedTo)||null,limit:Math.min(Math.max(Number(t.limit)||100,1),200)},r=JSON.stringify(n),i=Number(this._workCenterListGenerationByAgent[s]||0)+1,o=Number(this._workCenterListEventGenerationByAgent[s]||0);this._workCenterListGenerationByAgent={...this._workCenterListGenerationByAgent,[s]:i},this._workCenterListQueryByAgent={...this._workCenterListQueryByAgent,[s]:r},this._workCenterListFiltersByAgent={...this._workCenterListFiltersByAgent,[s]:n},this.workCenterLoadingByAgent={...this.workCenterLoadingByAgent,[s]:!0},this.workCenterErrorByAgent={...this.workCenterErrorByAgent,[s]:null};try{let a=await this.workCenterRequest("list",n,s),l=(Array.isArray(a?.items)?a.items:[]).filter(d=>!this.workItemDeleted(s,d?.id));if(this._workCenterListGenerationByAgent[s]===i&&this._workCenterListQueryByAgent[s]===r&&this.workCenterAgentId===s){let d=l,u=this._workCenterListEventsByAgent[s]||{};for(let f of Object.values(u))Number(f?.generation)<=o||f?.queryKey!==r||(d=this.applyWorkItemBoardSummary(d,f.summary,n));this.workCenterItemsByAgent={...this.workCenterItemsByAgent,[s]:d},this.workCenterListPageByAgent={...this.workCenterListPageByAgent,[s]:{nextCursor:a?.nextCursor||null,queryKey:r}},this.workCenterWatcherByAgent={...this.workCenterWatcherByAgent,[s]:a?.watcher||null},this.workCenterLoadedByAgent={...this.workCenterLoadedByAgent,[s]:!0}}return l}catch(a){throw this._workCenterListGenerationByAgent[s]===i&&this._workCenterListQueryByAgent[s]===r&&(this.workCenterErrorByAgent={...this.workCenterErrorByAgent,[s]:a?.message||String(a)}),a}finally{this._workCenterListGenerationByAgent[s]===i&&this._workCenterListQueryByAgent[s]===r&&(this.workCenterLoadingByAgent={...this.workCenterLoadingByAgent,[s]:!1})}},async loadMoreWorkItems(e=null){let t=e||this.workCenterAgentId||this.currentAgent,s=this.workCenterListPageByAgent[t],n=this._workCenterListFiltersByAgent[t];if(!t||!s?.nextCursor||!n)return[];let r=s.queryKey,i=this._workCenterListGenerationByAgent[t],o=Number(this._workCenterListEventGenerationByAgent[t]||0),a=s.nextCursor,l=`${i}:${r}:${a}`;if(this._workCenterListMoreRequestsByAgent[t]?.key===l)return this._workCenterListMoreRequestsByAgent[t].request;this.workCenterListMoreLoadingByAgent={...this.workCenterListMoreLoadingByAgent,[t]:!0};let c=(async()=>{try{let d=await this.workCenterRequest("list",{...n,cursor:a},t),u=this.workCenterListPageByAgent[t];if(this._workCenterListGenerationByAgent[t]!==i||this._workCenterListQueryByAgent[t]!==r||u?.queryKey!==r||u?.nextCursor!==a||this.workCenterAgentId!==t)return[];let f=[...this.workCenterItemsByAgent[t]||[]];for(let g of Array.isArray(d?.items)?d.items:[]){if(this.workItemDeleted(t,g?.id))continue;let m=f.findIndex(v=>v.id===g.id);m<0?f.push(g):f[m]=ki([f[m]],g)[0]}let p=this._workCenterListEventsByAgent[t]||{};for(let g of Object.values(p))Number(g?.generation)<=o||g?.queryKey!==r||(f=this.applyWorkItemBoardSummary(f,g.summary,n));return this.workCenterItemsByAgent={...this.workCenterItemsByAgent,[t]:f},this.workCenterListPageByAgent={...this.workCenterListPageByAgent,[t]:{nextCursor:d?.nextCursor||null,queryKey:r}},d?.items||[]}finally{if(this._workCenterListMoreRequestsByAgent[t]?.key===l){let d={...this._workCenterListMoreRequestsByAgent};delete d[t],this._workCenterListMoreRequestsByAgent=d,this.workCenterListMoreLoadingByAgent={...this.workCenterListMoreLoadingByAgent,[t]:!1}}}})();return this._workCenterListMoreRequestsByAgent={...this._workCenterListMoreRequestsByAgent,[t]:{key:l,request:c}},c},workItemDeleted(e,t){return!!this._workCenterDeletedIdsByAgent[e]?.[t]},removeWorkItemState(e,t){this._workCenterDeletedIdsByAgent={...this._workCenterDeletedIdsByAgent,[e]:{...this._workCenterDeletedIdsByAgent[e]||{},[t]:!0}},this.beginWorkCenterDetailWrite(e),this.workCenterItemsByAgent={...this.workCenterItemsByAgent,[e]:(this.workCenterItemsByAgent[e]||[]).filter(n=>n.id!==t)},this.workCenterDetailByAgent[e]?.id===t&&(this.workCenterDetailByAgent={...this.workCenterDetailByAgent,[e]:null});let s=`${e}:${t}:`;for(let n of["workCenterActionMessages","workCenterActionMessagesLoading","workCenterActionMessagesError","workCenterActionRequests","workCenterActionRequestsLoading","workCenterActionRequestsError","workCenterActionRequestDetails","workCenterActionRequestDetailsLoading","workCenterActionRequestDetailsError","_workCenterActionMessageRequests","_workCenterActionMessageGenerationByKey","_workCenterActionRequestsGeneration","_workCenterActionRequestDetailsGeneration"]){let r={};for(let[i,o]of Object.entries(this[n]||{}))i.startsWith(s)||(r[i]=o);this[n]=r}},beginWorkCenterDetailWrite(e){let t=Number(this._workCenterDetailRequestGenerationByAgent[e]||0)+1;return this._workCenterDetailRequestGenerationByAgent={...this._workCenterDetailRequestGenerationByAgent,[e]:t},t},commitWorkCenterDetail(e,t,s){if(t?.id&&this.workItemDeleted(e,t.id)||s!=null&&Number(this._workCenterDetailRequestGenerationByAgent[e]||0)!==s)return!1;let n=this.workCenterDetailByAgent[e];return n?.id===t?.id&&Zu(t,n)?!1:(this.workCenterDetailByAgent={...this.workCenterDetailByAgent,[e]:t},!0)},async getWorkItem(e,t=null){let s=t||this.workCenterAgentId||this.currentAgent,n=this.beginWorkCenterDetailWrite(s),r=await this.workCenterRequest("get",{id:e},s);return this.commitWorkCenterDetail(s,r,n),this.workCenterDetailByAgent[s]||r},invalidateWorkItemActionMessages(e,t,s,n){if(!e||!t||!s)return null;let r=ct(n),i=gn(e,t,s,r);this._workCenterActionMessageGenerationByKey={...this._workCenterActionMessageGenerationByKey,[i]:Number(this._workCenterActionMessageGenerationByKey[i]||0)+1};for(let a of["workCenterActionMessages","workCenterActionMessagesLoading","workCenterActionMessagesError"]){let l={...this[a]};delete l[i],this[a]=l}let o={...this._workCenterActionMessageRequests};for(let a of Object.keys(o))a.startsWith(`${i}:`)&&delete o[a];return this._workCenterActionMessageRequests=o,i},async loadWorkItemActionMessages(e,t,s,n,r=null){let i=r||this.workCenterAgentId||this.currentAgent,o=ct(s),a=gn(i,e,t,o),l=Number(this._workCenterActionMessageGenerationByKey[a]||0),c=`${a}:${n==null?"latest":String(n)}`;if(this._workCenterActionMessageRequests[c])return this._workCenterActionMessageRequests[c];this.workCenterActionMessagesLoading={...this.workCenterActionMessagesLoading,[a]:!0},this.workCenterActionMessagesError={...this.workCenterActionMessagesError,[a]:null};let d=(async()=>{try{let u=await this.workCenterRequest("get_action_messages",{id:e,actionId:t,generation:o,cursor:n,limit:20},i);if(this.workItemDeleted(i,e)||ct(u?.generation)!==o||Number(this._workCenterActionMessageGenerationByKey[a]||0)!==l)return u;let f=this.workCenterActionMessages[a]?.messages||[],p=vr(f,u?.messages||[]),g=this.workCenterActionMessages[a],m=g?.nextCursor,v=n==null?null:Number(n),k=m==null?null:Number(m),w=!g||v==null||k!=null&&v===k;return this.workCenterActionMessages={...this.workCenterActionMessages,[a]:{generation:o,messages:p,nextCursor:w?u?.nextCursor??null:m,total:Math.max(Number(u?.total)||0,Number(g?.total)||0,p.length)}},u}catch(u){throw Number(this._workCenterActionMessageGenerationByKey[a]||0)===l&&(this.workCenterActionMessagesError={...this.workCenterActionMessagesError,[a]:u?.message||String(u)}),u}finally{if(this._workCenterActionMessageRequests[c]===d){let u={...this._workCenterActionMessageRequests};delete u[c],this._workCenterActionMessageRequests=u;let f=Object.keys(u).some(p=>p.startsWith(`${a}:`));this.workCenterActionMessagesLoading={...this.workCenterActionMessagesLoading,[a]:f}}}})();return this._workCenterActionMessageRequests={...this._workCenterActionMessageRequests,[c]:d},d},async loadWorkItemActionRequests(e,t,s,n=null){let r=n||this.workCenterAgentId||this.currentAgent,i=ct(s),o=Ba(r,e,t,i),a=Number(this._workCenterActionRequestsGeneration[o]||0)+1;this._workCenterActionRequestsGeneration={...this._workCenterActionRequestsGeneration,[o]:a},this.workCenterActionRequestsLoading={...this.workCenterActionRequestsLoading,[o]:!0},this.workCenterActionRequestsError={...this.workCenterActionRequestsError,[o]:null};try{let l=await this.workCenterRequest("get_action_requests",{id:e,actionId:t,generation:i},r),c=!this.workItemDeleted(r,e)&&ct(l?.generation)===i&&this._workCenterActionRequestsGeneration[o]===a;return c&&(this.workCenterActionRequests={...this.workCenterActionRequests,[o]:l?.requests||[]}),c?l?.requests||[]:this.workCenterActionRequests[o]||[]}catch(l){throw this._workCenterActionRequestsGeneration[o]===a&&(this.workCenterActionRequestsError={...this.workCenterActionRequestsError,[o]:l?.message||String(l)}),l}finally{this._workCenterActionRequestsGeneration[o]===a&&(this.workCenterActionRequestsLoading={...this.workCenterActionRequestsLoading,[o]:!1})}},async loadWorkItemActionRequest(e,t,s,n,r,i=null){let o=i||this.workCenterAgentId||this.currentAgent,a=ct(s),c=`${Ba(o,e,t,a)}:${n}:${r}`,d=Number(this._workCenterActionRequestDetailsGeneration[c]||0)+1;this._workCenterActionRequestDetailsGeneration={...this._workCenterActionRequestDetailsGeneration,[c]:d},this.workCenterActionRequestDetailsLoading={...this.workCenterActionRequestDetailsLoading,[c]:!0},this.workCenterActionRequestDetailsError={...this.workCenterActionRequestDetailsError,[c]:null};try{let u=await this.workCenterRequest("get_action_request",{id:e,actionId:t,generation:a,runId:n,requestId:r},o),f=!this.workItemDeleted(o,e)&&ct(u?.generation)===a&&this._workCenterActionRequestDetailsGeneration[c]===d;return f&&(this.workCenterActionRequestDetails={...this.workCenterActionRequestDetails,[c]:u?.request||null}),f?u?.request||null:this.workCenterActionRequestDetails[c]||null}catch(u){throw this._workCenterActionRequestDetailsGeneration[c]===d&&(this.workCenterActionRequestDetailsError={...this.workCenterActionRequestDetailsError,[c]:u?.message||String(u)}),u}finally{this._workCenterActionRequestDetailsGeneration[c]===d&&(this.workCenterActionRequestDetailsLoading={...this.workCenterActionRequestDetailsLoading,[c]:!1})}},async loadWorkCenterSettings(e=null){let t=e||this.workCenterAgentId||this.currentAgent;if(!t)throw new Error("No Agent selected");let s=Number(this._workCenterSettingsGenerationByAgent[t]||0)+1;this._workCenterSettingsGenerationByAgent={...this._workCenterSettingsGenerationByAgent,[t]:s},this.workCenterSettingsLoadingByAgent={...this.workCenterSettingsLoadingByAgent,[t]:!0},this.workCenterSettingsErrorByAgent={...this.workCenterSettingsErrorByAgent,[t]:null};try{let n=await this.workCenterRequest("get_settings",{},t);return this._workCenterSettingsGenerationByAgent[t]===s&&(this.workCenterSettingsByAgent={...this.workCenterSettingsByAgent,[t]:n?.settings||null},this.workCenterRuntimeByAgent={...this.workCenterRuntimeByAgent,[t]:n?.runtime||null}),n}catch(n){throw this._workCenterSettingsGenerationByAgent[t]===s&&(this.workCenterSettingsErrorByAgent={...this.workCenterSettingsErrorByAgent,[t]:n?.message||String(n)}),n}finally{this._workCenterSettingsGenerationByAgent[t]===s&&(this.workCenterSettingsLoadingByAgent={...this.workCenterSettingsLoadingByAgent,[t]:!1})}},async refreshWorkCenterRuntime(e=null){let t=e||this.workCenterAgentId||this.currentAgent;if(!t)throw new Error("No Agent selected");let s=Number(this._workCenterSettingsGenerationByAgent[t]||0)+1;this._workCenterSettingsGenerationByAgent={...this._workCenterSettingsGenerationByAgent,[t]:s},this.workCenterSettingsLoadingByAgent={...this.workCenterSettingsLoadingByAgent,[t]:!0},this.workCenterSettingsErrorByAgent={...this.workCenterSettingsErrorByAgent,[t]:null};try{let n=await this.workCenterRequest("refresh_runtime",{},t);return this._workCenterSettingsGenerationByAgent[t]===s&&(this.workCenterSettingsByAgent={...this.workCenterSettingsByAgent,[t]:n?.settings||null},this.workCenterRuntimeByAgent={...this.workCenterRuntimeByAgent,[t]:n?.runtime||null}),n}catch(n){throw this._workCenterSettingsGenerationByAgent[t]===s&&(this.workCenterSettingsErrorByAgent={...this.workCenterSettingsErrorByAgent,[t]:n?.message||String(n)}),n}finally{this._workCenterSettingsGenerationByAgent[t]===s&&(this.workCenterSettingsLoadingByAgent={...this.workCenterSettingsLoadingByAgent,[t]:!1})}},async saveWorkCenterSettings(e,t=null){let s=t||this.workCenterAgentId||this.currentAgent;if(!s)throw new Error("No Agent selected");let n=Number(this._workCenterSettingsGenerationByAgent[s]||0)+1;this._workCenterSettingsGenerationByAgent={...this._workCenterSettingsGenerationByAgent,[s]:n};let r=await this.workCenterRequest("update_settings",{settings:e},s);return this._workCenterSettingsGenerationByAgent[s]===n&&(this.workCenterSettingsByAgent={...this.workCenterSettingsByAgent,[s]:r?.settings||null},this.workCenterRuntimeByAgent={...this.workCenterRuntimeByAgent,[s]:r?.runtime||null},this.workCenterSettingsErrorByAgent={...this.workCenterSettingsErrorByAgent,[s]:null}),r},previewWorkCenterPlan(e={},t=null){let s=t||this.workCenterAgentId||this.currentAgent;return this.workCenterRequest("preview",e,s)},async createWorkItem(e,t=null){let s=t||this.workCenterAgentId||this.currentAgent,n=this.beginWorkCenterDetailWrite(s),r=await this.workCenterRequest("create",e,s);return await this.listWorkItems(s,this._workCenterListFiltersByAgent[s]||{}),this.commitWorkCenterDetail(s,r,n),r},async updateWorkItem(e,t,s=null){let n=s||this.workCenterAgentId||this.currentAgent,r=this.beginWorkCenterDetailWrite(n),i=await this.workCenterRequest("update",{id:e,patch:t},n);return await this.listWorkItems(n,this._workCenterListFiltersByAgent[n]||{}),this.commitWorkCenterDetail(n,i,r),i},async startWorkItem(e,t=null){let s=t||this.workCenterAgentId||this.currentAgent,n=this.beginWorkCenterDetailWrite(s),r=await this.workCenterRequest("start",{id:e},s);return await this.listWorkItems(s,this._workCenterListFiltersByAgent[s]||{}),this.commitWorkCenterDetail(s,r,n),r},async cancelWorkItem(e,t=null){let s=t||this.workCenterAgentId||this.currentAgent,n=this.beginWorkCenterDetailWrite(s),r=await this.workCenterRequest("cancel",{id:e},s);return await this.listWorkItems(s,this._workCenterListFiltersByAgent[s]||{}),this.commitWorkCenterDetail(s,r,n),r},async resumeWorkItem(e,t,s=null){let n=s||this.workCenterAgentId||this.currentAgent,r=this.beginWorkCenterDetailWrite(n),i=await this.workCenterRequest("resume",{id:e,revision:t},n);return await this.listWorkItems(n,this._workCenterListFiltersByAgent[n]||{}),this.commitWorkCenterDetail(n,i,r),i},async deleteWorkItem(e,t,s=null){let n=s||this.workCenterAgentId||this.currentAgent,r=await this.workCenterRequest("delete",{id:e,revision:t},n);return this.removeWorkItemState(n,e),r},async postWorkItemMessage(e,t,s,n,r=[],i=null,o={},a=null){if(!this.hydrateWorkCenterBrowserState())throw new Error("Work Center browser owner is unavailable; sign in again and retry");let l=i||this.workCenterAgentId||this.currentAgent,c=this.prepareWorkCenterMessageEnvelope({agentId:l,workItemId:e,target:s,text:t,quote:a,attachments:r,revision:n,planRevision:o.planRevision,ledgerRevision:o.ledgerRevision,coordinatorRevision:o.coordinatorRevision});if(!c)throw new Error("Work Center browser owner changed; reopen Work Center and try again");let d=c.clientMessageId,u=this.workCenterDetailByAgent[l]?.id===e?this.workCenterDetailByAgent[l]:null,f=await this.workCenterRequest("post_work_item_message",{id:c.workItemId,clientMessageId:d,text:c.text,target:c.target,revision:c.revision,planRevision:c.planRevision||Number(u?.planRevision)||0,ledgerRevision:c.ledgerRevision||Number(u?.ledgerRevision)||0,coordinatorRevision:Number.isInteger(Number(c.coordinatorRevision))?Number(c.coordinatorRevision):Number(u?.coordinatorRevision)||0,...c.quote?{quote:c.quote}:{},attachments:c.attachments},l);if(c.target.kind==="coordinator"){if(!f?.accepted)throw new Error("Work Center Coordinator did not accept the message");return this.confirmWorkCenterMessageEnvelope(l,e,d),f}return await this.listWorkItems(l,this._workCenterListFiltersByAgent[l]||{}),this.confirmWorkCenterMessageEnvelope(l,e,d),f},async sendWorkItemMessage(e,t,s,n=[],r=null,i={},o=null){let a=r||this.workCenterAgentId||this.currentAgent,l=this.workCenterDetailByAgent[a]?.id===e?this.workCenterDetailByAgent[a]:null,c=await this.workCenterRequest("work_item_message",{id:e,text:t,revision:s,planRevision:Number.isInteger(Number(i.planRevision))?Number(i.planRevision):Number(l?.planRevision)||0,ledgerRevision:Number.isInteger(Number(i.ledgerRevision))?Number(i.ledgerRevision):Number(l?.ledgerRevision)||0,coordinatorRevision:Number.isInteger(Number(i.coordinatorRevision))?Number(i.coordinatorRevision):Number(l?.coordinatorRevision)||0,...Qe(o)?{quote:Qe(o)}:{},attachments:Array.isArray(n)?n:[]},a);if(!c?.accepted)throw new Error("Work Center Coordinator did not accept the message");return c},async retryWorkItemAction(e,t,s,n,r=null){let i=r||this.workCenterAgentId||this.currentAgent,o=this.beginWorkCenterDetailWrite(i),a=await this.workCenterRequest("retry_action",{id:e,actionId:t,revision:s,generation:n},i);return await this.listWorkItems(i,this._workCenterListFiltersByAgent[i]||{}),this.commitWorkCenterDetail(i,a,o),a},async sendWorkItemActionInput(e,t,s,n,r,i=[],o=null,a=null){let l=o||this.workCenterAgentId||this.currentAgent,c=Number(this._workCenterActionInputGenerationByAgent[l]||0)+1;this._workCenterActionInputGenerationByAgent={...this._workCenterActionInputGenerationByAgent,[l]:c};let d=Qe(a),u=await this.workCenterRequest("action_input",{id:e,text:t,actionId:s,revision:n,generation:r,attachments:i,...d?{quote:d}:{}},l);await this.listWorkItems(l,this._workCenterListFiltersByAgent[l]||{});let f=this.workCenterDetailByAgent[l],p=f?.actions?.find(m=>m?.id===s),g=f?.id===e&&Number(f.revision)===Number(n)&&p&&Number(p.generation)===Number(r);return this._workCenterActionInputGenerationByAgent[l]===c&&g&&!Ku(u,f)?(this.workCenterDetailByAgent={...this.workCenterDetailByAgent,[l]:u},u):f?.id===e?f:u},async guideWorkItemAction(e,t,s,n,r,i=[],o=null){let a=o||this.workCenterAgentId||this.currentAgent,l=this.beginWorkCenterDetailWrite(a),c=await this.workCenterRequest("guide",{id:e,guidance:t,actionId:s,revision:n,generation:r,attachments:i},a);return await this.listWorkItems(a,this._workCenterListFiltersByAgent[a]||{}),this.commitWorkCenterDetail(a,c,l),c},previewWorkItemAttachment(e,t,s=null){let n=s||this.workCenterAgentId||this.currentAgent;return this.workCenterRequest("preview_attachment",{id:e,attachmentId:t},n)},applyWorkCenterEvent(e,t){if(!e||!t?.workItem)return;let s=t.workItem;if(t.clientMessageId){this.confirmWorkCenterMessageEnvelope(e,s.id,t.clientMessageId);let u=Object.entries(this.workCenterPending||{}).find(([,f])=>f?.agentId===e&&f.clientMessageId===t.clientMessageId);if(u){let[f,p]=u;clearTimeout(p.timer),delete this.workCenterPending[f],p.resolve(t.type==="coordinator.turn_started"?{accepted:!0,turnId:null,receipt:!0}:t.workItem)}}let n=this.workCenterItemsByAgent[e]||[];if(t.type==="work_item.deleted"){this.removeWorkItemState(e,s.id);return}if(this.workItemDeleted(e,s.id))return;let r=this._workCenterListFiltersByAgent[e]||{},i=this._workCenterListEventsByAgent[e]?.[s.id]?.summary||null,o=n.some(u=>u?.id===s.id)?n:i?[i]:[],a=ki(o,s).find(u=>u?.id===s.id)||s,l=Number(this._workCenterListEventGenerationByAgent[e]||0)+1;this._workCenterListEventGenerationByAgent={...this._workCenterListEventGenerationByAgent,[e]:l},this._workCenterListEventsByAgent={...this._workCenterListEventsByAgent,[e]:{...this._workCenterListEventsByAgent[e]||{},[s.id]:{generation:l,queryKey:this._workCenterListQueryByAgent[e]||null,summary:a}}};let c=this.applyWorkItemBoardSummary(n,a,r);this.workCenterItemsByAgent={...this.workCenterItemsByAgent,[e]:c};let d=this.workCenterDetailByAgent[e];if(d?.id===s.id){let u=t.type==="run.finished"&&t.actionId&&Array.isArray(s.actionStats)&&s.actionStats.some(k=>k?.id===t.actionId)?{...s,eventActionId:t.actionId}:s,f=qa(d,u),p=Number(s.coordinatorRevision),g=Number(d.coordinatorRevision)||0,m=Number.isInteger(p)&&p>g,v=zu(d,u);this.workCenterDetailByAgent={...this.workCenterDetailByAgent,[e]:Yu(d,s)},v&&this.refreshWorkItemDetailAfterActionChange(e,s,m?null:f)}},async refreshWorkItemDetailAfterActionChange(e,t,s=null){let n=s?(Array.isArray(t.actionStats)?t.actionStats:[]).find(m=>m?.id===s.actionId):(Array.isArray(t.actionStats)?t.actionStats:[]).find(m=>m?.id===t.currentActionId)||t.currentAction,r=s?.actionId||t.currentActionId||null,i=Number(s?.generation??n?.generation),o=Number.isInteger(i)&&i>0?i:null,a=Number(t.coordinatorRevision),l=!s&&Number.isInteger(a)&&a>=0?a:null,c=Number(s?.attempt),d=Number.isInteger(c)&&c>=0?c:null,u=l!=null?`${t.id}:coordinator:${l}`:`${t.id}:${r}${o==null?"":`:${o}`}${d==null?"":`:${d}`}`;if(this._workCenterDetailEventRefreshByAgent[e]?.key===u)return;let f=this.beginWorkCenterDetailWrite(e),p={key:u,generation:f};this._workCenterDetailEventRefreshByAgent={...this._workCenterDetailEventRefreshByAgent,[e]:p},s&&this.invalidateWorkItemActionMessages(e,t.id,s.actionId,s.generation);let g=r&&o!=null?this.loadWorkItemActionMessages(t.id,r,o,null,e).catch(()=>null):null;try{let m=await this.workCenterRequest("get",{id:t.id},e),v=this.workCenterDetailByAgent[e],k=v?.actions?.find(M=>M?.id===r),w=m?.actions?.find(M=>M?.id===r),I=o==null||ct(k?.generation)===o,h=o==null||ct(w?.generation)>=o,y=l==null||Number(m?.coordinatorRevision)===l,b=l!=null||I&&h&&(t.currentActionId==null?m?.currentActionId==null:v?.currentActionId===t.currentActionId&&m?.currentActionId===t.currentActionId);v?.id===t.id&&y&&b&&this.commitWorkCenterDetail(e,m,f)&&g&&await g}catch{}finally{if(this._workCenterDetailEventRefreshByAgent[e]===p){let m={...this._workCenterDetailEventRefreshByAgent};delete m[e],this._workCenterDetailEventRefreshByAgent=m}}},cacheYeaftAgentStatus(e,t,{allowBootstrapCatalog:s=!1}={}){if(!e||!t)return;let n=this.yeaftStatusByAgent[e]||{},r=Number(n.catalogRevision)||0,i=Number(t.catalogRevision)||0,o=typeof n.catalogEpoch=="string"?n.catalogEpoch:"",a=typeof t.catalogEpoch=="string"?t.catalogEpoch:"",l=Number(n.catalogRefreshedAt)||0,c=Number(t.catalogRefreshedAt)||0,d=Array.isArray(t.availableModels),u=t.type==="yeaft_status"&&d&&(i>0||c>0),f=Array.isArray(this._yeaftRetiredCatalogEpochsByAgent?.[e])?this._yeaftRetiredCatalogEpochsByAgent[e]:[],p=!!a&&f.includes(a),g=!!a&&a===o,m=i>0?g&&i===r:c>0&&c===l,v=i>0?!!a&&(a!==o||i>r):r===0&&c>l,k=i>0?!!t.catalogDigest&&!!n.catalogDigest&&t.catalogDigest===n.catalogDigest:t.catalogDigest===n.catalogDigest,w=u&&!p&&(v||m&&k),h=w||s&&r===0&&l===0&&!u&&d,y={...t};if(!h)for(let M of Sy)delete y[M];let b={...n,...y};if(h){if(w&&o&&a&&o!==a){let M=[...f.filter(x=>x!==o),o].slice(-Iy);this._yeaftRetiredCatalogEpochsByAgent={...this._yeaftRetiredCatalogEpochsByAgent||{},[e]:M}}b.availableModels=t.availableModels,b.catalogRefreshedAt=w?c:null,b.catalogEpoch=w&&a||null,b.catalogRevision=w&&i||null,b.catalogDigest=w&&t.catalogDigest||null}this.yeaftStatusByAgent={...this.yeaftStatusByAgent,[e]:b},this.currentAgent===e&&this.applyCachedYeaftStatus(e)},applyCachedYeaftStatus(e=this.currentAgent){let t=e?this.yeaftStatusByAgent[e]:null;return t?(this.yeaftModel=t.model||null,this.yeaftModelEffort=t.modelEffort||null,this.yeaftAvailableModels=Array.isArray(t.availableModels)?t.availableModels:[],this.yeaftModelsRefreshing=!!t.refreshing,this.yeaftModelRefreshError=t.refreshError||null,this.yeaftYeaftDir=t.yeaftDir||null,this.yeaftStatus={skills:t.skills,mcpServers:t.mcpServers,tools:t.tools,multiVp:!!t.multiVp},!0):!1},activateYeaftAgentCatalog(e,t=this.currentAgent){let s=e?this.yeaftStatusByAgent[e]:null;return s&&this.applyCachedYeaftStatus(e),Array.isArray(s?.availableModels)?!0:(this.yeaftModel=null,this.yeaftModelEffort=null,this.yeaftAvailableModels=[],s||(this.yeaftStatus=null),this.yeaftModelsRefreshing=!!e&&!s?.refreshError,this.yeaftModelRefreshError=s?.refreshError||null,t!==e&&(this.yeaftYeaftDir=null),!1)},activateYeaftAgent(e,t=null){if(!e)return!1;let s=this.currentAgent;return this.currentAgent=e,t&&(this.currentAgentInfo=t),this.activateYeaftAgentCatalog(e,s)},resolveYeaftSessionAgentId(e){return be(this,e)},requestYeaftSessionInventory(){if(this.yeaftSessionInventoryCompleteSupported===!1&&this.yeaftSessionHydrateRequestId)return this.yeaftSessionHydrateRequestId;if(this._yeaftSessionInventorySocketQuarantined)return this.manualReconnect(),null;clearTimeout(this._legacyYeaftSessionHydrateTimer),this._legacyYeaftSessionHydrateTimer=null;let e=`session_inventory_${crypto.randomUUID()}`;this.yeaftSessionHydrateRequestId=e,this.yeaftSessionHydrateSlices=[],this._hasHandledAgentList=!1,this._hasHandledYeaftSessionHydrate=!1,this.yeaftSessionHydrateError=null;let t=this.conversations.map(n=>n.id).filter(Boolean);return this.sendWsMessage({type:"get_agents",requestId:e,conversationIds:t.length>0?t:void 0})?(setTimeout(()=>{this.yeaftSessionHydrateRequestId===e&&(this.yeaftSessionHydrateRequestId=null,this.yeaftSessionHydrateSlices=[],this.yeaftSessionHydrateError="session_inventory_timeout",this.yeaftSessionInventoryCompleteSupported!==!0&&(this._yeaftSessionInventorySocketQuarantined=!0))},wy),e):(this.yeaftSessionHydrateRequestId=null,this.yeaftSessionHydrateSlices=[],this.yeaftSessionHydrateError="session_inventory_send_failed",null)},beginYeaftHistoryLoad(e){let t=Ac(this,e);if(!t)return null;let{agentId:s,sessionId:n}=e||{};return setTimeout(()=>{Un(this,{agentId:s,sessionId:n,requestId:t.requestId,error:"history_load_timeout"})},Cc),t},finishYeaftHistoryLoad(e,t={},s="chunk"){return xc(this,e,t,s)},isCurrentYeaftHistoryResponse(e){return Zo(this,e)},syncActiveYeaftHistoryLoad(){return ks(this)},enterYeaft(e=null,{deferBootstrap:t=!1}={}){let s=this.currentAgent;Ha(this);let n=Fs(this),r=!e&&n?be(this,n):null,i=e||r||this.currentAgent||null;if(!i){let a=this.agents.find(l=>l.online);a&&(i=a.id)}if(i&&this.currentAgent!==i){this.selectAgent(i),this.currentAgent=i;let a=this.agents.find(l=>l.id===i);a&&(this.currentAgentInfo=a)}if(!this.applyCachedYeaftStatus(i)&&s&&s!==i&&(this.yeaftAvailableModels=[],this.yeaftStatus=null,this.yeaftModelsRefreshing=!0,this.yeaftModelRefreshError=null),i){let a=this.yeaftConversationIdsByAgent?.[i]||null;a||(a=`yeaft-local-${i}-${Date.now()}`,this.yeaftConversationIdsByAgent={...this.yeaftConversationIdsByAgent||{},[i]:a}),this.yeaftConversationId=a}else this.yeaftConversationId||(this.yeaftConversationId=`yeaft-local-${Date.now()}`);this.messagesMap[this.yeaftConversationId]||(this.messagesMap[this.yeaftConversationId]=[]),$u(this),this.currentView="yeaft",Va("yeaft"),this.hasMoreMessages=!1,this.loadingMoreMessages=!1,this.yeaftHasMoreHistory=!1,this.yeaftLoadingMoreHistory=!1,this.yeaftOldestLoadedSeq=null,this._yeaftReconnectCatchUpPending=!1,this.loadOpenedYeaftSessionsForConnectedAgents(null,{force:!0}),t||this.requestYeaftSessionBootstrap({forceSessionReady:!0,catchUpHistory:!0,forceHistoryReplay:!0})},loadOpenedYeaftSessionsForConnectedAgents(e=null,{force:t=!1}={}){let s=Array.isArray(e)?e.filter(Boolean):Array.isArray(this.agents)?this.agents.filter(i=>i&&i.online&&i.id).map(i=>i.id):[],n=[...new Set(s)];(!this._yeaftOpenedSessionsLoadedAgents||typeof this._yeaftOpenedSessionsLoadedAgents!="object")&&(this._yeaftOpenedSessionsLoadedAgents={});let r=[];for(let i of n)!t&&this._yeaftOpenedSessionsLoadedAgents[i]||(this._yeaftOpenedSessionsLoadedAgents[i]=Date.now(),r.push(i),this.sessionCrudRequest("list",{},{agentId:i}).catch(o=>{delete this._yeaftOpenedSessionsLoadedAgents[i]}));return r},requestYeaftSessionBootstrap({forceSessionReady:e=!1,catchUpHistory:t=!1,forceHistoryReplay:s=!1}={}){if(!this.currentAgent)return;let n=Fs(this),r=n?be(this,n):this.currentAgent,i=ve(r,n),o=n?this.yeaftSessionHistoryState[i]:null,a=e||!this.yeaftSessionReady||!this.yeaftModel||!this.yeaftStatus,l=Number.isFinite(o?.latestSeq)?o.latestSeq:null,c=!!n&&!!this.yeaftConversationId&&Array.isArray(this.messagesMap?.[this.yeaftConversationId])&&this.messagesMap[this.yeaftConversationId].some(I=>I&&(I.sessionId??I.groupId??null)===n),d=!!this._yeaftHistoryBrowserHydrationBySession?.[i];n&&r&&!o?.loaded&&!o?.loading&&!c&&!d&&(d=!0,this.hydrateYeaftHistoryBrowserCache(n,r,{revalidate:!0}));let u=!!n&&!d&&bd({sessionState:o,hasCachedSessionRows:c,force:!!s}),f=!!n&&!d&&!u&&yd(o,t);if(!a&&!u&&!f)return!1;let p=`${r}:${n||"__none__"}`,g=a&&!u&&!f;if(g&&this.yeaftBootstrapMetaLoadingKey===p)return!1;g&&(this.yeaftBootstrapMetaLoadingKey=p);let m=null;n&&u?m=this.beginYeaftHistoryLoad({agentId:r,sessionId:n,mode:"recent",preserveLoaded:!1}):n&&c&&!o?.loaded?(this.yeaftSessionHistoryState={...this.yeaftSessionHistoryState,[i]:{...o||{},loaded:!0,loading:!1,hasMore:!!o?.hasMore,oldestSeq:Number.isFinite(o?.oldestSeq)?o.oldestSeq:null,count:o?.count||0,latestSeq:l}},this.yeaftLoadingMoreHistory=!1):n&&f&&(m=this.beginYeaftHistoryLoad({agentId:r,sessionId:n,mode:"delta",preserveLoaded:!0,latestSeq:l}));let v={type:"yeaft_load_history",agentId:r,sessionId:n,...m?{requestId:m.requestId}:{}};f?v.afterSeq=l:v.limit=u?xi:0;let k=_s();v.perfTraceId=k;let w=f?"delta":u?"recent":"metadata";return n&&(this.yeaftHistoryPerfTraceBySession={...this.yeaftHistoryPerfTraceBySession||{},[i]:k}),Ge(this,{traceId:k,phase:"history.request_send",agentId:r,sessionId:n,messageType:v.type,bytes:JSON.stringify(v).length,detail:{mode:w,limit:v.limit??null,afterSeq:v.afterSeq??null,hasCachedSessionRows:c,needSessionReady:a}}),this.sendWsMessage(v),!0},leaveYeaft(){this.activateChatView({persistPreference:!0})},fetchYeaftToolStats(){this.currentAgent&&(this.yeaftToolStatsLoading=!0,this.sendWsMessage({type:"yeaft_fetch_tool_stats",agentId:this.currentAgent}),this._fetchYeaftToolStatsTimer&&clearTimeout(this._fetchYeaftToolStatsTimer),this._fetchYeaftToolStatsTimer=setTimeout(()=>{this.yeaftToolStatsLoading&&(this.yeaftToolStatsLoading=!1,this.yeaftToolStats={...this.yeaftToolStats||{snapshot:{},registered:[],unused:[]},error:null,notice:"Tool stats are unavailable right now. Try again after the agent reconnects.",fetchedAt:Date.now()}),this._fetchYeaftToolStatsTimer=null},1e4))},loadYeaftDebugHistory({groupId:e,limit:t,dreamLimit:s,indexOnly:n=!1,detailTurnId:r=null,search:i=void 0}={}){if(!this.currentAgent)return;let o=typeof i=="string"?i.trim():(this.yeaftDebugSearch||"").trim(),a=typeof r=="string"&&r,l=o&&!a?kp:Ja,c=Number.isFinite(t)&&t>0?t:this.yeaftDebugHistoryLimit||l,d=Math.max(1,Math.min(l,c)),u=a?"detail":"list",f=`dbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,p=JSON.stringify({agentId:this.currentAgent,groupId:e||null,limit:d,dreamLimit:Number.isFinite(s)&&s>0?s:5,indexOnly:!!n,detailTurnId:r||null,search:a?"":o});if(this._yeaftDebugHistoryInFlightKey===p)return;this._yeaftDebugHistoryInFlightKey=p,a?this._yeaftDebugHistoryLatestDetailRequestId=f:this._yeaftDebugHistoryLatestListRequestId=f,this.yeaftDebugHistoryLimit=d,this.yeaftDebugHistoryLoading=!0,this.yeaftDebugHistoryError=null;let g={type:"yeaft_fetch_debug_history",agentId:this.currentAgent,requestId:f,requestKind:u,limit:d,dreamLimit:Number.isFinite(s)&&s>0?s:5};n&&(g.indexOnly=!0),typeof r=="string"&&r?g.detailTurnId=r:o&&(g.search=o),typeof e=="string"&&e&&(g.sessionId=e),this.sendWsMessage(g),this._fetchYeaftDebugHistoryTimer&&clearTimeout(this._fetchYeaftDebugHistoryTimer),this._fetchYeaftDebugHistoryTimer=setTimeout(()=>{this.yeaftDebugHistoryLoading&&(this.yeaftDebugHistoryLoading=!1,this.yeaftDebugHistoryError="Debug history is unavailable right now. Try again after the agent reconnects.",this.yeaftDebugPanel?.status==="loading"&&(this.yeaftDebugPanel={...this.yeaftDebugPanel,status:"error",error:this.yeaftDebugHistoryError})),this._yeaftDebugHistoryInFlightKey=null,this._fetchYeaftDebugHistoryTimer=null},1e4)},openYeaftTurnDebug({sessionId:e=null,turnId:t=null}={}){if(!this.currentAgent)return;let s=`dbgpanel_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,n=t?"loading":"idle";this.yeaftDebugPanel={open:!0,status:n,requestId:s,agentId:this.currentAgent,sessionId:e||null,turnId:t||null,error:null},t&&this.loadYeaftDebugHistory({groupId:e||void 0,limit:1,dreamLimit:5,detailTurnId:t})},closeYeaftDebugPanel(){let t=(this.yeaftDebugPanel||{}).turnId||null;if(this.yeaftDebugPanel={open:!1,status:"idle",requestId:null,agentId:null,sessionId:null,turnId:null,error:null},t&&this.yeaftDebugTurnsById&&this.yeaftDebugTurnsById[t]){let s={...this.yeaftDebugTurnsById};delete s[t],this.yeaftDebugTurnsById=s,this.yeaftDebugTurnOrder=(this.yeaftDebugTurnOrder||[]).filter(n=>n!==t),this.yeaftDebugLoops=(this.yeaftDebugLoops||[]).filter(n=>!n||n.turnId!==t)}},agentIdForSession(e){return be(this,e)},sendYeaftSessionMessage({groupId:e,text:t,mentions:s,attachments:n,quote:r}){let i=be(this,e);if(!e||!i)return;let o=Array.isArray(n)?n.filter(g=>g&&g.fileId):[],a=Qe(r),l=o.length>0;if(!t?.trim()&&!l)return;let c=t?.trim()?t:"(attached files)",d=`u_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,u=_s();this.yeaftPerfTraceByMessageId={...this.yeaftPerfTraceByMessageId||{},[d]:u},Ge(this,{traceId:u,phase:"send.prepare",agentId:i,sessionId:e,turnId:d,messageType:"yeaft_session_send",detail:{mentionCount:Array.isArray(s)?s.length:0,attachmentCount:o.length,quoted:!!a}});let f=tt(this,e);if(f){let g={id:d,messageId:d,clientMessageId:d,stableKey:ss(i,e,d),uiKey:ss(i,e,d),type:"user",content:c,sessionId:e,turnId:d,...a?{quote:a}:{}};if(o.length>0&&(g.attachments=o.map(m=>({fileId:m.fileId,name:m.name,preview:m.preview,isImage:!!m.isImage,mimeType:m.mimeType||""}))),this.addMessageToConversation(f,g),this.processingConversations[f]=!0,e){let m=St(i,e);this.yeaftProcessingSessions={...this.yeaftProcessingSessions,...m?{[m]:!0}:{}}}this._turnCompletedConvs?.delete(f),this._closedAt?.[f]&&delete this._closedAt[f],this.getOrCreateExecutionStatus(f),cn(this,f)}let p={type:"yeaft_session_send",agentId:i,id:d,sessionId:e,text:c,mentions:Array.isArray(s)?s:[],perfTraceId:u,...a?{quote:a}:{}};o.length>0&&(p.attachments=o.map(g=>({fileId:g.fileId,isImage:!!g.isImage}))),Ge(this,{traceId:u,phase:"send.websocket_send",agentId:i,sessionId:e,turnId:d,messageType:p.type,bytes:JSON.stringify(p).length}),this.sendWsMessage(p)},cancelYeaftTask({agentId:e=null,sessionId:t,taskId:s}){let n=typeof t=="string"?t.trim():"",r=typeof s=="string"?s.trim():"",i=be(this,n,e);return!i||!n||!r?!1:(this.yeaftStoppingTasksById={...this.yeaftStoppingTasksById,[Qa(i,n,r)]:!0},this.sendWsMessage({type:"yeaft_task_cancel",agentId:i,sessionId:n,taskId:r,clientRequestId:`task_cancel_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}),!0)},hydrateYeaftHistoryBrowserCache(e,t=null,{revalidate:s=!1}={}){let n=e||null,r=be(this,n,t),i=rs();if(!i||!r||!n)return s&&this.revalidateYeaftHistoryBrowserCache(n,r),Promise.resolve(!1);let o=ve(r,n),a=`${i.epoch}:${crypto.randomUUID()}`;return this._yeaftHistoryBrowserHydrationBySession={...this._yeaftHistoryBrowserHydrationBySession||{},[o]:a},$c({fence:i,agentId:r,sessionId:n}).then(l=>{if(!l||this._yeaftHistoryBrowserHydrationBySession?.[o]!==a)return!1;let c=tt(this,n,r);if(!c)return!1;let d=this.messagesMap[c]||[];Ms(this,c,l.rows),this.messagesMap[c]=ui(d,l.rows).sort((p,g)=>{let m=Number.isFinite(p?.seq)?p.seq:null,v=Number.isFinite(g?.seq)?g.seq:null;return m!==null&&v!==null&&m!==v?m-v:m!==null&&v===null?-1:m===null&&v!==null?1:(p?.timestamp||0)-(g?.timestamp||0)});let u=this.yeaftSessionHistoryState[o]||{},f=Math.max(Number.isFinite(u.latestSeq)?u.latestSeq:-1,Number.isFinite(l.latestSeq)?l.latestSeq:-1);return this.yeaftSessionHistoryState={...this.yeaftSessionHistoryState,[o]:{...u,loaded:!0,loading:!!u.loading,latestSeq:f>=0?f:null,streamId:l.streamId||null,revision:Number.isFinite(l.revision)?l.revision:null,oldestSeq:Number.isFinite(u.oldestSeq)?u.oldestSeq:l.oldestSeq,hasMore:u.loaded?!!u.hasMore:!!l.hasMore,count:Math.max(Number(u.count)||0,Number(l.rowCount)||0),browserCached:!0}},zn(this,{conversationId:c,agentId:r,sessionId:n,incomingRows:l.rows,activeAgentId:r,activeSessionId:n}),this.syncActiveYeaftHistoryLoad(),s&&this.revalidateYeaftHistoryBrowserCache(n,r),!0}).catch(()=>(s&&this.revalidateYeaftHistoryBrowserCache(n,r),!1)).finally(()=>{if(this._yeaftHistoryBrowserHydrationBySession?.[o]!==a)return;let{[o]:l,...c}=this._yeaftHistoryBrowserHydrationBySession;this._yeaftHistoryBrowserHydrationBySession=c})},revalidateYeaftHistoryBrowserCache(e,t=null){let s=e||null,n=be(this,s,t);if(!n||!s||this.currentView!=="yeaft")return!1;let r=ve(n,s),i=this.yeaftSessionHistoryState?.[r]||null;if(i?.loading)return!1;let o=Number.isFinite(i?.latestSeq)?i.latestSeq:null,a=o===null?"recent":"delta",l=this.beginYeaftHistoryLoad({agentId:n,sessionId:s,mode:a,preserveLoaded:o!==null,latestSeq:o});if(!l)return!1;let c={type:"yeaft_load_history",agentId:n,sessionId:s,requestId:l.requestId,...o===null?{limit:xi}:{afterSeq:o,maxRows:cp,maxBytes:dp,...typeof i?.streamId=="string"?{streamId:i.streamId}:{},...Number.isFinite(i?.revision)?{revision:i.revision}:{}}};return o!==null&&(this.yeaftSessionHistoryState={...this.yeaftSessionHistoryState,[r]:{...this.yeaftSessionHistoryState[r],syncingAfterSeq:o}}),this.sendWsMessage(c)?!0:(Un(this,{agentId:n,sessionId:s,requestId:l.requestId,error:"history_load_send_failed"}),!1)},continueYeaftHistoryDelta(e,t=null,s=null){let n=e||null,r=be(this,n,t);if(!r||!n||!Number.isFinite(s))return!1;let i=ve(r,n),o=this.yeaftSessionHistoryState?.[i]||null;if(o?.loading)return!1;let a=this.beginYeaftHistoryLoad({agentId:r,sessionId:n,mode:"delta",preserveLoaded:!0,latestSeq:s});if(!a)return!1;this.yeaftSessionHistoryState={...this.yeaftSessionHistoryState,[i]:{...this.yeaftSessionHistoryState[i],syncingAfterSeq:s}};let l={type:"yeaft_load_history",agentId:r,sessionId:n,requestId:a.requestId,afterSeq:s,maxRows:cp,maxBytes:dp,...typeof o?.streamId=="string"?{streamId:o.streamId}:{},...Number.isFinite(o?.revision)?{revision:o.revision}:{}};return this.sendWsMessage(l)?!0:(Un(this,{agentId:r,sessionId:n,requestId:a.requestId,error:"history_load_send_failed"}),!1)},persistYeaftHistoryBrowserCache(e,t=null,s=null){let n=e||null,r=be(this,n,t),i=rs(),o=s||tt(this,n,r);if(!i||!r||!n||!o)return Promise.resolve(!1);let a=ve(r,n),l=(this.messagesMap[o]||[]).filter(c=>(c?.sessionId??c?.groupId??null)===n);return Vc({fence:i,agentId:r,sessionId:n,rows:l,historyState:this.yeaftSessionHistoryState[a]||null})},removeYeaftHistoryBrowserCache(e,t){let s=rs();return!s||!e||!t?Promise.resolve(!0):ia({fence:s,agentId:e,sessionId:t}).catch(()=>!1)},clearYeaftHistoryMemory({agentId:e=null,sessionId:t=null,preserveLiveRows:s=!1,preserveSessionOwner:n=!1}={}){let r=e||null,i=t||null,o=r&&i?ve(r,i):null,a={};for(let[p,g]of Object.entries(this._yeaftHistoryWindowPendingByKey||{})){if(!(!o||g?.agentId===r&&g?.sessionId===i)){a[p]=g;continue}clearTimeout(g?.timeout),g?.resolve?.(!1)}this._yeaftHistoryWindowPendingByKey=a;let l=r&&this.yeaftConversationIdsByAgent?.[r]||null,c=o?new Set([l].filter(Boolean)):new Set(Object.values(this.yeaftConversationIdsByAgent||{}).filter(Boolean));!o&&this.yeaftConversationId&&c.add(this.yeaftConversationId);let d={...this.messagesMap||{}};for(let p of c)Array.isArray(d[p])&&(d[p]=o?d[p].filter(g=>(g?.sessionId??g?.groupId??null)!==i?!0:s&&!wt(g)):[]);this.messagesMap=d;let u=p=>{if(!o)return{};let{[o]:g,...m}=p||{};return m};if(this.yeaftSessionHistoryState=u(this.yeaftSessionHistoryState),this.yeaftHistoryCacheState=u(this.yeaftHistoryCacheState),this.yeaftMessageWindowState=u(this.yeaftMessageWindowState),this._yeaftHistoryBrowserHydrationBySession=u(this._yeaftHistoryBrowserHydrationBySession),this.yeaftHistoryOutlineBySession=u(this.yeaftHistoryOutlineBySession),o){let p=this._yeaftHistoryOutlineTimeouts?.[o];p&&clearTimeout(p),this._yeaftHistoryOutlineTimeouts=u(this._yeaftHistoryOutlineTimeouts)}else{for(let p of Object.values(this._yeaftHistoryOutlineTimeouts||{}))p&&clearTimeout(p);this._yeaftHistoryOutlineTimeouts={}}if((!o||this.yeaftHistorySearchState?.agentId===r&&this.yeaftHistorySearchState?.sessionId===i)&&(this._yeaftHistorySearchTimeout&&clearTimeout(this._yeaftHistorySearchTimeout),this._yeaftHistorySearchTimeout=null,this.yeaftHistorySearchState={requestId:null,agentId:null,sessionId:null,query:"",senderKey:"",loading:!1,results:[],hasMore:!1,nextBeforeSeq:null,nextCursor:null,error:null}),this._yeaftHistoryRevealLeases=o?Object.fromEntries(Object.entries(this._yeaftHistoryRevealLeases||{}).filter(([,p])=>p?.sessionKey!==o)):{},o||(this.yeaftHasMoreHistory=!1,this.yeaftLoadingMoreHistory=!1,this.yeaftOldestLoadedSeq=null),!n&&i&&this.yeaftSessionAgentById?.[i]===r){let{[i]:p,...g}=this.yeaftSessionAgentById;this.yeaftSessionAgentById=g}this.syncActiveYeaftHistoryLoad()},getYeaftMessageWindowKey(e=null,t=null){let s=e||this.yeaftActiveSessionFilter||null,n=be(this,s,t);return ve(n,s)},pruneYeaftMessageWindow(e=null,t=null){if(this.currentView!=="yeaft")return;let s=this.getYeaftMessageWindowKey(e,t);Object.values(this._yeaftHistoryRevealLeases||{}).some(r=>r?.sessionKey===s)||(this.yeaftMessageWindowState={...this.yeaftMessageWindowState,[s]:{visibleTurns:Os()}})},expandYeaftMessageWindow(e=null,t=br(),s=null){if(this.currentView!=="yeaft")return;let n=this.getYeaftMessageWindowKey(e,s),i=(this.yeaftMessageWindowState[n]?.visibleTurns||Os())+Math.max(1,Number.isFinite(t)?Math.floor(t):br());this.yeaftMessageWindowState={...this.yeaftMessageWindowState,[n]:{visibleTurns:i}}},isYeaftMessageCached(e,t,s=null,n=null){let r=e||this.yeaftActiveSessionFilter||null,i=s||tt(this,r,n);return!i||!t?!1:(this.messagesMap[i]||[]).some(o=>(!r||(o?.sessionId??o?.groupId??null)===r)&&((o?.id||o?.messageId)===t||o?.persistedMessageId===t))},revealYeaftMessage(e,t,s=null,n=null){let r=e||this.yeaftActiveSessionFilter||null,i=be(this,r,n),o=s||tt(this,r,i);if(!o||!t)return!1;let a=(this.messagesMap[o]||[]).filter(g=>g?._historyWindowPrefetched===!0?!1:r?(g?.sessionId??g?.groupId??null)===r:!0),c=a.findIndex(g=>(g?.id||g?.messageId)===t||g?.persistedMessageId===t);if(c<0){let g=(this.messagesMap[o]||[]).find(m=>m?._historyWindowPrefetched===!0&&(m?.sessionId??m?.groupId??null)===r&&((m?.id||m?.messageId)===t||m?.persistedMessageId===t));if(!g)return!1;g._historyWindowPrefetched=!1,a.push(g),a.sort((m,v)=>{let k=Number.isFinite(m?.seq)?m.seq:null,w=Number.isFinite(v?.seq)?v.seq:null;return k!==null&&w!==null&&k!==w?k-w:k!==null&&w===null?-1:k===null&&w!==null?1:(m?.timestamp||0)-(v?.timestamp||0)}),c=a.indexOf(g)}let d=np(a),u=d.findIndex(g=>c>=g.start&&c<g.end);if(u<0)return!1;a[c]._historyWindowPrefetched=!1;let f=Math.max(Os(),d.length-u),p=this.getYeaftMessageWindowKey(r,i);return this.yeaftMessageWindowState={...this.yeaftMessageWindowState,[p]:{visibleTurns:f}},!0},getYeaftHistoryOutlineState(e=null,t=null){let s=e||this.yeaftActiveSessionFilter||null,n=be(this,s,t),r=ve(n,s),i=this.yeaftHistoryOutlineBySession[r]||{requestId:null,agentId:n,sessionId:s,loading:!1,results:[],hasMore:!1,nextBeforeSeq:null,nextCursor:null,totalCount:null,loaded:!1,retryAttempt:0,error:null},o=tt(this,s,n),a=o?this.messagesMap[o]||[]:[],l=new Map((i.results||[]).map(f=>[wr(f),f])),c=0;for(let f of a){if((f?.sessionId??f?.groupId??null)!==s)continue;let p=f.messageId||f.id;if(!p)continue;let g=f.type==="user"&&!!f.clientMessageId&&p===f.clientMessageId,m=f.type==="assistant"&&f.isStreaming===!0;if(!g&&!m)continue;let v=f.type,k=f.turnId||f.threadId||p,w=f.speakerVpId||f.vpId||null,I=wr({role:v,messageId:p,clientMessageId:f.clientMessageId,turnId:k,speakerVpId:w}),h=l.get(I),b=(typeof f.content=="string"?f.content:"").replace(/\s+/g," ").trim();l.set(I,{...h,agentId:n,sessionId:s,messageId:Number.isFinite(h?.seq)?h.messageId:p,...f.clientMessageId?{clientMessageId:f.clientMessageId}:{},turnId:k,role:v,speakerVpId:w||h?.speakerVpId||null,timestamp:f.timestamp||f.ts||h?.timestamp||null,snippet:b.length>180?`${b.slice(0,180).trimEnd()}\u2026`:b||h?.snippet||""}),h||(c+=1)}let d=f=>{let p=typeof f=="number"?f:Date.parse(f||"");return Number.isFinite(p)?p:0},u=Array.from(l.values()).sort((f,p)=>Number.isFinite(f.seq)&&Number.isFinite(p.seq)?f.seq-p.seq:d(f.timestamp)-d(p.timestamp));return{...i,results:u,totalCount:Number.isFinite(i.totalCount)?i.totalCount+c:i.totalCount}},promoteYeaftHistoryOutlineRow(e,t=null){let s=e?.sessionId??e?.groupId??null,n=ve(t,s),r=this.yeaftHistoryOutlineBySession[n];if(!s||!t||!r?.loaded||r.loading)return!1;let i=e?.type;if(i!=="user"&&i!=="assistant")return!1;let o=e.dbMessageId||e.messageId||e.id||null,a=_y(o);if(!o||!Number.isFinite(a))return!1;let l=e.turnId||e.threadId||o,c=e.speakerVpId||e.vpId||null,u=(typeof e.content=="string"?e.content:"").replace(/\s+/g," ").trim(),f=wr({role:i,messageId:o,clientMessageId:e.clientMessageId,turnId:l,speakerVpId:c}),p=new Map((r.results||[]).map(I=>[wr(I),I])),g=p.get(f);p.set(f,{...g,agentId:t,sessionId:s,messageId:o,...e.clientMessageId?{clientMessageId:e.clientMessageId}:{},turnId:l,seq:a,role:i,speakerVpId:c,timestamp:e.timestamp||e.ts||g?.timestamp||null,snippet:u.length>180?`${u.slice(0,180).trimEnd()}\u2026`:u||g?.snippet||""});let m=50,v=Array.from(p.values()).sort((I,h)=>(I.seq||0)-(h.seq||0)),k=v.length>m,w=v.slice(-m);return this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[n]:{...r,results:w,hasMore:r.hasMore||k,nextBeforeSeq:k&&Number.isFinite(w[0]?.seq)?w[0].seq:r.nextBeforeSeq,totalCount:Number.isFinite(r.totalCount)&&!g?r.totalCount+1:r.totalCount}},!0},promoteCompletedYeaftHistoryOutline(e,t=null,s=null){let n=this.messagesMap[e]||[],r=null,i=[];for(let o=n.length-1;o>=0;o--){let a=n[o];if(a?.type==="user")break;if(t&&a?.turnId&&a.turnId!==t||a?.type!=="assistant")continue;let l=typeof a.content=="string"?a.content.replace(/\s+/g," ").trim():"";r?!String(r.content||"").trim()&&l&&(r=a):r=a,l&&i.unshift(l)}return r?this.promoteYeaftHistoryOutlineRow({...r,content:i.join(" ")},s):!1},invalidateYeaftHistoryOutline(e,t=null){let s=ve(t,e),n=this.yeaftHistoryOutlineBySession[s];if(!e||!t||!n)return!1;if(n.loading)return this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[s]:{...n,refreshPending:!0}},!0;this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[s]:{...n,loaded:!1,refreshPending:!1}};let r=be(this,e);return this.currentView==="yeaft"&&this.yeaftActiveSessionFilter===e&&r===t?this.loadYeaftHistoryOutline({force:!0,targetSessionId:e,targetAgentId:t}):!0},loadYeaftHistoryOutline({append:e=!1,force:t=!1,targetSessionId:s=null,targetAgentId:n=null,retryAttempt:r=0}={}){if(this.currentView!=="yeaft"&&!s)return!1;let i=s||this.yeaftActiveSessionFilter||null,o=n||be(this,i);if(!i||!o)return!1;let a=ve(o,i),l=this.getYeaftHistoryOutlineState(i,o);if(!e&&l.loaded&&!t)return!0;if(e&&(!l.hasMore||!Number.isFinite(l.nextBeforeSeq))||l.loading)return!1;if(!yp(this,o,"session_history_outline"))return this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[a]:{...l,error:"unsupported",loading:!1}},!1;let c=`history_outline_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,d={...l,requestId:c,agentId:o,sessionId:i,loading:!0,requestAppend:e,refreshPending:!1,retryAttempt:r,error:null};this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[a]:d};let u=this._yeaftHistoryOutlineTimeouts[a];u&&clearTimeout(u);let f=setTimeout(()=>{let m=this.yeaftHistoryOutlineBySession[a];if(m?.requestId!==c)return;let v={...this._yeaftHistoryOutlineTimeouts};delete v[a],this._yeaftHistoryOutlineTimeouts=v;let k=m.refreshPending===!0;this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[a]:{...m,requestId:null,loading:!1,requestAppend:!1,loaded:k?!1:m.loaded,refreshPending:!1,error:k?null:"timeout"}},k&&this.loadYeaftHistoryOutline({force:!0,targetSessionId:i,targetAgentId:o})},1e4);this._yeaftHistoryOutlineTimeouts={...this._yeaftHistoryOutlineTimeouts,[a]:f};let p=_s(),g={type:"yeaft_load_history_outline",agentId:o,sessionId:i,requestId:c,perfTraceId:p,limit:50,...e&&l.nextCursor?{cursor:l.nextCursor}:{},...e&&!l.nextCursor&&Number.isFinite(l.nextBeforeSeq)?{beforeSeq:l.nextBeforeSeq}:{}};return Ge(this,{traceId:p,phase:"history_outline.request_send",agentId:o,sessionId:i,messageType:g.type,bytes:JSON.stringify(g).length,detail:{append:e,limit:g.limit}}),this.sendWsMessage(g),!0},handleYeaftHistoryOutline(e){if(!e?.agentId||!e?.sessionId)return!1;let t=ve(e.agentId,e.sessionId),s=this.yeaftHistoryOutlineBySession[t];if(!s||e.requestId!==s.requestId)return!1;let n=this._yeaftHistoryOutlineTimeouts[t];n&&clearTimeout(n);let r={...this._yeaftHistoryOutlineTimeouts};delete r[t],this._yeaftHistoryOutlineTimeouts=r;let i=Number.isInteger(s.retryAttempt)?s.retryAttempt:0;if(ky.has(e.error)&&i<up.length){let u=up[i],f=setTimeout(()=>{let p=this.yeaftHistoryOutlineBySession[t];if(p?.requestId!==e.requestId||p.loading!==!0)return;let g={...this._yeaftHistoryOutlineTimeouts};delete g[t],this._yeaftHistoryOutlineTimeouts=g;let m=p.refreshPending===!0;this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[t]:{...p,requestId:null,loading:!1,refreshPending:!1}},this.loadYeaftHistoryOutline({append:m?!1:s.requestAppend===!0,force:!0,targetSessionId:e.sessionId,targetAgentId:e.agentId,retryAttempt:i+1})},u);return this._yeaftHistoryOutlineTimeouts={...this._yeaftHistoryOutlineTimeouts,[t]:f},!0}let o=Array.isArray(e.results)?e.results.map(u=>({...u,agentId:e.agentId,sessionId:e.sessionId})):[],a=s.requestAppend?[...s.results||[],...o]:o,l=new Map(a.filter(u=>u?.messageId).map(u=>[wr(u),u])),c=Array.from(l.values()).sort((u,f)=>(u.seq||0)-(f.seq||0)),d=s.refreshPending===!0;return this.yeaftHistoryOutlineBySession={...this.yeaftHistoryOutlineBySession,[t]:{...s,requestId:null,loading:!1,requestAppend:!1,refreshPending:!1,loaded:d?!1:!e.error,results:c,hasMore:!!e.hasMore,nextBeforeSeq:Number.isFinite(e.nextBeforeSeq)?e.nextBeforeSeq:null,nextCursor:e.nextCursor&&typeof e.nextCursor=="object"?e.nextCursor:null,totalCount:Number.isFinite(e.totalCount)?e.totalCount:s.totalCount,error:d?null:e.error||null}},d&&this.loadYeaftHistoryOutline({force:!0,targetSessionId:e.sessionId,targetAgentId:e.agentId}),!0},searchYeaftHistory(e,{append:t=!1,senderKey:s=""}={}){if(this.currentView!=="yeaft")return!1;let n=typeof e=="string"?e.trim():"",r=typeof s=="string"&&(s==="user"||s.startsWith("vp:"))?s.slice(0,103):"",i=this.yeaftActiveSessionFilter||null,o=be(this,i);if(this._yeaftHistorySearchTimeout&&(clearTimeout(this._yeaftHistorySearchTimeout),this._yeaftHistorySearchTimeout=null),!i||!o||Array.from(n).length<1&&!r)return this.yeaftHistorySearchState={requestId:null,agentId:o,sessionId:i,query:n,senderKey:r,loading:!1,results:[],hasMore:!1,nextBeforeSeq:null,nextCursor:null,error:null},!1;let a=this.yeaftHistorySearchState||{};if(!yp(this,o,"session_history_search"))return this.yeaftHistorySearchState={requestId:null,agentId:o,sessionId:i,query:n,senderKey:r,loading:!1,results:[],hasMore:!1,nextBeforeSeq:null,nextCursor:null,error:"unsupported"},!1;let l=`history_search_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;this.yeaftHistorySearchState={requestId:l,agentId:o,sessionId:i,query:n,senderKey:r,loading:!0,results:t&&a.query===n&&a.senderKey===r?a.results:[],hasMore:!1,nextBeforeSeq:t&&a.query===n&&a.senderKey===r?a.nextBeforeSeq:null,nextCursor:t&&a.query===n&&a.senderKey===r&&a.nextCursor||null,error:null},this._yeaftHistorySearchTimeout=setTimeout(()=>{this.yeaftHistorySearchState?.requestId===l&&(this._yeaftHistorySearchTimeout=null,this.yeaftHistorySearchState={...this.yeaftHistorySearchState,loading:!1,error:"timeout"})},1e4);let c=_s(),d={type:"yeaft_search_history",agentId:o,sessionId:i,requestId:l,perfTraceId:c,query:n,senderKey:r,limit:20,...t&&a.query===n&&a.senderKey===r&&a.nextCursor?{cursor:a.nextCursor}:{},...t&&a.query===n&&a.senderKey===r&&!a.nextCursor&&Number.isFinite(a.nextBeforeSeq)?{beforeSeq:a.nextBeforeSeq}:{}};return Ge(this,{traceId:c,phase:"history_search.request_send",agentId:o,sessionId:i,messageType:d.type,bytes:JSON.stringify(d).length,detail:{append:t,limit:d.limit,queryLength:Array.from(n).length,senderFilter:!!r}}),this.sendWsMessage(d),!0},handleYeaftHistorySearchResult(e){let t=this.yeaftHistorySearchState||{};if(!e||e.requestId!==t.requestId||e.agentId!==t.agentId||e.sessionId!==t.sessionId||e.query!==t.query||(e.senderKey||"")!==t.senderKey)return!1;this._yeaftHistorySearchTimeout&&(clearTimeout(this._yeaftHistorySearchTimeout),this._yeaftHistorySearchTimeout=null);let s=Array.isArray(e.results)?e.results.map(r=>({...r,agentId:e.agentId,sessionId:e.sessionId})):[],n=new Map((t.results||[]).map(r=>[Wn(r),r]));for(let r of s)(r?.entryId||r?.messageId)&&n.set(Wn(r),r);return this.yeaftHistorySearchState={...t,loading:!1,results:Array.from(n.values()),hasMore:!!e.hasMore,nextBeforeSeq:Number.isFinite(e.nextBeforeSeq)?e.nextBeforeSeq:null,nextCursor:e.nextCursor&&typeof e.nextCursor=="object"?e.nextCursor:null,error:e.error||null},!0},loadYeaftHistoryWindow(e,{validateCached:t=!1}={}){let s=e?.sessionId||this.yeaftActiveSessionFilter||null,n=e?.agentId||be(this,s),r=Wn(e);if(!s||!n||!e?.entryId||!Number.isFinite(e.indexGeneration)||!Number.isFinite(e.entryStartSeq)||!e?.messageId||!Number.isFinite(e.seq))return Promise.resolve(!1);let i=tt(this,s,n);if((this.messagesMap[i]||[]).some(p=>(p?.sessionId??p?.groupId??null)===s&&p?.historyEntryId===e.entryId&&p?.historyIndexGeneration===e.indexGeneration)&&!t)return Promise.resolve(!0);let a=ve(n,`${s}:${r}:generation:${e.indexGeneration}`),l=this._yeaftHistoryWindowPendingByKey||{};if(l[a]?.promise)return l[a].promise;let c=`history_window_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,d=null,u=new Promise(p=>{d=p}),f=setTimeout(()=>{if(this._yeaftHistoryWindowPendingByKey?.[a]?.requestId!==c)return;let{[a]:g,...m}=this._yeaftHistoryWindowPendingByKey;this._yeaftHistoryWindowPendingByKey=m,d(!1)},1e4);return this._yeaftHistoryWindowPendingByKey={...l,[a]:{requestId:c,agentId:n,sessionId:s,entryId:e.entryId||null,indexGeneration:Number.isFinite(e.indexGeneration)?e.indexGeneration:null,entryStartSeq:Number.isFinite(e.entryStartSeq)?e.entryStartSeq:null,resultId:r,messageId:e.messageId,prefetch:!t,resolve:d,timeout:f,promise:u}},this.sendWsMessage({type:"yeaft_load_history_window",agentId:n,sessionId:s,requestId:c,prefetch:!t,...e.entryId?{entryId:e.entryId}:{},...Number.isFinite(e.indexGeneration)?{indexGeneration:e.indexGeneration}:{},...Number.isFinite(e.entryStartSeq)?{entryStartSeq:e.entryStartSeq}:{},anchorMessageId:e.messageId,anchorSeq:e.seq,beforeTurns:5,afterTurns:5,maxRows:200,maxBytes:512*1024}),u},beginYeaftHistoryReveal(e){let t=e?.sessionId||null,s=e?.agentId||null,n=tt(this,t,s);if(!t||!s||!n)return null;let r=ve(s,t),i=`${r}${n}`,o=++this._yeaftHistoryRevealSequence,a={key:i,token:o,sessionKey:r,agentId:s,sessionId:t,conversationId:n};return this._yeaftHistoryRevealLeases={...this._yeaftHistoryRevealLeases||{},[i]:a},a},finishYeaftHistoryReveal(e){if(!e?.key||!Number.isFinite(e.token)||this._yeaftHistoryRevealLeases?.[e.key]?.token!==e.token)return!1;let{[e.key]:s,...n}=this._yeaftHistoryRevealLeases;return this._yeaftHistoryRevealLeases=n,!0},async revealYeaftHistoryResult(e,t=null){let s=!t,n=t||this.beginYeaftHistoryReveal(e),r=e?.sessionId||null,i=e?.agentId||null,o=tt(this,r,i);if(!n||!r||!i||!o||!e?.messageId)return this.finishYeaftHistoryReveal(n),!1;if(!await this.loadYeaftHistoryWindow(e,{validateCached:!0}))return this.finishYeaftHistoryReveal(n),!1;if(this.currentView!=="yeaft"||this.yeaftActiveSessionFilter!==r||be(this,r)!==i||tt(this,r,i)!==o)return this.finishYeaftHistoryReveal(n),!1;let l=this.revealYeaftMessage(r,e.messageId,o,i);return(!l||s)&&this.finishYeaftHistoryReveal(n),l},pendingYeaftHistoryWindow(e){let s=Object.entries(this._yeaftHistoryWindowPendingByKey||{}).find(([,i])=>i?.requestId===e?.requestId);if(!s)return null;let[n,r]=s;return e.agentId!==r.agentId||e.sessionId!==r.sessionId||e.entryId&&r.entryId&&e.entryId!==r.entryId||Number.isFinite(e.indexGeneration)&&Number.isFinite(r.indexGeneration)&&e.indexGeneration!==r.indexGeneration?null:{pendingKey:n,pending:r}},handleYeaftHistoryWindow(e,t=null){let s=this.pendingYeaftHistoryWindow(e);if(!s)return!1;let{pendingKey:n,pending:r}=s;r.prefetch===!0&&e.prefetch!==!0&&(e.prefetch=!0),clearTimeout(r.timeout);let{[n]:i,...o}=this._yeaftHistoryWindowPendingByKey;this._yeaftHistoryWindowPendingByKey=o;let a=!e.error&&!!t&&this.isYeaftMessageCached(r.sessionId,r.messageId,t,r.agentId);return r.resolve(!!a),!!a},createYeaftSession({displayName:e,vpIds:t,defaultVpId:s,workDir:n,agentId:r}={}){let i=Array.isArray(t)?t.slice():[],o=s&&i.includes(s)?s:i[0]||null,a=(e||"").trim(),l=(n||"").trim(),c={roster:i,defaultVpId:o};return a&&(c.name=a),l&&(c.workDir=l),this.sessionCrudRequest("create",c,{agentId:r})},handleYeaftOutput(e){if(!e)return;let t=e.agentId||this.yeaftAgentId||this.currentAgent||null,s=e.conversationId||e.event?.conversationId||null,n=dn(this,t,s);if(e.data&&n){if(e.data.type!=="result")return;let a=Td(this,t,s);if(!a)return;let l=e.turnId?hn(this,t,e.turnId):"",c=!!(l&&this.activeVpTurns?.[l])||(this.messagesMap?.[a]||[]).some(d=>d?.turnId===e.turnId&&(d.isStreaming||d.status==="pending"));if(!e.turnId||!c)return;e={...e,conversationId:a}}if(e.perfTraceId&&(Ge(this,{traceId:e.perfTraceId,phase:"receive.yeaft_output",agentId:e.agentId||null,sessionId:e.sessionId||null,vpId:e.vpId||null,turnId:e.turnId||null,threadId:e.threadId||null,messageType:e.data?.type||e.event?.type||e.type}),e.turnId&&(this.yeaftPerfTraceByTurnId={...this.yeaftPerfTraceByTurnId||{},[e.turnId]:e.perfTraceId})),e.data){let a=e.agentId||null,l=qt(this,a,e.conversationId);if(l){let d=Xa(e,e.turnId||"session");for(let u of["retry","retrying","thinking"])ln(this,l,`${u}:${d}`);e.data?.tool_use_result&&ln(this,l,`tool:${d}`)}let c=e.turnId?hn(this,e.agentId||null,e.turnId):"";if(c&&this.activeVpTurns?.[c]?.retryAttempt){let{retryAttempt:d,retryMax:u,retryDelayMs:f,retryReason:p,retryRecoveryMode:g,...m}=this.activeVpTurns[c];this.activeVpTurns={...this.activeVpTurns,[c]:m}}if(l){let d=e.sessionId??e.groupId??null,u=bp(this,d,a),f=a&&this.yeaftConversationIdsByAgent?this.yeaftConversationIdsByAgent[a]:null,p=xt(this,a);p&&p.targetConversationId!==l?cr(this,a,l):!p&&f&&f!==l&&!String(f).startsWith("yeaft-local-")&&(Tt(this,f,l,{removeSource:f!==this.yeaftConversationId}),ar(this,a,f,l)),ka(this,a,l);let g=xt(this,a,l),m=g?.sourceConversationId||f,v=!u&&m===this.yeaftConversationId;if(this.currentView==="yeaft"&&a&&m&&m!==l){let b=!v&&(!!g||String(m).startsWith("yeaft-local-"));Tt(this,m,l,{removeSource:b}),v?mi(this,a,m,l):b&&lr(this,a,l)}a&&(this.yeaftConversationIdsByAgent={...this.yeaftConversationIdsByAgent||{},[a]:l}),(u||!this.yeaftConversationId)&&(this.yeaftConversationId=l),u&&(this.activeConversations=[l]),this.messagesMap[l]||(this.messagesMap[l]=[]);let k=this._currentYeaftAgentId,w=this._currentYeaftSessionId,I=this._currentYeaftVpId,h=this._currentYeaftTurnId,y=this._currentYeaftThreadId;a&&(this._currentYeaftAgentId=a),d!=null&&(this._currentYeaftSessionId=d),e.vpId&&(this._currentYeaftVpId=e.vpId),e.turnId&&(this._currentYeaftTurnId=e.turnId),e.threadId&&(this._currentYeaftThreadId=e.threadId);try{let b=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.handleAssistantOutputFrame(l,e.data,a),e.perfTraceId){let T=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();Ge(this,{traceId:e.perfTraceId,phase:"store.apply_output",agentId:e.agentId||null,sessionId:d||null,vpId:e.vpId||null,turnId:e.turnId||null,threadId:e.threadId||null,messageType:e.data?.type||null,durationMs:T-b}),vi(this,{traceId:e.perfTraceId,agentId:e.agentId||null,sessionId:d||null,vpId:e.vpId||null,turnId:e.turnId||null,threadId:e.threadId||null,messageType:e.data?.type||null})}let M=e.data,x=M?.message?.id||M?.id||null,D=Ry(x),V=Array.isArray(M?.message?.content)?M.message.content:[],E=V.some(T=>T?.type==="tool_use"),_=!!M?.tool_use_result||V.some(T=>T?.type==="tool_result");if(d){let T=!_&&!Py(this,l,d)&&(M?.type==="user"||M?.type==="assistant"&&!E)?D:null,A=ve(e.agentId||null,d),R=this.yeaftSessionHistoryState[A]||{},j=Number.isFinite(R.latestSeq)?R.latestSeq:-1;T!==null&&T>j&&(this.yeaftSessionHistoryState={...this.yeaftSessionHistoryState,[A]:{...R,latestSeq:T}})}}finally{this._currentYeaftAgentId=k,this._currentYeaftSessionId=w,this._currentYeaftVpId=I,this._currentYeaftTurnId=h,this._currentYeaftThreadId=y}}return}let r=e.event;if(!r)return;let i={...r,vpId:r.vpId||e.vpId||null,threadId:r.threadId||e.threadId||null,turnId:r.turnId||e.turnId||null},o=qt(this,e.agentId||null,e.conversationId);if(o){let a=Xa(i);r.type==="tool_start"?or(this,o,`tool:${a}`):r.type==="tool_end"?ln(this,o,`tool:${a}`):r.type==="llm_retry"?or(this,o,`retry:${a}`):r.type==="vp_async_task_wait_start"?or(this,o,`async-wait:${a}`):r.type==="vp_async_task_wait_end"&&ln(this,o,`async-wait:${a}`)}switch(r.type){case"project_mutation_result":r.projectsAuthoritative===!0?this.finishProjectMutation(r):this.finishLegacyProjectMutation(r,e.agentId||null);break;case"ask_user_question":{let a=qt(this,e.agentId||null,e.conversationId);if(!a||!r.requestId)break;let l=fp(e,r,a),c=()=>{let d=this.messagesMap[a]||[],u=mp(d,l,a);if(u){if(u.askAnswered||u.askExpired)return!0;u.toolName="AskUserQuestion",r.toolCallId&&!u.toolId&&(u.toolId=r.toolCallId),u.agentId=l.agentId||u.agentId||null,u.askRequestId=r.requestId,u.askQuestions=r.questions||[],u.askCreatedAt=r.createdAt||null,u.askExpiresAt=r.expiresAt||null,r.replay&&(u.askPending=!1,u.pendingAnswers=null,u.askSubmitGeneration=null),u.isHistory=!1;let g=hp(this,l);return g&&Ga(u,g),this.messagesMap={...this.messagesMap,[a]:d.slice()},!0}if(!r.replay)return!1;let f={id:`ask-card-${r.requestId}`,type:"tool-use",toolName:"AskUserQuestion",toolId:r.toolCallId||null,toolInput:{questions:r.questions||[]},askRequestId:r.requestId,askQuestions:r.questions||[],askCreatedAt:r.createdAt||null,askExpiresAt:r.expiresAt||null,agentId:l.agentId,sessionId:l.sessionId,vpId:l.vpId,speakerVpId:l.vpId,turnId:l.turnId,threadId:l.threadId||"main",hasResult:!1,isHistory:!1,timestamp:r.createdAt||Date.now()},p=hp(this,l);return p&&Ga(f,p),d.push(f),this.messagesMap={...this.messagesMap,[a]:d.slice()},!0};if(!c()){let d=0,u=setInterval(()=>{d+=1,(c()||d>=10)&&clearInterval(u)},200)}break}case"ask_user_answered":case"ask_user_expired":{let a=qt(this,e.agentId||null,e.conversationId);if(!a||!r.requestId)break;let l=this.messagesMap[a]||[],c=fp(e,r,a),d=mp(l,c,a);if(!d){My(this,c,r);break}Ga(d,r),this.messagesMap={...this.messagesMap,[a]:l.slice()};break}case"session_ready":{let a=r.conversationId,l=e.agentId||this.currentAgent;if(dn(this,l,a))break;let c=l&&this.yeaftConversationIdsByAgent?this.yeaftConversationIdsByAgent[l]:null,d=this.yeaftConversationId?String(this.yeaftConversationId):"",u=d.startsWith("yeaft-local-")&&(!l||d.startsWith(`yeaft-local-${l}-`)||/^yeaft-local-\d/.test(d))?this.yeaftConversationId:null,f=c||u,p=r.sessionId||e.sessionId||null,g=bp(this,p,l),m=xt(this,l);m&&m.targetConversationId!==a?cr(this,l,a):!m&&c&&c!==a&&!String(c).startsWith("yeaft-local-")&&ar(this,l,c,a),ka(this,l,a);let k=xt(this,l,a)?.sourceConversationId||f,w=!g&&k===this.yeaftConversationId;if(k&&k!==a){let M=!w;Tt(this,k,a,{removeSource:M}),w?mi(this,l,k,a):M&&lr(this,l,a)}else this.messagesMap[a]||(this.messagesMap[a]=[]);l&&(this.yeaftConversationIdsByAgent={...this.yeaftConversationIdsByAgent||{},[l]:a},this.cacheYeaftAgentStatus(l,r,{allowBootstrapCatalog:g})),g&&(this.yeaftModel=r.model,this.yeaftModelEffort=r.modelEffort||null,this.yeaftSessionReady=!0,this.yeaftBootstrapMetaLoadingKey=null,l?this.applyCachedYeaftStatus(l):this.yeaftAvailableModels=r.availableModels||[]);let I=Array.isArray(r.tasks)?r.tasks:[],h={};for(let[M,x]of Object.entries(this.yeaftActiveTasksBySession||{})){let D=Object.fromEntries(Object.entries(x||{}).filter(([,E])=>E?.id&&E.status==="running"&&E.agentId&&E.agentId!==l)),V=Za(D);Object.keys(V).length>0&&(h[M]=V)}for(let M of I){if(!M?.id||!M.sessionId||M.status!=="running")continue;let x=ve(l,M.sessionId);h[x]={...h[x]||{},[M.id]:{...M,agentId:l}}}this.yeaftActiveTasksBySession=h,g&&(r.yeaftDir&&(this.yeaftYeaftDir=r.yeaftDir),this.yeaftStatus={skills:r.skills,mcpServers:r.mcpServers,tools:r.tools,multiVp:!!r.multiVp}),(g||!this.yeaftConversationId)&&(this.yeaftConversationId=a),g&&(this.activeConversations=[a]);let y=e.agentId||this.currentAgent||null,b=y||"__current__";this._yeaftVpSubscribedAgentKey!==b&&(this._yeaftVpSubscribedAgentKey=b,this.sendWsMessage(y?{type:"yeaft_vp_subscribe",agentId:y}:{type:"yeaft_vp_subscribe"}));break}case"yeaft_status":{let a=e.agentId||this.currentAgent;a&&this.cacheYeaftAgentStatus(a,r);break}case"context_usage":break;case"turn_open":{if(!r.turnId)break;let a={turnId:r.turnId,userPrompt:r.userPrompt||"",vpId:r.vpId||e.vpId||null,sessionId:r.sessionId||e.sessionId||null,openedAt:r.at||Date.now(),closedAt:null,totalMs:0,totalTokens:0,loopCount:0,memoryLoaded:null,memoryLoadedMeta:null,memoryAdjust:null,tools:[],detailsLoaded:!0};this.yeaftDebugTurnsById={...this.yeaftDebugTurnsById,[r.turnId]:a},this.yeaftDebugTurnOrder.includes(r.turnId)||(this.yeaftDebugTurnOrder=[...this.yeaftDebugTurnOrder,r.turnId]);break}case"turn_close":{if(!r.turnId)break;let a=this.yeaftDebugTurnsById[r.turnId];if(!a)break;this.yeaftDebugTurnsById={...this.yeaftDebugTurnsById,[r.turnId]:{...a,closedAt:Date.now(),totalMs:r.totalMs||0,totalTokens:r.totalTokens||0,loopCount:r.loopCount||a.loopCount||0}};break}case"memory_used":{if(!r.turnId)break;let a=this.yeaftDebugTurnsById[r.turnId];if(!a)break;this.yeaftDebugTurnsById={...this.yeaftDebugTurnsById,[r.turnId]:{...a,memoryLoaded:Array.isArray(r.loaded)?r.loaded:[],memoryLoadedMeta:r.meta||null}};break}case"dream_memory_loaded":{let a=Array.isArray(r.resident)?r.resident:[];if(r.turnId){let c=this.yeaftDebugTurnsById[r.turnId];c&&(this.yeaftDebugTurnsById={...this.yeaftDebugTurnsById,[r.turnId]:{...c,dreamMemoryLoaded:a,dreamMemoryLoadedInto:r.loadedInto||"system_prompt.memory"}})}let l={};for(let c of a){let d=c&&typeof c.scope=="string"?c.scope:null,u=d&&/^sessions\/[^/]+$/.test(d)?d:d&&/^group\/[^/]+$/.test(d)?`sessions/${d.slice(6)}`:null;u&&(l[u]={scope:u,sourceScope:d,sessionId:u.slice(9),turnId:r.turnId||null,vpId:r.vpId||null,loadedInto:r.loadedInto||"system_prompt.memory",summary:c.summary||"",truncated:!!c.truncated,receivedAt:Date.now()})}Object.keys(l).length>0&&(this.yeaftDreamPromptLoads={...this.yeaftDreamPromptLoads,...l});break}case"memory_adjust":{if(!r.turnId)break;let a=this.yeaftDebugTurnsById[r.turnId];if(!a)break;this.yeaftDebugTurnsById={...this.yeaftDebugTurnsById,[r.turnId]:{...a,memoryAdjust:{sessionKey:r.sessionKey||null,added:r.added||0,evicted:r.evicted||0,skipped:r.skipped||0,reason:r.reason||""}}};break}case"tool_exec":{if(!r.turnId)break;let a=this.yeaftDebugTurnsById[r.turnId];if(!a)break;let l=[...a.tools||[],{loopNumber:r.loopNumber||0,callId:r.callId||null,name:r.name||"?",durationMs:r.durationMs||0,isError:!!r.isError}];this.yeaftDebugTurnsById={...this.yeaftDebugTurnsById,[r.turnId]:{...a,tools:l}};break}case"loop":{if(this.yeaftDebugLoops.push({turnId:r.turnId||null,loopNumber:r.loopNumber||0,model:r.model,usage:r.usage||{inputTokens:0,outputTokens:0,totalTokens:0},latencyMs:r.latencyMs,ttfbMs:r.ttfbMs,stopReason:r.stopReason,at:typeof r.at=="number"?r.at:null,sessionId:e.sessionId||null,vpId:e.vpId||r.vpId||null}),this.yeaftDebugLoops.length>wp){let a=qu({loops:this.yeaftDebugLoops,turnsById:this.yeaftDebugTurnsById,turnOrder:this.yeaftDebugTurnOrder,maxLoops:Math.max(wp,this.yeaftDebugHistoryLimit||0)});this.yeaftDebugLoops=a.loops,this.yeaftDebugTurnsById=a.turnsById,this.yeaftDebugTurnOrder=a.turnOrder}break}case"llm_retry":{if(!e.turnId)break;let a=hn(this,e.agentId||null,e.turnId),l=this.activeVpTurns?.[a];if(!l)break;let c=r.reason==="stream_idle_timeout"?"stream_idle_timeout":"transient_error";this.activeVpTurns={...this.activeVpTurns,[a]:{...l,retryAttempt:r.attempt||0,retryMax:r.maxRetries||0,retryDelayMs:r.delayMs||0,retryReason:c,retryRecoveryMode:r.recoveryMode||"restart"}};break}case"recall":case"consolidate":case"fallback":case"thinking_delta":break;case"reflection":{let a=qt(this,e.agentId||null,e.conversationId)||"unknown",l=Array.isArray(r.loopRange)?r.loopRange:[0,0],c=`${a}:${r.trigger}:${l[0]}-${l[1]}`,d=this.yeaftReflectionCards[c],u=this.messagesMap[a]||[],f=d?d.anchorMsgId:u.length>0&&u[u.length-1].id||null,p=d?d.anchorOrder:u.length;this.yeaftReflectionCards={...this.yeaftReflectionCards,[c]:{key:c,conversationId:a,turnId:r.turnId||d&&d.turnId||null,loopNumber:r.loopNumber||d&&d.loopNumber||null,trigger:r.trigger,status:r.status,loopRange:l,toolCount:r.toolCount||0,content:r.content||"",durationMs:r.durationMs||0,error:r.error||null,sessionId:e.sessionId||null,anchorMsgId:f,anchorOrder:p,updatedAt:Date.now()}};break}case"model_switched":this.yeaftModel=r.model,this.yeaftModelEffort=r.modelEffort||null;break;case"yeaft_task_event":{let a=r.task;if(!a?.id||!a.sessionId)break;let l=e.agentId||be(this,a.sessionId),c=ve(l,a.sessionId),d={...a,agentId:l},u={...this.yeaftActiveTasksBySession},f={...u[c]||{}};a.status==="running"?f[a.id]=d:delete f[a.id];let p=Za(f);if(Object.keys(p).length>0?u[c]=p:delete u[c],this.yeaftActiveTasksBySession=u,a.status!=="running"){let{[Qa(l,a.sessionId,a.id)]:g,...m}=this.yeaftStoppingTasksById||{};this.yeaftStoppingTasksById=m}break}case"yeaft_task_cancel_result":{let a=r.taskId||r.task?.id||null,l=r.task?.sessionId||r.sessionId||e.sessionId||null,c=e.agentId||be(this,l);if(a&&l&&r.success===!1){let{[Qa(c,l,a)]:u,...f}=this.yeaftStoppingTasksById||{};this.yeaftStoppingTasksById=f}let d=r.task;if(d?.id&&d.sessionId){let u=ve(c,d.sessionId),f={...this.yeaftActiveTasksBySession},p={...f[u]||{}};d.status==="running"?p[d.id]={...d,agentId:c}:delete p[d.id];let g=Za(p);Object.keys(g).length>0?f[u]=g:delete f[u],this.yeaftActiveTasksBySession=f}break}case"sub_agent_event":{let a=qt(this,e.agentId||null,e.conversationId)||"unknown",l=r.agentId;if(!l)break;let c=r.payload||{},d=`${a}:${l}`,u=this.yeaftSubAgentCards[d],f=this.messagesMap[a]||[],p=u?u.anchorMsgId:f.length>0&&f[f.length-1].id||null,g=u?u.anchorOrder:f.length,m=u?{...u}:{key:d,conversationId:a,agentId:l,agentName:c.agentName||"sub-agent",status:"running",text:"",toolCallCount:0,turns:0,error:null,expanded:!1,anchorMsgId:p,anchorOrder:g,updatedAt:Date.now(),sessionId:e.sessionId||null};switch(c.agentName&&!m.agentName&&(m.agentName=c.agentName),c.type){case"sub_agent_status":m.status=c.status||m.status,c.error&&(m.error=c.error);break;case"text_delta":break;case"tool_use":case"tool_call":m.toolCallCount=Number(m.toolCallCount||0)+1;break;case"tool_start":break;case"tool_result":case"tool_end":break;case"sub_agent_turn_end":{m.turns+=1;let v=typeof c.content=="string"?c.content.trim():"";v&&(m.text=m.text?`${m.text}
9
9
 
10
10
  ${v}`:v),m.status!=="failed"&&m.status!=="closed"&&(m.status=c.status||"idle");break}case"error":c.error&&(m.error=c.error.message||String(c.error));break;default:break}m.updatedAt=Date.now(),this.yeaftSubAgentCards={...this.yeaftSubAgentCards,[d]:m};break}case"history_loaded":{let a={...r,agentId:e.agentId||null,requestId:r.requestId||e.requestId||null};if(a.requestId&&!this.isCurrentYeaftHistoryResponse(a))break;let l=e.agentId||null,c=r.sessionId??null,d=ve(l,c),u=e.perfTraceId||this.yeaftHistoryPerfTraceBySession?.[d];u&&Ge(this,{traceId:u,phase:"history.loaded_event",agentId:e.agentId||null,sessionId:r.sessionId||null,messageType:r.type,detail:{mode:r.mode||"recent",count:r.count||0,hasMore:!!r.hasMore}});let f=r.mode==="delta"?"delta":"recent",p=this.yeaftSessionHistoryState[d]||{},g=Number.isFinite(r.latestSeq)?r.latestSeq:Number.isFinite(p.latestSeq)?p.latestSeq:null,m=Number.isFinite(r.nextBeforeSeq)?r.nextBeforeSeq:Number.isFinite(r.oldestSeq)?r.oldestSeq:Number.isFinite(p.serverOldestFetchedSeq)?p.serverOldestFetchedSeq:Number.isFinite(p.oldestSeq)?p.oldestSeq:null,v=f==="delta"?{...p,loaded:!0,loading:!1,latestSeq:g,syncingAfterSeq:null,count:(p.count||0)+(r.count||0)}:{...p,loaded:!0,loading:!1,hasMore:!!r.hasMore,serverHasMore:!!r.hasMore,oldestSeq:m,serverOldestFetchedSeq:m,count:typeof r.count=="number"?r.count:0,latestSeq:g,syncingAfterSeq:null},k=a.requestId?this.finishYeaftHistoryLoad(a,v,"completion"):null;k||(this.yeaftSessionHistoryState={...this.yeaftSessionHistoryState,[d]:v});let w=ve(l?this.currentAgent:null,this.yeaftActiveSessionFilter??null);if(d===w)f==="recent"&&(this.yeaftHasMoreHistory=v.hasMore,this.yeaftOldestLoadedSeq=v.serverOldestFetchedSeq),this.yeaftLoadingMoreHistory=!!k?.loading;else if(this.yeaftLoadingMoreHistory){let I=this.yeaftSessionHistoryState[w]||null;this.yeaftLoadingMoreHistory=!!I?.loading}}break;case"vp_snapshot":{let a=window.Pinia?.useVpStore?.()||window.__useVpStore&&window.__useVpStore();a&&a.applySnapshot(r,e.agentId||null,e.requestId||null);break}case"vp_snapshot_error":{let a=window.Pinia?.useVpStore?.()||window.__useVpStore&&window.__useVpStore();a&&a.failSnapshot(e.agentId||null,e.requestId||null,r.error||r.message||"VP library request failed");break}case"vp_updated":{let a=window.Pinia?.useVpStore?.()||window.__useVpStore&&window.__useVpStore();a&&r.vp&&a.upsert(r.vp,r.reason,e.agentId||null);break}case"vp_removed":{let a=window.Pinia?.useVpStore?.()||window.__useVpStore&&window.__useVpStore();a&&r.vpId&&a.remove(r.vpId,r.reason,e.agentId||null);break}case"vp_crud_result":{let a=this._vpCrudPending&&this._vpCrudPending.get(r.requestId);a&&(this._vpCrudPending.delete(r.requestId),a.resolve({ok:!!r.ok,op:r.op,vpId:r.vpId,vp:r.vp,error:r.error||null}));break}case"group_list_updated":case"session_list_updated":case"yeaft_session_hydrate":{let a=window.Pinia?.useSessionsStore?.()||window.__useSessionsStore&&window.__useSessionsStore(),l=r.sessions||[];if(r.projectsAuthoritative===!0&&Array.isArray(r.projects)?this.applySessionCatalogSnapshot(this.sessionCatalog,r.projects):Array.isArray(r.projects)&&e.agentId&&this.applyLegacyProjectSnapshot(r.projects,e.agentId),r.type!=="yeaft_session_hydrate"&&this.yeaftSessionHydrateRequestId&&this.yeaftSessionInventoryCompleteSupported===!0){let p=Array.isArray(this.yeaftSessionHydrateSlices)?this.yeaftSessionHydrateSlices.filter(g=>g.agentId!==(e.agentId||null)):[];this.yeaftSessionHydrateSlices=[...p,{agentId:e.agentId||null,sessions:l}];break}let c=a&&a.activeSessionId||null,d=a?.activeSessionKey&&a.sessions?.[a.activeSessionKey]?.agentId||null;a&&(a.applySnapshot(l,e.agentId||null),this._hasHandledYeaftSessionHydrate=!0,this.yeaftSessionHydrateError=null);let u=a&&a.activeSessionId||null,f=a?.activeSessionKey&&a.sessions?.[a.activeSessionKey]?.agentId||null;if(this.currentView==="yeaft"&&u){let p=f||be(this,u,e.agentId||null),g=ve(p,u),m=this.yeaftSessionHistoryState[g]||null;this.setActiveSessionFilter(u,{agentId:p,force:d!==p||vd(u,c,m)})}break}case"group_roster_changed":case"session_roster_changed":{let a=window.Pinia?.useSessionsStore?.()||window.__useSessionsStore&&window.__useSessionsStore();a&&a.applyRosterChange(r,e.agentId||null);break}case"group_crud_result":case"session_crud_result":{let a=window.Pinia?.useSessionsStore?.()||window.__useSessionsStore&&window.__useSessionsStore();a&&a.applyCrudResult(r,e.agentId||null);let l=Promise.resolve();if(r.ok&&r.op==="delete"&&r.sessionId){let d=rs();l=(async()=>{if(!e.agentId)throw new Error("Session delete result is missing its Agent owner");if(d&&!await ia({fence:d,agentId:e.agentId,sessionId:r.sessionId}))throw new Error("Browser history cache was not removed");this.clearYeaftHistoryMemory({agentId:e.agentId,sessionId:r.sessionId})})(),l.catch(u=>{})}let c=this._sessionCrudPending&&this._sessionCrudPending.get(r.requestId);c&&(async()=>{let u=null;try{await l}catch(v){u=v}if(this._sessionCrudPending?.get(r.requestId)!==c)return;this._sessionCrudPending.delete(r.requestId);let f=r.session||r.group||null,p=f&&e.agentId&&!f.agentId?{...f,agentId:e.agentId}:f,g=r.sessionId||null,m=r.sessions||null;c.resolve({ok:!!r.ok&&!u,op:r.op,session:p,sessionId:g,sessions:m,config:r.config||null,error:u?{code:"browser_cache_cleanup_failed",message:u.message}:r.error||null})})();break}case"vp_turn_start":{if(!r.turnId||!r.vpId)break;let a=Da(e.agentId||null,r.turnId)||r.turnId;if(this.activeVpTurns={...this.activeVpTurns,[a]:{agentId:e.agentId||null,turnId:r.turnId,vpId:r.vpId,sessionId:r.sessionId||null,threadId:r.threadId||null,isStreaming:!0,startedAt:r.ts||Date.now()}},r.sessionId){let l=St(e.agentId||null,r.sessionId);this.yeaftProcessingSessions={...this.yeaftProcessingSessions,...l?{[l]:!0}:{[r.sessionId]:!0}}}break}case"vp_turn_end":{if(!r.turnId)break;let a=hn(this,e.agentId||null,r.turnId),l=r.sessionId||this.activeVpTurns?.[a]?.sessionId||null;r.reason==="end_turn"&&l&&this.markYeaftSessionUnread(l,e.agentId||null);let{[a]:c,...d}=this.activeVpTurns;this.activeVpTurns=d;let{[a]:u,...f}=this.stoppingVpTurnIds;this.stoppingVpTurnIds=f;let p=r.sessionId||c?.sessionId||null,g=e.agentId||c?.agentId||null,m=r.vpId||c?.vpId||null;if(!(p&&m?Object.values(this.activeVpTurns||{}).some(y=>y?.vpId===m&&st(y,p,g)):!1)&&p&&m){let y={...this.vpStatuses||{}},b=!1;for(let[M,x]of Object.entries(y))x?.vpId===m&&st(x,p,g)&&kr.has(x.state)&&(y[M]={...x,state:"idle",turnId:null,since:r.ts||Date.now()},b=!0);b&&(this.vpStatuses=y)}this.clearYeaftSessionProcessingIfIdle(p,{agentId:g});let w={end_turn:"completed",route_forward:"completed",aborted:"aborted",errored:"errored",error:"errored",cancelled:"cancelled",canceled:"cancelled"}[r.reason]||"completed",I=Date.now(),h=qt(this,e.agentId||null,e.conversationId);if(h&&Array.isArray(this.messagesMap[h])){let y=this.messagesMap[h],b=sp(y,r);for(let M=0;M<y.length;M++){let x=y[M];if(!x||x.type!=="assistant")continue;let D=x.sessionId??x.groupId;r.sessionId&&D&&D!==r.sessionId||r.vpId&&x.speakerVpId&&x.speakerVpId!==r.vpId||r.turnId&&x.turnId&&x.turnId!==r.turnId||x.status&&x.status!=="pending"||(x.status=w,x.turnEndAt=I,x.turnEndReason=r.reason||null,r.detail&&(x.turnEndDetail=r.detail),Number.isFinite(r.durationMs)&&(x.turnDurationMs=r.durationMs),b=!0)}b&&(this.messagesMap={...this.messagesMap,[h]:y.slice()}),this.pruneConversationMessageRetention(h,p,g)}break}case"yeaft_turn_aborted":{let a=Array.isArray(r.turnIds)?r.turnIds.filter(Boolean):[];r.turnId&&a.push(r.turnId);let l=r.sessionId||null,c=r.vpId||null,d=new Set;for(let g of a){let m=hn(this,e.agentId||null,g),v=this.activeVpTurns?.[m]||null;(!v||st(v,v.sessionId,e.agentId||null))&&d.add(m)}if(c)for(let[g,m]of Object.entries(this.activeVpTurns||{}))!m||m.vpId!==c||st(m,l,e.agentId||null)&&d.add(g);if(d.size===0)break;let u=l,f={...this.activeVpTurns||{}},p={...this.stoppingVpTurnIds||{}};for(let g of d){let m=f[g];!u&&m?.sessionId&&(u=m.sessionId),delete f[g],delete p[g]}this.activeVpTurns=f,this.stoppingVpTurnIds=p,this.clearYeaftSessionProcessingIfIdle(u||null,{agentId:e.agentId||null});break}case"yeaft_aborted":{let a=r.sessionId||e.sessionId||null;a?(this.activeVpTurns=Object.fromEntries(Object.entries(this.activeVpTurns||{}).filter(([,l])=>!st(l,a,e.agentId||null))),this.stoppingVpTurnIds=Object.fromEntries(Object.entries(this.stoppingVpTurnIds||{}).filter(([l])=>this.activeVpTurns?.[l])),this.vpStatuses=Object.fromEntries(Object.entries(this.vpStatuses||{}).filter(([,l])=>!st(l,a,e.agentId||null))),this.clearYeaftSessionProcessingIfIdle(a,{agentId:e.agentId||null,ignoreStatuses:!0})):r.all&&lp(this,e.agentId||null);break}case"vp_typing_start":{if(!r.vpId)break;let a=qt(this,e.agentId||null,e.conversationId);if(!a)break;this.yeaftVpTyping=Ou(this.yeaftVpTyping,a,r.vpId);break}case"vp_typing_end":{if(!r.vpId)break;let a=qt(this,e.agentId||null,e.conversationId);if(!a)break;this.yeaftVpTyping=Fu(this.yeaftVpTyping,a,r.vpId);break}case"vp_status_changed":{if(!r.vpId||!r.state)break;if(o){let u=Xa(i);if(r.state==="thinking"||r.state==="retrying"||r.state==="tool")or(this,o,`${r.state}:${u}`);else if(r.state==="streaming"||r.state==="idle"||r.state==="error")for(let f of["thinking","retrying","tool"])ln(this,o,`${f}:${u}`)}let a=r.sessionId||null,l=e.agentId||null,c=Ai(l,a,r.vpId),d={agentId:l,state:r.state,since:r.since||Date.now(),turnId:r.turnId||null,title:r.title||"",sessionId:a,vpId:r.vpId};if(this.vpStatuses={...this.vpStatuses,[c]:d},a&&kr.has(r.state)){let u=St(l,a);this.yeaftProcessingSessions={...this.yeaftProcessingSessions,...u?{[u]:!0}:{[a]:!0}}}else a&&this.clearYeaftSessionProcessingIfIdle(a,{agentId:l});this.restoreActiveYeaftSessionFromStatuses([d],l);break}case"vp_status_snapshot":{let a=Array.isArray(r.statuses)?r.statuses:[],l=r.sessionId;if(l==null){let c={...this.vpStatuses||{}};if(e.agentId)for(let[d,u]of Object.entries(c))(!u?.agentId||u.agentId===e.agentId)&&delete c[d];else for(let d of Object.keys(c))delete c[d];for(let d of a){if(!d||!d.vpId)continue;let u=d.sessionId||d.groupId||null,f=Ai(e.agentId||null,u,d.vpId);c[f]={agentId:e.agentId||null,state:d.state,since:d.since||Date.now(),turnId:d.turnId||null,title:d.title||"",sessionId:u,vpId:d.vpId}}this.vpStatuses=c}else{let c={...this.vpStatuses};for(let[d,u]of Object.entries(c))u&&u.sessionId===l&&(!e.agentId||!u.agentId||u.agentId===e.agentId)&&delete c[d];for(let d of a){if(!d||!d.vpId)continue;let u=d.sessionId||d.groupId||null,f=Ai(e.agentId||null,u,d.vpId);c[f]={agentId:e.agentId||null,state:d.state,since:d.since||Date.now(),turnId:d.turnId||null,title:d.title||"",sessionId:u,vpId:d.vpId}}this.vpStatuses=c}this.yeaftProcessingSessions=by(this,e.agentId||null,a,l??null),this.restoreActiveYeaftSessionFromStatuses(a,e.agentId||null);break}case"yeaft_dream_snapshot":{let a=r&&r.snapshot,l=a&&typeof a.scope=="string"?a.scope:null;l&&(this.yeaftDreamSnapshots={...this.yeaftDreamSnapshots,[l]:{...a,receivedAt:Date.now()}});break}case"yeaft_dream_status":{let a=window.Pinia?.useVpStore?.()||window.__useVpStore&&window.__useVpStore();a&&a.applyDreamStatus(r);break}case"yeaft_dream_result":{let a=window.Pinia?.useVpStore?.()||window.__useVpStore&&window.__useVpStore();a&&a.applyDreamResult(r),r?.snapshot?.scope&&(this.yeaftDreamSnapshots={...this.yeaftDreamSnapshots,[r.snapshot.scope]:{...r.snapshot,receivedAt:Date.now()}});{let l=typeof r?.snapshot?.scope=="string"&&r.snapshot.scope?r.snapshot.scope:typeof r?.sessionId=="string"&&r.sessionId?`sessions/${r.sessionId}`:null;if(!l)break;let c=this.yeaftDreamLatest[l]||null;this.yeaftDreamLatest={...this.yeaftDreamLatest,[l]:{scope:l,phase:"result",status:r.skipped?"skipped":r.success?"success":"error",startedAt:c?.startedAt??null,finishedAt:Date.now(),mergedCount:typeof r.entriesCreated=="number"?r.entriesCreated:c?.mergedCount??null,error:r.skipped||r.success?null:r.error||"unknown",manual:typeof r?.manual=="boolean"?r.manual:c?.manual??null,durationMs:typeof r.durationMs=="number"?r.durationMs:c?.durationMs??null,llmCallCount:typeof r.llmCallCount=="number"?r.llmCallCount:c?.llmCallCount??0,inputTokens:typeof r.inputTokens=="number"?r.inputTokens:c?.inputTokens??0,outputTokens:typeof r.outputTokens=="number"?r.outputTokens:c?.outputTokens??0,totalTokens:typeof r.totalTokens=="number"?r.totalTokens:c?.totalTokens??0,metrics:r.metrics||c?.metrics||null,passBreakdown:r.passBreakdown||r.metrics?.passBreakdown||c?.passBreakdown||null,isRunning:!1}},this._appendDreamEvent(l,{type:"dream_progress",phase:"result",sessionId:r.sessionId,status:r.skipped?"skipped":r.success?"success":"error",success:!!r.success,entriesCreated:typeof r.entriesCreated=="number"?r.entriesCreated:null,trigger:r.trigger||null,error:r.skipped||r.success?null:r.error||null,skipped:!!r.skipped,skippedReason:r.skippedReason||null,durationMs:typeof r.durationMs=="number"?r.durationMs:null,llmCallCount:typeof r.llmCallCount=="number"?r.llmCallCount:0,inputTokens:typeof r.inputTokens=="number"?r.inputTokens:0,outputTokens:typeof r.outputTokens=="number"?r.outputTokens:0,totalTokens:typeof r.totalTokens=="number"?r.totalTokens:0,metrics:r.metrics||null,passBreakdown:r.passBreakdown||r.metrics?.passBreakdown||null,ts:Date.now()})}break}case"dream_progress":{let a=r?.phase||"unknown",l=null;typeof r?.target=="string"&&r.target.includes("/")?l=r.target:typeof r?.sessionId=="string"&&r.sessionId?l=`sessions/${r.sessionId}`:l="*";let c=a==="done",d=a==="error"||r?.status==="error",u=!c&&!d,f=p=>{let g=this.yeaftDreamLatest[p]||null;return{scope:p,phase:a,status:d?"error":c?"success":"running",startedAt:g?.startedAt&&u?g.startedAt:r?.ts||g?.startedAt||Date.now(),finishedAt:c||d?r?.ts||Date.now():null,mergedCount:typeof r?.mergedCount=="number"?r.mergedCount:typeof r?.targets=="number"?r.targets:g?.mergedCount??null,error:d?r?.error||"unknown":null,manual:typeof r?.manual=="boolean"?r.manual:g?.manual??!1,durationMs:typeof r?.duration=="number"?r.duration:typeof r?.durationMs=="number"?r.durationMs:g?.durationMs??null,llmCallCount:typeof r?.llmCallCount=="number"?r.llmCallCount:g?.llmCallCount??0,inputTokens:typeof r?.inputTokens=="number"?r.inputTokens:g?.inputTokens??0,outputTokens:typeof r?.outputTokens=="number"?r.outputTokens:g?.outputTokens??0,totalTokens:typeof r?.totalTokens=="number"?r.totalTokens:g?.totalTokens??0,metrics:r?.metrics||g?.metrics||null,passBreakdown:r?.passBreakdown||r?.metrics?.passBreakdown||g?.passBreakdown||null,isRunning:u}};if(l==="*"){let p={...this.yeaftDreamLatest,"*":f("*")};for(let g of Object.keys(this.yeaftDreamLatest))g!=="*"&&(p[g]=f(g));this.yeaftDreamLatest=p}else this.yeaftDreamLatest={...this.yeaftDreamLatest,[l]:f(l)};this._appendDreamEvent(l,r);break}}},_appendDreamEvent(e,t){if(!e||!t)return;let s=Date.now(),n={...t,at:s},r=Array.isArray(this.yeaftDreamEvents?.[e])?this.yeaftDreamEvents[e]:[],i=l=>[l?.type||"",l?.phase||"",(l?.sessionId??l?.groupId)||"",l?.target||"",l?.ts||l?.at||""].join("|"),o=i(n);if(r.some(l=>i(l)===o))return;let a=[...r,n];a.length>Sp&&a.splice(0,a.length-Sp),this.yeaftDreamEvents={...this.yeaftDreamEvents,[e]:a}},fetchExpertRoleDefinitions(){if(this.expertRoleDefinitions)return;let e=this.currentAgent;e&&this.sendWsMessage({type:"get_expert_roles",agentId:e})},setYeaftSidebarEnabled(e){try{typeof localStorage<"u"&&localStorage.removeItem("yeaft-sidebar-enabled")}catch{}},vpCrudRequest(e,t){(!this._vpCrudPending||typeof this._vpCrudPending.get!="function")&&(this._vpCrudPending=new Map);let s="vpc_"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,8),r={create:"yeaft_vp_create",update:"yeaft_vp_update",delete:"yeaft_vp_delete",read:"yeaft_vp_read"}[e];if(!r)return Promise.resolve({ok:!1,op:e,error:{code:"bad_op",message:"unknown op: "+e}});let i={type:r,requestId:s};return e==="create"||e==="update"?i.payload=t||{}:i.vpId=t,new Promise(o=>{let a=setTimeout(()=>{this._vpCrudPending&&this._vpCrudPending.has(s)&&(this._vpCrudPending.delete(s),o({ok:!1,op:e,error:{code:"timeout",message:"vp_crud timeout"}}))},1e4);this._vpCrudPending.set(s,{resolve:l=>{clearTimeout(a),o(l)}}),this.sendWsMessage(i)})},sessionCrudRequest(e,t,s={}){(!this._sessionCrudPending||typeof this._sessionCrudPending.get!="function")&&(this._sessionCrudPending=new Map);let n="grc_"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,8),i={list:"yeaft_list_sessions",create:"yeaft_create_session",rename:"yeaft_rename_session",update:"yeaft_update_session",update_config:"yeaft_update_session_config",archive:"yeaft_archive_session",delete:"yeaft_delete_session",add_member:"yeaft_session_add_member",remove_member:"yeaft_session_remove_member",set_default_vp:"yeaft_session_set_default_vp",reorder:"reorder_yeaft_sessions",scan_workdir:"yeaft_scan_workdir_sessions",restore:"yeaft_restore_session"}[e];if(!i)return Promise.resolve({ok:!1,op:e,error:{code:"bad_op",message:"unknown op: "+e}});let o={type:i,requestId:n};e==="create"?o.payload=t||{}:t&&typeof t=="object"&&Object.assign(o,t);let a=s&&s.agentId?s.agentId:null;a&&(o.agentId=a);let l=window.Pinia?.useSessionsStore?.()||window.__useSessionsStore&&window.__useSessionsStore();return l&&l.markPending(n,e),new Promise(c=>{let d=setTimeout(()=>{this._sessionCrudPending&&this._sessionCrudPending.has(n)&&(this._sessionCrudPending.delete(n),c({ok:!1,op:e,error:{code:"timeout",message:"group_crud timeout"}}))},1e4);this._sessionCrudPending.set(n,{resolve:u=>{clearTimeout(d),c(u)}}),this.sendWsMessage(o)})},markYeaftSessionUnread(e,t=null){if(!e)return!1;let s=be(this,e,t);if(!s)return!1;let n=li(s,e);return this.currentView==="yeaft"&&this.yeaftActiveSessionFilter===e&&be(this,e)===s||this.yeaftUnreadSessionKeys?.[n]?!1:(this.yeaftUnreadSessionKeys={...this.yeaftUnreadSessionKeys,[n]:!0},!0)},markYeaftSessionRead(e,t=null){if(!e)return!1;let s=be(this,e,t);if(!s)return!1;let n=li(s,e);if(!this.yeaftUnreadSessionKeys?.[n])return!1;let{[n]:r,...i}=this.yeaftUnreadSessionKeys;return this.yeaftUnreadSessionKeys=i,!0},restoreActiveYeaftSessionFromStatuses(e=[],t=null){if(this.yeaftActiveSessionFilter)return null;let n=(Array.isArray(e)?e:[]).filter(o=>o&&(o.sessionId||o.groupId)&&!["idle","offline","completed","failed","aborted"].includes(o.state)).sort((o,a)=>(a.updatedAt||a.since||0)-(o.updatedAt||o.since||0)),r=n[0]?.sessionId||n[0]?.groupId||null;if(!r)return null;let i=t||n[0]?.agentId||Ip(this,r);if(!i)return null;this.setActiveSessionFilter(r,{agentId:i,force:!0});try{let o=window.Pinia?.useSessionsStore?.()||window.__useSessionsStore&&window.__useSessionsStore();o&&typeof o.setActive=="function"&&o.setActive(r,i)}catch{}return r},setActiveSessionFilter(e,t={}){let s=this.yeaftActiveSessionFilter||null,n=e||null,r=n?be(this,n,t.agentId||null):this.currentAgent,i=!!n&&n===s&&!!r&&!!this.currentAgent&&r!==this.currentAgent,o=!!t.force||i;if(this.yeaftActiveSessionFilter=n,r&&n&&this.currentAgent!==r){this.selectAgent(r);let l=this.agents.find(c=>c.id===r);this.activateYeaftAgent(r,l||null)}else r&&n&&this.activateYeaftAgent(r);r&&n&&(this.markYeaftSessionRead(n,r),Rc(this,r,n));let a=!o&&n===s;if(r&&n){this.yeaftSessionAgentById={...this.yeaftSessionAgentById||{},[n]:r};let l=this.yeaftConversationIdsByAgent?.[r]||null;l||(l=`yeaft-local-${r}-${Date.now()}`,this.yeaftConversationIdsByAgent={...this.yeaftConversationIdsByAgent||{},[r]:l}),this.yeaftConversationId=l,this.messagesMap[l]||(this.messagesMap[l]=[]),this.currentView==="yeaft"&&(this.activeConversations=[l])}try{let l=window.Pinia?.useSessionsStore?.()||window.__useSessionsStore&&window.__useSessionsStore();l&&typeof l.setActive=="function"&&l.setActive(n,r||null);let c=l?.activeSessionKey||null;c?localStorage.setItem("lastViewedYeaftSession",c):localStorage.removeItem("lastViewedYeaftSession")}catch{}this.syncActiveYeaftHistoryLoad(),this.hydrateYeaftHistoryBrowserCache(n,r,{revalidate:!0})},async switchYeaftModel(e,t=null,s=void 0){if(!e||!this.currentAgent)return;let n=t||null;if(n){let r={model:e};return s!==void 0&&(r.modelEffort=s||null),await this.sessionCrudRequest("update_config",{sessionId:n,config:r},{agentId:be(this,n)})}return this.sendWsMessage({type:"yeaft_model_switch",model:e,modelEffort:s||null,agentId:this.currentAgent}),null},setYeaftDebugSearch(e){this.yeaftDebugSearch=typeof e=="string"?e:"",this._yeaftDebugSearchTimer&&clearTimeout(this._yeaftDebugSearchTimer),this._yeaftDebugSearchTimer=setTimeout(()=>{this._yeaftDebugSearchTimer=null,this.yeaftDebugLoops=[],this.yeaftDebugTurnsById={},this.yeaftDebugTurnOrder=[],this.loadYeaftDebugHistory({limit:this.yeaftDebugSearch.trim()?kp:Ja,dreamLimit:5,indexOnly:!0,search:this.yeaftDebugSearch})},250)},setYeaftDebugSessionFilter(e){e==null?this.yeaftDebugSessionFilter=null:this.yeaftDebugSessionFilter=String(e)},toggleSubAgentCardExpand(e){let t=this.yeaftSubAgentCards?.[e];t&&(this.yeaftSubAgentCards={...this.yeaftSubAgentCards,[e]:{...t,expanded:!t.expanded}})},loadTelemetrySettings(){return this.currentAgent?new Promise(e=>{this._telemetryPending||(this._telemetryPending={}),this._telemetryPending.load=e,this.sendWsMessage({type:"get_telemetry_settings",agentId:this.currentAgent})}):(this.telemetrySettings={enabled:!0,retentionDays:3,flushIntervalMs:1e3,maxQueueSize:5e3,rawExchangeMaxBytes:524288,traceTextMaxBytes:262144,loaded:!0},Promise.resolve(this.telemetrySettings))},updateTelemetrySettings(e){return this.currentAgent?new Promise(t=>{this._telemetryPending||(this._telemetryPending={}),this._telemetryPending.update=t,this.sendWsMessage({type:"update_telemetry_settings",agentId:this.currentAgent,settings:e||{}})}):Promise.resolve({error:"no agent"})},loadSearchSettings(){return this.currentAgent?new Promise(e=>{this._searchPending||(this._searchPending={}),this._searchPending.load=e,this.sendWsMessage({type:"get_search_settings",agentId:this.currentAgent})}):(this.searchSettings={backend:"tavily",tavilyKeyConfigured:!1,tavilyKeyMasked:null,disableHtmlFallback:!1,loaded:!0},Promise.resolve(this.searchSettings))},updateSearchSettings(e){return this.currentAgent?new Promise(t=>{this._searchPending||(this._searchPending={}),this._searchPending.update=t,this.sendWsMessage({type:"update_search_settings",agentId:this.currentAgent,settings:e||{}})}):Promise.resolve({error:"no agent"})},loadTavilyUsage(){return this.currentAgent?(this.tavilyUsageLoading=!0,new Promise(e=>{this._searchPending||(this._searchPending={}),this._searchPending.usage=e,this.sendWsMessage({type:"get_tavily_usage",agentId:this.currentAgent})})):Promise.resolve(null)},loadYeaftMcpServers(){if(!this.currentAgent)return this.yeaftMcpServers=[],this.yeaftMcpRuntime={connected:!1,toolCount:0,perServer:[]},Promise.resolve({servers:[],runtime:this.yeaftMcpRuntime});this.yeaftMcpLoading=!0;let e=`mcp-list-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise(t=>{this._mcpPending||(this._mcpPending={}),this._mcpPending[e]=t,this.sendWsMessage({type:"yeaft_mcp_list",agentId:this.currentAgent,requestId:e})})},addYeaftMcpServer(e){if(!this.currentAgent)return Promise.resolve({error:"no agent"});this.yeaftMcpLoading=!0;let t=`mcp-add-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise(s=>{this._mcpPending||(this._mcpPending={}),this._mcpPending[t]=s,this.sendWsMessage({type:"yeaft_mcp_add",agentId:this.currentAgent,requestId:t,server:e||{}})})},removeYeaftMcpServer(e){if(!this.currentAgent)return Promise.resolve({error:"no agent"});this.yeaftMcpLoading=!0;let t=`mcp-rem-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise(s=>{this._mcpPending||(this._mcpPending={}),this._mcpPending[t]=s,this.sendWsMessage({type:"yeaft_mcp_remove",agentId:this.currentAgent,requestId:t,name:e})})},reloadYeaftMcpServer(e){if(!this.currentAgent)return Promise.resolve({error:"no agent"});this.yeaftMcpLoading=!0;let t=`mcp-rel-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise(s=>{this._mcpPending||(this._mcpPending={}),this._mcpPending[t]=s,this.sendWsMessage({type:"yeaft_mcp_reload",agentId:this.currentAgent,requestId:t,name:e||null})})},clearYeaftMessages(){let e=this.yeaftConversationId;e&&(Ce(this,e),delete this.messagesMap[e],delete this.processingConversations[e],delete this.executionStatusMap[e],delete this.refreshingSessionMap[e],this._closedAt&&delete this._closedAt[e],this._turnCompletedConvs?.delete(e)),this.yeaftConversationId=this.currentAgent?`yeaft-local-${this.currentAgent}-${Date.now()}`:`yeaft-local-${Date.now()}`,this.currentAgent&&(this.yeaftConversationIdsByAgent={...this.yeaftConversationIdsByAgent||{},[this.currentAgent]:this.yeaftConversationId}),this.messagesMap[this.yeaftConversationId]=[],this.activeConversations=[this.yeaftConversationId],this.yeaftSessionReady=!1,this.yeaftModel=null,this.yeaftAvailableModels=[],this.yeaftStatus=null,this._yeaftAskTerminalEvents={},this.yeaftDebugLoops=[],this.yeaftDebugTurnsById={},this.yeaftDebugTurnOrder=[],this.yeaftDebugHistoryLoading=!1,this.yeaftDebugHistoryError=null,this.yeaftDebugHistoryFetchedAt=0,this.yeaftDebugSearch="",this.yeaftDebugSessionFilter=null,this.yeaftDebugPanel={open:!1,status:"idle",requestId:null,agentId:null,sessionId:null,turnId:null,error:null},this._yeaftDebugSearchTimer&&(clearTimeout(this._yeaftDebugSearchTimer),this._yeaftDebugSearchTimer=null),this._fetchYeaftDebugHistoryTimer&&(clearTimeout(this._fetchYeaftDebugHistoryTimer),this._fetchYeaftDebugHistoryTimer=null),this._yeaftDebugHistoryInFlightKey=null,this._yeaftDebugHistoryLatestListRequestId=null,this._yeaftDebugHistoryLatestDetailRequestId=null,this.yeaftReflectionCards={},this.yeaftSubAgentCards={},this.yeaftDreamLatest={},this.yeaftDreamEvents={},this.vpStatuses={},this.currentAgent&&this.sendWsMessage({type:"yeaft_reset",agentId:this.currentAgent})},togglePaneRightPanel(e,t=null){if(t&&this.isSplitMode){let s=this.panels.find(n=>n.id===t);if(s){s.activeRightPanel=s.activeRightPanel===e?null:e;return}}this.activeRightPanel=this.activeRightPanel===e?null:e},getPaneRightPanel(e){if(e&&this.isSplitMode){let t=this.panels.find(s=>s.id===e);if(t)return t.activeRightPanel}return this.activeRightPanel},setPaneRightPanel(e,t){if(e&&this.isSplitMode){let s=this.panels.find(n=>n.id===e);if(s){s.activeRightPanel=t;return}}this.activeRightPanel=t},applySessionCatalogSnapshot(e,t=null,s=null){let n=r=>{let i=new Set;return(Array.isArray(r)?r:[]).filter(o=>!o?.catalogKey||i.has(o.catalogKey)?!1:(i.add(o.catalogKey),!0)).map(o=>({...o}))};if(this.sessionCatalog=n(e),Array.isArray(s)&&(this.hiddenSessionCatalog=n(s)),Array.isArray(t)){this.sessionProjects=t.filter(i=>i?.id).map(i=>({...i,members:Array.isArray(i.members)?i.members.filter(o=>o?.agentId&&o?.sessionId):i.agentId?(i.sessionIds||[]).map(o=>({agentId:i.agentId,sessionId:o})):[]}));let r=new Map;for(let i of this.sessionProjects)for(let o of i.members)r.set(`${o.agentId}${o.sessionId}`,i.id);this.sessionCatalog=this.sessionCatalog.map(i=>i.runtimeProvider==="yeaft"?{...i,projectId:r.get(`${i.routeRef?.agentId}${i.routeRef?.sessionId}`)||null}:i)}this.sessionCatalogLoaded=!0},mutateProject(e,t={},s=null){let n=s||t.agentId||this.currentAgent||null;if(e==="move_session"&&!n)return Promise.resolve({ok:!1,error:{code:"missing_agent"}});let r=`project_${crypto.randomUUID()}`;return new Promise(i=>{let o=setTimeout(()=>{delete this.projectMutationRequests[r],i({ok:!1,error:{code:"timeout"}})},1e4);this.projectMutationRequests[r]={connectionGeneration:Number(this.chatHistoryConnectionGeneration||0),catalogOrder:Array.isArray(t.catalogOrder)?t.catalogOrder:null,resolve:l=>{clearTimeout(o),i(l)}},this.sendWsMessage({type:"yeaft_project_mutation",...n?{agentId:n,targetAgentId:n}:{},requestId:r,op:e,...t})||(clearTimeout(o),delete this.projectMutationRequests[r],i({ok:!1,error:{code:"send_failed"}}))})},applyLegacyProjectSnapshot(e,t){if(!t||!Array.isArray(e))return;let s=this.sessionProjects.filter(r=>r.legacyAgentId!==t),n=e.filter(r=>r?.id).map(r=>({...r,id:`${t}${r.id}`,legacyProjectId:r.id,legacyAgentId:t,members:(r.sessionIds||[]).map(i=>({agentId:t,sessionId:i}))}));this.applySessionCatalogSnapshot(this.sessionCatalog,[...s,...n])},finishLegacyProjectMutation(e,t){if(!e?.requestId)return!1;let s=this.projectMutationRequests[e.requestId]||null;return!s||s.connectionGeneration!==Number(this.chatHistoryConnectionGeneration||0)?!1:(delete this.projectMutationRequests[e.requestId],e.ok&&Array.isArray(e.projects)&&t&&this.applyLegacyProjectSnapshot(e.projects,t),s.resolve(e),!0)},finishProjectMutation(e){if(!e?.requestId)return!1;let t=this.projectMutationRequests[e.requestId]||null;if(!t||t.connectionGeneration!==Number(this.chatHistoryConnectionGeneration||0))return!1;if(delete this.projectMutationRequests[e.requestId],e.ok){if(Array.isArray(t.catalogOrder)){let s=new Map(this.sessionCatalog.map(r=>[r.catalogKey,r])),n=t.catalogOrder.map((r,i)=>{let o=s.get(r?.catalogKey);return o?{...o,sortRank:i}:null}).filter(Boolean);n.length===this.sessionCatalog.length&&(this.sessionCatalog=n,vp(n))}Array.isArray(e.projects)&&this.applySessionCatalogSnapshot(this.sessionCatalog,e.projects)}return t.resolve(e),!0},toggleCatalogSessionPin(e){if(!e?.catalogKey||!e?.routeRef||Object.keys(this.sessionCatalogMutationRequests).length>0)return!1;let t=`session_ui_${crypto.randomUUID()}`,s=er(this,t),n=!e.pinned;return e.pinned=n,this.sendWsMessage({type:"set_session_ui_metadata",requestId:t,catalogKey:e.catalogKey,routeRef:e.routeRef,pinned:n,sortRank:Number.isFinite(e.sortRank)?e.sortRank:null})?!0:(this.sessionCatalog=s,delete this.sessionCatalogMutationRequests[t],!1)},hideCatalogSession(e){if(!e?.catalogKey||!e?.routeRef||Object.keys(this.sessionCatalogMutationRequests).length>0)return!1;let t=`session_hide_${crypto.randomUUID()}`,s=er(this,t);return this.sessionCatalog=this.sessionCatalog.filter(r=>r.catalogKey!==e.catalogKey),this.hiddenSessionCatalog=[...(this.hiddenSessionCatalog||[]).filter(r=>r.catalogKey!==e.catalogKey),{...e,hidden:!0}],this.sendWsMessage({type:"set_session_ui_metadata",requestId:t,catalogKey:e.catalogKey,routeRef:e.routeRef,hidden:!0,...Number.isFinite(e.sortRank)?{sortRank:e.sortRank}:{}})?!0:(this.sessionCatalog=s,this.hiddenSessionCatalog=Array.isArray(this.sessionCatalogMutationRequests[t]?.previousHiddenCatalog)?this.sessionCatalogMutationRequests[t].previousHiddenCatalog:[],delete this.sessionCatalogMutationRequests[t],!1)},restoreCatalogSession(e){if(!e?.catalogKey||!e?.routeRef||Object.keys(this.sessionCatalogMutationRequests).length>0)return!1;let t=`session_restore_${crypto.randomUUID()}`,s=er(this,t);return this.hiddenSessionCatalog=(this.hiddenSessionCatalog||[]).filter(r=>r.catalogKey!==e.catalogKey),this.sessionCatalog=this.sessionCatalog.some(r=>r.catalogKey===e.catalogKey)?this.sessionCatalog:[...this.sessionCatalog,{...e,hidden:!1}],this.sendWsMessage({type:"set_session_ui_metadata",requestId:t,catalogKey:e.catalogKey,routeRef:e.routeRef,hidden:!1,...Number.isFinite(e.sortRank)?{sortRank:e.sortRank}:{}})?!0:(this.sessionCatalog=s,this.hiddenSessionCatalog=Array.isArray(this.sessionCatalogMutationRequests[t]?.previousHiddenCatalog)?this.sessionCatalogMutationRequests[t].previousHiddenCatalog:[],delete this.sessionCatalogMutationRequests[t],!1)},renameCatalogSession({row:e,title:t}={}){if(!e?.routeRef||!t)return!1;let{runtimeProvider:s,agentId:n,sessionId:r}=e.routeRef;if(s==="yeaft")this.sessionCrudRequest("rename",{sessionId:r,name:t},{agentId:n});else if(s==="claude-code"||s==="copilot")this.renameChatSession(r,t,n);else return!1;return!0},reorderCatalogSessions(e){if(!Array.isArray(e)||e.length===0||Object.keys(this.sessionCatalogMutationRequests).length>0)return!1;let t=`session_order_${crypto.randomUUID()}`,s=er(this,t);return this.sessionCatalog=e.map((r,i)=>({...r,sortRank:i})),this.sendWsMessage({type:"reorder_session_catalog",requestId:t,sessions:this.sessionCatalog.map((r,i)=>({catalogKey:r.catalogKey,routeRef:r.routeRef,pinned:!!r.pinned,sortRank:i}))})?!0:(this.sessionCatalog=s,delete this.sessionCatalogMutationRequests[t],!1)},finishSessionCatalogMutation(e){if(!Bc(this,e))return!1;if(e?.ok===!0&&e?.type==="session_ui_metadata_updated"){let s=n=>{n&&(n.pinned=e.pinned===!0,Object.prototype.hasOwnProperty.call(e,"sortRank")&&(n.sortRank=Number.isFinite(e.sortRank)?e.sortRank:null))};s(this.sessionCatalog.find(n=>n.catalogKey===e.catalogKey)),s(this.hiddenSessionCatalog.find(n=>n.catalogKey===e.catalogKey))}return e?.ok===!0&&e?.type==="session_catalog_reorder_result"&&vp(this.sessionCatalog),!0},openCatalogSession(e){if(!e?.catalogKey||!e.routeRef)return!1;let{runtimeProvider:t,agentId:s,sessionId:n}=e.routeRef;if(this.activeCatalogKey=e.catalogKey,t==="yeaft"){let r=this.isSessionHistorySyncing(e.routeRef);return this.enterYeaft(s,{deferBootstrap:!0}),this.setActiveSessionFilter(n,{agentId:s,force:!1}),r||this.reloadYeaftMessages(),!0}return t!=="claude-code"&&t!=="copilot"?!1:(this.currentView==="yeaft"&&this.leaveYeaft(),this.selectConversation(n,s,{refresh:!0}),!0)},syncChatConversationHistory(e){if(!e)return null;let t=is(e);if(this.chatHistoryRequests[t]?.loading)return this.chatHistoryRequests[t].requestId;let s=Ps(this.messagesMap[e]);return this.requestChatHistory(e,s===null?{mode:"recent",turns:5}:{mode:"delta",afterMessageId:s})},requestChatHistory(e,{mode:t="recent",turns:s=null,beforeId:n=null,afterMessageId:r=null}={}){if(!e)return null;let i=is(e);if(this.chatHistoryRequestIdSupported!==!0&&this.chatHistoryRequests[i]?.loading)return null;let o=n??r??null,a=this.beginChatHistoryRequest(e,t,o);return this.sendWsMessage({type:"sync_messages",conversationId:e,...s!=null?{turns:s}:{},...n!=null?{beforeId:n}:{},...r!=null?{afterMessageId:r}:{},requestId:a})?(setTimeout(()=>{aa(this,i,a,"history_load_timeout")},1e4),a):(aa(this,i,a,"send_failed"),null)},beginChatHistoryRequest(e,t="recent",s=null){return Nc(this,e,t,s)},isCurrentChatHistoryResponse(e){if(!e?.conversationId||!e?.requestId||!e?.catalogKey)return!1;let t=is(e.conversationId);if(e.catalogKey!==t)return!1;let s=this.chatHistoryRequests[t];return!!s&&s.loading===!0&&s.requestId===e.requestId&&Number(s.connectionGeneration||0)===Number(this.chatHistoryConnectionGeneration||0)},finishChatHistoryRequest(e){if(!this.isCurrentChatHistoryResponse(e))return!1;let t=this.chatHistoryRequests[e.catalogKey];return this.chatHistoryRequests[e.catalogKey]={...t,loading:!1},!0},isRefreshingSession(e){return e?!!this.refreshingSessionMap[e]:this.refreshingSession},setRefreshingSession(e,t){e&&(this.refreshingSessionMap[e]=t),this.refreshingSession=t},enterBtwMode(){this.btwMode=!0,this.btwMessages=[],this.btwLoading=!1,this.btwSessionId=null},sendBtwQuestion(e){this.currentConversation&&(this.btwMessages.push({role:"user",content:e}),this.btwMessages.push({role:"assistant",content:""}),this.btwLoading=!0,this.sendWsMessage({type:"btw_question",conversationId:this.currentConversation,question:e,btwSessionId:this.btwSessionId}))},closeBtw(){this.btwMode=!1,this.btwMessages=[],this.btwLoading=!1,this.btwSessionId=null},appendBtwDelta(e){let t=this.btwMessages[this.btwMessages.length-1];t&&t.role==="assistant"&&(t.content+=e)},addSubagent(e,t){this.subagents[e]||(this.subagents[e]={}),this.subagents[e][t.id]={id:t.id,slug:t.slug||t.id,type:t.type||"Task",description:t.description||"",parentToolUseId:t.parentToolUseId||null,status:"running",startTime:Date.now(),messages:[],toolCallCount:0},e===this.currentConversation&&this.activeRightPanel!=="subagents"&&(this.activeRightPanel="subagents")},appendSubagentMessage(e,t,s){let n=this.subagents[e];if(!n||!n[t])return;let r=n[t];if(s?.type==="tool"){r.toolCallCount=Number(r.toolCallCount||0)+1;return}s?.type==="text"&&r.messages.push(s)},completeSubagent(e,t){let s=this.subagents[e];!s||!s[t]||(s[t].status="completed")},sendWsMessage(e){return id(this,e)},parseWsMessage(e){return od(this,e)},connect(){ad(this)},ensureConnected(){return nr(this)},scheduleReconnect(){ld(this)},manualReconnect(){cd(this)},startHeartbeat(){dd(this)},stopHeartbeat(){ud(this)},setupVisibilityHandler(){pd(this)},handleMessage(e){iu(this,e)},getOrCreateExecutionStatus(e){return Pa(this,e)},handleAssistantOutputFrame(e,t,s=null){Yd(this,e,t,s)},handleClaudeOutput(e,t){this.handleAssistantOutputFrame(e,t,null)},addMessageToConversation(e,t){return di(this,e,t)},pruneConversationMessageRetention(e,t=null,s=null,n=void 0){return Mc(this,{conversationId:e,sessionId:t,agentId:s,limits:n})},appendToAssistantMessageForConversation(e,t,s){wd(this,e,t,s)},finishStreamingForConversation(e,t){kd(this,e,t)},sweepStaleStreamingForConversation(e){Sd(this,e)},appendToAssistantMessage(e){this.appendToAssistantMessageForConversation(this.currentConversation,e)},finishStreaming(){this.finishStreamingForConversation(this.currentConversation)},addMessage(e){this.addMessageToConversation(this.currentConversation,e)},loadHistoryMessages(e){Id(this,e)},formatDbMessage(e){return ya(e)},formatDbMessageForHistoryHydration(e){return Ad(e)},selectAgent(e){return fu(this,e)},createConversation(e,t=null,s=null,n=void 0){gu(this,e,t,s,n)},resumeConversation(e,t,s=null,n=null,r=null){mu(this,e,t,s,n,r)},selectConversation(e,t,s={}){hu(this,e,t,s)},updateConversationSettings(e,t){$a(this,e,t)},toggleConversationMcp(e,t){vu(this,e,t)},deleteConversation(e,t){bu(this,e,t)},closeSession(e,t){yu(this,e,t)},appendColumn(e){Iu(this,e)},removeColumn(e){Cu(this,e)},sendMessageToConversation(e,t,s=[],n={}){Au(this,e,t,s,n)},cancelExecutionForConversation(e){xu(this,e)},addPanel(){if(this.panels.length>=3)return;let e=(t,s)=>({id:t,conversationId:s,activeRightPanel:null});if(this.panels.length===0){let t=localStorage.getItem("splitPanesSaved");if(t){try{let s=JSON.parse(t);if(Array.isArray(s)&&s.length>=2){let n=new Set(this.conversations.map(i=>i.id)),r=s.filter(i=>i&&typeof i.id=="string").map(i=>({...e(i.id,null),conversationId:i.conversationId&&n.has(i.conversationId)?i.conversationId:null}));if(r.length>=2){this.panels=r,this.activePanelId=r[0].id;for(let i of r)i.conversationId&&!this.activeConversations.includes(i.conversationId)&&this.activeConversations.push(i.conversationId),i.conversationId&&!this.messagesMap[i.conversationId]&&(this.messagesMap[i.conversationId]=[],this.requestChatHistory(i.conversationId,{mode:"recent",turns:5}));localStorage.removeItem("splitPanesSaved"),this.saveOpenSessions();return}}}catch{}localStorage.removeItem("splitPanesSaved")}this.panels=[e("panel-0",this.currentConversation),e("panel-1",null)],this.activePanelId="panel-0"}else{let t="panel-"+Date.now();this.panels.push(e(t,null))}this.saveOpenSessions()},removePanel(e){let t=this.panels.findIndex(s=>s.id===e);if(!(t<0)){if(this.panels.splice(t,1),this.panels.length<=1){let s=this.panels[0];s?.conversationId&&(this.activeConversations=[s.conversationId]),this.panels=[],this.activePanelId=null}else this.activePanelId===e&&(this.activePanelId=this.panels[0]?.id||null);this.saveOpenSessions()}},setPanelConversation(e,t,{refresh:s=!1}={}){let n=this.panels.find(i=>i.id===e);if(!n)return;let r=n.conversationId===t;n.conversationId=t,t&&!this.activeConversations.includes(t)&&this.activeConversations.push(t),t&&!this.messagesMap[t]?(this.messagesMap[t]=[],this.syncChatConversationHistory(t)):t&&(s||!r)&&this.syncChatConversationHistory(t),this.saveOpenSessions()},setActivePanel(e){this.activePanelId=e},splitToPanel(e){if(!e)return;let t=(s,n)=>({id:s,conversationId:n,activeRightPanel:null});if(this.panels.length===0)this.panels=[t("panel-0",this.currentConversation),t("panel-"+Date.now(),e)],this.activePanelId=this.panels[1].id;else if(this.panels.length>=3)this.panels[this.panels.length-1].conversationId=e,this.activePanelId=this.panels[this.panels.length-1].id;else{let s="panel-"+Date.now();this.panels.push(t(s,e)),this.activePanelId=s}this.activeConversations.includes(e)||this.activeConversations.push(e),this.messagesMap[e]||(this.messagesMap[e]=[],this.requestChatHistory(e,{mode:"recent",turns:5})),this.saveOpenSessions()},isInAnyPanel(e){return this.panels.some(t=>t.conversationId===e)},setSessionPinned(e,t,s={}){if(!e)return;let n=s&&s.agentId?s.agentId:null,r=n?!!cs()?.sessionById?.(e,n)?.pinned:this.pinnedSessions.includes(e);if(t&&!r)this.pinnedSessions.unshift(e);else if(!t&&r){let i=this.pinnedSessions.indexOf(e);i>=0&&this.pinnedSessions.splice(i,1)}try{localStorage.setItem("pinned-sessions",JSON.stringify(this.pinnedSessions))}catch{}try{let i=window.Pinia?.useSessionsStore?.()||window.__useSessionsStore&&window.__useSessionsStore(),o=be(this,e,n);i&&typeof i.applyPinState=="function"&&i.applyPinState(e,!!t,o)}catch{}},togglePin(e,t={}){let s=t&&t.agentId?t.agentId:null,n=s?cs()?.sessionById?.(e,s):null,r=t&&Object.prototype.hasOwnProperty.call(t,"pinned"),o=!(n?!!n.pinned:r?!!t.pinned:this.pinnedSessions.includes(e));this.setSessionPinned(e,o,{agentId:s});let a={type:o?"pin_session":"unpin_session",conversationId:e};t&&t.sessionKind==="yeaft"&&(a.sessionKind="yeaft",t.agentId&&(a.agentId=t.agentId),t.sessionName&&(a.sessionName=t.sessionName),t.workDir&&(a.workDir=t.workDir)),this.sendWsMessage(a)},isSessionPinned(e){return this.pinnedSessions.includes(e)},applyServerPinSnapshot(e,t,s){if(!Array.isArray(this.pinnedSessions))return;let n=new Set(this.pinnedSessions),r=[];for(let i of t)n.has(i)||r.push(i);if(r.length>0&&(this.pinnedSessions=[...r,...this.pinnedSessions]),e){let i=this.pinnedSessions.filter(o=>s(o)?t.has(o):!0);i.length!==this.pinnedSessions.length&&(this.pinnedSessions=i)}try{localStorage.setItem("pinned-sessions",JSON.stringify(this.pinnedSessions))}catch{}},clearYeaftSessionProcessingIfIdle(e,{agentId:t=null,ignoreStatuses:s=!1}={}){if(!e)return;let n=t||be(this,e);if(Object.values(this.activeVpTurns||{}).some(a=>st(a,e,n))||!s&&Object.values(this.vpStatuses||{}).some(l=>st(l,e,n)&&kr.has(l?.state)))return;let i=St(n,e),o={...this.yeaftProcessingSessions||{}};i&&delete o[i],Mi(this,e,n)&&delete o[e],this.yeaftProcessingSessions=o},sendMessage(e,t=[],s={}){wu(this,e,t,s)},cancelExecution(){ku(this)},cancelYeaft(){if(!this.currentAgent)return;this.sendWsMessage({type:"yeaft_abort_all",agentId:this.currentAgent});let e=this.yeaftConversationIdsByAgent?.[this.currentAgent]||this.yeaftConversationId;e&&delete this.processingConversations[e],lp(this,this.currentAgent)},cancelYeaftSession(e){let t=be(this,e);!t||!e||(this.sendWsMessage({type:"yeaft_abort_all",agentId:t,sessionId:e}),this.activeVpTurns=Object.fromEntries(Object.entries(this.activeVpTurns||{}).filter(([,s])=>!st(s,e,t))),this.stoppingVpTurnIds=Object.fromEntries(Object.entries(this.stoppingVpTurnIds||{}).filter(([s])=>this.activeVpTurns?.[s])),this.vpStatuses=Object.fromEntries(Object.entries(this.vpStatuses||{}).filter(([,s])=>!st(s,e,t))),this.clearYeaftSessionProcessingIfIdle(e,{agentId:t,ignoreStatuses:!0}))},cancelVpTurn(e,{sessionId:t=null,vpId:s=null}={}){let n=be(this,t);if(!n||!e)return;let r=hn(this,n,e);this.stoppingVpTurnIds={...this.stoppingVpTurnIds,[r]:Date.now()};let i={type:"yeaft_abort_turn",agentId:n,turnId:e};t&&(i.sessionId=t),s&&(i.vpId=s),this.sendWsMessage(i)},cancelVpTurnForSession(e,t=null){if(!e)return!1;let s=t||this.yeaftActiveSessionFilter||null;if(!s)return!1;let n=be(this,s);if(!n)return!1;let r=this.activeVpTurns||{},i=null,o=-1/0;for(let[a,l]of Object.entries(r)){if(!l||l.vpId!==e||!st(l,s,n))continue;let c=typeof l.startedAt=="number"?l.startedAt:0;c>=o&&(o=c,i=a)}if(!i){let a=this.vpStatuses?.[Ai(n,s,e)]||null;a?.turnId&&!["idle","offline"].includes(a.state)&&(i=a.turnId)}if(i){let a=r[i]?.turnId||i;return this.cancelVpTurn(a,{sessionId:s,vpId:e}),!0}return this.sendWsMessage({type:"yeaft_abort_turn",agentId:n,sessionId:s,vpId:e}),!0},answerUserQuestion(e,t,s){Su(this,e,t,s)},refreshAgents(){Tu(this)},refreshConversation(){Mu(this)},restartAgent(e){Pu(this,e)},upgradeAgent(e){Ru(this,e)},loadMoreMessages(){if(this.currentView==="yeaft"||this.loadingMoreMessages||!this.hasMoreMessages||!this.currentConversation)return;this.loadingMoreMessages=!0;let e=this._loadMoreGeneration=(this._loadMoreGeneration||0)+1,s=(this.messagesMap[this.currentConversation]||[]).find(i=>i.dbMessageId),n=this.currentConversation,r=s?.dbMessageId??null;this.requestChatHistory(n,{mode:"older",turns:5,beforeId:r}),setTimeout(()=>{this._loadMoreGeneration===e&&this.loadingMoreMessages&&this.currentConversation===n&&(this.loadingMoreMessages=!1)},1e4)},reloadYeaftMessages(){if(this.currentView!=="yeaft")return!1;let e=Fs(this),t=be(this,e);if(!t)return!1;let s=ve(t,e),n=this.yeaftConversationId,r=this.yeaftSessionHistoryState?.[s];if(r?.loading)return r.requestId||!1;let i=this.beginYeaftHistoryLoad({agentId:t,sessionId:e,mode:"recent",preserveLoaded:!1});if(!i)return!1;let o=_s();this.yeaftHistoryPerfTraceBySession={...this.yeaftHistoryPerfTraceBySession||{},[s]:o};let a={type:"yeaft_load_history",agentId:t,limit:xi,sessionId:e,requestId:i.requestId,perfTraceId:o};return Ge(this,{traceId:o,phase:"history.request_send",agentId:t,sessionId:e,messageType:a.type,bytes:JSON.stringify(a).length,detail:{mode:"manual-reload",limit:xi}}),this.sendWsMessage(a)?!0:(Un(this,{agentId:t,sessionId:e,requestId:i.requestId,error:"history_load_send_failed"}),!1)},loadMoreYeaftHistory(e=br()){if(this.currentView!=="yeaft"||this.yeaftLoadingMoreHistory||!this.yeaftHasMoreHistory)return;let t=Fs(this),s=be(this,t);if(!s)return;let n=Math.min(50,Math.max(1,Number.isFinite(e)?Math.floor(e):br())),r=ve(s,t),i=this.yeaftHistoryCacheState?.[r]?.ranges||[],o=this.yeaftSessionHistoryState?.[r]||{},a=Number(this.yeaftHistoryCacheState?.[r]?.rangeEpoch)||0,l=Pd(o,i,a);if(this.yeaftSessionHistoryState={...this.yeaftSessionHistoryState||{},[r]:l.state},!l.request){this.syncActiveYeaftHistoryLoad();return}let c=this.beginYeaftHistoryLoad({agentId:s,sessionId:t,mode:"older",preserveLoaded:!0,latestSeq:this.yeaftSessionHistoryState[r]?.latestSeq??null});if(!c)return;let d=_s();this.yeaftHistoryPerfTraceBySession={...this.yeaftHistoryPerfTraceBySession||{},[r]:d};let u={type:"yeaft_load_more_history",agentId:s,sessionId:t,requestId:c.requestId,beforeSeq:l.request.beforeSeq,pageKind:l.request.kind,gapStopAtSeq:l.request.stopAtSeq,cacheEpoch:l.request.cacheEpoch,turns:n,perfTraceId:d};Ge(this,{traceId:d,phase:"history_more.request_send",agentId:s,sessionId:t,messageType:u.type,bytes:JSON.stringify(u).length,detail:{beforeSeq:u.beforeSeq,turns:u.turns,pageKind:l.request.kind,gapStopAtSeq:l.request.stopAtSeq}}),this.sendWsMessage(u)},checkPendingRecovery(){qc(this)},performRecovery(){Wc(this)},dismissRecovery(){jc(this)},autoRestoreConversation(e){Uc(this,e)},saveOpenSessions(){xs(this)},getLastSession(){return zc(this)},clearLastSession(){Yc(this)},listHistorySessions(e){Gc(this,e)},listFolders(){return Qc(this)},listFoldersForAgent(e,t){return Zc(this,e,t)},listModelsForAgent(e,t){return Xc(this,e,t)},listHistorySessionsForAgent(e,t,s){Jc(this,e,t,s)},async loadGlobalSessions(e=20){return ed(this,e)},async deleteGlobalSession(e){return td(this,e)},findAgentForSession(e){return ca(this,e)},isSessionResumable(e){return sd(this,e)},_isRecentlyClosed(e){return Rs(this,e)},_startProcessingWatchdog(e){an(this,e)},_resetProcessingWatchdog(e){pi(this,e)},_stopProcessingWatchdog(e){Ce(this,e)},startRefreshTimeout(e){let t=e||this.currentConversation;t&&(this._refreshTimeouts||(this._refreshTimeouts={}),this._refreshTimeouts[t]&&clearTimeout(this._refreshTimeouts[t]),this._refreshTimeouts[t]=setTimeout(()=>{this.setRefreshingSession(t,!1),delete this._refreshTimeouts[t]},1e4))},toggleTheme(){this.theme=this.theme==="dark"?"light":"dark",this.themeFollowSystem=!1,localStorage.setItem("theme",this.theme),document.documentElement.setAttribute("data-theme",this.theme),document.documentElement.classList.toggle("light",this.theme==="light")},initTheme(){if(document.documentElement.setAttribute("data-theme",this.theme),document.documentElement.classList.toggle("light",this.theme==="light"),this.themeFollowSystem&&typeof window<"u"&&window.matchMedia){let e=window.matchMedia("(prefers-color-scheme: dark)"),t=s=>{this.themeFollowSystem&&(this.theme=s.matches?"dark":"light",document.documentElement.setAttribute("data-theme",this.theme),document.documentElement.classList.toggle("light",this.theme==="light"))};e.addEventListener?e.addEventListener("change",t):e.addListener&&e.addListener(t)}},loadModelsDevRegistry({forceRefresh:e=!1}={}){let t=this.modelsDevRegistry.loaded&&!this.modelsDevRegistry.error&&Date.now()-this.modelsDevRegistry.fetchedAt<36e5;if(!e&&t)return Promise.resolve(this.modelsDevRegistry);let s=this.currentAgent;if(!s)return Promise.resolve(this.modelsDevRegistry);if(this._modelsDevPending&&(!e||this._modelsDevPending.force))return new Promise(n=>this._modelsDevPending.resolvers.push(n));if(this._modelsDevPending){let n=this._modelsDevPending;this._modelsDevPending=null,n.timer&&clearTimeout(n.timer);for(let r of n.resolvers)r(this.modelsDevRegistry)}return new Promise(n=>{let r={resolvers:[n],force:e,timer:null};this._modelsDevPending=r;try{this.sendWsMessage({type:"get_models_dev_registry",agentId:s,forceRefresh:e})}catch{this._modelsDevPending===r&&(this._modelsDevPending=null),n(this.modelsDevRegistry);return}r.timer=setTimeout(()=>{if(this._modelsDevPending===r){this._modelsDevPending=null;for(let i of r.resolvers)i(this.modelsDevRegistry)}},2e4)})},changeLocale(e){if(this.locale=e,Jn(e),this.currentAgent)try{this.sendWsMessage({type:"update_llm_config",agentId:this.currentAgent,config:{language:e}})}catch{}},async fetchCustomExpertRoles(){let e=De();try{let t={};e.token&&(t.Authorization=`Bearer ${e.token}`);let s=await fetch("/api/expert-roles/custom",{headers:t});if(s.ok){let n=await s.json();this.customExpertRoles=n.roles||[]}}catch{}},async createCustomExpertRole(e){let t=De();try{let s={"Content-Type":"application/json"};t.token&&(s.Authorization=`Bearer ${t.token}`);let n=await fetch("/api/expert-roles/custom",{method:"POST",headers:s,body:JSON.stringify(e)});if(n.ok){let r=await n.json();return this.customExpertRoles.push(r.role),r.role}else{let r=await n.json().catch(()=>({}));throw new Error(r.error||"Failed to create custom expert role")}}catch(s){throw s}},async updateCustomExpertRole(e,t){let s=De();try{let n={"Content-Type":"application/json"};s.token&&(n.Authorization=`Bearer ${s.token}`);let r=await fetch(`/api/expert-roles/custom/${e}`,{method:"PUT",headers:n,body:JSON.stringify(t)});if(r.ok){let i=await r.json(),o=this.customExpertRoles.findIndex(a=>a.id===e);return o!==-1&&(this.customExpertRoles[o]=i.role),i.role}else{let i=await r.json().catch(()=>({}));throw new Error(i.error||"Failed to update custom expert role")}}catch(n){throw n}},async deleteCustomExpertRole(e){let t=De();try{let s={};t.token&&(s.Authorization=`Bearer ${t.token}`);let n=await fetch(`/api/expert-roles/custom/${e}`,{method:"DELETE",headers:s});if(n.ok)return this.customExpertRoles=this.customExpertRoles.filter(r=>r.id!==e),!0;{let r=await n.json().catch(()=>({}));throw new Error(r.error||"Failed to delete custom expert role")}}catch(s){throw s}},toggleWorkbench(){this.workbenchExpanded=!this.workbenchExpanded,this.workbenchExpanded||(this.workbenchMaximized=!1)},toggleSidebar(){this.sidebarCollapsed=!this.sidebarCollapsed},toggleSessionSidebar(){this.sessionSidebarOpen=!this.sessionSidebarOpen},closeSessionSidebar(){this.sessionSidebarOpen=!1},toggleWorkbenchMaximized(){this.workbenchMaximized=!this.workbenchMaximized},renameChatSession(e,t,s=null){let n=t&&t.trim()?t.trim():"";n?this.customConversationTitles[e]=n:delete this.customConversationTitles[e],this.sendWsMessage({type:"update_conversation_settings",conversationId:e,...s?{agentId:s}:{},title:n})},openFileInExplorer(e){this.currentConversation&&(this.workbenchExpanded=!0,window.dispatchEvent(new CustomEvent("open-file-in-explorer",{detail:{filePath:e,conversationId:this.currentConversation}})))},logout(){De().logout(),this.authenticated=!1,this.sessionKey=null,this.agents=[],this.currentAgent=null,this.currentAgentInfo=null,this.yeaftStatusByAgent={},this._yeaftRetiredCatalogEpochsByAgent={},this.conversations=[],this.activeConversations=[],this.messagesMap={},this.conversationTitles={},this.customConversationTitles={},this.processingConversations={},this.executionStatusMap={},this.workbenchExpanded=!1,this.subagents={},this.activeSubagentId=null,this.activeRightPanel=null,this.pinnedSessions=[],this.clearWorkCenterBrowserState(),this.ws&&this.ws.close()}}})});function tl(e,t){!e||typeof e.handleYeaftOutput!="function"||!t||e.handleYeaftOutput({event:t})}function $y(e){let t=String(e||""),s=2166136261;for(let n=0;n<t.length;n++)s^=t.charCodeAt(n),s=Math.imul(s,16777619)>>>0;return s>>>0}function nl(e){if(!e)return ds[0];let t=String(e).toLowerCase();return Ly[t]||ds[$y(t)%ds.length]}function Vy(e){return nl(e).background}function Hy(e){return nl(e).foreground}function sl(){let e=typeof window<"u"&&window.Pinia&&window.Pinia.useChatStore?window.Pinia.useChatStore():null;return e&&typeof e.locale=="string"?e.locale:typeof localStorage<"u"&&localStorage.getItem("locale")||""}function Oy(e,t=""){return e?String(t||"").startsWith("zh")?e.descriptionZh||e.roleZh||e.description||e.role||"":e.description||e.role||e.descriptionZh||e.roleZh||"":""}var Dy,ds,Ly,NS,Rt,vn=N(()=>{({defineStore:Dy}=Pinia);ds=[{key:"rat",label:"Rat",glyph:"R",background:"var(--vp-avatar-rat-bg)",foreground:"var(--vp-avatar-rat-fg)"},{key:"ox",label:"Ox",glyph:"O",background:"var(--vp-avatar-ox-bg)",foreground:"var(--vp-avatar-ox-fg)"},{key:"tiger",label:"Tiger",glyph:"T",background:"var(--vp-avatar-tiger-bg)",foreground:"var(--vp-avatar-tiger-fg)"},{key:"rabbit",label:"Rabbit",glyph:"B",background:"var(--vp-avatar-rabbit-bg)",foreground:"var(--vp-avatar-rabbit-fg)"},{key:"dragon",label:"Dragon",glyph:"D",background:"var(--vp-avatar-dragon-bg)",foreground:"var(--vp-avatar-dragon-fg)"},{key:"snake",label:"Snake",glyph:"S",background:"var(--vp-avatar-snake-bg)",foreground:"var(--vp-avatar-snake-fg)"},{key:"horse",label:"Horse",glyph:"H",background:"var(--vp-avatar-horse-bg)",foreground:"var(--vp-avatar-horse-fg)"},{key:"goat",label:"Goat",glyph:"G",background:"var(--vp-avatar-goat-bg)",foreground:"var(--vp-avatar-goat-fg)"},{key:"monkey",label:"Monkey",glyph:"M",background:"var(--vp-avatar-monkey-bg)",foreground:"var(--vp-avatar-monkey-fg)"},{key:"rooster",label:"Rooster",glyph:"K",background:"var(--vp-avatar-rooster-bg)",foreground:"var(--vp-avatar-rooster-fg)"},{key:"dog",label:"Dog",glyph:"D",background:"var(--vp-avatar-dog-bg)",foreground:"var(--vp-avatar-dog-fg)"},{key:"pig",label:"Pig",glyph:"P",background:"var(--vp-avatar-pig-bg)",foreground:"var(--vp-avatar-pig-fg)"}],Ly=Object.freeze({steve:ds[8],ada:ds[3],linus:ds[0],martin:ds[4]}),NS=ds.map(e=>e.background);Rt=Dy("vp",{state:()=>({vps:{},vpOrder:[],emptyLibrary:!1,lastSnapshotAt:0,snapshotStatus:"idle",snapshotAgentId:null,snapshotRequestId:null,snapshotError:"",lastVpSnapshotAgentId:null,lastChange:null,dreamStatus:{},groupDreamStatus:{}}),getters:{vpList(e){return e.vpOrder.map(t=>e.vps[t]).filter(Boolean)},vpCount(e){return e.vpOrder.length},vpById:e=>t=>e.vps[t]||null,vpLabel:e=>t=>{let s=e.vps[t];return s?sl().startsWith("zh")&&s.displayNameZh?s.displayNameZh:s.displayName||s.vpId||t:t},vpDescription:e=>t=>Oy(e.vps[t],sl()),vpInitial:e=>t=>{let s=e.vps[t],n=sl().startsWith("zh"),r=s&&(s.avatar||n&&s.displayNameZh||s.displayName||s.vpId)||t||"?";return String(r).charAt(0).toUpperCase()||"?"},vpColor:e=>t=>{let s=e.vps[t];return s&&s.color?s.color:Vy(t)},vpTextColor:()=>e=>Hy(e),vpAvatarMotif:()=>e=>nl(e),dreamStatusFor:e=>t=>e.dreamStatus[t]||{status:"idle",lastRunAt:null,lastResult:null,lastError:null},groupDreamStatusFor:e=>t=>e.groupDreamStatus[t]||{status:"idle",lastRunAt:null,lastResult:null,lastError:null}},actions:{applySnapshot(e,t=null,s=null){let n=this.snapshotAgentId||null;if(n&&t&&t!==n||s&&this.snapshotRequestId&&s!==this.snapshotRequestId)return!1;let r=e&&Array.isArray(e.vps)?e.vps:[];return this._setActiveSnapshot({vps:r,emptyLibrary:!!(e&&e.emptyLibrary),agentId:t||n||null,requestId:s||this.snapshotRequestId||null,receivedAt:Date.now()}),!0},beginSnapshot(e,t){this.vps={},this.vpOrder=[],this.emptyLibrary=!1,this.lastVpSnapshotAgentId=null,this.snapshotStatus="loading",this.snapshotAgentId=e||null,this.snapshotRequestId=t||null,this.snapshotError=""},failSnapshot(e,t,s=""){return!this.snapshotRequestId||!t||t!==this.snapshotRequestId||e&&this.snapshotAgentId&&e!==this.snapshotAgentId?!1:(this.snapshotStatus="error",this.snapshotAgentId=e||this.snapshotAgentId||null,this.snapshotRequestId=t||this.snapshotRequestId||null,this.snapshotError=String(s||"VP library request failed"),!0)},_setActiveSnapshot({vps:e,emptyLibrary:t,agentId:s,requestId:n,receivedAt:r}){this.vps={},this.vpOrder=[];for(let i of e||[])this._upsertInternal(i);this.emptyLibrary=!!t,this.lastSnapshotAt=r||Date.now(),this.lastVpSnapshotAgentId=s||null,this.snapshotStatus="ready",this.snapshotAgentId=s||null,this.snapshotRequestId=n||null,this.snapshotError=""},upsert(e,t=null,s=null){return s&&this.snapshotAgentId&&s!==this.snapshotAgentId?!1:(this._upsertInternal(e),e&&e.vpId&&(this.lastChange={vpId:e.vpId,kind:"updated",reason:t||null,at:Date.now()}),!0)},remove(e,t=null,s=null){return s&&this.snapshotAgentId&&s!==this.snapshotAgentId||!e?!1:(delete this.vps[e],this.vpOrder=this.vpOrder.filter(n=>n!==e),this.lastChange={vpId:e,kind:"removed",reason:t||"file.removed",at:Date.now()},!0)},_upsertInternal(e){if(!e||!e.vpId)return;let t=!!this.vps[e.vpId];this.vps[e.vpId]={...this.vps[e.vpId]||{},...e},t||this.vpOrder.push(e.vpId),this.emptyLibrary&&(this.emptyLibrary=!1)},triggerDream(e){if(!e)return;this.dreamStatus={...this.dreamStatus,[e]:{...this.dreamStatus[e]||{},status:"running",lastError:null}};let t=window.Pinia&&window.Pinia.useChatStore?window.Pinia.useChatStore():null;t&&typeof t.sendWsMessage=="function"&&t.sendWsMessage({type:"yeaft_dream_trigger",vpId:e})},triggerGroupDream(e,t={}){if(!e)return;this.groupDreamStatus={...this.groupDreamStatus,[e]:{...this.groupDreamStatus[e]||{},status:"running",lastError:null}};let s=window.Pinia&&window.Pinia.useChatStore?window.Pinia.useChatStore():null,n=Date.now();if(tl(s,{type:"dream_progress",phase:"start",groupId:e,manual:!0,trigger:"manual",source:"header-button",ts:n}),!s||typeof s.sendWsMessage!="function"){tl(s,{type:"yeaft_dream_result",groupId:e,success:!1,skipped:!0,skippedReason:"chat-store-unavailable",trigger:"manual",error:null});return}let r={type:"yeaft_dream_trigger",sessionId:e},i=t&&t.agentId?t.agentId:typeof s.agentIdForSession=="function"?s.agentIdForSession(e):s.currentAgent;i&&(r.agentId=i),s.sendWsMessage(r)===!1&&tl(s,{type:"yeaft_dream_result",groupId:e,success:!1,skipped:!0,skippedReason:"websocket-not-open",trigger:"manual",error:null})},applyDreamStatus(e){if(!e)return;let t=e.sessionId;if(t){this.groupDreamStatus={...this.groupDreamStatus,[t]:{...this.groupDreamStatus[t]||{},status:e.status==="running"?"running":e.status||"idle"}};return}if(!e.vpId)return;let s=e.vpId;this.dreamStatus={...this.dreamStatus,[s]:{...this.dreamStatus[s]||{},status:e.status==="running"?"running":e.status||"idle"}}},applyDreamResult(e){if(!e)return;let t=!!e.success,s=!!e.skipped,n={mergedCount:e.mergedCount??null,extractedCount:e.extractedCount??null,entriesCreated:typeof e.entriesCreated=="number"?e.entriesCreated:e.mergedCount??e.extractedCount??0,skipped:s,skippedReason:e.skippedReason||null,sessionsProcessed:typeof e.sessionsProcessed=="number"?e.sessionsProcessed:null,sessionsSkipped:typeof e.sessionsSkipped=="number"?e.sessionsSkipped:null,targetsApplied:typeof e.targetsApplied=="number"?e.targetsApplied:null,durationMs:typeof e.durationMs=="number"?e.durationMs:null,llmCallCount:typeof e.llmCallCount=="number"?e.llmCallCount:0,inputTokens:typeof e.inputTokens=="number"?e.inputTokens:0,outputTokens:typeof e.outputTokens=="number"?e.outputTokens:0,totalTokens:typeof e.totalTokens=="number"?e.totalTokens:0,metrics:e.metrics||null,passBreakdown:e.passBreakdown||e.metrics?.passBreakdown||null,targetErrors:Array.isArray(e.targetErrors)?e.targetErrors:[]},r=t||s?null:e.error||null,i=s?"skipped":t?"success":"error",o=e.sessionId;if(o){this.groupDreamStatus={...this.groupDreamStatus,[o]:{status:i,lastRunAt:Date.now(),lastResult:n,lastError:r}};return}if(!e.vpId)return;let a=e.vpId;this.dreamStatus={...this.dreamStatus,[a]:{status:i,lastRunAt:Date.now(),lastResult:n,lastError:r}}}}})});function rl(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e){let t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Ri(e){return!e||typeof e!="object"?0:rl(e.lastMessageAt)||rl(e.updatedAt)||rl(e.createdAt)||0}function il(e,t){let s=Ri(t)-Ri(e);return s!==0?s:String(e?.id||"").localeCompare(String(t?.id||""))}function xp(e){return[...Array.isArray(e)?e:[]].sort(il)}var _i=N(()=>{});function Tp(){try{if(typeof localStorage>"u")return{};let e=JSON.parse(localStorage.getItem(_p)||"{}");return e&&typeof e=="object"?e:{}}catch{return{}}}function Fy(e){try{typeof localStorage<"u"&&localStorage.setItem(_p,JSON.stringify(e&&typeof e=="object"?e:{}))}catch{}}function Mp(){try{return typeof localStorage>"u"?[]:Sr(JSON.parse(localStorage.getItem(Ep)||"[]"))}catch{return[]}}function By(e){try{typeof localStorage<"u"&&localStorage.setItem(Ep,JSON.stringify(Sr(e)))}catch{}}function Dp(e,t){return`${e||""}${t||""}`}function Wt(e){return e&&e.agentId&&e.id?Dp(e.agentId,e.id):""}function _t(e,t){return t?e?Dp(e,t):String(t):""}function Ny(e){return typeof e=="string"?e:String(e||"")}function dt(e,t,s=null){let n=Ny(t);if(!n)return"";let r=_t(s,n),i=r?e.sessions[r]:null;if(i&&(s||i.agentId||e.inventoryIdentityMode==="legacy-bare"))return r;if(s){let c=e.sessions[n];return e.inventoryIdentityMode==="legacy-bare"&&c&&!c.agentId?n:""}let o=e.sessions[n];if(o){if(o.agentId||e.inventoryIdentityMode==="legacy-bare")return n;let c=e.activeSessionKey?e.sessions[e.activeSessionKey]:null;return c?.agentId&&c.id===n?e.activeSessionKey:""}if(e.activeSessionKey&&e.sessions[e.activeSessionKey]?.id===n)return e.activeSessionKey;let a=e.sessionOrder.filter(c=>e.sessions[c]?.id===n),l=Ir();if(l?.currentAgent){let c=a.find(d=>e.sessions[d]?.agentId===l.currentAgent);if(c)return c}return a[0]||""}function ol(e,t,s=null){return dt(e,t,s)||""}function al(e){if(e.inventoryIdentityMode==="legacy-bare"){let t=e.activeSessionKey?e.sessions[e.activeSessionKey]:null,s=t&&!t.agentId?t:e.activeSessionId?e.sessions[e.activeSessionId]:null;e._retiredBareActiveSessionId=s&&!s.agentId&&s.id||null,e.sessionOrder=e.sessionOrder.filter(n=>e.sessions[n]?.agentId),e._retiredBareActiveSessionId&&(e.activeSessionId=null,e.activeSessionKey=null)}e.inventoryIdentityMode="agent-scoped"}function qy(e){let t=e._preferredExactSessionIdentity||null;if(!t)return!1;e._preferredExactSessionIdentity=null;let s=e.sessions[t.key]||null,n=Ir(),r=s?.id===t.sessionId&&s.agentId===t.agentId,i=n?.currentView!=="yeaft"||typeof n.setActiveSessionFilter=="function";if(r&&i){if(e.activeSessionId=t.sessionId,e.activeSessionKey=t.key,n?.currentView==="yeaft")n.setActiveSessionFilter(t.sessionId,{agentId:t.agentId,force:!0});else if(n){n.yeaftActiveSessionFilter=t.sessionId,n.yeaftSessionAgentById={...n.yeaftSessionAgentById||{},[t.sessionId]:t.agentId};try{localStorage.setItem("lastViewedYeaftSession",t.key)}catch{}}return!0}if(e.activeSessionId=null,e.activeSessionKey=null,n?.yeaftActiveSessionFilter===t.sessionId&&(n.yeaftActiveSessionFilter=null),n?.yeaftSessionAgentById?.[t.sessionId]===t.agentId){let o={...n.yeaftSessionAgentById};delete o[t.sessionId],n.yeaftSessionAgentById=o}try{let o=gr(localStorage.getItem("lastViewedYeaftSession")||"");o.agentId===t.agentId&&o.sessionId===t.sessionId&&localStorage.removeItem("lastViewedYeaftSession")}catch{}return!0}function Ei(e){let t=e._retiredBareActiveSessionId||null;if(!t)return!1;let s=Ir();if(e.inventoryIdentityMode==="legacy-bare"){let r=e.sessions[t];return e._retiredBareActiveSessionId=null,!r||r.agentId?!1:(e.activeSessionId=t,e.activeSessionKey=t,s?.currentView==="yeaft"&&typeof s.setActiveSessionFilter=="function"?s.setActiveSessionFilter(t,{force:!0}):s&&(s.yeaftActiveSessionFilter=t),!0)}let n=e.sessionOrder.filter(r=>{let i=e.sessions[r];return i?.agentId&&i.id===t});if(n.length===1){let r=n[0],i=e.activeSessionId===t&&e.activeSessionKey===r,o=e.sessions[r]?.agentId||null;return e.activeSessionId=t,e.activeSessionKey=r,i||(s?.currentView==="yeaft"&&typeof s.setActiveSessionFilter=="function"?(s.setActiveSessionFilter(t,{agentId:o,force:!0}),e._retiredBareActiveSessionId=t):s&&(s.yeaftActiveSessionFilter=t)),!0}e.activeSessionId=null,e.activeSessionKey=null,s?.yeaftActiveSessionFilter===t&&(s.yeaftActiveSessionFilter=null);try{let r=localStorage.getItem("lastViewedYeaftSession")||"";gr(r).sessionId===t&&localStorage.removeItem("lastViewedYeaftSession")}catch{}return!0}function Sr(e){let t=[],s=new Set;for(let n of Array.isArray(e)?e:[]){let r=typeof n=="string"?n:String(n||"");!r||s.has(r)||(s.add(r),t.push(r))}return t}function ll(e,t){let s=Sr(e),n=new Set(s),r=Sr(t).filter(o=>n.has(o)),i=new Set(r);return[...r,...s.filter(o=>!i.has(o))]}function Di(e,t=!1){return!e||typeof e!="object"?!!t:Object.prototype.hasOwnProperty.call(e,"pinned")?e.pinned===!0:Object.prototype.hasOwnProperty.call(e,"isPinned")?e.isPinned===!0:!!t}function Pp(e){return!e||typeof e!="object"?!1:e.running===!0||e.active===!0||e.isActive===!0||e.isRunning===!0}function Rp(e){if(!e||typeof e!="object")return 0;let t=e.latestActivityAt||e.lastActivityAt||e.lastMessageAt||e.updatedAt||0;if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t){let s=Date.parse(t);return Number.isFinite(s)?s:0}return 0}function Ir(){try{if(typeof window<"u"&&window.Pinia&&typeof window.Pinia.useChatStore=="function")return window.Pinia.useChatStore()}catch{}return null}var _p,Ep,Wy,Lp,$p=N(()=>{_i();mr();_p="yeaft-session-order-by-agent",Ep="yeaft-session-order-global";({defineStore:Wy}=Pinia);Lp=Wy("sessions",{state:()=>({sessions:{},sessionOrder:[],activeSessionId:null,activeSessionKey:null,inventoryIdentityMode:"empty",_retiredBareActiveSessionId:null,_preferredExactSessionIdentity:null,lastSnapshotAt:0,lastCrudResult:null,pending:{}}),getters:{sessionList(e){let t=e.sessionOrder.map(d=>e.sessions[d]).filter(Boolean),s=Ir(),n=s&&Array.isArray(s.pinnedSessions)?new Set(s.pinnedSessions):new Set;for(let d of t)d&&d.id&&d.pinned&&n.add(d.id);let r=[],i=[];for(let d of t)d.pinned||!d.agentId&&n.has(d.id)?r.push(d):i.push(d);let o=d=>[...d].sort((u,f)=>{let p=Number.isFinite(u?.sortOrder)?u.sortOrder:Number.MAX_SAFE_INTEGER,g=Number.isFinite(f?.sortOrder)?f.sortOrder:Number.MAX_SAFE_INTEGER;return p!==g?p-g:il(u,f)}),a=[...o(r),...o(i)],l=Mp();if(l.length===0)return a;let c=new Map(l.map((d,u)=>[d,u]));return a.sort((d,u)=>{let f=c.has(Wt(d))?c.get(Wt(d)):Number.MAX_SAFE_INTEGER,p=c.has(Wt(u))?c.get(Wt(u)):Number.MAX_SAFE_INTEGER;return f!==p?f-p:0})},sessionCount(e){return e.sessionOrder.length},sessionById:e=>(t,s=null)=>{let n=dt(e,t,s);return n&&e.sessions[n]||null},activeSession(e){return e.activeSessionKey&&e.sessions[e.activeSessionKey]||null},hasLoadedSnapshot(e){return e.lastSnapshotAt>0},isEmpty(e){return e.sessionOrder.length===0},activeNeedsInvite(e){let t=e.activeSessionKey?e.sessions[e.activeSessionKey]:null;return t?!t.defaultVpId&&(!Array.isArray(t.roster)||t.roster.length===0):!1}},actions:{applySnapshot(e,t=null,{deferActivation:s=!1}={}){let n=Array.isArray(e)?e:[],r=!1;if(t){al(this);let o={...this.sessions},a=new Set;for(let p of n){if(!p||!p.id)continue;let g=_t(t,p.id);a.add(g),o[g]=this._normalize(p,t,Di(this.sessions[g]))}for(let p of this.sessionOrder){let g=this.sessions[p];g&&g.agentId===t&&!a.has(p)&&delete o[p]}let l=this.sessionOrder.filter(p=>o[p]),c=new Set(l),d=[];for(let p of n){if(!p||!p.id)continue;let g=_t(t,p.id);o[g]&&!c.has(g)&&d.push(g)}this.sessions=o;let u=[...l,...d],f=Mp();if(f.length>0){let p=new Map(u.map(k=>[Wt(o[k]),k]).filter(([k])=>k)),g=f.map(k=>p.get(k)).filter(Boolean),m=new Set(g);u=[...g,...u.filter(k=>!m.has(k))];let v=new Map(f.map((k,w)=>[k,w]));for(let k of u){let w=Wt(o[k]);w&&v.has(w)&&(o[k]={...o[k],sortOrder:v.get(w)})}}if(t&&f.length===0){let p=Tp(),g=Sr(p[t]);if(g.length>0){let m=g.map(y=>_t(t,y)),v=new Set(m),k=ll(u.filter(y=>o[y]?.agentId===t),m),w=this.sessionOrder.some(y=>o[y]?.agentId===t),I=0;w?u=this.sessionOrder.filter(y=>o[y]).map(y=>o[y]?.agentId===t?k[I++]:y).concat(k.slice(I)):u=u.map(y=>o[y]?.agentId===t?k[I++]:y);let h=new Map(m.map((y,b)=>[y,b]));for(let y of k)o[y]&&v.has(y)&&(o[y]={...o[y],sortOrder:h.get(y)})}}this.sessionOrder=u}else{if(this.inventoryIdentityMode==="agent-scoped")return;if(Object.values(this.sessions).some(c=>c&&c.agentId)){this.inventoryIdentityMode="agent-scoped";return}let a={},l=[];for(let c of n){if(!c||!c.id)continue;let d=_t(null,c.id);a[d]=this._normalize(c,null,Di(this.sessions[d])),l.push(d)}this.sessions=a,this.sessionOrder=l,this.inventoryIdentityMode="legacy-bare"}s||(r=qy(this)||Ei(this)),this.lastSnapshotAt=Date.now();let i=Ir();if(i&&t){let o={...i.yeaftSessionAgentById||{}};for(let a of n)a&&a.id&&!o[a.id]&&(o[a.id]=t);i.yeaftSessionAgentById=o}if(!s&&!r){let o=null;try{o=localStorage.getItem("lastViewedYeaftSession")||null}catch{}let l=(o?this.sessions[o]:null)?o:o?dt(this,o,t):"",c=l?this.sessions[l]:null,d=c&&(!t||c.agentId===t),u=this.sessionOrder.filter(I=>this.sessions[I]&&(!t||this.sessions[I].agentId===t)&&this.sessions[I].running).sort((I,h)=>Rp(this.sessions[h])-Rp(this.sessions[I]))[0]||null,f=u?this.sessions[u]?.id:null,p=this.sessionList[0]||null,g=p?.id||null,m=g?dt(this,g,p?.raw?.agentId||null):"",v=f||(d?c.id:null)||g,k=u||(d?l:"")||m||ol(this,v,t),w=this.activeSessionKey?this.sessions[this.activeSessionKey]?.agentId:null;if(this.activeSessionId&&!dt(this,this.activeSessionId,w)?(this.activeSessionId=v,this.activeSessionKey=k||null):!this.activeSessionId&&this.sessionOrder.length>0&&!this._retiredBareActiveSessionId?(this.activeSessionId=v,this.activeSessionKey=k||null):this.activeSessionId&&(this.activeSessionKey=ol(this,this.activeSessionId,w)||this.activeSessionKey),i&&!this._retiredBareActiveSessionId){let I=this.activeSessionId||v,h=null;if((i.yeaftActiveSessionFilter&&!dt(this,i.yeaftActiveSessionFilter)||!i.yeaftActiveSessionFilter&&I)&&(h=I),h){let y=ol(this,h),b=y&&this.sessions[y]?.agentId||null;i.currentView==="yeaft"&&typeof i.setActiveSessionFilter=="function"?i.setActiveSessionFilter(h,{agentId:b,force:!0}):i.yeaftActiveSessionFilter=h,this.activeSessionKey=y||this.activeSessionKey}}}if(i&&typeof i.applyServerPinSnapshot=="function"){let o=new Set;for(let l of n){if(!l||!l.id)continue;let c=_t(t,l.id),d=this.sessions[c];d&&d.pinned&&o.add(l.id)}let a=l=>{let c=dt(this,l,t),d=c?this.sessions[c]:null;return d?d.agentId===t:!1};i.applyServerPinSnapshot(t,o,a)}},applyRosterChange(e,t=null){if(!e)return;let s=e.sessionId||e.groupId;if(!s)return;let n=t||e.agentId||null;if(n)al(this);else if(this.inventoryIdentityMode!=="legacy-bare")return;let r=dt(this,s,n)||_t(n,s),i=this.sessions[r];if(!i){let o=this._normalize({id:s,name:e.name||s,roster:Array.isArray(e.roster)?e.roster:[],defaultVpId:e.defaultVpId||null},n);this.sessions[r]=o,this.sessionOrder.push(r),Ei(this);return}this.sessions[r]={...i,name:e.name||i.name,roster:Array.isArray(e.roster)?e.roster.slice():i.roster,defaultVpId:e.defaultVpId!=null?e.defaultVpId:i.defaultVpId,announcement:typeof e.announcement=="string"?e.announcement:i.announcement},Ei(this)},applyCrudResult(e,t=null){if(!e)return;this.lastCrudResult={...e,at:Date.now()},e.requestId&&this.pending[e.requestId]&&delete this.pending[e.requestId];let s=e.session||e.group||null,n=t||e.agentId||s?.agentId||null;e.ok&&e.op==="list"&&Array.isArray(e.sessions)&&this.applySnapshot(e.sessions,n),e.ok&&(e.op==="create"||e.op==="restore")&&s&&s.id&&this.applySnapshotUpsert(s,n)&&this.setActive(s.id,n);let r=e.sessionId||e.groupId,i=this.inventoryIdentityMode==="legacy-bare",o=r&&(n||i)?dt(this,r,n):"";if(e.ok&&(e.op==="archive"||e.op==="delete")&&r&&o&&(delete this.sessions[o],this.sessionOrder=this.sessionOrder.filter(a=>a!==o),(this.activeSessionKey===o||i&&this.activeSessionId===r)&&(this.activeSessionKey=this.sessionOrder[0]||null,this.activeSessionId=this.activeSessionKey&&this.sessions[this.activeSessionKey]?.id||null)),e.ok&&e.op==="update_config"&&r){let a=o?this.sessions[o]:null;a&&(this.sessions[o]={...a,config:e.config&&typeof e.config=="object"?{...e.config}:{}})}},applySnapshotUpsert(e,t=null){if(!e||!e.id)return"";let s=t||e.agentId||null;if(s)al(this);else if(this.inventoryIdentityMode!=="legacy-bare")return"";let n=dt(this,e.id,s)||_t(s,e.id),r=!!this.sessions[n],i=this.sessions[n]||{};return this.sessions[n]={...i,...this._normalize(e,s,Di(i))},r||this.sessionOrder.push(n),Ei(this),n},setActive(e,t=null){let s=dt(this,e,t);e&&s&&this.sessions[s]?(this.activeSessionId=e,this.activeSessionKey=s,this._retiredBareActiveSessionId=null):(this.activeSessionId=null,this.activeSessionKey=null)},reorderSessionsForAgent(e,t){if(!e)return[];let s=this.sessionOrder.filter(l=>this.sessions[l]?.agentId===e),n=ll(s,t.map(l=>_t(e,l)));if(n.length===0)return[];let r=new Map(n.map((l,c)=>[l,c])),i=0;this.sessionOrder=this.sessionOrder.map(l=>this.sessions[l]?.agentId===e?n[i++]:l);for(let l of n)this.sessions[l]={...this.sessions[l],sortOrder:r.get(l)};let o=Tp(),a=n.map(l=>this.sessions[l]?.id).filter(Boolean);return o[e]=a,Fy(o),a},reorderSessionsGlobally(e){let t=this.sessionOrder.map(a=>Wt(this.sessions[a])).filter(Boolean),s=ll(t,e);if(s.length===0)return[];let n=new Map(this.sessionOrder.map(a=>[Wt(this.sessions[a]),a]).filter(([a])=>a)),r=s.map(a=>n.get(a)).filter(Boolean),i=new Set(r);this.sessionOrder=[...r,...this.sessionOrder.filter(a=>!i.has(a))];let o=new Map(s.map((a,l)=>[a,l]));for(let a of this.sessionOrder){let l=Wt(this.sessions[a]);l&&o.has(l)&&(this.sessions[a]={...this.sessions[a],sortOrder:o.get(l)})}return By(s),s.map(a=>{let l=n.get(a),c=l?this.sessions[l]:null;return c?{agentId:c.agentId,sessionId:c.id}:null}).filter(Boolean)},applyPinState(e,t,s=null){if(!s&&this.inventoryIdentityMode!=="legacy-bare")return;let n=dt(this,e,s);!e||!n||!this.sessions[n]||(this.sessions[n]={...this.sessions[n],pinned:!!t})},markPending(e,t){e&&(this.pending[e]=t)},clearLastResult(){this.lastCrudResult=null},resetInventory(){this.sessions={},this.sessionOrder=[],this.activeSessionId=null,this.activeSessionKey=null,this.inventoryIdentityMode="empty",this._retiredBareActiveSessionId=null,this._preferredExactSessionIdentity=null,this.lastSnapshotAt=0},beginInventoryCommit(e=null,t=null){if(this.resetInventory(),e&&t){let s=_t(t,e);this.activeSessionId=e,this.activeSessionKey=s,this._preferredExactSessionIdentity={sessionId:e,agentId:t,key:s}}else e&&(this._retiredBareActiveSessionId=e)},_normalize(e,t=null,s=!1){return{id:e.id,name:e.name||e.id,roster:Array.isArray(e.roster)?e.roster.slice():[],defaultVpId:e.defaultVpId||null,announcement:typeof e.announcement=="string"?e.announcement:"",config:e.config&&typeof e.config=="object"?{...e.config}:{},workDir:typeof e.workDir=="string"?e.workDir:"",createdAt:e.createdAt||null,updatedAt:e.updatedAt||null,lastMessageAt:e.lastMessageAt||null,running:Pp(e),active:Pp(e),runningVpCount:Number.isFinite(Number(e.runningVpCount))?Number(e.runningVpCount):0,latestActivityAt:e.latestActivityAt||e.lastActivityAt||e.lastMessageAt||null,agentId:t||e.agentId||null,pinned:Di(e,s),sortOrder:Number.isFinite(e.sortOrder)?e.sortOrder:null}}}})});function Li(){try{if(window.Pinia&&typeof window.Pinia.useAuthStore=="function")return window.Pinia.useAuthStore()}catch{}return null}function cl(){try{return localStorage.getItem("authToken")||null}catch{return null}}function Op(){let e=Li();if(e)try{return e.getActiveToken?.()||e.token||cl()}catch{return e.token||cl()}return cl()}function Uy(e,t){if(!e)return!1;let s=Op();if(s&&s!==t)return!1;try{localStorage.setItem("authToken",e)}catch{}let n=Li();return n&&(n.token=e),!0}function Ky(e){try{let t=typeof e=="string"?e:e?.url;return!t||typeof window>"u"||!window.location?null:new URL(t,window.location.href)}catch{return null}}function Hp(e){return!e||typeof window>"u"||!window.location?!1:e.origin===window.location.origin&&e.pathname.startsWith("/api/")}function zy(e){if(!e)return!1;let t=e.pathname;return!!(jy.has(t)||t.startsWith("/api/auth/sso/poll/")||/^\/api\/auth\/sso\/[^/]+\/start(?:-qr)?$/.test(t))}function Yy(e,t){return t?.headers?new Headers(t.headers):e&&typeof e=="object"&&e.headers?new Headers(e.headers):new Headers}function Gy(e){let t=e.get("Authorization");return!t||!t.startsWith("Bearer ")?null:t.slice(7)}function Qy(e,t){return{...e||{},headers:t}}function Zy(e,t,s,n){let r=Li();r&&typeof r.handleAuthResponse=="function"?r.handleAuthResponse(e,t,s,n):r&&typeof r.handleAuthFailure=="function"&&n&&r.handleAuthFailure(void 0,t,s)}function Fp(){if(Vp||typeof window>"u"||!window.fetch)return;Vp=!0;let e=window.fetch.bind(window);window.fetch=async function(s,n){let r=Ky(s),i=Hp(r)&&!zy(r),o=Hp(r)?{...n||{},credentials:"same-origin"}:n,a=null,l=i?Li():null,c=l?.authGeneration,d=!!l?.isAuthenticated;if(i){let f=Yy(s,n);a=Gy(f),a||(a=Op(),a&&(f.set("Authorization",`Bearer ${a}`),o=Qy(o,f)))}let u=await e(s,o);try{let f=u.headers&&u.headers.get&&u.headers.get("X-New-Token");f&&Uy(f,a),i&&u.status===401&&Zy(u,a,c,d)}catch{}return u}}var Vp,jy,Bp=N(()=>{Vp=!1,jy=new Set(["/api/auth/mode","/api/auth/login","/api/auth/aad","/api/auth/verify","/api/auth/verify-totp","/api/auth/setup-totp","/api/auth/register","/api/auth/password-reset/request","/api/auth/password-reset/verify"])});var Np,qp=N(()=>{Np={"common.loading":"\u52A0\u8F7D\u4E2D...","common.confirm":"\u786E\u5B9A","common.apply":"\u5E94\u7528","common.cancel":"\u53D6\u6D88","common.delete":"\u5220\u9664","common.copy":"\u590D\u5236","common.copied":"\u5DF2\u590D\u5236","common.close":"\u5173\u95ED","common.refresh":"\u5237\u65B0","common.open":"\u6253\u5F00","common.save":"\u4FDD\u5B58","common.search":"\u641C\u7D22","common.back":"\u8FD4\u56DE","common.noSubdirectories":"\u65E0\u5B50\u76EE\u5F55","common.drives":"\u9A71\u52A8\u5668","common.rootDir":"\u6839\u76EE\u5F55","common.comma":"\uFF0C","common.select":"\u9009\u62E9","mermaid.export":"\u5BFC\u51FA","mermaid.exportMd":"\u5BFC\u51FA MD","mermaid.exportPng":"\u5BFC\u51FA PNG","mermaid.exportJpg":"\u5BFC\u51FA JPG","chat.toolActionsOmitted":"\u5DF2\u7701\u7565 {count} \u4E2A\u5386\u53F2\u5DE5\u5177\u52A8\u4F5C","login.subtitle":"Yeaft Web Code Agent","login.username":"\u7528\u6237\u540D","login.password":"\u5BC6\u7801","login.login":"\u767B\u5F55","login.loggingIn":"\u767B\u5F55\u4E2D...","login.enterUsername":"\u8BF7\u8F93\u5165\u7528\u6237\u540D","login.enterPassword":"\u8BF7\u8F93\u5165\u5BC6\u7801","login.noAccount":"\u6CA1\u6709\u8D26\u53F7\uFF1F","login.registerWithCode":"\u6CE8\u518C\u65B0\u8D26\u53F7","login.or":"\u6216","login.usePassword":"\u4F7F\u7528\u8D26\u53F7\u5BC6\u7801\u767B\u5F55","login.useSso":"\u8FD4\u56DE\u5355\u70B9\u767B\u5F55","login.noProviders":"\u7BA1\u7406\u5458\u5C1A\u672A\u542F\u7528\u4EFB\u4F55\u7B2C\u4E09\u65B9\u767B\u5F55\u3002","login.microsoft":"\u4F7F\u7528 Microsoft \u8D26\u53F7\u767B\u5F55","login.github":"\u4F7F\u7528 GitHub \u8D26\u53F7\u767B\u5F55","login.google":"\u4F7F\u7528 Google \u8D26\u53F7\u767B\u5F55","login.wechat":"\u4F7F\u7528\u5FAE\u4FE1\u626B\u7801\u767B\u5F55","login.alipay":"\u4F7F\u7528\u652F\u4ED8\u5B9D\u8D26\u53F7\u767B\u5F55","login.wechat.mobileUnsupported":"\u5FAE\u4FE1\u767B\u5F55\u6682\u4EC5\u652F\u6301\u7535\u8111\u7AEF\uFF0C\u8BF7\u5728\u7535\u8111\u6D4F\u89C8\u5668\u4E2D\u626B\u7801\u767B\u5F55\u3002","login.alipay.mobileWaiting":"\u6B63\u5728\u7B49\u5F85\u4F60\u5728\u652F\u4ED8\u5B9D\u4E2D\u786E\u8BA4\u2026 \u5B8C\u6210\u540E\u8FD4\u56DE\u672C\u9875\u9762\u5C06\u81EA\u52A8\u767B\u5F55\u3002","login.alipay.relaunch":"\u91CD\u65B0\u6253\u5F00\u652F\u4ED8\u5B9D","login.qr.title":"\u626B\u7801\u767B\u5F55","login.qr.titleAlipay":"\u652F\u4ED8\u5B9D\u626B\u7801\u767B\u5F55","login.qr.titleWechat":"\u5FAE\u4FE1\u626B\u7801\u767B\u5F55","login.qr.hint":"\u8BF7\u4F7F\u7528\u624B\u673A\u626B\u63CF\u4E8C\u7EF4\u7801\u5B8C\u6210\u6388\u6743","login.error.enterUsername":"\u8BF7\u8F93\u5165\u7528\u6237\u540D","login.error.enterPassword":"\u8BF7\u8F93\u5165\u5BC6\u7801","login.error.enter6Digit":"\u8BF7\u8F93\u51656\u4F4D\u9A8C\u8BC1\u7801","login.error.enterInviteCode":"\u8BF7\u8F93\u5165\u9080\u8BF7\u7801","login.error.usernameMinLen":"\u7528\u6237\u540D\u81F3\u5C112\u4E2A\u5B57\u7B26","login.error.passwordMinLen":"\u5BC6\u7801\u81F3\u5C116\u4F4D","login.error.passwordMismatch":"\u4E24\u6B21\u5BC6\u7801\u4E0D\u4E00\u81F4","login.error.enterVerifyCode":"\u8BF7\u8F93\u5165\u9A8C\u8BC1\u7801","login.error.loginFailed":"\u767B\u5F55\u5931\u8D25","login.forgot.link":"\u5FD8\u8BB0\u5BC6\u7801\uFF1F","login.forgot.title":"\u91CD\u7F6E\u5BC6\u7801","login.forgot.emailHint":"\u8F93\u5165\u8D26\u6237\u7ED1\u5B9A\u7684\u90AE\u7BB1\uFF0C\u6211\u4EEC\u5C06\u53D1\u9001 6 \u4F4D\u91CD\u7F6E\u9A8C\u8BC1\u7801\u3002","login.forgot.sendCode":"\u53D1\u9001\u91CD\u7F6E\u9A8C\u8BC1\u7801","login.forgot.sending":"\u53D1\u9001\u4E2D...","login.forgot.codeSent":"\u5982\u679C\u90AE\u7BB1\u5DF2\u6CE8\u518C\uFF0C\u91CD\u7F6E\u9A8C\u8BC1\u7801\u5DF2\u53D1\u9001\u3002\u8BF7\u5728\u4E0B\u65B9\u8F93\u5165\u9A8C\u8BC1\u7801\u4E0E\u65B0\u5BC6\u7801\u3002","login.forgot.resetBtn":"\u91CD\u7F6E\u5BC6\u7801","login.forgot.resetting":"\u91CD\u7F6E\u4E2D...","login.forgot.success":"\u5BC6\u7801\u5DF2\u91CD\u7F6E\uFF0C\u53EF\u4EE5\u4F7F\u7528\u65B0\u5BC6\u7801\u767B\u5F55\u3002","login.forgot.emailInvalid":"\u8BF7\u8F93\u5165\u6709\u6548\u7684\u90AE\u7BB1","login.register.title":"\u65B0\u7528\u6237\u6CE8\u518C","login.register.inviteCode":"\u9080\u8BF7\u7801","login.register.username":"\u7528\u6237\u540D","login.register.password":"\u5BC6\u7801\uFF08\u81F3\u5C116\u4F4D\uFF09","login.register.confirmPassword":"\u786E\u8BA4\u5BC6\u7801","login.register.email":"\u90AE\u7BB1\uFF08\u53EF\u9009\uFF09","login.register.submit":"\u6CE8\u518C","login.register.submitting":"\u6CE8\u518C\u4E2D...","login.register.back":"\u8FD4\u56DE\u767B\u5F55","login.register.success":"\u6CE8\u518C\u6210\u529F\uFF0C\u8BF7\u767B\u5F55","login.register.enterCode":"\u8BF7\u8F93\u5165\u9080\u8BF7\u7801","login.register.usernameMin":"\u7528\u6237\u540D\u81F3\u5C112\u4E2A\u5B57\u7B26","login.register.passwordMin":"\u5BC6\u7801\u81F3\u5C116\u4F4D","login.register.passwordMismatch":"\u4E24\u6B21\u5BC6\u7801\u4E0D\u4E00\u81F4","login.totp.setupTitle":"\u8BBE\u7F6E\u53CC\u56E0\u7D20\u8BA4\u8BC1","login.totp.setupHint":"\u4F7F\u7528 Microsoft Authenticator \u6216 Google Authenticator \u626B\u63CF\u4E0B\u65B9\u4E8C\u7EF4\u7801","login.totp.manualKey":"\u6216\u624B\u52A8\u8F93\u5165\u5BC6\u94A5\uFF1A","login.totp.enterCode":"\u8F93\u51656\u4F4D\u9A8C\u8BC1\u7801","login.totp.complete":"\u5B8C\u6210\u8BBE\u7F6E","login.totp.verifying":"\u9A8C\u8BC1\u4E2D...","login.totp.verify":"\u9A8C\u8BC1","login.totp.prompt":"\u8BF7\u8F93\u5165 Authenticator \u5E94\u7528\u4E2D\u7684\u9A8C\u8BC1\u7801","login.totp.invalidCode":"\u8BF7\u8F93\u51656\u4F4D\u9A8C\u8BC1\u7801","login.email.codeSent":"\u9A8C\u8BC1\u7801\u5DF2\u53D1\u9001\u81F3 {email}","login.email.enterCode":"\u8F93\u5165\u9A8C\u8BC1\u7801","login.email.verify":"\u9A8C\u8BC1","login.email.verifying":"\u9A8C\u8BC1\u4E2D...","login.email.enterCodeError":"\u8BF7\u8F93\u5165\u9A8C\u8BC1\u7801","chat.agent.select":"\u9009\u62E9 Agent","chat.agent.manage":"\u7BA1\u7406 Agent","chat.agent.none":"\u6682\u65E0 Agent","chat.agent.restarting":"\u91CD\u542F\u4E2D","chat.agent.restart":"\u91CD\u542F","chat.agent.restartConfirm":`\u786E\u5B9A\u8981\u91CD\u542F Agent "{name}" \u5417\uFF1F
11
11
  \u6240\u6709\u6D3B\u8DC3\u7684\u4F1A\u8BDD\u5C06\u88AB\u4E2D\u65AD\u3002`,"chat.agent.upgrade":"\u5347\u7EA7","chat.agent.upgrading":"\u5347\u7EA7\u4E2D","chat.agent.upgradeConfirm":`\u5347\u7EA7 Agent "{name}" \u5230\u6700\u65B0\u7248\u672C\uFF1F