UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

137 lines • 72.1 kB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./pending-session-create-B6nT760e.js","./control-ui-boot-shared-JlZTSJEC.js","./control-ui-boot-shared-3SP_aL-Y.js","./control-ui-boot-shared-90V688bk.js","./control-ui-boot-shared-DBJri5ri.js","./control-ui-boot-shared-BykNRHBP.js","./control-ui-boot-shared-Rs4iS2kF.js","./plugin-contracts-runtime-CsJ0WpAd.js","./markdown-runtime-Hc-lvqnn.js","./control-ui-boot-shared-CG9HtEG-.js","./control-ui-boot-shared-CcmBeh0v.js","./control-ui-boot-shared-BR12heUA.js","./chat-transcript-layout-w3EszKw8.js","./sidebar-update-runtime-B0vYzX3D.js","./control-ui-boot-new-BTHisEC4.js","./css-config-njfbfHBk.js","./control-ui-core-D-VUH4Gq.css","./control-ui-boot-shared-BJ_QKfFn.css","./css-chat-DCHf01mf.css","./css-chat-custodian-new-session-CEndYuO5.css","./sidebar-update-runtime-ah7rgQE7.css","./css-cron-custodian-new-session-Ci5c-FgJ.css","./chat-transcript-styles-DHHd4Hhc.css","./css-new-session-C71huhgC.css","./css-config-vi6FusyS.css","./control-ui-boot-new-D-SpiTTi.css"])))=>i.map(i=>d[i]);
import{n as e}from"./rolldown-runtime-8BhlS34s.js";import{Bi as t,Br as n,Ca as r,Da as i,Gi as a,Oa as o,Oi as s,Pa as c,Ta as l,Ui as u,Vt as d,_a as f,br as p,ct as m,et as h,fa as g,ga as _,ha as v,ii as y,ka as b,pa as x,qr as S,sa as ee,st as te,to as ne,ua as C,va as re,wa as ie,yr as ae,zi as oe,zr as se,zt as ce}from"./control-ui-foundation-ZY_Flbbd.js";import{Dc as le,Gl as ue,Ns as de,Tc as fe,Tl as pe,Xn as w,Yn as me,Yr as he,Zc as T,_l as ge,_n as _e,ac as ve,bc as ye,bn as be,cc as xe,cr as Se,dc as Ce,dl as E,dn as we,fc as Te,hc as D,hl as Ee,hu as O,ks as De,lc as Oe,ln as ke,lu as Ae,mc as je,ml as Me,nc as Ne,nl as k,oc as Pe,ol as Fe,ql as Ie,sc as Le,sl as A,su as Re,un as ze,uu as Be,vc as Ve,vl as He,vn as Ue,wc as We,xc as Ge,yc as Ke,yn as j}from"./control-ui-core-3P365fbR.js";import{$n as qe,$r as Je,C as Ye,E as Xe,Ha as Ze,Hn as Qe,Qr as $e,Sn as et,T as tt,Un as M,_i as N,ar as nt,co as rt,ei as it,er as at,fn as ot,gi as st,go as ct,mn as lt,n as ut,ni as dt,p as ft,pi as pt,r as mt,to as P,vi as ht,yi as gt,za as _t}from"./control-ui-core-CFW9Qtjn.js";import{$ as F,Q as vt,X as I,Y as yt,c as bt,ct as xt,m as St,nt as Ct,p as wt,s as Tt,ut as Et}from"./lit-runtime-P5vbNq6b.js";import{d as Dt,l as Ot}from"./gateway-runtime-5YzSCmfV.js";import{Ca as kt,Co as At,Di as jt,Fc as Mt,Hi as Nt,Mi as Pt,Nc as Ft,Ni as It,Oi as Lt,Pc as Rt,Ui as zt,Wi as Bt,bo as Vt,ji as Ht,ki as Ut,yo as Wt}from"./control-ui-boot-shared-DoKu-5Ju.js";import{C as L,O as R,S as z,f as Gt,g as Kt,j as qt,m as Jt,y as Yt}from"./config-runtime-CgOgfOrG.js";import{D as Xt,E as Zt,H as Qt,M as $t,N as en,U as tn,b as nn,j as rn,t as an,x as on}from"./control-ui-boot-shared-73R4ErOy.js";import{At as sn,Dt as B,Et as V,Ft as cn,It as ln,Mt as un,Nt as dn,Ot as fn,Pt as pn,Qr as mn,Tt as hn,di as gn,ei as _n,fi as vn,ii as yn,jt as bn,kt as xn,ni as Sn,ri as Cn,si as wn,ui as Tn,wt as En}from"./control-ui-boot-shared-CApmg5ot.js";import"./css-chat-Ckz95ikh.js";import"./css-cron-custodian-new-session-DdqVeFqw.js";import"./chat-transcript-styles-BVZgOT1t.js";import"./css-chat-custodian-new-session-B_euK-Vu.js";import"./css-agents-plugins-skill-workshop-skills-DvcafeYi.js";import"./css-new-session-BGJnpiJ5.js";import"./css-skill-workshop-D2ZfJfdl.js";import"./css-question-Ct0OXZAc.js";import{a as Dn,c as On,i as kn,n as An,o as jn,r as Mn,s as Nn,t as Pn}from"./session-snapshot-database-CobUvfK7.js";function Fn(){return(Fn=e((()=>{})))()}function In(){return(In=e((()=>{})))()}function Ln(){return(Ln=e((()=>{})))()}function Rn(e){let t=E(e)?.rest.match(g)?.[1];return t?t.toLowerCase().replaceAll(`-`,``):null}function zn(e,t,n=`main`){let a=e.filter(e=>E(e.key)?.agentId===c(t.agentId));if(t.kind!==`short`){let e=t.kind===`main`?i({agentId:t.agentId,mainKey:n}):t.sessionKey,r=a.find(t=>T(t.key,e));if(r||t.kind===`main`||!t.slugCandidate)return r}let o=a.filter(e=>{let n=Rn(e.key);return n&&(t.kind!==`short`||n.startsWith(t.shortId.toLowerCase().replaceAll(`-`,``)))}),s=t.kind===`short`?t.slugHint:t.slugCandidate,l=s?o.filter(e=>r(e.displayName)===s):[],u=l.length||t.kind!==`short`?l:o;return u.length===1?u[0]:void 0}function Bn(e,t,n){let r=new URLSearchParams(t.search).get(Te)?.trim(),i=Nt(e.gateway,t.pathname),a=r??i,o=!!(i&&i===a);if(a){let i=()=>{r&&Bt(e.gateway,t.pathname,r)},s=je(e,a,n.agentId);if(s&&zn([s],n))return i(),{sessionKey:s.key,row:s};let l=Rn(a),u=E(a)?.agentId;if(o&&l?.startsWith(n.shortId.toLowerCase().replaceAll(`-`,``))&&u&&c(u)===c(n.agentId))return i(),{sessionKey:a}}}function Vn(){return(Vn=e((()=>{v(),zt(),D(),k()})))()}function Hn(e){if(typeof e==`boolean`)return e;let t=u(e)?.enabled;return typeof t==`boolean`?t:void 0}function Un(e,t){let n=u(e),r=Hn(u(n?.tools)?.swarm),i=u(n?.agents),a=u(i?.entries),o=t?c(t):null,s=o?Object.keys(a??{}).find(e=>c(e)===o):null,l=s?u(a?.[s]):null;return Hn(u(l?.tools)?.swarm)??r??!0}function Wn(...e){let t=new Map;for(let n of e)for(let e of n){let n=t.get(e.key);(!n||(e.updatedAt??0)>=(n.updatedAt??0))&&t.set(e.key,e)}return[...t.values()]}async function Gn(e){return Pt({list:t=>e.sessions.list({...Ut(e.parentKey,Kn),offset:t}),initialResult:e.initialResult,isCurrent:e.isCurrent,missingResultError:`child session list returned no result`,mapPageRows:t=>{let n=Date.now();return t.map(t=>e.sessions.inheritRow({...t,runtimeSampledAt:n},t))}})}var Kn,qn;function Jn(){return(Jn=e((()=>{at(),Ht(),It(),k(),Kn=1e4,qn=class{constructor(){this.rows=[],this.key=``,this.generation=0,this.timer=null,this.retries={parent:{attempts:0,timer:null},children:{attempts:0,timer:null}},this.params=null,this.parent=null,this.parentRow=null,this.parentSummary=``,this.children=null,this.childResult=null,this.childRows=[],this.parentRequest=null,this.parentRefreshQueued=!1,this.parentRefreshForced=!1,this.publishingParentRead=!1}update(e){let t=`${e.sourceEpoch}:${e.agentId??``}:${e.parentKey}`,n=this.key!==t||this.params?.sessions!==e.sessions||this.parent&&!this.parent.isCurrent();n&&this.reset(t),this.params=e,n&&(this.childRows=e.currentRows().filter(t=>!T(t.key,e.parentKey)),this.rows=this.childRows,e.onRows(this.rows)),!(this.children||this.timer!==null)&&(this.timer=setTimeout(()=>this.connect(),250))}dispose(){this.reset(``)}connect(){this.timer=null;let e=this.params;if(!e)return;let t=this.generation,n=()=>this.generation===t,r=e.agentId??E(e.parentKey)?.agentId;r&&(this.parent=e.sessions.observeRow({key:e.parentKey,agentId:r},e=>{n()&&this.applyParent(e)},{onInvalidate:()=>{n()&&!this.parentRequest&&this.readParent()}}),this.children=e.sessions.observeList(Ut(e.parentKey,Kn),e=>{n()&&this.applyChildren(e)}),this.readParent(),this.children.refresh().catch(()=>{n()&&this.retry(`children`)}))}applyParent(e){let t=this.parentRow,n=JSON.stringify([e?.sessionId,e?.childSessions,e?.swarm?.groups.map(({children:e,...t})=>t),e?.swarm?.otherActiveGroups]),r=this.parentSummary!==n;this.parentRow=e&&!r&&t?.swarm&&e.swarm?{...e,swarm:{...e.swarm,groups:e.swarm.groups.map(e=>({...e,children:e.children??t.swarm?.groups.find(t=>t.groupId===e.groupId)?.children}))}}:e,this.parentSummary=n,this.rows=this.parentRow?Wn(this.childRows,[this.parentRow]):[],this.params?.onRows(this.rows),e&&r&&this.parent&&!this.publishingParentRead&&this.readParent()}recovered(e){let t=this.retries[e];t.timer!==null&&clearTimeout(t.timer),t.timer=null,t.attempts=0}retry(e){let t=this.retries[e];if(!this.params||t.timer!==null)return;let n=this.generation,r=Math.min(3e4,1e3*2**Math.min(t.attempts++,5));t.timer=setTimeout(()=>{t.timer=null,e===`parent`?this.readParent():this.children?.refresh().catch(()=>{n===this.generation&&this.retry(e)})},r)}readParent(e=!1){if(this.parentRequest)return this.parentRefreshQueued=!0,this.parentRefreshForced||=e,this.parentRequest;let t=this.params,n=this.parent;if(!t||!n?.isCurrent())return Promise.resolve();let r=this.generation,i=()=>r===this.generation&&n===this.parent,a=n.captureReconcile(),o=e=>{this.publishingParentRead=!0;let t;try{t=a(e)}finally{this.publishingParentRead=!1}t.status===`invalidated`?this.parentRefreshQueued=!0:t.status===`current`&&this.recovered(`parent`)},s=Promise.resolve().then(()=>t.readParent(e)).then(e=>{i()&&o(e??void 0)}).catch(e=>{i()&&(e instanceof qe&&e.code===`INVALID_REQUEST`?o(void 0):this.retry(`parent`))}).finally(()=>{if(i()&&this.parentRequest===s&&(this.parentRequest=null,this.parentRefreshQueued)){let e=this.parentRefreshForced;this.parentRefreshQueued=!1,this.parentRefreshForced=!1,this.readParent(e)}});return this.parentRequest=s,s}applyChildren(e){let t=this.params,n=e.result;if(e.error&&!e.loading){this.retry(`children`);return}if(!t||e.loading||!n||n===this.childResult)return;this.childResult=n;let r=new Map(this.childRows.map(e=>[e.key,e])),i=new Map(this.parentRow?.swarm?.groups.flatMap(e=>(e.children??[]).map(t=>[t.sessionKey,{...t,groupId:e.groupId}]))),a=n.sessions.filter(e=>{let t=r.get(e.key);return t?.swarmGroupId!==e.swarmGroupId||t?.status!==e.status}),o=new Set(n.sessions.map(e=>e.key)),s=[...i.keys()].some(e=>r.has(e)&&!o.has(e)),c=a.some(e=>{let t=i.get(e.key);return e.swarmGroupId&&(t?.groupId!==e.swarmGroupId||e.status&&t?.status!==e.status)});this.parentRow&&(s||c)&&this.readParent(!0);let l=this.generation,u=()=>l===this.generation&&this.childResult===n;Gn({sessions:t.sessions,parentKey:t.parentKey,initialResult:n,isCurrent:u}).then(e=>{if(!e||!u())return;let n=this.parentRow;this.childRows=e,this.rows=n?Wn(this.childRows,[n]):[],this.recovered(`children`),t.onRows(this.rows)}).catch(()=>{u()&&this.retry(`children`)})}reset(e){this.timer!==null&&clearTimeout(this.timer),this.parent?.dispose(),this.children?.dispose(),this.params=null,this.parent=null,this.parentRow=null,this.parentSummary=``,this.children=null,this.childResult=null,this.childRows=[],this.parentRequest=null,this.parentRefreshQueued=!1,this.parentRefreshForced=!1,this.rows=[],this.key=e,this.generation+=1,this.recovered(`parent`),this.recovered(`children`),this.timer=null}}})))()}function Yn(e){return new URLSearchParams(e.search).get(`draft`)||void 0}function Xn(e){return new URLSearchParams(e.search).get(Oe)===`1`}function Zn(e,t={}){let n=new URLSearchParams(e.search);for(let[e,r]of new URLSearchParams(t.search))n.set(e,r);n.delete(`draft`),n.delete(Oe);let r=n.toString();return{...e,...t,search:r?`?${r}`:``}}function Qn(e){return{draft:Yn(e),...Xn(e)?{focusComposer:!0}:{}}}function $n(e){let t=new URLSearchParams,n=Yn(e);return n&&t.set(`draft`,n),Xn(e)&&t.set(Oe,`1`),t.size>0?`?`+t.toString():``}function er(e,t,n=e?.sessionKey){return!e||!T(n,e.sessionKey)||t===e?void 0:e.draft}function H(){return(H=e((()=>{D(),k()})))()}function tr(){return{pathname:window.location.pathname,search:window.location.search,hash:window.location.hash}}function nr(e,t){return e.pathname===t.pathname&&e.search===t.search&&e.hash===t.hash}function rr(e,t){if(!e)return!1;let n=tr();if(nr(n,e))return!0;let r=new URLSearchParams(e.search).has(`draft`),i=new URLSearchParams(n.search).has(`draft`);return t&&r&&!i&&nr(Zn(n),Zn(e))}function ir(){return(ir=e((()=>{H()})))()}var ar;function or(){return(or=e((()=>{k(),ar=class{constructor(e){this.host=e}clear(){this.pending?.abort.abort(),this.pending=void 0}capture(e){this.clear();let t=this.host.ownerDocument.activeElement;return t&&([...this.host.querySelectorAll(`openclaw-chat-pane`)].some(n=>n.paneId===e&&n.contains(t))||[...this.host.querySelectorAll(`[data-unbound-pane-id]`)].some(n=>n.dataset.unboundPaneId===e&&n.contains(t)))?t:null}schedule(e,t,n){let r=new AbortController;this.pending={source:e,paneId:t.id,sessionKey:t.sessionKey,layout:n,href:window.location.href,abort:r},this.host.ownerDocument.addEventListener(`focusin`,()=>this.clear(),{signal:r.signal})}restore(e,t){let n=this.pending;if(!n)return;let r=this.host.ownerDocument.activeElement;if(e!==n.layout||window.location.href!==n.href||r!==n.source&&r!==this.host.ownerDocument.body){this.clear();return}if(t)return;let i=[...this.host.querySelectorAll(`openclaw-chat-pane`)].find(e=>e.paneId===n.paneId&&T(e.sessionKey,n.sessionKey)),a=i?.active&&i.presented?i.querySelector(`.chat-pane__header`):[...this.host.querySelectorAll(`[data-unbound-pane-id]`)].find(e=>e.dataset.unboundPaneId===n.paneId);a&&(this.clear(),a.focus({preventScroll:!0}))}}})))()}function sr(e,t,n){let r=(t-e.left)/e.width,i=(n-e.top)/e.height,a=r<=U?{edge:`left`,distance:r}:1-r<=U?{edge:`right`,distance:1-r}:null,o=i<=U?{edge:`up`,distance:i}:1-i<=U?{edge:`down`,distance:1-i}:null,s=a&&o?a.distance<=o.distance?a:o:a??o;return s?{kind:`edge`,edge:s.edge}:{kind:`center`}}function cr(e,t){let n={left:e.left,top:e.top,width:e.width,height:e.height};return t.kind===`center`?n:t.edge===`left`?{...n,width:e.width/2}:t.edge===`right`?{...n,left:e.left+e.width/2,width:e.width/2}:t.edge===`up`?{...n,height:e.height/2}:{...n,top:e.top+e.height/2,height:e.height/2}}var U;function lr(){return(lr=e((()=>{U=.3})))()}function ur(e,t,n,r){let i=t.paneId??t.dataset.unboundPaneId,a=e.querySelector(`.chat-split-view__drop-container`);if(!i||!a)return null;let o=t.getBoundingClientRect(),s=sr(o,n,r),c=cr(o,s),l=a.getBoundingClientRect();return{paneId:i,zone:s,rect:{left:c.left-l.left,top:c.top-l.top,width:c.width,height:c.height}}}var dr;function fr(){return(fr=e((()=>{Wt(),lr(),dr=class{constructor(e,t){this.host=e,this.options=t,this.indicator=null,this.dragDepth=0,this.dragFrame=0,this.pendingDragOver=null,this.handleDragEnter=e=>{this.options.sessionSplitAvailable()&&At(e.dataTransfer)&&(this.dragDepth+=1)},this.handleDragOver=e=>{if(!this.options.sessionSplitAvailable()||!At(e.dataTransfer))return;e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`);let t=(e.target instanceof Element?e.target:null)?.closest(`openclaw-chat-pane, [data-unbound-pane-id]`);if(!t||!this.host.contains(t)){this.clear();return}this.pendingDragOver={pane:t,x:e.clientX,y:e.clientY},!this.dragFrame&&(this.dragFrame=window.requestAnimationFrame(()=>{this.dragFrame=0;let e=this.pendingDragOver;if(this.pendingDragOver=null,!e||this.options.narrow()||!this.host.isConnected)return;let t=ur(this.host,e.pane,e.x,e.y);if(!t){this.clear();return}let n=this.indicator;(n?.paneId!==t.paneId||n.zone.kind!==t.zone.kind||t.zone.kind!==`center`&&(n.zone.kind!==`edge`||n.zone.edge!==t.zone.edge))&&(this.indicator=t,this.host.requestUpdate())}))},this.handleDragLeave=e=>{this.options.sessionSplitAvailable()&&At(e.dataTransfer)&&(this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&this.clear())},this.handleDrop=e=>{if(!this.options.sessionSplitAvailable()||!At(e.dataTransfer))return;e.preventDefault();let t=Vt(e.dataTransfer),n=(e.target instanceof Element?e.target:null)?.closest(`openclaw-chat-pane, [data-unbound-pane-id]`),r=n&&this.host.contains(n)?ur(this.host,n,e.clientX,e.clientY):null;this.clear(),t&&r&&this.options.applySessionDrop(t,r.paneId,r.zone)},this.clear=()=>{this.dragDepth=0,this.pendingDragOver=null,this.dragFrame&&=(window.cancelAnimationFrame(this.dragFrame),0),this.indicator&&(this.indicator=null,this.host.requestUpdate())}}connect(){this.host.addEventListener(`dragenter`,this.handleDragEnter),this.host.addEventListener(`dragover`,this.handleDragOver),this.host.addEventListener(`dragleave`,this.handleDragLeave),this.host.addEventListener(`drop`,this.handleDrop),window.addEventListener(`dragend`,this.clear)}disconnect(){this.host.removeEventListener(`dragenter`,this.handleDragEnter),this.host.removeEventListener(`dragover`,this.handleDragOver),this.host.removeEventListener(`dragleave`,this.handleDragLeave),this.host.removeEventListener(`drop`,this.handleDrop),window.removeEventListener(`dragend`,this.clear),this.clear()}}})))()}function pr(e,t,n){return!!(t&&n&&pe({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello},t.sessionKey,n.sessionKey,n.agentId,t.agentId))}function mr(e,t){let{command:n,agentId:r}=t;return n.kind!==`navigate`&&n.kind!==`split`&&n.kind!==`focus`&&n.kind!==`close-pane`?t:{...t,sessionKey:t.sessionKey?gr(e,t.sessionKey,r):void 0,command:{...n,sessionKey:gr(e,n.sessionKey,r)}}}function hr(e,t){if(!A(t?.sessionKey)||!t.agentId?.trim())return t;let n=gr(e,t.sessionKey,t.agentId);if(n===t.sessionKey)return t;let r=yr.get(t);return r?.sessionKey!==n&&(r={sessionKey:n,value:{...t,sessionKey:n}},yr.set(t,r)),r.value}function gr(e,t,n){return A(t)&&n?.trim()&&Fe({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello})?i({agentId:n,mainKey:Ee({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello})}):t}function _r(e,t,n,r=!1,i,a){let o=Ve(e,a??t?.agentId),s=t&&pe({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello,assistantAgentId:o},t.sessionKey,n,A(n)?o:void 0,t.agentId),c=i??t?.face??`chat`;i===void 0&&!s&&(c=ye(e,n,a??t?.agentId));let l=Ge({context:e,face:c,preferenceDerivedFace:i===void 0&&!s,sessionKey:n,agentId:a??t?.agentId,shortIdLength:t?.sessionKey===n?t.shortId?.length:void 0}).options,u=r&&s&&(t.draft||t.focusComposer)?Zn(tr(),l):l;e[r?`replace`:`navigate`](c,u)}function vr(e,t){if(!t.presented||t.pendingCreate||!(e instanceof CustomEvent))return;let{command:n,sessionKey:r,agentId:i}=mr(t.context,e.detail);if(n.kind===`navigate`){e.preventDefault(),t.layout&&t.unboundPaneIds.has(t.layout.activePaneId)&&t.adoptPaneNavigation(t.layout.activePaneId,n.sessionKey,i),t.updateRoute(n.sessionKey,!1,void 0,i);return}if(n.kind!==`split`&&n.kind!==`close-pane`&&n.kind!==`focus`||n.kind===`split`&&t.narrow)return;let a=hr(t.context,t.data)?.sessionKey?.trim(),o=t.layout??(n.kind===`split`&&a?t.classicLayout(a):void 0);if(!o)return;if(n.kind===`close-pane`){let r=xn(o).find(e=>e.sessionKey===n.sessionKey);if(!r)return;e.preventDefault(),t.closeSplitPane(o,r.id);return}let s=En(o,n,r);if(s===o)return;e.preventDefault(),t.persistLayout(s);let c=s&&V(s,s.activePaneId)?.pane;c&&t.updateRouteToPane(c)}var yr;function br(){return(br=e((()=>{D(),k(),ir(),H(),B(),yr=new WeakMap})))()}function xr(e,t,n){let r=new Set;for(let i of t.columns)for(let t of i.panes){let a=JSON.stringify([i.id,t.id]);for(let i of n.get(t.id)??[])i!==void 0&&(!e||!ft(e,i))&&r.add(JSON.stringify([a,i]))}return r}function Sr(e){let t=e.context?.sessions?.presentation.result?.sessions??[];return F`
    <div
      class="chat-split-view__cell ${e.splitMode&&e.active?`chat-split-view__cell--active`:``} ${e.narrow&&!e.active?`chat-split-view__cell--narrow-hidden`:``}"
      aria-current=${e.splitMode&&e.active?`true`:I}
      style="flex: ${e.narrow?1:e.weight} 1 0"
      @pointerdown=${()=>e.onFocusPane(e.pane.id)}
      @focusin=${()=>e.onFocusPane(e.pane.id)}
    >
      <div class="chat-pane-cache">
        ${e.unbound?F`
                <div
                  class="chat-split-view__unbound"
                  data-unbound-pane-id=${e.pane.id}
                  tabindex="0"
                  role="region"
                  aria-label=${O(`chat.splitView.chooseConversation`)}
                >
                  <strong>${O(`chat.splitView.chooseConversation`)}</strong>
                  <p>${O(`chat.splitView.missingOwner`)}</p>
                  ${e.onClosePane?F`<button class="btn" @click=${()=>e.onClosePane?.(e.pane.id)}>${O(`chat.splitView.closePane`)}</button>`:I}
                </div>
              `:I}
        ${e.sessionSlots.map(n=>{if(n===void 0||e.unbound)return I;let r=n===e.pane.sessionKey||T(n,e.pane.sessionKey),i=e.presented&&r&&(!e.narrow||e.active),a=e.active&&r,o=e.data&&T(n,e.data.sessionKey)?e.data:void 0,s=a?er(e.data,e.consumedDraftData,n):void 0,c=he(n,e.context?.gateway?.snapshot?.hello)||n,l=t.find(e=>T(e.key,c)),u=l?de(c,l):void 0;return e.context&&ft(e.context,n)?St(n,F`<openclaw-pending-session-create
                class="chat-pane-cache__pane ${r?`chat-pane-cache__pane--visible`:``}
                ${a?`chat-pane-cache__pane--active`:``}
                ${e.splitMode?`chat-split-view__pane`:``}"
                aria-hidden=${String(!i)}
                ?inert=${!i}
                .context=${e.context}
                .sessionKey=${n}
              ></openclaw-pending-session-create>`):St(n,F`<openclaw-chat-pane
              class="chat-pane-cache__pane ${r?`chat-pane-cache__pane--visible`:``} ${a?`chat-pane-cache__pane--active`:``} ${e.splitMode?`chat-split-view__pane`:``}"
              data-mcp-app-owner-key=${JSON.stringify([e.ownerKey,n])}
              aria-hidden=${i?`false`:`true`}
              ?inert=${!i}
              .paneId=${e.pane.id}
              .paneLabel=${O(`chat.splitView.panePosition`,{column:String(e.panePosition.column),row:String(e.panePosition.row),pane:e.pane.id})}
              .presentationId=${JSON.stringify([e.pane.id,n])}
              .chatMessagesBySession=${e.chatMessagesBySession}
              .sessionSnapshotStore=${e.sessionSnapshotStore}
              .sessionKey=${n}
              .agentId=${e.splitMode?E(n)?.agentId:void 0}
              .routeLoadingSkeleton=${o?.routeLoadingSkeleton??vt}
              .presented=${i}
              .visuallyPresented=${i}
              .active=${a}
              .draft=${s}
              .focusComposer=${e.draftFocus.shouldFocusPane(a,s,n,e.data)}
              .dashboardExpanded=${o?o.dashboardExpanded===!0:vt}
              .routeFace=${o?o.face??`chat`:vt}
              .presentationTitle=${u}
              .narrow=${e.narrow}
              .mergedChrome=${e.mergedChrome&&a}
              .navDrawerOpen=${e.navDrawerOpen&&a}
              .onboarding=${e.onboarding}
              .onOpenSplitView=${e.onOpenSplitView}
              .onSplitDown=${e.onSplitDown}
              .onSplitRight=${e.onSplitRight}
              .onClosePane=${e.onClosePane}
              .onFocusPane=${e.onFocusPane}
              .onPaneSessionChange=${(t,r,i)=>e.onPaneSessionChange(t,n,r,i)}
              .onSessionDeleted=${e.onSessionDeleted}
              .onFaceChange=${e.onFaceChange}
            ></openclaw-chat-pane>`)})}
      </div>
    </div>
  `}function Cr(e,t){let n=t.activePaneId!==void 0&&V(e,t.activePaneId)!==null;return F`
    <div
      class="chat-split-view ${t.narrow?`chat-split-view--narrow`:``} ${n?`chat-split-view--active-cell`:``}"
    >
      ${bt(e.columns,e=>e.id,(n,r)=>F`
          <div
            class="chat-split-view__column ${t.narrow&&!n.panes.some(t=>t.id===e.activePaneId)?`chat-split-view__column--narrow-hidden`:``}"
            style="flex: ${t.narrow?1:s(e.columnWeights[r],`rendered split column weight`)} 1 0"
          >
            ${bt(n.panes,e=>e.id,(e,r)=>F`
                ${t.renderPane(n,e,s(n.paneWeights[r],`rendered split pane weight`))}
                ${!t.narrow&&r<n.panes.length-1?F`
                        <resizable-divider
                          orientation="horizontal"
                          .splitRatio=${cn(n.paneWeights,r,`split pane weight`)}
                          .minRatio=${.15}
                          .maxRatio=${.85}
                          .label=${O(`nav.resize`)}
                          @resize=${e=>t.onResizePanes(n.id,r,e.detail.splitRatio)}
                          @resize-end=${t.onResizeEnd}
                        ></resizable-divider>
                      `:I}
              `)}
          </div>
          ${!t.narrow&&r<e.columns.length-1?F`
                  <resizable-divider
                    .splitRatio=${cn(e.columnWeights,r,`split column weight`)}
                    .minRatio=${.15}
                    .maxRatio=${.85}
                    .label=${O(`nav.resize`)}
                    @resize=${e=>t.onResizeColumns(r,e.detail.splitRatio)}
                    @resize-end=${t.onResizeEnd}
                  ></resizable-divider>
                `:I}
        `)}
    </div>
  `}function wr(e,t){return F`<div class="chat-split-view__drop-container">
    ${e}${t?F`<div
            class="chat-split-view__drop-indicator ${t.zone.kind===`center`?`chat-split-view__drop-indicator--center`:``}"
            style=${`left: ${t.rect.left}px; top: ${t.rect.top}px; width: ${t.rect.width}px; height: ${t.rect.height}px;`}
          >
            <span class="chat-split-view__drop-indicator-label"
              >${t.zone.kind===`center`?O(`chat.splitView.dropOpenHere`):O(`chat.splitView.dropSplit`)}</span
            >
          </div>`:I}
  </div>`}function Tr(e,t,n){return n?F`<openclaw-pending-session-create
    .context=${e}
    .sessionKey=${t}
  ></openclaw-pending-session-create>`:I}function Er(){return(Er=e((()=>{y(),yt(),wt(),pt(),Tt(),Be(),De(),Se(),k(),H(),B()})))()}function Dr(e){let t=new Map,n=e.snapshot.client,r=null,i=null,a=null,o=0,s=0,c=null,l=()=>{c?.abort(),c=null},u=()=>t.size>0,d=()=>{r=null,i=null,a=null,o=0},f=()=>{let n=e.snapshot.hello,r=new Set;for(let e of t.values())for(let t of e){let e=he(t,n).trim();e&&r.add(e)}return[...r].toSorted().slice(0,32)},p=jt(e,{sync:h,onAttach:()=>{n=e.snapshot.client,d()},onDetach:()=>{s+=1,l(),d()}}),{retry:m}=p;function h(){let t=e.snapshot,h=t.client;if(h!==n&&(m.reset(),n=h,d()),t.phase!==`connected`||h===null||t.hello===null||Dt(t,kr)!==!0){r=null,i=null,l(),a=null,o=0,u()||p.detach();return}let g=typeof document<`u`&&document.visibilityState===`hidden`?[]:f(),_=g.some(e=>!e.startsWith(`agent:`))?t.assistantAgentId:void 0,v=JSON.stringify({agentId:_,sessionKeys:g});if(t.hello===r&&v===i){!u()&&a===v&&o===s&&p.detach();return}r=t.hello,i=v;let y=++s;l(),c=new AbortController;let b=()=>p.attached&&y===s&&t.hello===r&&v===i;m.cancel(),h.request(kr,{..._?{agentId:_}:{},sessionKeys:g},{timeoutMs:ce,signal:c.signal}).then(()=>{b()&&(a=v,o=y,m.reset(),u()||p.detach())}).catch(()=>{b()&&(i=null,m.schedule(p.schedule))})}let g=(e,n)=>{let r=new Set(n.map(e=>e.trim()).filter(Boolean)),i=t.get(e);(i===void 0?r.size===0:i.size===r.size&&[...r].every(e=>i.has(e)))||(r.size===0?t.delete(e):t.set(e,r),m.reset(),u()?(p.attach(),p.schedule()):p.attached&&p.sync())};return{watch:g,unwatch:e=>g(e,[])}}function Or(e){let t=Ar.get(e);if(t)return t;let n=Dr(e);return Ar.set(e,n),n}var kr,Ar;function jr(){return(jr=e((()=>{d(),Ot(),Lt(),Se(),kr=`sessions.viewers.set`,Ar=new WeakMap})))()}var Mr;function Nr(){return(Nr=e((()=>{jr(),B(),Mr=class{constructor(e){this.owner=e,this.gateway=null}sync(e,t,n,r){let i=e&&typeof e.subscribe==`function`?e:null;this.gateway&&this.gateway!==i&&Or(this.gateway).unwatch(this.owner),this.gateway=i,i&&Or(i).watch(this.owner,ln(t,n).filter(e=>!r.has(e.id)).map(e=>e.sessionKey))}dispose(){this.gateway&&=(Or(this.gateway).unwatch(this.owner),null)}}})))()}function Pr(e,t){return W?W.expiresAt<=Date.now()?(W=void 0,!1):W.sourceData!==t&&T(W.sessionKey,e):!1}var Fr,Ir,Lr,Rr,W,zr;function Br(){return(Br=e((()=>{k(),Fr=3e4,Ir=15e3,Lr=250,Rr=`.agent-chat__composer-combobox textarea`,zr=class{constructor(e){this.host=e}rendered(e,t,n){let r=!!(e&&(t===void 0||t!==null&&T(t,e.sessionKey)));return e&&!e.draft&&r&&Pr(e.sessionKey,e)&&(W=void 0,this.maintain(e.sessionKey)),!!(e&&n!==e&&r&&(e.draft!==void 0||e.focusComposer))}shouldFocusPane(e,t,n,r){return!!(e&&r&&(t&&r.focusComposer||!t&&Pr(n,r)))}beforeDraftCleanup(e){e.focusComposer&&(W={expiresAt:Date.now()+Fr,sessionKey:e.sessionKey,sourceData:e})}maintain(e){this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0);let t=Date.now()+Ir,n,r=()=>{if(!this.host.isConnected){this.timer=void 0;return}let i=[...this.host.querySelectorAll(`openclaw-chat-pane`)].find(t=>t.active&&t.sessionKey!==void 0&&T(t.sessionKey,e))?.querySelector(Rr),a=document.activeElement,o=a===n||a===document.body||a instanceof HTMLElement&&!a.isConnected;if(i&&(!n||o))i.focus({preventScroll:!0}),n=i;else if(n&&!o){this.timer=void 0;return}this.timer=Date.now()<t?window.setTimeout(r,Lr):void 0};r()}}})))()}function Vr(e,t){return e?.presentedTranscriptsReady===!0&&(e.automaticPrefetchAllowed||!(!e.intentSessionKey||t&&e.intentSessionKey!==t))}function Hr(e){return e.lastActivityAt??e.updatedAt??0}function Ur(e,t){t===void 0?console.debug(`[chat-session-prefetch] ${e}`):console.debug(`[chat-session-prefetch] ${e}`,t)}function Wr(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Gr(e,t,n,r){return new Qr(e,t,n,r)}var Kr,qr,Jr,Yr,Xr,Zr,Qr;function $r(){return($r=e((()=>{Pe(),Qt(),gn(),Sn(),me(),Kr=2,qr=250,Jr=75,Yr=3e4,Xr=`openclaw-chat-prefetch`,Zr=class{constructor(e,t){this.cache=e,this.snapshotStore=t,this.connected=!1,this.snapshot=null,this.lastAttemptAt=new Map,this.delayTimer=null,this.delayDeadline=null,this.pendingIntent=!1,this.idleTimer=null,this.idleCallback=null,this.running=!1,this.rescheduleDelayMs=null,this.rescheduleIntent=!1,this.handleVisibilityChange=()=>{document.visibilityState===`visible`&&this.schedule()}}connect(){this.connected||(this.connected=!0,document.addEventListener(`visibilitychange`,this.handleVisibilityChange),this.schedule())}disconnect(){this.connected=!1,this.rescheduleDelayMs=null,this.rescheduleIntent=!1,document.removeEventListener(`visibilitychange`,this.handleVisibilityChange),this.cancelScheduledWork()}update(e){let t=this.snapshot;if(this.snapshot=e,!t||t.client!==e.client||t.listRevision!==e.listRevision||t.intentSessionKey!==e.intentSessionKey||t.automaticPrefetchAllowed!==e.automaticPrefetchAllowed||t.presentedTranscriptsReady!==e.presentedTranscriptsReady||!Wr(t.openSessionKeys,e.openSessionKeys)){let n=e.intentSessionKey!==null&&t?.intentSessionKey!==e.intentSessionKey;this.schedule(n?Jr:qr,n)}}schedule(e=qr,t=!1){if(!this.connected)return;if(this.running){this.rescheduleDelayMs=this.rescheduleDelayMs===null?e:Math.min(this.rescheduleDelayMs,e),this.rescheduleIntent||=t;return}this.pendingIntent||=t;let n=Date.now()+e;if(this.delayDeadline!==null&&this.delayDeadline<=n||!t&&(this.idleTimer!==null||this.idleCallback!==null))return;let r=this.pendingIntent;this.cancelScheduledWork(),this.pendingIntent=r,this.delayDeadline=n,this.delayTimer=globalThis.setTimeout(()=>{this.delayTimer=null,this.delayDeadline=null;let e=this.pendingIntent;this.pendingIntent=!1,e?this.runCycle():this.scheduleIdleCycle()},e)}scheduleIdleCycle(){if(this.connected){if(typeof window.requestIdleCallback==`function`){this.idleCallback=window.requestIdleCallback(()=>{this.idleCallback=null,this.runCycle()});return}this.idleTimer=globalThis.setTimeout(()=>{this.idleTimer=null,this.runCycle()},0)}}async runCycle(){if(this.connected&&!this.running&&document.visibilityState!==`hidden`){this.running=!0;try{let e=typeof navigator>`u`?void 0:navigator.locks;e?await e.request(Xr,{ifAvailable:!0},async e=>{e&&await this.prefetchEligibleSessions()}):await this.prefetchEligibleSessions()}catch(e){Ur(`cycle failed`,e)}finally{if(this.running=!1,this.rescheduleDelayMs!==null){let e=this.rescheduleDelayMs,t=this.rescheduleIntent;this.rescheduleDelayMs=null,this.rescheduleIntent=!1,this.schedule(e,t)}}}}async prefetchEligibleSessions(){let e=this.snapshot;if(!e?.client||!e.rows||!Vr(e)||document.visibilityState===`hidden`||!this.connected)return;let{client:t}=e;if(await this.snapshotStore.loadSavedAtIndex(),!this.isCurrent(e))return;for(let t of e.openSessionKeys){let n=wn(this.cache,e.snapshotHost,{sessionKey:t});n&&this.cache.size===20&&this.snapshotStore.write(w(e.snapshotHost,{sessionKey:t}),n)}let n=this.selectCandidates(e);n.deferMs!==null&&this.schedule(n.deferMs);for(let r of n.candidates){if(!Vr(this.snapshot,r.sessionKey))return;await this.prefetchCandidate(e,t,r)}}async prefetchCandidate(e,t,n){let r=this.snapshotStore.captureReadScope(n.snapshotKey),i=()=>this.isCurrent(e,n)&&r(),o=()=>i()&&Vr(this.snapshot,n.sessionKey);if(o()&&!this.isOpen(n.snapshotKey,this.snapshot))try{let s=wn(this.cache,e.snapshotHost,{sessionKey:n.snapshotKey});if(!s&&this.snapshotStore.readSavedAt(n.snapshotKey)!==null){if(s=await this.snapshotStore.read(n.snapshotKey),!o())return;s&&(_n(this.cache,e.snapshotHost,{sessionKey:n.snapshotKey},s),r=this.snapshotStore.captureReadScope(n.snapshotKey))}this.lastAttemptAt.set(n.snapshotKey,Date.now());let c=await tn(t,n.snapshotKey,this,o,s?.deltaCursor);if(!i())return;if(c.kind===`reset`){if(s?.deltaCursor!==void 0){let{deltaCursor:t,...i}=s;_n(this.cache,e.snapshotHost,{sessionKey:n.snapshotKey},i),s=i,r=this.snapshotStore.captureReadScope(n.snapshotKey)}if(!o()||(c=await tn(t,n.snapshotKey,this,o),!i()))return}if(this.isOpen(n.snapshotKey,this.snapshot))return;let l;if(c.kind===`delta`){for(let t of c.messages){let r=a(t);r&&Object.hasOwn(r,`message`)&&mn(this.cache,e.snapshotHost,{sessionKey:n.snapshotKey},r.message,r)}let t=wn(this.cache,e.snapshotHost,{sessionKey:n.snapshotKey});if(!t)return;l={...t,...c.inFlightRun?{}:{deltaCursor:c.deltaCursor},...Object.hasOwn(c.sessionInfo,`activeLeafEntryId`)?{displayedLeafEntryId:c.sessionInfo.activeLeafEntryId?.trim()||null}:{},sessionId:c.sessionInfo.sessionId?.trim()||t.sessionId}}else if(c.kind===`snapshot`)l=c.snapshot;else throw Error(`chat history page request returned a cursor reset`);_n(this.cache,e.snapshotHost,{sessionKey:n.snapshotKey},l)}catch(e){Ur(`history fetch failed for ${n.snapshotKey}`,e)}}selectCandidates(e){let t=new Set(e.openSessionKeys.map(t=>w(e.snapshotHost,{sessionKey:t}))),n=Math.max(0,20-t.size),r=(e.rows??[]).toSorted((t,n)=>Number(n.key===e.intentSessionKey)-Number(t.key===e.intentSessionKey)||Hr(n)-Hr(t)),i=[],a=new Set,o=null;for(let s of r){if(!Vr(e,s.key)||h(s))continue;let r=w(e.snapshotHost,{sessionKey:s.key,agentId:s.agentId});if(t.has(r)||a.has(r))continue;if(a.add(r),a.size>n)break;let c=Hr(s),l=this.snapshotStore.readSavedAt(r);if(l!==null&&l>=c)continue;let u=Date.now()-(this.lastAttemptAt.get(r)??0);if(u<Yr){let e=Yr-u;o=o===null?e:Math.min(o,e);continue}if(i.push({activityAt:c,sessionKey:s.key,snapshotKey:r,sessionId:s.sessionId,activeLeafEntryId:s.activeLeafEntryId,updatedAt:s.updatedAt}),i.length===Kr)break}return{candidates:i,deferMs:o}}isCurrent(e,t){let n=this.snapshot;if(!this.connected||document.visibilityState===`hidden`||!e.isCurrent()||!n||n.client!==e.client)return!1;if(!t)return!0;let r=!1;for(let e of n.rows??[]){if(w(n.snapshotHost,{sessionKey:e.key,agentId:e.agentId})!==t.snapshotKey)continue;let i=Hr(e);if(e.sessionId!==t.sessionId||e.activeLeafEntryId!==t.activeLeafEntryId||(e.updatedAt??0)>(t.updatedAt??0)||i>t.activityAt||h(e))return!1;r||=e.updatedAt===t.updatedAt&&i===t.activityAt}return r}isOpen(e,t){return!!t?.openSessionKeys.some(n=>w(t.snapshotHost,{sessionKey:n})===e)}cancelScheduledWork(){this.delayDeadline=null,this.pendingIntent=!1,this.delayTimer!==null&&(globalThis.clearTimeout(this.delayTimer),this.delayTimer=null),this.idleTimer!==null&&(globalThis.clearTimeout(this.idleTimer),this.idleTimer=null),this.idleCallback!==null&&(window.cancelIdleCallback(this.idleCallback),this.idleCallback=null)}},Qr=class{constructor(e,t,n,r){this.host=e,this.readContext=r,this.subscriptions=[],this.intentSessionKey=null,this.handleNavigationIntent=e=>{let t=e.composedPath().find(e=>e instanceof HTMLElement&&e.hasAttribute(`data-session-key`));if(t&&t.closest(`openclaw-app-shell`)!==this.paneRoot.closest(`openclaw-app-shell`))return;let n=t?.dataset.sessionKey??null;n!==this.intentSessionKey&&(this.intentSessionKey=n,this.sync())},this.sync=()=>{let e=this.readContext();if(e!==this.context&&(this.clearSubscriptions(),this.context=e,e&&(this.subscriptions=[e.gateway.subscribe(this.sync),e.sessions.subscribe(this.sync)])),!e)return;let t=[...this.paneRoot.querySelectorAll(`openclaw-chat-pane`)].filter(e=>e.closest(`openclaw-app-shell`)===this.paneRoot.closest(`openclaw-app-shell`)),n=t.flatMap(e=>e.sessionKey?[e.sessionKey]:[]),r=e.sessions,i=r.captureConnectionScope();this.prefetcher.update({client:i?.client??null,isCurrent:()=>this.context===e&&e.sessions===r&&i!==null&&r.isConnectionScopeCurrent(i),listRevision:e.sessions.canonicalListRevision,openSessionKeys:n,intentSessionKey:this.intentSessionKey,automaticPrefetchAllowed:t.some(e=>this.host.contains(e)&&e.conversationPresented===!0),presentedTranscriptsReady:!t.some(e=>e.presented!==!1&&e.transcriptLoading===!0),rows:e.sessions.state.result?.sessions??null,snapshotHost:{assistantAgentId:e.gateway.snapshot.assistantAgentId,agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello}})},this.paneRoot=e,this.prefetcher=new Zr(t,n),e.addController(this)}hostConnected(){this.paneRoot=this.host.closest(`openclaw-app-shell`)??this.host,this.paneRoot.addEventListener(ve,this.sync),this.paneRoot.addEventListener(Ne,this.sync),this.paneRoot.addEventListener(`pointerover`,this.handleNavigationIntent),this.paneRoot.addEventListener(`focusin`,this.handleNavigationIntent),this.prefetcher.connect(),this.sync()}hostUpdated(){this.sync()}hostDisconnected(){this.paneRoot.removeEventListener(ve,this.sync),this.paneRoot.removeEventListener(Ne,this.sync),this.paneRoot.removeEventListener(`pointerover`,this.handleNavigationIntent),this.paneRoot.removeEventListener(`focusin`,this.handleNavigationIntent),this.clearSubscriptions(),this.prefetcher.disconnect()}clearSubscriptions(){for(let e of this.subscriptions)e();this.subscriptions=[],this.context=void 0}}})))()}function ei(){try{return globalThis.indexedDB??null}catch{return null}}async function ti(e,t){await Ue({sessionKey:e,...t?{reason:t}:{}}),await kn(e)}async function ni(){let e=ei();if(e)try{await new Promise(t=>{let n=e.deleteDatabase(Pn);n.addEventListener(`success`,()=>t()),n.addEventListener(`error`,()=>t()),n.addEventListener(`blocked`,()=>t())})}catch{}}async function ri(){await Ue({}),await ni()}function ii(){return(ii=e((()=>{Dn(),_e()})))()}function ai(e,t){t===void 0?console.debug(`[chat-snapshot-cache] ${e}`):console.debug(`[chat-snapshot-cache] ${e}`,t)}function oi(e){try{let t=JSON.stringify(e);return t?JSON.parse(t):null}catch{return null}}function si(e,t){let n=gi.safeParse(e);return n.success&&(!t||n.data.sessionKey===t)?n.data:null}function ci(e,t){let n=oi(t.snapshot);return n?si({cursorMatchesSnapshot:!0,savedAt:t.savedAt,sessionId:t.snapshot.sessionId,sessionKey:e,snapshot:n}):null}async function li(){let e=await jn();if(!e)return[];try{let t=e.transaction(An,`readonly`),n=await Rt(t.objectStore(An).getAll());await Mt(t);let r=[];for(let t of n){let n=_i.safeParse(t);if(!n.success)return ai(`resetting cache after metadata shape mismatch`),await On(e),null;r.push(n.data)}return r}catch(t){return ai(`IndexedDB read failed`,t),await On(e),null}finally{e.close()}}function ui(e){let t=Cn(e.snapshot)??0;try{return t+JSON.stringify({cursorMatchesSnapshot:e.cursorMatchesSnapshot,savedAt:e.savedAt,sessionId:e.sessionId,sessionKey:e.sessionKey}).length}catch{return t}}async function di(e,t){if(e.length===0||t!==j)return[];let n=await jn();if(!n)return[];try{let t=n.transaction([Mn,An],`readwrite`),r=t.objectStore(Mn),i=t.objectStore(An),a=await Rt(i.getAll()),o=new Map;for(let e of a){let n=_i.safeParse(e);if(!n.success)throw t.abort(),Error(`IndexedDB metadata shape mismatch`);o.set(n.data.sessionKey,n.data)}for(let t of e){let e={savedAt:t.savedAt,sessionKey:t.sessionKey,weight:ui(t)};o.set(t.sessionKey,e),r.put(t),i.put(e)}let s=[...o.values()].toSorted((e,t)=>e.savedAt-t.savedAt),c=s.reduce((e,t)=>e+t.weight,0),l=[];for(;s.length>20||c>25165824;){let e=s.shift();if(!e)break;c-=e.weight,r.delete(e.sessionKey),i.delete(e.sessionKey),l.push(e.sessionKey)}return await Mt(t),l}catch(e){return ai(`resetting cache after IndexedDB write failure`,e),await On(n),null}finally{n.close()}}function fi(){for(let e of G)e.flush()}var pi,mi,hi,gi,_i,G,vi;function yi(){return(yi=e((()=>{Kt(),o(),Ft(),gn(),Sn(),Dn(),_e(),ii(),we(),pi=500,mi=Jt(`hasMore`,[L({completeSnapshot:Yt(!0).optional(),hasMore:Yt(!1),totalMessages:z().finite().nonnegative().optional()}).strict(),L({hasMore:Yt(!0),nextOffset:z().finite().nonnegative(),totalMessages:z().finite().nonnegative().optional()}).strict()]),hi=L({deltaCursor:R().optional(),displayedLeafEntryId:R().nullable().optional(),messages:Gt(qt()),pagination:mi,sessionId:R().nullable()}).strict(),gi=L({cursorMatchesSnapshot:Yt(!0).optional(),savedAt:z().finite().nonnegative(),sessionId:R().nullable(),sessionKey:R().min(1),snapshot:hi}).strict().refine(e=>e.sessionId===e.snapshot.sessionId),_i=L({savedAt:z().finite().nonnegative(),sessionKey:R().min(1),weight:z().finite().nonnegative()}).strict(),G=new Set,vi=class{constructor(e){this.memoryCache=e,this.connected=!1,this.pending=new Map,this.hydratedSnapshots=new Map,this.revisions=new Map,this.savedAtBySession=new Map,this.savedAtSeed=null,this.writeTimer=null,this.writeChain=Promise.resolve()}connect(){this.connected=!0,G.add(this)}disconnect(){this.connected=!1,this.flush().finally(()=>{this.connected||G.delete(this)})}captureReadScope(e){let t=j,n=this.revisions.get(e)??0;return()=>t===j&&n===(this.revisions.get(e)??0)}async read(e,t){let n=this.captureReadScope(e),r=ke(e);r&&t?.(r.readyAt);let i=await(r?.promise??Nn(e));if(i===void 0||!n())return null;let a=si(i,e);return a?(a.cursorMatchesSnapshot||delete a.snapshot.deltaCursor,vn(this.hydratedSnapshots,e,new WeakRef(a.snapshot)),a.snapshot):(ai(`resetting cache after record shape mismatch`),await On(),null)}async loadSavedAtIndex(){this.savedAtSeed??=this.seedSavedAtIndex(),await this.savedAtSeed}readSavedAt(e){return this.pending.get(e)?.savedAt??this.savedAtBySession.get(e)??null}write(e,t){b(e)||(ze(e),this.revisions.set(e,(this.revisions.get(e)??0)+1),Tn(this.hydratedSnapshots,e)?.deref()!==t&&(this.hydratedSnapshots.delete(e),this.schedule(e,t)))}async delete(e,t){this.forget(e),await ti(e,t)}forget(e){ze(e),this.revisions.set(e,(this.revisions.get(e)??0)+1),this.pending.delete(e),this.hydratedSnapshots.delete(e),this.savedAtBySession.delete(e),this.memoryCache?.delete(e)}async flush(){this.writeTimer!==null&&(globalThis.clearTimeout(this.writeTimer),this.writeTimer=null);let e=[...this.pending.entries()],t=new Map(e.map(([e])=>[e,this.revisions.get(e)??0]));this.pending.clear();let n=[];for(let[t,r]of e){let e=ci(t,r);e?n.push(e):await this.delete(t,`cache-eviction`)}let r=j;this.writeChain=this.writeChain.then(async()=>{let e=await di(n.filter(({sessionKey:e})=>t.get(e)===(this.revisions.get(e)??0)),r);if(e===null){this.resetSavedAtIndex();return}for(let t of e)this.pending.has(t)||this.savedAtBySession.delete(t)}),await this.writeChain}clearMemory(){this.writeTimer!==null&&(globalThis.clearTimeout(this.writeTimer),this.writeTimer=null),this.pending.clear(),this.hydratedSnapshots.clear(),this.revisions.clear(),this.savedAtBySession.clear(),this.memoryCache?.clear()}async whenIdle(){await this.writeChain}schedule(e,t){let n={savedAt:Date.now(),snapshot:t};this.pending.set(e,n),this.savedAtBySession.set(e,n.savedAt),this.writeTimer!==null&&globalThis.clearTimeout(this.writeTimer),this.writeTimer=globalThis.setTimeout(()=>{this.writeTimer=null,this.flush()},pi)}async seedSavedAtIndex(){let e=j,t=new Map(this.revisions),n=await li();if(e===j){if(!n){this.resetSavedAtIndex();return}for(let e of n){if((t.get(e.sessionKey)??0)!==(this.revisions.get(e.sessionKey)??0))continue;let n=this.savedAtBySession.get(e.sessionKey)??0;this.savedAtBySession.set(e.sessionKey,Math.max(n,e.savedAt))}}}resetSavedAtIndex(){this.savedAtBySession.clear();for(let[e,t]of this.pending)this.savedAtBySession.set(e,t.savedAt)}},be(async({sessionKey:e})=>{for(let t of G)e?t.forget(e):t.clearMemory();await Promise.all([...G].map(e=>e.whenIdle()))}),typeof window<`u`&&(window.addEventListener(`pagehide`,fi),document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&fi()}))})))()}var K;function bi(){return(bi=e((()=>{n(),Ct(),gt(),Ye(),_t(),ot(),mt(),Je(),k(),Ae(),xe(),ir(),or(),fr(),br(),Er(),on(),$t(),Xt(),Nr(),In(),an(),Br(),H(),Sn(),$r(),yi(),B(),K=class extends Re{get conversationPresented(){let e=this.context?.nativeConversation?.presentation;return this.presented&&(!e||e.visible)}get pendingCreate(){return this.data?.creation?.admitted===!1}get sessionSplitAvailable(){return this.presented&&!this.pendingCreate&&!this.narrow&&!this.nativeConversation&&!!this.data?.sessionKey?.trim()}get paneData(){return this.layout?hr(this.context,this.data):this.data}get singleBoundPane(){let e=this.layout?xn(this.layout):[],t=e.length===1?e[0]:void 0;return t&&!this.retainedSessions.unboundPaneIds.has(t.id)?t:void 0}constructor(){super(),this.navDrawerOpen=!1,this.presented=!0,this.narrow=!1,this.mergedChrome=!1,this.wasConversationPresented=!1,this.nativeConversation=Ze()?.surface===`conversation`,this.mediaQuery=null,this.mobileNavMediaQuery=null,this.consumedDraftData=null,this.draftFocus=new zr(this),this.messageCache=new Map,this.snapshotStore=new vi(this.messageCache),this.classicColumnId=`c1`,this.classicPaneId=`p1`,this.routeHref=``,this.closeFocus=new ar(this),this.sessionDrop=new dr(this,{sessionSplitAvailable:()=>this.sessionSplitAvailable,narrow:()=>this.narrow,applySessionDrop:(e,t,n)=>this.applySessionDrop(e,t,n)}),this.mcpAppUnmountGate=new ut(this),this.viewerPresence=new Mr(this),this.retainedSessions=new nn(this,{context:()=>this.context,presented:()=>this.conversationPresented,routeHref:()=>this.routeHref,layout:()=>this.layout??this.classicLayout(),narrow:()=>this.narrow,selectReplacement:(e,t,n)=>this.handlePaneSessionChange(e,t,n),adoptNavigation:(e,t,n)=>this.adoptPaneNavigation(e,t,n)}),this.handleViewportChange=e=>{this.narrow=e.matches,e.matches&&this.sessionDrop.clear()},this.handleMobileNavViewportChange=e=>{this.mergedChrome=this.resolveMergedChrome(e.matches)},this.handleUiCommand=e=>vr(e,{context:this.context,data:this.data,presented:this.presented,pendingCreate:this.pendingCreate,narrow:this.narrow||this.nativeConversation,layout:this.layout,unboundPaneIds:this.retainedSessions.unboundPaneIds,classicLayout:e=>this.classicLayout(e),adoptPaneNavigation:(e,t,n)=>this.adoptPaneNavigation(e,t,n),updateRoute:(e,t,n,r)=>this.updateRoute(e,t,n,r),closeSplitPane:(e,t)=>this.closeSplitPane(e,t),persistLayout:e=>this.persistLayout(e),updateRouteToPane:e=>this.updateRouteToPane(e)}),this.handleFocusPane=(e,t)=>{let n=this.layout;if(!(this.presented||t===`review-edit`)||!n||n.activePaneId===e)return;let r=V(n,e)?.pane;r&&(this.persistLayout(un(n,e)),this.updateRouteToPane(r))},this.handlePaneSessionChange=(e,t,n,r)=>{let i=n.trim();if(!this.presented||!i||window.location.href!==this.routeHref)return!1;let a=this.layout??this.classicLayout(),o=V(a,e)?.pane;return!o||!T(o.sessionKey,t)?!1:(this.layout&&A(i)&&He({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello},o.sessionKey)&&(i=o.sessionKey),this.layout?o.sessionKey===i||(this.persistLayout(dn(a,e,i)),a.activePaneId===e&&this.updateRoute(i,r?.replace),!0):T(o.sessionKey,i)?(this.syncRouteBindings(),!0):(this.updateRoute(i,r?.replace),!0))},this.handlePaneFaceChange=(e,t,n)=>{if(!this.presented)return;let r=V(this.layout??this.classicLayout(),e)?.pane.sessionKey;if(r&&T(r,t)){if((!this.layout||this.layout.activePaneId===e)&&T(this.data.sessionKey,t)&&(this.data.face??`chat`)===n){this.syncRouteBindings();return}this.layout&&this.layout.activePaneId!==e&&this.persistLayout(un(this.layout,e)),this.updateRoute(t,!1,n)}},this.openSplitView=()=>this.handleSplit(this.classicPaneId,`right`),this.handleSplitRight=e=>this.handleSplit(e,`right`),this.handleSplitDown=e=>this.handleSplit(e,`down`),this.handleClosePane=e=>{this.layout&&this.closeSplitPane(this.layout,e)},new Le(this).watch(()=>this.context?.sessions,(e,t)=>e.subscribe(t),void 0,()=>this.performUpdate()).watch(()=>this.context?.chatSubmissions,(e,t)=>e.subscribeCreate(t)).watch(()=>this.context?.placementStartup,(e,t)=>e.subscribe(t)).watch(()=>this.context?.gateway,(e,t)=>e.subscribe(t)).watch(()=>this.context?.nativeConversation,(e,t)=>e.subscribe(t)),Gr(this,this.messageCache,this.snapshotStore,()=>this.context)}connectedCallback(){super.connectedCallback(),this.toggleAttribute(`data-native-conversation`,this.nativeConversation),this.snapshotStore.connect(),yn(this.messageCache,this.snapshotStore),this.routeHref=window.location.href,this.layout=this.nativeConversation?void 0:lt().chatSplitLayout,this.retainedSessions.restore(this.layout?xn(this.layout):[]),this.unboundRoute=this.layout&&this.retainedSessions.unboundPaneIds.has(this.layout.activePaneId)?this.paneData:void 0,this.mediaQuery=window.matchMedia(`(max-width: 1099px)`),this.narrow=this.mediaQuery.matches,this.mediaQuery.addEventListener(`change`,this.handleViewportChange),this.mobileNavMediaQuery=window.matchMedia(Xe()),this.mergedChrome=this.resolveMergedChrome(this.mobileNavMediaQuery.matches),this.mobileNavMediaQuery.addEventListener(`change`,this.handleMobileNavViewportChange),this.sessionDrop.connect(),window.addEventListener($e,this.handleUiCommand),this.retainedSessions.connect(),this.syncRouteToActivePane(),this.syncRouteBindings();let e=this.layout??this.classicLayout();this.conversationPresented&&!this.pendingCreate&&this.viewerPresence.sync(this.context?.gateway,e,this.narrow,this.retainedSessions.unboundPaneIds)}disconnectedCallback(){this.closeFocus.clear(),this.snapshotStore.disconnect(),this.retainedSessions.disconnect(),this.viewerPresence.dispose(),this.mediaQuery?.removeEventListener(`change`,this.handleViewportChange),this.mediaQuery=null,this.mobileNavMediaQuery?.removeEventListener(`change`,this.handleMobileNavViewportChange),this.mobileNavMediaQuery=null,this.sessionDrop.disconnect(),window.removeEventListener($e,this.handleUiCommand),super.disconnectedCallback()}updated(e){if(this.wasConversationPresented&&!this.conversationPresented&&(this.retainedSessions.suspend(),this.sessionDrop.clear()),this.wasConversationPresented=this.conversationPresented,!this.conversationPresented||this.pendingCreate){this.closeFocus.clear(),this.viewerPresence.dispose();return}let t=this.layout??this.classicLayout();en(this,t,this.narrow),this.isConnected&&this.viewerPresence.sync(this.context?.gateway,t,this.narrow,this.retainedSessions.unboundPaneIds),this.closeFocus.restore(this.layout,this.mcpAppUnmountGate.retiring);let n=this.paneData,r=this.layout?V(this.layout,this.layout.activePaneId)?.pane:null,i=this.layout?r?.sessionKey??null:void 0,a=this.draftFocus.rendered(n,i,this.consumedDraftData),o=this.data!==this.processedRouteData;if(n&&(o||e.has(`presented`))){if(this.processedRouteData=this.data,this.routeHref=window.location.href,n?.canonicalLocation&&rr(n.canonicalLocationSource,this.consumedDraftData===n)){this.context.replace(n.face??`chat`,n.canonicalLocation);return}n?.canonicalLocationReady?.then(e=>{e&&this.isConnected&&this.presented&&this.paneData===n&&rr(n.canonicalLocationSource,this.consumedDraftData===n)&&this.context.replace(n.face??`chat`,this.consumedDraftData===n?Zn(e):e)}),(o||!this.singleBoundPane)&&this.syncRouteToActivePane(),this.syncRouteBindings(),this.retainedSessions.settleRoute()}n&&a&&queueMicrotask(()=>{this.isConnected&&this.presented&&this.paneData===n&&this.consumedDraftData!==n&&(this.draftFocus.beforeDraftCleanup(n),this.consumedDraftData=n,this.updateRoute(n.sessionKey,!0,n.face??`chat`),this.requestUpdate())});let s=this.singleBoundPane,c=this.layout?.columns[0];s&&c&&!this.mcpAppUnmountGate.retiring&&T(s.sessionKey,n?.sessionKey??``)&&(this.classicColumnId=c.id,this.classicPaneId=s.id,this.persistLayout(void 0))}resolveMergedChrome(e){let t=e&&!this.nativeConversation;return tt(t,this.closest(`.shell--onboarding`)!==null)}syncRouteToActivePane(){let e=this.layout,t=this.paneData?.sessionKey?.trim();if(!e||!t||this.pendingCreate)return;let n=V(e,e.activePaneId)?.pane;n&&n.sessionKey!==t&&(this.retainedSessions.unboundPaneIds.has(n.id)&&this.retainedSessions.wasPendingAtFocus()&&(this.unboundRoute=this.paneData),!(this.retainedSessions.unboundPaneIds.has(n.id)&&pr(this.context,this.unboundRoute,this.paneData))&&(this.retainedSessions.bindPane(n.id),this.persistLayout(dn(e,n.id,t))))}syncRouteBindings(e=this.data?.agentId){if(!this.presented||this.pendingCreate)return;let t=this.layout&&V(this.layout,this.layout.activePaneId)?.pane,n=(t?.sessionKey??this.data?.sessionKey)?.trim();this.context&&n&&(!t||!this.retainedSessions.unboundPaneIds.has(t.id))&&Zt(this.context,n,e)}adoptPaneNavigation(e,t,n){!this.layout||A(t)&&!n?.trim()||(this.retainedSessions.bindPane(e),this.unboundRoute=void 0,this.persistLayout(dn(this.layout,e,gr(this.context,t,n)),n))}persistLayout(e,t){this.layout=e,et({chatSplitLayout:this.singleBoundPane?void 0:e}),this.syncRouteBindings(t)}updateRoute(e,t=!1,n,r){this.presented&&_r(this.context,this.data,e,t,n,r)}updateRouteToPane(e){if(this.retainedSessions.unboundPaneIds.has(e.id)){this.retainedSessions.capturePendingNavigation(),this.unboundRoute=this.paneData;return}this.unboundRoute=void 0;let t=this.retainedSessions.findPane(e.id,e.sessionKey);this.updateRoute(e.sessionKey,!0,t?.captureNavigationFace?.())}applySessionDrop(e,t,n){let r=e.trim();if(!r)return;if(!this.layout&&n.kind===`center`){this.updateRoute(r);return}let i=this.layout??this.classicLayout(hr(this.context,this.data)?.sessionKey),a=this.layout?t:this.classicPaneId,o=V(i,a)?.pane;if(o&&(this.layout||o.sessionKey)){if(n.kind===`center`){if(o.sessionKey===r)return;let e=un(i,a);this.persistLayout(dn(e,a,r)),this.updateRoute(r,!0);return}this.persistLayout(fn(i,a,r,n.edge)),this.updateRoute(r,!0)}}handleSplit(e,t){let n=this.layout??this.classicLayout(hr(this.context,this.data)?.sessionKey?.trim()),r=V(n,e)?.pane;r?.sessionKey&&this.persistLayout(fn(n,e,r.sessionKey,t))}closeSplitPane(e,t){if(this.singleBoundPane)return;let n=this.closeFocus.capture(t),r=rn(this.context,this,e,t);this.retainedSessions.discardPane(t);let i=hn(e,t,this.retainedSessions.unboundPaneIds);if(!i&&r){let t=V(e,r.id);t&&(this.classicColumnId=t.column.id,this.classicPaneId=r.id,T(r.sessionKey,this.paneData?.sessionKey??``)||(i=this.classicLayout(r.sessionKey)))}this.persistLayout(i);let a=i?V(i,i.activePaneId)?.pane:r;a&&(this.updateRouteToPane(a),n&&this.closeFocus.schedule(n,a,i))}classicLayout(e=this.data?.sessionKey?.trim()??``){return pn(this.classicColumnId,this.classicPaneId,e)}renderSplitLayout(e,t,n){return Cr(e,{narrow:this.narrow,activePaneId:t&&this.conversationPresented?e.activePaneId:void 0,renderPane:(r,i,a)=>Sr({active:this.conversationPresented&&i.id===e.activePaneId,presented:this.conversationPresented,chatMessagesBySession:this.messageCache,sessionSnapshotStore:this.snapshotStore,consumedDraftData:this.consumedDraftData,context:this.context,data:this.paneData,draftFocus:this.draftFocus,mergedChrome:this.mergedChrome,narrow:this.narrow,navDrawerOpen:this.navDrawerOpen,onboarding:this.closest(`.shell--onboarding`)!==null,onClosePane:t?this.handleClosePane:void 0,onFaceChange:this.handlePaneFaceChange,onFocusPane:this.handleFocusPane,onOpenSplitView:t||this.narrow||this.nativeConversation?void 0:this.openSplitView,onPaneSessionChange:this.handlePaneSessionChange,onSessionDeleted:this.retainedSessions.removeSession,onSplitDown:t?this.handleSplitDown:void 0,onSplitRight:t?this.handleSplitRight:void 0,ownerKey:JSON.stringify([r.id,i.id]),pane:i,panePosition:{column:e.columns.indexOf(r)+1,row:r.panes.indexOf(i)+1},sessionSlots:n.get(i.id)??[],splitMode:t,unbound:this.retainedSessions.unboundPaneIds.has(i.id),weight:a}),onResizePanes:(e,t,n)=>{this.layout=this.layout?bn(this.layout,e,t,n):void 0},onResizeColumns:(e,t)=>{this.layout=this.layout?sn(this.layout,e,t):void 0},onResizeEnd:()=>this.persistLayout(this.layout)})}render(){if(this.pendingCreate)return this.mcpAppUnmountGate.render(`pending-create`,()=>Tr(this.context,this.data.sessionKey,this.conversationPresented),()=>[...this.querySelectorAll(`openclaw-chat-pane`)]);let e=this.layout??this.classicLayout(),t=this.retainedSessions.retain(xn(e)),n=xr(this.context,e,t),r=()=>wr(this.renderSplitLayout(e,!(!this.layout||this.singleBoundPane),t),this.sessionDrop.indicator);return this.mcpAppUnmountGate.render(JSON.stringify([...n]),r,()=>[...this.querySelectorAll(`openclaw-chat-pane`)].filter(e=>!n.has(e.dataset.mcpAppOwnerKey??``)))}},S([se({context:ht,subscribe:!0})],K.prototype,`context`,void 0),S([Et({attribute:!1})],K.prototype,`data`,void 0),S([Et({attribute:!1})],K.prototype,`navDrawerOpen`,void 0),S([Et({type:Boolean})],K.prototype,`presented`,void 0),S([xt()],K.prototype,`layout`,void 0),S([xt()],K.prototype,`narrow`,void 0),S([xt()],K.prototype,`mergedChrome`,void 0),customElements.get(`openclaw-chat-page`)||customElements.define(`openclaw-chat-page`,K)})))()}function xi(e){window.history.pushState({},``,e),window.dispatchEvent(new PopStateEvent(`popstate`))}function Si(e){return F`
    <section class="card">
      <h2>${O(`chat.sessionRoute.chooseTitle`)}</h2>
      <p>
        ${e.candidates.length>1?O(`chat.sessionRoute.multipleMatches`,{shortId:e.shortId}):O(`chat.sessionRoute.additionalMatches`)}
      </p>
      ${e.candidates.map(e=>F`
          <p>
            <a href=${e.href}>${e.displayName}</a><br />
            <small>${e.agentId} · ${e.idPrefix}</small>
          </p>
        `)}
      ${e.truncated&&e.candidates.length>1?F`<p><small>${O(`chat.sessionRoute.additionalMatches`)}</small></p>`:null}
    </section>
  `}function Ci(e){return dt({className:`session-route-not-found`,role:`status`,title:O(`chat.sessionRoute.notFoundTitle`),subtitle:O(`chat.sessionRoute.notFoundExplanation`),actions:F`
      <button class="btn primary" type="button" @click=${()=>xi(e.currentSessionHref)}>
        ${O(`chat.sessionRoute.goToMain`)}
      </button>
      <button class="btn" type="button" @click=${()=>xi(e.sessionsHref)}>
        ${O(`chat.sessionRoute.viewSessions`)}
      </button>
    `})}function wi(e,t=!1,n=!0){let r=e;return r?r.kind===`ambiguous`?Si(r):r.kind===`route-error`?F`<section class="card"><p role="alert">${r.message}</p></section>`:r.kind===`missing-session`?Ci(r):F`<openclaw-chat-page .data=${r} .presented=${n}></openclaw-chat-page>`:I}function Ti(e,t){return(e.data??t?.data)?.kind===`session`?Ei:void 0}var Ei;function Di(){return(Di=e((()=>{yt(),it(),Be(),Ei=`chat-page`})))()}var Oi,ki,Ai,ji;function Mi(){return(Mi=e((()=>{bi(),Di(),Oi=!0,ki=Ti,Ai=!0,ji=wi})))()}async function Ni(e,t,n,r){let i=await M(e.gateway,r);r.throwIfAborted();let{gateway:a,sessions:o}=e,{hello:s}=a.snapshot,l=a.snapshot.selfUser?.id,u=a.connectionRevision,d=e.lifecycleAbortSignal,f=!1,p=()=>!f&&!r.aborted&&!d?.aborted&&e.sessions===o&&a.connectionRevision===u&&a.snapshot.phase===`connected`&&a.snapshot.client===i&&a.snapshot.hello===s&&a.snapshot.selfUser?.id===l,m=Promise.resolve().then(async()=>{r.throwIfAborted();let e=await i.request(`sessions.resolve`,{shortId:t.shortId,...t.slugHint?{slugHint:t.slugHint}:{},agentId:t.agentId,allowMissing:!0});return r.throwIfAborted(),{...Pi(e),isCurrent:p}});if(t.namespace!==`chat`||n.search||n.hash||!s)return m;let h=ae(),g=!1,_=()=>{},v=()=>{},y=()=>{_(),v(),r.removeEventListener(`abort`,x),d?.removeEventListener(`abort`,x)},b=()=>{f=!0,y()},x=()=>{b(),h.reject(r.aborted?r.reason:d?.reason)};_=a.subscribeEvents(e=>{if(e.event!==`models.snapshot`||!p())return;let n=e.payload,r=n.target,i=n.scope;`shortId`in r&&r.agentId===t.agentId&&r.shortId===t.shortId&&r.slugHint===t.slugHint&&i.sessionKey&&i.agentId&&c(i.agentId)===c(t.agentId)&&E(i.sessionKey)?.agentId===c(t.agentId)&&Rn(i.sessionKey)?.startsWith(t.shortId.toLowerCase())&&h.resolve({kind:`prepared`,session:{key:i.sessionKey,agentId:i.agentId},resolution:m,isCurrent:p})}),v=a.subscribe(()=>{p()||b()}),r.addEventListener(`abort`,x,{once:!0}),d?.addEventListener(`abort`,x,{once:!0});try{r.throwIfAborted(),d?.throwIfAborted(),p()||b();let e=await Promise.race([m,h.promise]);if(e.kind===`prepared`){if(!p())return await m;g=!0,m.then(y,y)}return e}finally{_(),g||y()}}function Pi(e){return e.ok?{kind:`unique`,session:e}:e.candidates?.length?{kind:`ambiguous`,sessions:e.candidates,truncated:e.candidates.length===10}:{kind:`not-found`}}function Fi(){return(Fi=e((()=>{p(),Qe(),k(),Vn()})))()}function q(e,t,n){let r=Ee({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello}),a=i({agentId:n,mainKey:r});return{kind:`missing-session`,face:t,currentSessionHref:Ge({context:e,face:t,sessionKey:a,agentId:n}).href,sessionsHref:ct(`sessions`,e.basePath)}}function Ii(e,t,n){let r=e.toLowerCase().replaceAll(`-`,``);if(!x.test(r))return null;if(n)return r;let i=t.map(e=>e.toLowerCase().replaceAll(`-`,``));for(let e=8;e<=r.length;e+=1){let t=r.slice(0,e);if(i.filter(e=>e.startsWith(t)).length===1)return t}return r}async function J(e,t,n){let r=await M(e.gateway,n);n.throwIfAborted();let i=Li.get(r)??new Map;Li.set(r,i);let a=JSON.stringify([c(t.agentId),t.key,t.slug]),o=i.get(a);if(!o||o.controller.signal.aborted){let n=new AbortController,{hello:s}=e.gateway.snapshot,c=()=>e.gateway.snapshot.phase===`connected`&&e.gateway.snapshot.client===r&&e.gateway.snapshot.hello===s;o={controller:n,promise:Promise.resolve().then(async()=>{if(n.signal.throwIfAborted(),!c())return null;try{let e=await r.request(`sessions.resolve`,{reference:{key:t.key,...t.slug?{slug:t.slug}:{}},agentId:t.agentId,includeGlobal:!0,includeUnknown:!0,allowMissing:!0});return c()?Pi(e):null}catch(e){if(!c())return null;throw e}}),subscribers:new Set},i.set(a,o)}let s=o;return await kt(s,n,n,()=>{s.subscribers.size===0&&i.get(a)===s&&i.delete(a)})}var Li;function Ri(){return(Ri=e((()=>{v(),rt(),Qe(),D(),k(),Fi(),Li=new WeakMap})))()}function zi(e,t){return t.length>=e.minPrefixLength&&t.length<=e.fullLength&&Vi.test(t)}function Bi(e){let t=ne(e.threadId),n=e.shareRoute;if(!t||!Hi.test(n.routeSegment)||f(n.routeSegment)||t.length!==n.fullLength||!Vi.test(t))return null;let i=Math.min(n.fullLength,Math.max(n.minPrefixLength,Math.floor(e.prefixLength??n.minPrefixLength))),a=r(e.displayName);return`${l(e.basePath)}/${n.routeSegment}/${a?`${a}-`:``}${t.slice(0,i)}`}var Vi,Hi;function Ui(){return(Ui=e((()=>{ie(),_(),Vi=/^[0-9a-f]+$/u,Hi=/^[a-z][a-z0-9-]*$/u})))()}function Wi(e,t){let n=new URLSearchParams(t.search),r=n.get(P),i=r||t.pathname,a=re({pathname:i,basePath:e.basePath});if(!a||!r)return a?{target:a,location:t}:null;n.delete(P);let o=n.toString();return{target:a,location:{...t,pathname:i,search:o?`?${o}`:``}}}function Y(e){return{kind:`route-error`,message:e,face:`chat`}}async function Gi(e,t,n){let r=Wi(e,t);if(!r)return null;let{target:i,location:a}=r;try{let t=await M(e.gateway,n);n.throwIfAborted();let r=ge({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello}),o=await t.request(`sessions.catalog.list`,{agentId:r,search:i.shortId,limitPerHost:2});n.throwIfAborted();let s=o.catalogs.filter(e=>e.shareRoute?.routeSegment===i.routeSegment),c=s.length===1?s[0]:void 0;if(!c?.shareRoute)return Y(O(`chat.sessionRoute.catalogShareUnavailable`));let l=c.shareRoute;if(!zi(l,i.shortId))return Y(O(`chat.sessionRoute.catalogShareInvalid`,{catalog:c.label}));if(c.error)return Y(c.error.message);let u=c.hosts.filter(e=>e.hostId===l.hostId),d=u.length===1?u[0]:void 0;if(!d)return Y(O(`chat.sessionRoute.catalogShareUnavailable`));if(d?.error)return Y(d.error.message);let f=d.sessions.filter(e=>zi(l,e.threadId)&&e.threadId.length===l.fullLength&&e.threadId.startsWith(i.shortId));if(f.length>1||d.nextCursor){let t=f.flatMap(t=>{let n=Bi({shareRoute:l,threadId:t.threadId,displayName:t.name,basePath:e.basePath,prefixLength:l.fullLength});return n?[{agentId:c.label,displayName:t.name?.trim()||t.threadId,href:n,idPrefix:t.threadId}]:[]});return{kind:`ambiguous`,shortId:i.shortId,candidates:t,truncated:!!d.nextCursor,face:`chat`}}let p=f[0];if(!p)return q(e,`chat`,r);let m=Bi({shareRoute:l,threadId:p.threadId,displayName:p.name,basePath:e.basePath,prefixLength:i.shortId.length});return m?{kind:`session`,sessionKey:We({catalogId:c.id,hostId:l.hostId,threadId:p.threadId},r),agentId:r,draft:void 0,face:`chat`,...m===a.pathname?{}:{canonicalLocation:{...a,pathname:m},canonicalLocationSource:a}}:Y(O(`chat.sessionRoute.catalogShareUnavailable`))}catch(e){return n.throwIfAborted(),Y(ue(e,O(`chat.sessionRoute.catalogShareUnavailable`)))}}function Ki(){return(Ki=e((()=>{te(),Ui(),rt(),Qe(),Be(),Ie(),le(),k(),Ri()})))()}function X(e){return{...Qn(e),...new URLSearchParams(e.search).get(`dashboard`)===`expanded`?{dashboardExpanded:!0}:{}}}function qi(e){return new URLSearchParams(e.search).get(Ce)===`1`}function Ji(e,t){let n=new URLSearchParams(e.search);n.delete(t);let r=n.toString();return{...e,search:r?`?${r}`:``}}function Z(e){return Ji(Ji(e,Ce),Te)}function Q(e){return Ee({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello})}function Yi(e){return!!(e.agents.state.agentsList?.mainKey?.trim()||e.gateway.snapshot.phase===`connected`&&e.gateway.snapshot.hello)}function Xi(e,t,n,r){let i=E(r);if(!i)return null;let a=Q(e).toLowerCase();if(i.rest.toLowerCase()!==a)return null;let o=N(n,i.agentId,r,e.basePath,{mainKey:a});return o&&o!==t.pathname?{...Z(t),pathname:o}:null}function Zi(e){let t=e.face,n=Me(e.row.key),r=N(t,n,e.row.key,e.context.basePath,{displayName:e.row.displayName,mainKey:Q(e.context),shortIdLength:e.shortIdLength});if(!r)return;let i=Z(e.location);return r!==e.location.pathname||i.search!==e.location.search?{...i,pathname:r}:null}function Qi(e,t){let n=Q(e),r=m(t.pathname,e.basePath,n);if(r)return{target:r,location:t};let i=new URLSearchParams(t.search).get(P);if(!i)return null;let a=m(i,e.basePath,n);return a?{target:a,location:{...Ji(t,P),pathname:i}}:null}function $i(e,t){return i({agentId:t.agentId,mainKey:Q(e)})}function ea(e,t,n,r,i){let a=n.sessions.flatMap(e=>{let t=Rn(e.key);return t?[{row:e,uuid:t}]:[]}),o=a.map(({uuid:e})=>e);return a.flatMap(({row:a,uuid:s})=>{let c=Ii(s,o,n.truncated);if(!c)return[];let l=Me(a.key),u=i?Ke(a):t,d=N(u,l,a.key,e.basePath,{displayName:a.displayName,mainKey:Q(e),shortIdLength:c.length});return d?[{agentId:l,displayName:a.displayName?.trim()||a.key,href:`${d}${$n(r)}`,idPrefix:c}]:[]})}function $(e){let t=e.preferenceDerived?Ke(e.row):e.face,n=Zi({context:e.context,location:e.location,face:t,row:e.row,...e.shortId?{shortIdLength:e.shortId.length}:{}});return n===void 0?null:(n&&e.isResolutionSourceCurrent()&&Bt(e.context.gateway,n.pathname,e.row.key),{kind:`session`,sessionKey:e.row.key,...e.row.agentId?{agentId:e.row.agentId}:{},...X(e.location),face:t,...e.shortId&&e.shortId.length>8?{shortId:e.shortId}:{},...n?{canonicalLocation:n,canonicalLocationSource:e.location}:{}})}function ta(e){if(!A(e.row.key))return $(e);let t=e.preferenceDerived?Ke(e.row):e.face,n=N(t,e.target.agentId,$i(e.context,e.target),e.context.basePath,{mainKey:Q(e.context)});if(!n)return null;let r=Z(e.location),i=n!==e.location.pathname||r.search!==e.location.search?{...r,pathname:n}:void 0;return{kind:`session`,sessionKey:e.row.key,agentId:e.target.agentId,...X(e.location),face:t,...i?{canonicalLocation:i,canonicalLocationSource:e.location}:{}}}async function na(e,t,n,r,i){let{client:a,hello:o}=e.gateway.snapshot,s=()=>e.gateway.snapshot.phase===`connected`&&e.gateway.snapshot.client===a&&e.gateway.snapshot.hello===o,c=n===`chat`&&await Gi(e,t,r);if(c)return c;let l=Qi(e,t);if(!l||l.target.namespace!==n)return C({routeId:n});let{target:u}=l,d=l.location,f=qi(d),p=i?.sessionKey&&(u.kind===`short`||u.kind===`literal`&&u.slugCandidate)?await J(e,{key:i.sessionKey,agentId:u.agentId},r):void 0;if(p===null)throw Error(`The Gateway connection changed while resolving the session.`);let m=Yi(e)&&e.agents.state.agentsList?.scope!==`global`,h=fe(d.search);if(u.kind===`main`&&h){let t=We(h),i=f?Z(d):null,a=n;if(f){let n=await J(e,{key:t,agentId:u.agentId},r);if(n?.kind===`unique`){a=Ke(n.session);let t=N(a,u.agentId,$i(e,u),e.basePath,{mainKey:Q(e)});t&&(i={...Z(d),pathname:t})}}return{kind:`session`,sessionKey:We(h,u.agentId),agentId:u.agentId,...X(d),face:a,...i?{canonicalLocation:i,canonicalLocationSource:d}:{}}}if(u.kind===`main`){(f||!m)&&await M(e.gateway,r);let t=$i(e,u);if(f){let i=await J(e,{key:t,agentId:u.agentId},r);if(i?.kind===`unique`)return ta({context:e,isResolutionSourceCurrent:s,location:d,face:n,row:i.session,target:u,preferenceDerived:f})??C({routeId:n})}let i=f?Z(d):null;return{kind:`session`,sessionKey:t,...X(d),face:n,...i&&i.search!==d.search?{canonicalLocation:i,canonicalLocationSource:d}:{}}}if(u.kind===`literal`){let t=m||e.gateway.snapshot.phase===`connected`&&Yi(e),a=f||!!u.slugCandidate;if(!t&&a&&(await M(e.gateway,r),t=Yi(e),t))return await na(e,d,n,r,i);if(a){let a=t&&!i?je(e,u.sessionKey,u.agentId):void 0,o=p??(a?{kind:`unique`,session:a}:await J(e,{key:u.sessionKey,agentId:u.agentId,...u.slugCandidate?{slug:u.slugCandidate}:{}},r));if(o?.kind===`unique`){let t=$({context:e,isResolutionSourceCurrent:s,location:d,face:n,row:o.session,preferenceDerived:f});return t?{...t,...a?{sessionResolutionFromCache:!0}:{}}:C({routeId:n})}if(u.slugCandidate){if(o?.kind===`not-found`)return q(e,n,u.agentId);if(o?.kind===`ambiguous`)return{kind:`ambiguous`,shortId:u.slugCandidate,candidates:ea(e,n,o,d,f),truncated:o.truncated,face:n}}}let o=t?Xi(e,d,n,u.sessionKey):null,c=E(u.sessionKey),l=!t&&c?M(e.gateway,r).then(()=>Xi(e,d,n,u.sessionKey)).catch(()=>null):void 0,h=f?Z(d):null;return{kind:`session`,sessionKey:u.sessionKey,...X(d),face:n,...o?{canonicalLocation:o,canonicalLocationSource:d}:h&&h.search!==d.search?{canonicalLocation:h,canonicalLocationSource:d}:{},...l?{canonicalLocationReady:l,canonicalLocationSource:d}:{}}}let g=i?void 0:Bn(e,d,u);if(g&&!g.row){let e=Z(d),t=e.search!==d.search;return{kind:`session`,sessionKey:g.sessionKey,agentId:u.agentId,...X(d),face:n,...u.shortId.length>8?{shortId:u.shortId}:{},...t?{canonicalLocation:e,canonicalLocationSource:d}:{}}}let _=g?.row;!g&&m&&!f&&!i&&(await e.sessions.whenCachedRosterSettled(),r.throwIfAborted(),e.sessions.state.resultCached&&(_=zn(e.sessions.state.result?.sessions??[],u,Q(e))));let v=p?{...p,isCurrent:s}:_?{kind:`unique`,session:_,isCurrent:s}:await Ni(e,u,d,r);if(v.kind===`prepared`){let t=v.resolution.then(t=>!v.isCurrent()||t.kind!==`unique`||t.session.key!==v.session.key||(t.session.agentId??Me(t.session.key))!==v.session.agentId?null:$({context:e,isResolutionSourceCurrent:v.isCurrent,location:d,face:n,row:t.session,preferenceDerived:!1,shortId:u.shortId})?.canonicalLocation??null).catch(()=>null);return{kind:`session`,sessionKey:v.session.key,agentId:v.session.agentId,face:n,routeLoadingSkeleton:!0,...u.shortId.length>8?{shortId:u.shortId}:{},canonicalLocationReady:t,canonicalLocationSource:d}}if(v.kind===`not-found`){if(p)return q(e,n,u.agentId);let t=await J(e,{key:u.literalSessionKey,agentId:u.agentId},r);return t?.kind===`unique`?$({context:e,isResolutionSourceCurrent:s,location:d,face:n,row:t.session,preferenceDerived:f})??C({routeId:n}):t?.kind===`not-found`?q(e,n,u.agentId):C({routeId:n})}if(v.kind===`ambiguous`)return{kind:`ambiguous`,shortId:u.shortId,candidates:ea(e,n,v,d,f),truncated:v.truncated,face:n};let y=$({context:e,isResolutionSourceCurrent:v.isCurrent,location:d,face:n,row:v.session,preferenceDerived:f,shortId:u.shortId});return y?{...y,..._?{sessionResolutionFromCache:!0}:{routeLoadingSkeleton:!0}}:C({routeId:n})}async function ra(e,t,{location:n,signal:r,cause:i,deps:a}){let o=(i===`revalidate`?e.router.getState().matches.find(e=>e.routeId===t&&e.deps===a):void 0)?.data,s=await na(e,n,t,r,i===`revalidate`?{sessionKey:o?.kind===`session`?o.sessionKey:void 0}:void 0),c=e.chatSubmissions.creation;return`kind`in s&&s.kind===`session`&&(c?.sessionKey===s.sessionKey&&(s.creation=c),(s.creation||e.placementStartup.get(s.sessionKey)?.initialTurn)&&(await oe(()=>import(`./pending-session-create-B6nT760e.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]),import.meta.url),r.throwIfAborted())),s}function ia(){return(ia=e((()=>{ee(),rt(),st(),nt(),Qe(),le(),zt(),D(),k(),H(),Ki(),Ri(),Vn(),Fi(),t()})))()}export{Wn as C,In as D,Ln as E,Fn as O,Un as S,Vn as T,ti as _,Ri as a,Gn as b,Ii as c,ji as d,ki as f,ri as g,ni as h,Qi as i,Oi as l,bi as m,na as n,q as o,Ai as p,ra as r,J as s,ia as t,Mi as u,ii as v,zn as w,Jn as x,qn as y};