UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

670 lines • 529 kB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./video-poster-Ds-NFg37.js","./control-ui-boot-shared-DBJri5ri.js","./plugin-contracts-runtime-CsJ0WpAd.js","./markdown-runtime-Hc-lvqnn.js","./config-runtime-CgOgfOrG.js","./css-chat-Ckz95ikh.js","./chat-transcript-layout-w3EszKw8.js","./css-chat-custodian-new-session-B_euK-Vu.js","./sidebar-update-runtime-B0vYzX3D.js","./control-ui-core-D-VUH4Gq.css","./css-chat-DCHf01mf.css","./css-chat-custodian-new-session-CEndYuO5.css","./control-ui-boot-shared-BJ_QKfFn.css","./sidebar-update-runtime-ah7rgQE7.css","./chat-native-runtime-recovery-ttYYPde6.js","./chat-sidebar-region.runtime-BeUv-jNa.js","./panel-tab-strip-BM8uM2tc.js","./panel-empty-state-BO6bnLg_.js","./chat-sidebar-region-Bnr5VgzZ.css","./terminal-panel-registration-D5VvSsFk.js","./terminal-panel-registration-DCAn7CIA.js","./scrollbar-styles-BielkyQ9.js","./dock-panel-styles-lbOjSYYD.js","./dock-destination-controls-BlZlW68m.js","./theme-color-DAo4KRoc.js","./catalog-terminal-start-CKAPUE5U.js","./link-reader-panel-DdSQDdBY.js","./link-reader-response-Cct0r21o.js","./browser-panel-BZcARBB-.js","./browser-panel-DNPuq5oF.js","./gateway-websocket-url-cYJwVUmD.js","./desktop-panel-YZcYHBlM.js","./desktop-panel-B-wMMJaC.js","./desktop-focus-window-BlH9P8oZ.js","./portals-page-BjP25pFE.js","./portals-page-pG5r4WM8.css","./chat-session-rail-RNyFzpdR.js","./chat-session-rail-BUhZvTJ7.css","./session-discussion-panel-CrbgRdV1.js","./composer-draft-store.runtime-v4vUYxIm.js","./board-view-3OMPWlN8.js","./board-view-BD5Z3h_5.js","./control-ui-disabled-DNN1S8_t.js","./near-viewport-observer-WgGck829.js","./widget-sandbox-host-BQH21b5-.js","./board-view-DSwvd-aj.css","./chat-outbox-receipts-Cg60kvyq.js","./swarm-roster-udqDx5Ow.js","./control-ui-boot-chat-DCYcb1Hy.js","./css-cron-custodian-new-session-DdqVeFqw.js","./chat-transcript-styles-BVZgOT1t.js","./css-agents-plugins-skill-workshop-skills-DvcafeYi.js","./css-new-session-BGJnpiJ5.js","./css-skill-workshop-D2ZfJfdl.js","./css-question-Ct0OXZAc.js","./session-snapshot-database-CobUvfK7.js","./css-cron-custodian-new-session-Ci5c-FgJ.css","./chat-transcript-styles-DHHd4Hhc.css","./css-agents-plugins-skill-workshop-skills-DP4CzO_X.css","./css-new-session-C71huhgC.css","./css-skill-workshop-CWhVVscF.css","./css-question-DeaP1V6y.css","./control-ui-boot-chat-CPmZGJw4.css","./chat-pane-placement.runtime-D8SiBRyF.js","./control-ui-boot-new-BTHisEC4.js","./css-config-njfbfHBk.js","./cloud-worker-stop.runtime-Deft5Au6.js","./css-config-vi6FusyS.css","./control-ui-boot-new-D-SpiTTi.css","./session-organizer-operations.runtime-iW_lN0Ec.js","./session-workspace-recovery.runtime-DzJr_zYd.js","./input-dialog-3BQGQ1js.js","./input-dialog-CHRxMdbT.js","./modal-dialog-BgQB7Fm_.js"])))=>i.map(i=>d[i]);
import{n as e}from"./rolldown-runtime-8BhlS34s.js";import{At as t,Bi as n,Br as r,Da as i,Ea as a,Et as o,Gi as s,Ji as c,Ki as l,Li as u,Oa as d,Pa as f,Tt as p,Ui as m,Vi as h,Xt as g,Yi as _,Zt as v,br as y,di as b,eo as x,et as S,gi as C,ha as w,hi as T,ka as E,kt as D,li as O,no as k,qr as A,ro as j,to as ee,ya as te,yr as ne,zi as M,zr as re}from"./control-ui-foundation-ZY_Flbbd.js";import{$c as ie,$r as ae,$t as oe,Ar as se,Bn as ce,Br as le,Bs as N,C as ue,Cc as de,Cs as fe,Cu as pe,Dc as me,Di as he,Dl as ge,Dr as _e,El as ve,Er as ye,Es as be,Fl as xe,Fn as Se,Fr as Ce,Gi as we,Gl as P,Gn as Te,Gt as Ee,Hn as De,Ht as Oe,Il as ke,Ir as Ae,Jr as je,Ki as Me,Kl as Ne,Ll as Pe,Ln as Fe,Ml as Ie,Mr as Le,Nc as Re,Ns as ze,Oc as Be,On as Ve,Pc as He,Qc as Ue,Qi as We,Qr as Ge,R as Ke,Rl as qe,Rn as Je,Rr as Ye,Sl as Xe,T as Ze,Tl as Qe,Tn as $e,Ts as et,Ul as tt,Un as nt,Ur as rt,Ut as it,Vc as at,Vn as ot,Wi as st,Wl as ct,Wt as lt,Xc as ut,Xi as dt,Xn as ft,Yi as pt,Yn as mt,Yr as ht,Zc as F,Zl as gt,Zr as _t,_l as vt,_n as yt,_t as bt,ac as xt,al as St,an as Ct,at as wt,bl as Tt,bn as Et,c as Dt,cc as Ot,cl as kt,cn as At,cr as I,dl as jt,ei as L,el as Mt,en as Nt,eu as Pt,gl as Ft,hc as It,hl as Lt,hu as R,i as Rt,ic as zt,il as Bt,in as Vt,jn as Ht,jo as Ut,jr as z,kc as Wt,kn as Gt,ks as Kt,l as qt,li as Jt,ll as Yt,lu as Xt,ml as Zt,n as Qt,nc as $t,nl as B,nn as en,nu as tn,oc as nn,ol as rn,pa as an,ql as on,r as sn,rc as cn,ri as V,rn as ln,rr as un,rt as dn,s as fn,sc as pn,sl as mn,su as hn,tl as gn,tn as _n,tu as vn,u as yn,ui as bn,ul as xn,uu as H,vl as Sn,vt as Cn,wl as wn,ws as Tn,xc as En,xl as Dn,xt as On,yc as kn,zl as An,zn as jn,zr as Mn}from"./control-ui-core-3P365fbR.js";import{$ as Nn,B as Pn,F as Fn,M as In,N as Ln,Q as Rn,R as zn,T as Bn,X as Vn,Y as Hn,Z as Un,a as Wn,o as Gn,s as Kn,w as qn,z as Jn}from"./control-ui-boot-shared-JlZTSJEC.js";import{$n as Yn,$r as Xn,A as Zn,Ai as Qn,Bi as $n,Br as er,Bt as tr,D as nr,Dn as rr,Ea as ir,En as ar,Et as or,Fi as sr,Gt as cr,Ht as lr,Ii as ur,Jr as dr,K as fr,Kr as pr,Kt as mr,Mi as hr,O as gr,Or as _r,Ot as vr,Qt as yr,Sn as br,Tn as xr,Tt as Sr,U as Cr,Ur as wr,Vt as Tr,W as Er,Xi as U,Xr as Dr,Yr as Or,Yt as kr,Zi as Ar,Zr as jr,Zt as Mr,_n as Nr,_r as Pr,at as Fr,bi as Ir,co as Lr,dr as Rr,ei as zr,er as Br,fn as Vr,fr as Hr,gr as Ur,hi as Wr,hr as Gr,k as Kr,ki as qr,kt as Jr,mi as Yr,mn as Xr,or as Zr,ot as Qr,p as $r,pi as ei,pn as ti,pr as ni,rr as ri,rt as ii,sr as ai,st as oi,ti as si,uo as ci,ur as li,va as ui,vi as di,vr as fi,wn as pi,wr as mi,xi as hi,xr as gi,yi as _i,zi as vi,zt as yi}from"./control-ui-core-CFW9Qtjn.js";import{$ as W,X as G,Y as bi,ct as xi,d as Si,j as Ci,k as wi,nt as Ti,u as Ei,ut as K}from"./lit-runtime-P5vbNq6b.js";import{N as Di,_t as Oi,gt as ki,i as Ai,j as ji,mt as Mi,n as Ni,nt as Pi,pt as Fi,r as Ii,t as Li,tt as Ri,vt as zi,yt as Bi}from"./control-ui-boot-shared-3SP_aL-Y.js";import{C as Vi,Ft as Hi,Gt as Ui,Ht as Wi,I as Gi,It as Ki,Kt as qi,Lt as Ji,Mt as Yi,Nt as Xi,Pt as Zi,Rt as Qi,S as $i,Ut as ea,Vt as ta,Wt as na,dt as ra,ft as ia,j as aa,jt as oa,v as sa,w as ca,zt as la}from"./control-ui-boot-shared-Rs4iS2kF.js";import{c as ua,d as da,l as fa,u as pa}from"./gateway-runtime-5YzSCmfV.js";import{$ as ma,$c as ha,$n as ga,Al as _a,An as va,As as ya,At as ba,B as xa,Bc as Sa,Br as Ca,Bs as wa,Bt as Ta,Ca as Ea,Ci as Da,Cn as Oa,Dc as ka,Dn as Aa,Ds as ja,Ec as Ma,Ei as Na,El as Pa,Es as Fa,Et as Ia,F as La,Fn as Ra,Fo as za,Fr as Ba,Fs as Va,Ft as Ha,Gc as Ua,Gi as Wa,Go as Ga,Hc as Ka,Hn as qa,Ho as Ja,Ht as Ya,I as Xa,Ic as Za,Ii as Qa,In as $a,Io as eo,Ir as to,Is as no,It as ro,Jc as io,Jt as ao,Kc as oo,Ki as so,L as co,Lc as lo,Li as uo,Ln as fo,Ls as po,Mn as mo,Ms as ho,Mt as go,No as _o,Ns as vo,Nt as yo,Oc as bo,Ol as xo,On as So,Os as Co,P as wo,Pn as To,Po as Eo,Ps as Do,Pt as Oo,Q as ko,Qo as Ao,R as jo,Ri as Mo,Rn as No,Ro as Po,Rr as Fo,Rs as Io,Sn as Lo,Ss as Ro,Ti as zo,Tn as Bo,Ts as Vo,Tt as Ho,U as Uo,Ui as Wo,V as Go,Vc as Ko,Vi as qo,Vn as Jo,Vs as Yo,Vt as Xo,W as Zo,Wo as Qo,Xc as $o,Xo as es,Y as ts,Yc as ns,Yo as rs,Z as is,Zo as as,_a as os,_c as ss,_o as cs,aa as ls,ac as us,ai as ds,al as fs,an as ps,ba as ms,bn as hs,br as gs,cc as _s,ci as vs,cl as ys,cn as bs,cs as xs,ct as Ss,dc as Cs,do as ws,ec as Ts,en as Es,es as Ds,et as Os,fl as ks,fo as As,ft as js,gc as Ms,go as Ns,gs as Ps,hi as Fs,ho as Is,ic as Ls,ii as Rs,il as zs,in as Bs,it as Vs,jl as Hs,jt as Us,ks as Ws,kt as Gs,lc as Ks,li as qs,ll as Js,ln as Ys,ls as Xs,ml as Zs,ms as Qs,na as $s,ni as ec,nl as tc,nn as nc,nr as rc,nt as ic,oc as ac,oi as oc,on as sc,oo as cc,ot as lc,pc as uc,pl as dc,q as fc,qc as pc,qi as mc,rc as hc,ri as gc,rn as _c,rr as vc,rt as yc,sc as bc,si as xc,sl as Sc,sn as Cc,so as wc,st as Tc,tc as Ec,tn as Dc,tr as Oc,tt as kc,ui as Ac,uo as jc,us as Mc,ut as Nc,wi as Pc,xn as Fc,xs as Ic,yn as Lc,yr as Rc,yt as zc,zc as Bc,zn as Vc,zr as Hc,zs as Uc}from"./control-ui-boot-shared-DoKu-5Ju.js";import{S as Wc,_ as Gc}from"./control-ui-boot-shared-90V688bk.js";import{$a as Kc,$o as qc,$t as Jc,Bt as Yc,D as Xc,E as Zc,Fn as Qc,Fo as $c,Go as el,Hr as tl,Ht as nl,Io as rl,J as il,Jo as al,Jt as ol,Ko as sl,Li as cl,Lt as ll,Pa as ul,Qa as dl,Qo as fl,Ri as pl,Rt as ml,To as hl,Ut as gl,Vt as _l,Wr as vl,Wt as yl,X as bl,Xo as xl,Xt as Sl,Y as Cl,Yo as wl,Za as Tl,Zo as El,Zt as Dl,_i as Ol,_r as kl,_t as Al,aa as jl,bi as Ml,bn as Nl,dt as Pl,en as Fl,eo as Il,er as Ll,ft as Rl,gr as zl,gt as Bl,ht as Vl,jt as Hl,kn as Ul,li as Wl,ln as Gl,mt as Kl,nn as ql,no as Jl,nr as Yl,oi as Xl,pn as Zl,pr as Ql,pt as $l,qo as eu,rn as tu,sa as nu,si as ru,to as iu,tr as au,vi as ou,wo as su,yi as cu,zt as lu}from"./control-ui-boot-shared-CG9HtEG-.js";import{St as uu,X as du,Y as fu,_ as pu,g as mu,gt as hu,ht as gu,mt as _u}from"./control-ui-boot-shared-BykNRHBP.js";import{$t as vu,A as yu,An as bu,At as xu,B as Su,Bn as Cu,Br as wu,C as Tu,Cn as Eu,Ct as Du,D as Ou,Dn as ku,Dt as Au,E as ju,En as Mu,Er as Nu,Et as Pu,Fn as Fu,Gr as Iu,H as Lu,Hn as Ru,Hr as zu,In as Bu,Jr as Vu,Kr as Hu,Ln as Uu,Lr as Wu,Mn as Gu,Mr as Ku,Mt as qu,Nn as Ju,Nt as Yu,O as Xu,On as Zu,Or as Qu,Ot as $u,Pn as ed,Pr as td,Pt as nd,Qt as rd,Rn as id,Rr as ad,S as od,St as sd,T as cd,Tn as ld,Tr as ud,Tt as dd,Un as fd,Ur as pd,V as md,Vn as hd,Vr as gd,Wr as _d,Yr as vd,Zr as yd,Zt as bd,_ as xd,_n as Sd,_r as Cd,_t as wd,a as Td,ai as Ed,at as Dd,b as Od,bn as kd,br as Ad,bt as jd,c as Md,ct as Nd,d as Pd,dn as Fd,dt as Id,ei as Ld,en as Rd,fn as zd,ft as Bd,g as Vd,gn as Hd,gr as Ud,gt as Wd,h as Gd,hn as Kd,ht as qd,i as Jd,ii as Yd,in as Xd,ir as Zd,it as Qd,j as $d,jn as ef,jr as tf,jt as nf,k as rf,kn as af,kt as of,l as sf,ln as cf,lt as lf,m as uf,mn as df,mt as ff,n as pf,nt as mf,o as hf,oi as gf,on as _f,ot as vf,pn as yf,pt as bf,qr as xf,r as Sf,rn as Cf,rr as wf,rt as Tf,s as Ef,si as Df,st as Of,t as kf,tn as Af,tt as jf,un as Mf,ut as Nf,v as Pf,vn as Ff,vt as If,w as Lf,wr as Rf,wt as zf,xn as Bf,xr as Vf,xt as Hf,y as Uf,yn as Wf,yt as Gf,zn as Kf}from"./control-ui-boot-shared-CcmBeh0v.js";import{A as qf,B as Jf,C as Yf,D as Xf,E as Zf,F as Qf,H as $f,I as ep,L as tp,M as np,N as rp,O as ip,P as ap,R as op,S as sp,T as cp,U as lp,V as up,W as dp,_ as fp,a as pp,b as mp,d as hp,f as gp,g as _p,i as vp,j as yp,k as bp,l as xp,m as Sp,o as Cp,p as wp,s as Tp,u as Ep,v as Dp,w as Op,x as kp,y as Ap,z as jp}from"./control-ui-boot-shared-BR12heUA.js";import{$ as Mp,$n as Np,$r as Pp,$t as Fp,Ai as Ip,An as Lp,Ar as Rp,B as zp,Bn as Bp,Bt as Vp,Ci as Hp,Cn as Up,Cr as Wp,Di as Gp,Dn as Kp,Dt as qp,Ei as Jp,En as Yp,Et as Xp,F as Zp,Fn as Qp,Fr as $p,G as em,Gn as tm,Gt as nm,H as rm,Hn as im,Ht as am,I as om,In as sm,Ir as cm,It as lm,J as um,Jn as dm,Jt as fm,K as pm,Kt as mm,L as hm,Ln as gm,Lr as _m,Lt as vm,M as ym,Mn as bm,Mr as xm,N as Sm,Nn as Cm,Nr as wm,Oi as Tm,On as Em,Or as Dm,P as Om,Pn as km,Pr as Am,Q as jm,Qn as Mm,Qr as Nm,Qt as Pm,R as Fm,Rn as Im,Rt as Lm,S as Rm,Si as zm,Sn as Bm,Ti as Vm,U as Hm,Un as Um,Ut as Wm,V as Gm,Vt as Km,W as qm,Wn as Jm,Wt as Ym,Xn as Xm,Xt as Zm,Yn as Qm,Yt as $m,Zn as eh,Zt as th,_i as nh,_n as rh,_t as ih,ai as ah,an as oh,at as sh,bi as ch,bn as lh,ci as uh,cn as dh,di as fh,dn as ph,dr as mh,dt as hh,ei as gh,en as _h,er as vh,fi as yh,fn as bh,ft as xh,gi as Sh,gn as Ch,hi as wh,hn as Th,hr as Eh,in as Dh,j as Oh,ji as kh,jn as Ah,jr as jh,kn as Mh,kt as Nh,li as Ph,lt as Fh,mi as Ih,mn as Lh,mt as Rh,ni as zh,nn as Bh,oi as Vh,on as Hh,or as Uh,pi as Wh,pn as Gh,pt as Kh,q as qh,qn as Jh,qt as Yh,rn as Xh,rt as Zh,si as Qh,sn as $h,sr as eg,ti as tg,tn as ng,tt as rg,ut as ig,vi as ag,vn as og,wn as sg,x as cg,xi as lg,xn as ug,yi as dg,yn as fg,z as pg,zt as mg}from"./control-ui-boot-shared-CApmg5ot.js";function hg(e){if(!e||typeof e!=`object`)return;let t=e,n=b(t.receivedToAckMs),r=b(t.loadSessionMs),i=b(t.prepareAttachmentsMs),a={...n===void 0?{}:{receivedToAckMs:n},...r===void 0?{}:{loadSessionMs:r},...i===void 0?{}:{prepareAttachmentsMs:i}};return Object.keys(a).length>0?a:void 0}function gg(e){return e===`in_flight`||e===`ok`||e===`timeout`||e===`error`?e:`started`}function _g(e,t){if(!e||typeof e!=`object`)return{runId:t,status:`started`};let n=e,r=typeof n.runId==`string`&&n.runId.trim()?n.runId.trim():t,i=hg(n.serverTiming),a=typeof n.messageSeq==`number`&&Number.isSafeInteger(n.messageSeq)&&n.messageSeq>0?n.messageSeq:void 0;return{runId:r,status:gg(n.status),...i?{serverTiming:i}:{},...a===void 0?{}:{messageSeq:a},...n.stopReason===`restart`?{stopReason:`restart`}:{}}}function vg(e){return e?.status===`timeout`||e?.status===`error`}function yg(){return(yg=e((()=>{T()})))()}function bg(e){if(typeof URL<`u`&&typeof URL.createObjectURL==`function`)return URL.createObjectURL(e)}function xg(e){return _n(e.attachment.id),Nt.set(e.attachment.id,{blob:e.file,dataUrl:e.dataUrl}),e.attachment}function Sg(e){return e.dataUrl??Nt.get(e.id)?.dataUrl??null}function Cg(e){let t=Nt.get(e.id);if(t?.videoPoster)return t.videoPoster.promise;if(!(t?.blob instanceof File)||t.blob.size>536870912)return null;let n=t.blob,r=bg(n);if(!r)return null;let i=new AbortController,a={controller:i,promise:M(async()=>{let{requestVideoPoster:e}=await import(`./video-poster-Ds-NFg37.js`);return{requestVideoPoster:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url).then(({requestVideoPoster:e})=>e({key:n,src:r,width:54,height:54,signal:i.signal}),()=>null).then(t=>!t||Nt.get(e.id)?.videoPoster!==a?null:(a.url=bg(t),a.url??null)).finally(()=>Vt(r))};return t.videoPoster=a,a.promise}function wg(e){let t=/^data:([^,]*),(.*)$/s.exec(e);if(!t)return null;let n=t[1]??``,r=t[2]??``;try{if(n.toLowerCase().includes(`;base64`)){let e=atob(r.replace(/\s+/gu,``)),t=Uint8Array.from(e,e=>e.charCodeAt(0));return new Blob([t],{type:n.split(`;`,1)[0]})}return new Blob([decodeURIComponent(r.replace(/\+/gu,`%20`))],{type:n.split(`;`,1)[0]})}catch{return null}}function Tg(e){let t=Nt.get(e.id);if(t?.blob)return t.blob;let n=Sg(e);if(!n)return null;let r=wg(n);return r&&Nt.set(e.id,{...t,blob:r,dataUrl:n}),r}function Eg(e){let t=e.previewUrl??Nt.get(e.id)?.previewUrl;if(t)return t;let n=Tg(e),r=n&&bg(n);return r&&Nt.set(e.id,{...Nt.get(e.id),previewUrl:r}),r??Sg(e)}function Dg(e){return e.map(e=>{let{id:t,previewUrl:n,...r}=e,i=Sg(e);return{...r,id:kg(),...i?{dataUrl:i}:{}}})}function Og(e,t){let n=new Set(t.flat().map(e=>e.id));en(e.filter(e=>!n.has(e.id)))}function kg(){return`att-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Ag(e,t=[]){return en(e),t.flatMap(({mimeType:e,data:t})=>Ng.test(e)&&t.length<=Fg&&Di(t)&&ji(t)<=Pg?[{id:kg(),mimeType:e,dataUrl:`data:${e};base64,${t}`}]:[])}function jg(e){let t=Nt.get(e);if(t){if(ln(t),t.previewUrl){Nt.set(e,{previewUrl:t.previewUrl});return}Nt.delete(e)}}function Mg(e=[]){for(let t of e)jg(t.id)}var Ng,Pg,Fg;function Ig(){return(Ig=e((()=>{oe(),n(),Ng=/^image\/[\w.+-]+$/u,Pg=5242880,Fg=Math.ceil(Pg/3)*4})))()}function Lg(e,t){return!!(t.pendingRunId||t.sendState===`waiting-model`||e.retryable.has(t.id)||!e.durableSeen.has(t.id))}function Rg(e){let t=pe();return t&&!Vg.has(t)&&Vg.set(t,++Hg),`${t?Vg.get(t):0}\u0000${e.settings?.gatewayUrl?.trim()||`default`}\u0000${e.client?.recoveryScope??``}`}function q(e){let t=Rg(e),n=Wg.get(t)??new Ug(t);return Wg.set(t,n),n.adoptSubscriptions(e),n}function zg(e){if(!ka(e))return[];let t=Wg.get(Rg(e));return Fa(e).flatMap(e=>e.queue.filter(n=>t?t.needsReview(e,n):!n.pendingRunId&&(n.sendState===`failed`||n.sendState===`unconfirmed`||n.sendState===`held`)).map(t=>({id:t.id,sessionKey:e.sessionKey,agentId:e.agentId,unconfirmed:t.sendState===`unconfirmed`||t.sendState===`held`,command:!!t.localCommandName})))}var Bg,Vg,Hg,Ug,Wg,Gg;function Kg(){return(Kg=e((()=>{Ma(),lo(),Vo(),Cs(),B(),Ig(),zu(),up(),Bg=[`sendRunId`,`sendAttempts`,`sendState`,`sendError`],Vg=new WeakMap,Hg=0,Ug=class{constructor(e){this.ownerGatewayKey=e,this.hosts=new Map,this.panes=new Set,this.live=new Map,this.hydrating=new Set,this.unsubscribe=null}state(e){let t=this.hosts.get(e);if(t)return t;let n=Ft(e,e.sessionKey),r=new Set(ja(e,n)?.queue.map(e=>e.id)),i={byScope:new Map,durableSeen:r,retryable:new Set};return e.chatQueue.length&&i.byScope.set(N(n),{scope:n,queue:e.chatQueue.filter(t=>bo(e,t))}),this.hosts.set(e,i),i}durable(e,t){return Fa(e).find(({queue:e})=>e.some(e=>e.id===t))}locate(e,t){let n=this.durable(e,t),r=n??this.local(this.state(e),t)?.scope;if(!r)return;let{sessionKey:i,agentId:a}=r,o={sessionKey:i,agentId:a},s=this.snapshot(e,o,n?.queue??[]).find(e=>e.id===t);return s?{item:s,scope:o,durable:n?.queue.find(e=>e.id===t)}:void 0}project(e,t){let n={...e};if(t.attachments){let r=new Map(t.attachments.map(e=>[e.id,e]));n.attachments=(e.attachments??t.attachments).map(e=>Object.assign({},e,r.get(e.id)))}for(let e of[`sendSubmittedAtMs`,`sendRequestStartedAtMs`])typeof t[e]==`number`&&(n[e]=t[e]);return n}readLive(e,t,n){let r=this.live.get(e);if(!r)return;let i=r.get(t);if(i?.expectedDurableVersion&&(!n||!Bc(i.expectedDurableVersion,n))||i?.submissionIsCurrent&&!i.submissionIsCurrent()){r.delete(t),r.size||this.live.delete(e);return}return i}snapshot(e,t,n=ja(e,t)?.queue??[]){let r=N(t),i=this.state(e),a=i.byScope.get(r)?.queue??[],o=new Map(a.map(e=>[e.id,e])),s=n.map(e=>{i.durableSeen.add(e.id);let t=o.get(e.id),n=this.readLive(r,e.id,e)?.item;return t?.pendingRunId||t?.sendState===`waiting-model`?t:n&&n.sendRunId===e.sendRunId?n:t&&t.sendRunId===e.sendRunId?this.project(e,t):e}),c=new Set(n.map(e=>e.id));return s.push(...a.filter(e=>!c.has(e.id)&&Lg(i,e))),this.prune(e),s.toSorted(ya)}syncHost(e,t={}){if(this.ownerGatewayKey!==Rg(e)){q(e).syncHost(e,t);return}ka(e),e.chatQueue=this.snapshot(e,Ft(e,e.sessionKey));for(let t of e.chatQueue){let n=t.attachmentPayload?.key;if(!n||t.attachmentStorageError||this.hydrating.has(n)||t.attachments?.every(e=>Sg(e)))continue;this.hydrating.add(n);let r=jp(e);lp(e,t).then(i=>{if(!r())return;let a=this.durable(e,t.id),o=a?.queue.find(e=>e.id===t.id);if(a&&o?.attachmentPayload?.key===n){if(i.status===`ready`){if(i.update.attachmentPayload?.key!==n){let n=t.sendState===`waiting-reconnect`&&o.sendState===`unconfirmed`&&Bc(o,{...bc(t,a),sendState:`unconfirmed`});if(!Vu(e,a.sessionKey,n?o:t,{...o,...i.update},a.agentId))return}this.keep(e,a,{...o,attachments:i.update.attachments,...i.update.attachmentPayload?.key===n?{}:{attachmentPayload:i.update.attachmentPayload,sendState:i.update.sendState,sendError:i.update.sendError}})}else Vu(e,a.sessionKey,o,Jf(o,i.reason),a.agentId);this.publish(e)}}).finally(()=>this.hydrating.delete(n))}t.requestUpdate!==!1&&e.requestUpdate?.()}publish(e,t=!1){e&&this.syncHost(e);for(let n of this.panes)n!==e&&(t&&this.reconcile(n,this.state(n)),this.syncHost(n))}adoptSubscriptions(e){let t=Gg.get(e)?.owner;if(!t||t===this)return;let n=!1;for(let e of t.panes)if(Rg(e)===this.ownerGatewayKey){Gg.get(e).owner=this,t.hosts.delete(e);for(let[n,r]of t.live){for(let[t,n]of r)n.owner===e&&r.delete(t);r.size||t.live.delete(n)}e.chatQueue=[],t.detach(e),this.attach(e),n=!0}n&&this.publish()}attach(e){this.panes.add(e),this.unsubscribe??=ss(()=>this.publish(void 0,!0))}detach(e){this.panes.delete(e),this.panes.size||(this.unsubscribe?.(),this.unsubscribe=null),this.prune(e)}subscribe(e,t){let n={owner:this,onDiscard:t};return Gg.set(e,n),this.attach(e),this.reconcile(e,this.state(e)),this.syncHost(e,{requestUpdate:!1}),()=>{Gg.get(e)===n&&(Gg.delete(e),n.owner.detach(e))}}reconcile(e,t){let n=new Set(Fa(e).flatMap(e=>e.queue.map(e=>e.id)));n.forEach(e=>t.durableSeen.add(e));for(let e of t.byScope.values())e.queue=e.queue.filter(e=>n.has(e.id)||Lg(t,e))}retirePendingRun(e,t){let n=e.chatQueue.filter(e=>e.pendingRunId===t),r=Ft(e,e.sessionKey),i=this.state(e),a=i.byScope.get(N(r));a&&(a.queue=a.queue.filter(e=>e.pendingRunId!==t));for(let e of n)i.retryable.delete(e.id);return this.syncHost(e),n}keep(e,{sessionKey:t,agentId:n},r,i=!1){let a={sessionKey:t,agentId:n},o=this.state(e),s=N(a),c=[...ja(e,a)?.queue??[],...[...this.hosts.values()].flatMap(e=>e.byScope.get(s)?.queue.filter(t=>Lg(e,t))??[])],l=c.find(e=>e.id===r.id),u=Math.max(...c.map(Ws)),d=l?l.orderKey:r.orderKey??(r.createdAt<=u?u+1:void 0),f=bc(r,a);d===void 0?delete f.orderKey:f.orderKey=d;let p=[...o.byScope.get(s)?.queue??[]],m=p.findIndex(e=>e.id===r.id);return m<0?p.push(f):p[m]=f,p.sort(ya),o.byScope.set(s,{scope:a,queue:p}),i&&o.retryable.add(r.id),this.syncHost(e),f}local(e,t){for(let{scope:n,queue:r}of e.byScope.values()){let e=r.findIndex(e=>e.id===t);if(e>=0)return{scope:n,queue:r,index:e}}}change(e,t,n,r=!1){let i=this.state(e),a=this.local(i,t);if(!a)return this.prune(e),null;let o=a.queue[a.index];if(n){let s=n(o);return a.queue[a.index]=s,r&&i.retryable.add(t),this.syncHost(e),s}i.retryable.delete(t);let s=this.durable(e,t)?.queue.find(e=>e.id===t);return s?(i.durableSeen.add(t),a.queue[a.index]=this.project(s,o)):a.queue.splice(a.index,1),this.syncHost(e),o}update(e,t){let n=[];for(let{id:r,update:i}of t){let t=this.locate(e,r);if(!t)return null;n.push({...t,next:i(t.item)})}let r=n.filter(e=>e.durable),i=r[0]?.scope,a=!i||vd(e,i.sessionKey,r.map(({item:e,next:t})=>({expected:e,next:t})),i.agentId);for(let{item:t,scope:n,next:i}of r){let r=i.sendState===`sending`||i.sendState===`executing-command`;a?(i.sendState===`waiting-model`?this.keep(e,n,i):this.change(e,t.id),this.projectLive(e,n,t.id,r?i:void 0)):r?this.syncHost(e):this.projectLive(e,n,t.id)}return a?n.map(({item:t,durable:n,next:r})=>n?r:this.change(e,t.id,()=>r)):null}admit(e,t,n,r){let i=this.keep(e,t.scope,n),a=wu(e,t,i,r);return a===`admitted`&&n.sendState!==`waiting-model`&&this.change(e,n.id),a}remove(e,t,n){let r=this.locate(e,t),i=r?.durable,a=e.chatQueue.find(e=>e.id===t),o=r&&this.readLive(N(r.scope),t,i);if(o&&o.owner!==e&&!(a&&i&&Bg.every(e=>a[e]===i[e]))||r?.durable&&!xf(e,r.scope.sessionKey,t,r.item,r.scope.agentId))return this.syncHost(e),null;if(r&&(this.projectLive(e,r.scope,t),this.change(e,t)),this.publish(void 0,!0),r&&n?.discard)for(let e of this.panes)Gg.get(e)?.onDiscard?.(r.item);return r?.item??null}hasVolatile(e,t){return this.hosts.get(e)?.retryable.has(t)??!1}anyPane(e){for(let t of this.panes)if(e(t))return!0;return!1}hasPendingSubmission(e,t){return!!this.readLive(N(e),t.id,t)?.submissionIsCurrent}needsReview(e,t){let n=N(e);if(this.readLive(n,t.id,t))return!1;for(let e of this.hosts.values())if(e.byScope.get(n)?.queue.some(e=>e.id===t.id&&e.sendState===`waiting-model`))return!1;return!t.pendingRunId&&(t.sendState===`failed`||t.sendState===`unconfirmed`||t.sendState===`held`)}beginSubmission(e,t,n){let r=this.locate(e,t);if(!r?.durable||r.item.sendState!==`waiting-idle`||r.durable.sendState!==`waiting-idle`||!r.item.sendRunId||(r.item.sendAttempts??0)!==0||r.item.sendRequestStartedAtMs!==void 0)return;let i=N(r.scope),a=this.live.get(i)??new Map,o={item:n.inline?{...r.item,sendState:`submitting`}:r.item,owner:e,expectedDurableVersion:r.durable,submissionIsCurrent:n.isCurrent};return a.set(t,o),this.live.set(i,a),this.publish(e),{release:()=>{this.live.get(i)?.get(t)===o&&this.projectLive(e,r.scope,t)}}}projectLive(e,t,n,r){let i=N(t),a=this.live.get(i)??new Map;r?(a.set(n,{item:r,owner:e}),this.live.set(i,a)):(a.delete(n),a.size||this.live.delete(i)),this.publish(e),this.prune(e)}allItems(e){let t=Fa(e).flatMap(t=>this.snapshot(e,t,t.queue)),n=[...this.state(e).byScope.values()].flatMap(({queue:e})=>e),r=new Map([...n,...t].map(e=>[e.id,e]));return this.prune(e),[...r.values()]}prune(e){let t=this.hosts.get(e);t&&!this.panes.has(e)&&![...t.byScope.values()].some(({queue:e})=>e.some(e=>Lg(t,e)))&&!this.live.size&&this.hosts.delete(e),!this.unsubscribe&&!this.live.size&&!this.hosts.size&&queueMicrotask(()=>{!this.unsubscribe&&!this.live.size&&!this.hosts.size&&Wg.get(this.ownerGatewayKey)===this&&Wg.delete(this.ownerGatewayKey)})}},Wg=new Map,Gg=new WeakMap})))()}function qg(e){return ho(e)&&(e.sendState===void 0||e.sendState===`waiting-idle`)&&!e.localCommandName}function Jg(e){return e.toSorted(ya).find(qg)}function Yg(e,t){return t(e)||q(e).anyPane(e=>t(e))}function Xg(e,t,n,r,i={}){let a=Ft(e,t,r??n.agentId);return q(e).keep(e,a,n,i.retryable)}function Zg(e,t,n,r,i){let a=t.trim();if(!a)return null;let o={id:p(),text:a,createdAt:Date.now(),refreshSessions:n,localCommandArgs:r?.args,localCommandName:r?.name,sessionKey:e.sessionKey,agentId:_t(e,e.sessionKey),...i?{sender:i}:{}};return Xg(e,e.sessionKey,o,o.agentId)}function Qg(e,t,n,r){let i=t.trim();if(!i)return;let a={id:p(),text:i,createdAt:Date.now(),pendingRunId:n,...r?{sender:r}:{}};Xg(e,e.sessionKey,a)}function $g(e,t,n){let r=Ft(e,t,n);return q(e).snapshot(e,r)}function e_(e,t){return q(e).locate(e,t)?.item??null}function t_(e,t,n){return q(e).update(e,[{id:t,update:n}])?.[0]??null}function n_(e,t,n){if(!n||t.sessionId&&t.sessionId!==n)return!1;let r=e_(e,t.id);return!r||r.sessionId&&r.sessionId!==n||!Bc(r,t)?!1:r.sessionId&&r.sendState!==`unconfirmed`?!0:t_(e,t.id,e=>({...e,sessionId:n,...e.sendState===`unconfirmed`?{sendState:`waiting-idle`,sendError:void 0}:{}}))!==null}function r_(e,t,n,r){return q(e).admit(e,t,n,r)===`admitted`}function i_(e,t){if(!t?.length)return t?[]:void 0;let n=new Set((e.chatAttachments??[]).map(e=>e.id));return t.filter(e=>!n.has(e.id))}function a_(e,t,n){let r=e_(e,t),i=r?q(e).remove(e,t,n):null;return i&&en(i_(e,i.attachments)),i?`removed`:r?`rejected`:`absent`}function o_(e,t,n){let r=s_(e,t,n);if(!r)return null;let i=q(e).remove(e,r.item.id);return i?(en(i_(e,i.attachments)),i):null}function s_(e,t,n){if(!t)return null;let r=N(n),i=Fa(e).find(e=>N(e)===r),a=i?.queue.find(e=>e.sendRunId===t);return a&&i?{item:a,outbox:i}:null}function c_(e,t){if(!t)return;let n=q(e).retirePendingRun(e,t);for(let t of n)en(i_(e,t.attachments))}function l_(){return(l_=e((()=>{lo(),I(),B(),o(),Ig(),Kg(),zu()})))()}function u_(e,t){return JSON.stringify([e,t])}function d_(e){let t=m(e),n=m(t?.__openclaw);return typeof n?.id==`string`?n.id:typeof t?.messageId==`string`?t.messageId:void 0}function f_(e,t){let n=m(e),r=m(n?.__openclaw),i=d_(e);return(Io(t)===`assistant`||i?.startsWith(`pending:`))&&!n?.openclawMessageToolMirror&&r?.truncated===!0?i:void 0}function p_(){return(p_=e((()=>{aa(),Va()})))()}function m_(e){if(!m(e))return null;try{return po(e)}catch{return null}}function h_(e){return e.messages.some(({message:e})=>{let t=m(m(e)?.provenance);return t?.kind===`inter_session`&&t.sourceTool===`sessions_send`||t?.kind===`internal_system`&&t.sourceTool===`cron`&&!!(t.jobId&&t.runId&&t.sourceSessionKey)})}function g_(e){return!!e.senderSession||h_(e)}function __(e){return m(m(e.messages[0]?.message)?.__openclaw)?.turnBoundary===!0}function v_(e){if(e.kind===`notice`)return e.startsTurn===!0;if(e.kind===`message`)return Io(Yo(e.message)).toLowerCase()===`user`;if(e.kind!==`group`)return!1;let t=e.role.toLowerCase();return t===`user`||__(e)||t===`assistant`&&h_(e)}function y_(){return(y_=e((()=>{Va()})))()}function b_(e,t,n){let r=e,i=Array.isArray(r.content)?[...r.content]:typeof r.content==`string`?[{type:`text`,text:r.content}]:typeof r.text==`string`?[{type:`text`,text:r.text}]:[];return i.some(e=>{let n=Uc(e);return n&&Do(n,t)})?e:{...r,content:[...i,{type:`canvas`,preview:t,...n?{rawText:n}:{}}]}}function x_(e,t,n){let r=x(t);if(!r)return!0;let i=n&&d_(e),a=n&&i?n.messages.get(u_(n.agentId,i)):void 0;if(a?.status===`loaded`){let t=Io(po(e).role);if(f_(e,t))return x(t===`assistant`?ac(a.markdown):a.markdown).includes(r)}return x(Ec(e)).includes(r)}function S_(e){let t=m(e);if(!t)return null;let n=q_.get(t);if(n!==void 0)return n;let r=C_(t);return q_.set(t,r),r}function C_(e){if(!m_(e))return null;let t=Xs(e);for(let n=t.length-1;n>=0;n--){let r=t[n];if(r?.preview?.kind===`canvas`)return{preview:r.preview,text:r.outputText??null,timestamp:H_(e)}}let n=Ec(e)??void 0,r=e,i=typeof r.toolName==`string`?r.toolName:typeof r.tool_name==`string`?r.tool_name:void 0,a=Mc(n,i);return a?.kind===`canvas`?{preview:a,text:n??null,timestamp:H_(e)}:null}function w_(e,t){let n=k_(m(e)??{}),r=t.preview.viewId?`viewId:${t.preview.viewId}`:t.preview.url?`url:${t.preview.url}`:null;return n&&r?JSON.stringify([n,r]):null}function T_(e,t=e.timestamp){return b_({role:`assistant`,content:[],...t==null?{}:{timestamp:t}},e.preview,e.text)}function E_(e,t){let n=null;for(let r=t-1;r>=0&&(n=H_(e[r]),n==null);--r);let r=null;for(let n=t+1;n<e.length&&(r=H_(e[n]),r==null);n+=1);return n!=null&&r!=null?n<r?Math.min(n+1,r):r:n==null?r:n+1}function D_(e,t,n=0,r=e.length){let i=n,a=r;for(let o=n;o<r;o+=1){let n=e[o];if(!n||!v_(n))continue;let r=n.kind===`notice`?n.timestamp:n.kind===`message`?m_(n.message)?.timestamp??null:null;if(t!=null&&r!=null&&r>t){a=o;break}i=o+1}let o=null,s=null;for(let n=i;n<a;n++){let r=e[n];if(r?.kind!==`message`)continue;let i=m(r.message);if(typeof i?.role!=`string`||i.role.toLowerCase()!==`assistant`)continue;o={index:n,item:r};let a=m_(r.message)?.timestamp;if(t!=null&&a!=null){if(a<=t){s={anchor:o,timestamp:a};continue}return s&&t-s.timestamp<=a-t?s.anchor:o}}return s?.anchor??o}function O_(e,t,n=0,r=e.length){if(t==null)return r;for(let i=n;i<r;i+=1){let n=e[i];if(n?.kind!==`message`)continue;let r=m_(n.message);if(r&&Io(r.role).toLowerCase()===`user`&&r.timestamp!=null&&r.timestamp>t)return i}return r}function k_(e){return zn({...e,id:void 0})}function A_(e,t){return zn(e)??k_(t)}function j_(e){return m(m(e)?.__openclaw)?.kind===`pending-send`}function M_(e){let t=m(m(e)?.__openclaw),n=t?.state,r=t?.id;return t?.kind!==`pending-send`||n!==`failed`&&n!==`unconfirmed`&&n!==`held`&&n!==`waiting-reconnect`||typeof r!=`string`?null:{id:r,state:n,...typeof t.error==`string`?{error:t.error}:{}}}function N_(e){let t=m(e),n=typeof t?.messageId==`string`&&t.messageId.trim()?t.messageId:t?.id;return ea(e,{messageId:n})}function P_(e){let t=N_(e);return t?.role===`user`?t.runId:null}function F_(e){let t=N_(e)?.id;return j_(e)||t?.startsWith(`pending:`)?null:t??null}function I_(e){let t=N_(e);return t?.sendId?`send:${t.sendId}`:t?.isImported?t.externalSource?`import:${t.externalSource}`:t.sequence===null?null:`import-seq:${t.sequence}`:t?.id?`id:${t.id}`:t?.sequence==null?null:`seq:${t.sequence}`}function L_(e){if(e&&typeof e==`object`){let t=J_.get(e);if(t)return t}let t=m(e),n=[typeof t?.role==`string`?t.role:``,typeof t?.toolCallId==`string`?t.toolCallId:``,t?Ec(e):``].join(`\0`),r=`p${he(n).toString(36)}${n.length.toString(36)}`;return e&&typeof e==`object`&&J_.set(e,r),r}function R_(e,t=I_){let n=e.map(t),r=new Map;for(let e of n)e&&r.set(e,(r.get(e)??0)+1);let i=new Map;return e.map((e,t)=>{let a=n[t],o=a==null||(r.get(a)??0)>1?`${a??`legacy`}:projection:${L_(e)}`:a??`legacy`,s=i.get(o)??0;i.set(o,s+1);let c=m(e),l=typeof c?.toolCallId==`string`?c.toolCallId:``,u=typeof c?.role==`string`?c.role:`unknown`,d=`${o}:${s}`;return{kind:`message`,key:l?`tool:${u}:${l}:${d}`:`msg:${d}`,message:e}})}function z_(e,t=m_(e)){if(!t)return!1;let n=Io(t.role),r=n===`assistant`&&t.senderLabel?.trim();return!!(n===`tool`||t.content.length||t.replyTarget||r||n===`user`&&Ls(e).length)}function B_(e){let t=Pi(e);return t.trim().length>0?t:``}function V_(e){return Ip({text:e.text,workContext:e.workContext,mentions:e.mentions,attachments:e.attachments,createdAt:e.createdAt,runId:e.sendRunId??e.pendingRunId,replyToId:e.replyToId,sender:e.sender,pending:{id:e.id,state:e.sendState,error:e.sendError}})}function H_(e){return O(m(e)?.timestamp)??null}function U_(e){switch(e.kind){case`message`:return H_(e.message);case`divider`:case`notice`:return e.timestamp;case`stream`:case`question`:return e.startedAt;case`reading-indicator`:return null}return null}function W_(e,t){let n=e.reduce((e,t)=>{let n=U_(t);return n==null?e:e==null||n>e?n:e},null);return n!=null&&t<=n?n+1:t}function G_(e,t){let n=t?.afterKey?e.findIndex(e=>e.key===t.afterKey):-1,r=t?.beforeKey?e.findIndex(e=>e.key===t.beforeKey):-1;return{minimum:n+1,maximum:r>=0?r:e.length}}function K_(e,t){let n=new Map,r=new Map;for(let{item:e,bounds:i,predecessorKey:a}of t){let t=U_(e);t!=null&&n.set(e.key,t);let o=r.get(e.key)??{};i&&(o.bounds=i),a&&(o.predecessorKey=a),r.set(e.key,o)}let i=t.map(({item:e},t)=>{let i=U_(e),a=r.get(e.key)?.predecessorKey,o=a?n.get(a):null;return{item:e,index:t,predecessorKey:a,effectiveTimestamp:i!=null&&o!=null?Math.max(i,o):i}}).toSorted((e,t)=>e.effectiveTimestamp==null&&t.effectiveTimestamp==null?e.index-t.index:e.effectiveTimestamp==null?1:t.effectiveTimestamp==null?-1:e.effectiveTimestamp===t.effectiveTimestamp?e.predecessorKey===t.item.key?1:t.predecessorKey===e.item.key?-1:e.index-t.index:e.effectiveTimestamp-t.effectiveTimestamp);for(let{item:t,effectiveTimestamp:n}of i){let{minimum:i,maximum:a}=G_(e,r.get(t.key)?.bounds);if(n==null){e.splice(a,0,t);continue}let o=e.findIndex((e,t)=>{if(t<i||t>=a)return!1;let r=U_(e);return r==null||r>n});o===-1?e.splice(a,0,t):e.splice(o,0,t)}}var q_,J_;function Y_(){return(Y_=e((()=>{ta(),T(),aa(),Ri(),In(),hc(),Va(),Qs(),us(),p_(),y_(),kh(),q_=new WeakMap,J_=new WeakMap})))()}function X_(e){let t=ea(e);if(t?.runId)return t.runId;let n=m(e);return Vm(e)??j(n?.runId)??j(m(n?.openclawStreamFallback)?.runId)}function Z_(e){return Wi(e)!==void 0}function Q_(e){let t=j(e);return t?{runId:t}:void 0}function $_(e){let t=j(e);return t?{boundaryId:`send:${t}`}:void 0}function ev(){let e=new Map,t=new Map;return{add(n,r,i){r&&(n&&e.set(wh(n,r),i),t.set(r,t.has(r)?null:i))},get(n,r){return r?(n?e.get(wh(n,r)):void 0)??t.get(r)??void 0:void 0}}}function tv(e){return e.kind===`message`&&v_(e)}function nv(e){let t=e.findLast(tv);return t?{afterKey:t.key}:null}function rv(e){let t;return n=>{if(!t){t=new Map;let n;for(let r=e.length-1;r>=0;r--){let i=e[r];if(!v_(i))continue;let a=i.kind===`message`?P_(i.message):null;a!==null&&t.set(a,{afterKey:i.key,...n?{beforeKey:n}:{}}),n=i.key}}return t.get(n)??null}}function iv(e,t,n,r){if(typeof t!=`string`||!t.trim())return n==null?null:r;let i=e(t);return t===n?i?{afterKey:i.afterKey}:r:i||n==null?i:r?.afterKey?{beforeKey:r.afterKey}:null}function av(e,t){if(t.length===0)return;let n=new Map,r={};for(let t of e)if(t.kind===`divider`&&n.clear(),v_(t)||t.kind===`divider`)r.beforeKey=t.key,r={afterKey:t.key};else if(t.kind===`message`)for(let e of Sh(t.message)){if(!e.runId)continue;let t=wh(e.runId,e.id);n.set(t,n.has(t)&&n.get(t)!==r?null:r)}for(let e of t){let t=Sh(e.item.message).map(e=>e.runId?n.get(wh(e.runId,e.id)):void 0),[r]=t;r&&t.every(e=>e===r)&&(e.bounds=r)}}function ov(){return(ov=e((()=>{ta(),Y_(),y_(),ch(),nh()})))()}function sv(e,t,n){let r=n?[{kind:`notice`,key:n.key,timestamp:n.timestamp,text:R(`chat.pendingInputs.${n.status}`)}]:[],i=m(m(e.message)?.provenance);if(i?.kind!==`internal_system`)return[e,...r];let a=t??m_(e.message);if(!a||Io(a.role)!==`user`)return[e,...r];let o=Ih(typeof i.sourceTool==`string`?i.sourceTool:void 0),s=n&&o?.pendingSummaryKeys?.[n.status],c=s??o?.summaryKey,l=c?R(c):Ec(e.message)?.replace(/^\[System\] /u,``);return l?.trim()?[{kind:`notice`,key:e.key,icon:o?.icon??`cpu`,label:R(o?o.labelKey:`common.system`),...o?.startsTurn===!1?{}:{startsTurn:!0},...o?.collapsedBody?{collapsedBody:!0}:{},text:l,timestamp:a.timestamp,...$_(P_(e.message))},...s?[]:r]:r}function cv(){return(cv=e((()=>{H(),hc(),Va(),Y_(),ov(),y_(),Wh()})))()}function lv(e){let t=m(e);return t?.role===`custom`&&t.customType===xv}function uv(e,t){let n=m(e),r=m(n?.__openclaw);return!(r?.kind!==`compaction`&&!lv(e)||!t.runId||r?.runId!==t.runId||t.itemId&&r.itemId!==t.itemId)}function dv(e){let t=e.command??R(`chat.systemNotice.guardian.requestedAction`),n={kind:`notice`,key:e.key,icon:`shieldCheck`,timestamp:e.timestamp};return e.source===`system`?{...n,icon:`cpu`,label:R(`common.system`),text:e.message??``}:e.kind===`approved`?{...n,label:R(`chat.systemNotice.guardian.approvedSummary`,{action:t}),text:``}:e.kind===`warning`?{...n,label:R(`chat.systemNotice.guardian.warningLabel`),text:e.message??R(`chat.systemNotice.guardian.warningFallback`),tone:`danger`}:e.kind===`reviewing`||e.kind===`strict-review-required`?{...n,label:R(`chat.systemNotice.guardian.strictReviewRequiredLabel`),text:R(`chat.systemNotice.guardian.strictReviewRequiredSummary`),tone:`danger`}:{...n,label:R(`chat.systemNotice.guardian.deniedLabel`),text:R(`chat.systemNotice.guardian.deniedSummary`,{action:t,risk:e.riskLevel??R(`chat.systemNotice.guardian.unknownRisk`),rationale:e.rationale??R(`chat.systemNotice.guardian.noRationale`)}),tone:`danger`}}function fv(e,t,n,r=`complete`){let i=e.tokensBefore,a=e.tokensAfter,o=typeof i==`number`&&Number.isFinite(i)&&typeof a==`number`&&Number.isFinite(a)&&i>a?Math.floor(i-a):null;return{kind:`divider`,key:typeof e.id==`string`?`divider:compaction:${e.id}`:`divider:compaction:${t}:${n}`,label:R(r===`active`?`chat.composer.compactingContext`:`chat.composer.contextCompacted`),compaction:r,...o===null?{}:{metric:R(`chat.compaction.savedTokens`,{count:Ze(o)})},timestamp:t}}function pv(e,t,n){return{kind:`divider`,key:typeof e.id==`string`?`divider:reset:${e.id}`:`divider:reset:${t}:${n}`,label:R(`chat.sessionReset.label`),icon:`rotateCcw`,description:R(`chat.sessionReset.description`),timestamp:t}}function mv(e){return(e.sendAttempts??0)>0||e.sendState!==`waiting-reconnect`&&typeof e.sendSubmittedAtMs==`number`}function hv(e){return mv(e)&&!e.localCommandName&&(e.sendState===`failed`||e.sendState===`unconfirmed`||e.sendState===`held`||e.sendState===`waiting-reconnect`||e.sendState===`waiting-idle`&&!!e.sendError)}function gv(e){return mv(e)&&(e.sendState===`waiting-model`||e.sendState===`submitting`||e.sendState===`sending`||hv(e))}function _v(e,t,n,r,i,a){let o=r.filter(gv),s=o.filter(e=>!hv(e)),c=s.find(e=>e.sendState===`submitting`||e.sendState===`sending`)??s[0],l=c?.sendRunId??c?.pendingRunId,u=i.map(e=>e.runId).findLast(e=>typeof e==`string`&&e.length>0),d=a.map(m),f=d.map(e=>e?.runId).findLast(e=>typeof e==`string`&&e.length>0),p=c?.sendState===`submitting`||c?.sendState===`sending`?l:void 0,h=t??p??u??f??l,g=Sv.get(e),_=g&&(!h||!g.runId||g.runId===h)?g:null,v=[_?.startedAt,n,...o.filter(e=>h?(e.sendRunId??e.pendingRunId)===h:e===c).map(e=>e.createdAt),...i.filter(e=>!h||e.runId===h).map(e=>e.ts),...d.filter(e=>!h||e?.runId===h).map(e=>e?.__openclawToolStreamReceivedAt)].filter(e=>typeof e==`number`&&Number.isFinite(e)),y=v.length>0?Math.min(...v):Date.now(),b=_?.key??`stream-working:${JSON.stringify([e,h??`anonymous-${++Cv}`])}`;return Sv.set(e,{key:b,runId:h??_?.runId??null,startedAt:y}),{key:b,runId:h??_?.runId??null,startedAt:y}}function vv(e){Sv.delete(e)}function yv(){Sv.clear(),Cv=0}function bv(e,t){let{sessionKey:n,agentId:r=null,gatewayClient:i=null,indicator:a,row:o,usageByRun:s}=t,c=e.turnRecapWatch;if((c?.sessionKey!==n||c.agentId!==r||c.gatewayClient!==i)&&(c=null),a){let t=a.runId;if(!t)return e.turnRecapWatch=null,null;c?.runId!==t&&(c={sessionKey:n,agentId:r,gatewayClient:i,runId:t,recap:null})}if(e.turnRecapWatch=c,!c)return null;let l=s?.get(c.runId)?.outputTokens??c.recap?.outputTokens??null;if(o?.lastRunId===c.runId){let e=o.runtimeMs;o.status===`done`&&typeof e==`number`&&Number.isFinite(e)?c.recap={runtimeMs:e,outputTokens:l}:o.status&&o.status!==`done`&&(c.recap=null)}return c.recap&&c.recap.outputTokens!==l&&(c.recap={...c.recap,outputTokens:l}),a||!c.recap?null:{...c.recap,runId:c.runId}}var xv,Sv,Cv;function wv(){return(wv=e((()=>{H(),Ke(),xv=`openclaw.context-compaction`,Sv=new Map,Cv=0})))()}function Tv(e,t,n,r=[]){if(t.queuedCount===0)return[];let i=t.nextBefore===void 0&&t.items.length===t.total,a=new Map(n?.map(e=>[e.runId,e])),o=new Set(n===void 0?[]:r),s=new Map((i?[]:e).map(e=>[e.id,e]));for(let e of t.items)e.queued?s.set(e.id,e):s.delete(e.id);return[...s.values()].filter(e=>{let t=e.runId?a.get(e.runId):void 0;return t?t.state===`pending`&&t.queued:!e.runId||!o.has(e.runId)})}function Ev(e){return e.toSorted((e,t)=>e.acceptedAt-t.acceptedAt).flatMap(e=>{if(!e.queued||e.state!==`queued`||!e.runId)return[];let t=po(e.message),n=t.content.flatMap(e=>e.type===`attachment`||e.type===`attachment_error`?[e.attachment.label]:e.type===`image`?e.sources.flatMap(e=>e.fileName?[e.fileName]:[]):[]),r=t.content.filter(e=>e.type===`image`).length;return[{id:`pending-input:${e.id}`,text:Ts(e.message)||n.join(`, `)||(r?R(`chat.queue.imageCount`,{count:String(r)}):``),createdAt:e.acceptedAt,pendingRunId:e.runId,serverQueued:!0,sender:t.sender??void 0}]})}function Dv(e,t,n=[],r=[],i=!1,a){let o=[];for(let s of e){if(t?.trim()&&!x_(s.message,t,a))continue;let e;s.state===`queued`?s.runId&&(i||r.includes(s.runId))&&(e=i?`waitingForWorkerSetup`:`waitingForWorkspaceSync`):e=s.state===`interrupted`&&s.runId&&n.some(e=>e.sendRunId===s.runId&&e.sendState!==`failed`&&e.sendState!==`held`)?`resuming`:s.state===`cancelled`?`cancelled`:`interrupted`,o.push(...R_([s.message],()=>s.runId?`send:${s.runId}`:`pending-input:${s.id}`).flatMap(t=>sv({...t,startsTurn:!0},void 0,e?{status:e,key:`pending-input:${s.id}:state`,timestamp:s.acceptedAt}:void 0)))}return o}function Ov(e){let t=Rv.get(e);return t?.sessionKey===e.sessionKey&&t.sessionId===(e.currentSessionId??null)&&t.agentId===Dn(e)?t:void 0}function kv(e){Rv.delete(e)}function Av(e){let t=Xf(e,np(e,{agentId:Dn(e)})),n=[...Ov(e)?.queuedInputs.map(e=>e.runId)??[],...t.entries.filter(e=>e.pending&&e.identity?.role===`user`).map(e=>e.pendingRunId),...e.chatQueue.filter(e=>(e.sendAttempts??0)>0||e.sendState===`unconfirmed`).map(e=>e.sendRunId)],r=new Set(n.filter(e=>!!(e&&e.length<=256)));return[...new Set([...Ov(e)?.receiptRunIds.filter(e=>r.has(e))??[],...r])]}function jv(e){return Av(e).slice(0,50).toSorted()}function Mv(e,t,n=[]){let r=new Set(n);t.receiptRunIds=Av(e).toSorted((e,t)=>Number(r.has(e))-Number(r.has(t)))}function Nv(e,t,n){let{page:r,acceptedRunIds:i}=rp(e,t,n),a=new Set([...(n??[]).filter(e=>e.state===`consumed`||e.state===`pending`&&e.cancelled).map(e=>e.runId),...r.items.filter(e=>e.state===`cancelled`).map(e=>e.runId)]);for(let t of e.chatQueue){let n=ks(e.chatMessages,t.sendRunId,!0);t.sendRunId&&(a.has(t.sendRunId)||n&&(n.id!==null||n.sequence!==null))&&(!t.sessionId||t.sessionId===e.currentSessionId)?a_(e,t.id):t.sendRunId&&i.has(t.sendRunId)&&(!t.sessionId||t.sendState===`unconfirmed`)&&n_(e,t,e.currentSessionId??void 0)}return r}function Pv(e,t,n){return Ov(e)===t&&t.request===n&&e.client===n.client&&e.connected&&e.connectionEpoch===n.connectionEpoch}function Fv(e,t,n={}){let r=Nv(e,t,n.receipts),i=Ov(e),a=Tv(i?.queuedInputs??[],r,n.receipts,n.queriedRunIds);i?(i.queuedInputs=a,i.queuedCount=r.queuedCount??0,i.queueBefore=r.nextBefore,i.revision+=1,i.request&&!Pv(e,i,i.request)&&(i.request=void 0),i.before===void 0&&(i.page=r,i.error=void 0),i.before!==void 0&&!i.request&&Iv(e,i.before,`refresh`)):(i={sessionKey:e.sessionKey,sessionId:e.currentSessionId??null,agentId:Dn(e),page:r,queuedInputs:a,receiptRunIds:[],queuedCount:r.queuedCount??0,queueBefore:r.nextBefore,revision:0,get loading(){return this.request?.kind===`navigation`}},Rv.set(e,i)),Mv(e,i,n.queriedRunIds),!i.request&&i.queuedInputs.length<i.queuedCount&&i.queueBefore!==void 0&&Iv(e,i.queueBefore,`discovery`),e.requestUpdate?.()}async function Iv(e,t,n){let r=Ov(e),i=e.client;if(!r||!i||!e.connected||r.request&&Pv(e,r,r.request)&&(n!==`navigation`||r.request.kind===`navigation`))return;let a={before:t,kind:n,client:i,connectionEpoch:e.connectionEpoch};r.request=a,r.error=void 0,n===`navigation`&&e.requestUpdate?.();let o=()=>Pv(e,r,a);try{for(;o();){let t=r.revision,n=jv(e),s=await i.request(`chat.history`,{sessionKey:r.sessionKey,agentId:r.agentId,limit:20,...n.length?{inputRunIds:n}:{},...a.before===void 0?{}:{pendingBefore:a.before}});if(!o()||s.sessionId!==r.sessionId)return;if(r.revision!==t)continue;let c=Nv(e,s.pendingInputs,s.inputReceipts);if(r.queuedInputs=Tv(r.queuedInputs,c,s.inputReceipts,n),r.queuedCount=c.queuedCount??r.queuedCount,Mv(e,r,n),a.kind!==`discovery`&&(r.page=c,r.before=a.before),(a.kind===`discovery`||a.before===void 0)&&(r.queueBefore=c.nextBefore),r.queuedInputs.length<r.queuedCount&&r.queueBefore!==void 0){a.kind=`discovery`,a.before=r.queueBefore;continue}return}}catch(e){o()&&(r.error=P(e))}finally{r.request===a&&(r.request=void 0,Ov(e)===r&&e.requestUpdate?.())}}function Lv(e,t){return Iv(e,t,`navigation`)}var Rv;function zv(){return(zv=e((()=>{aa(),H(),dc(),hc(),Va(),on(),B(),l_(),cv(),Y_(),ip(),Rv=new WeakMap})))()}function Bv(e){if(typeof e!=`string`||!e.includes(`github.com`))return[];let t=[];for(let n of e.matchAll(Kv)){let e=n[0].replace(/[.,;:!?]+$/u,``);rl(e)?.kind===`pull`&&t.push(e)}return t}function Vv(e){let t=JSON.stringify(Ft(e,e.sessionKey)),n=Yv.get(e);return(!n||n.client!==e.client||n.connectionEpoch!==e.connectionEpoch||n.conversation!==t)&&(n={client:e.client,connectionEpoch:e.connectionEpoch,conversation:t,receipts:new Set},Yv.set(e,n)),n}function Hv(e,t,n){let r=n!==null&&n.length<=Jv;if(!(r&&t.receipts.has(n))&&e.refreshSessionPullRequests?.({refresh:!0,automatic:!0})===!0&&r&&(t.receipts.add(n),t.receipts.size>qv)){let e=t.receipts.values().next().value;e!==void 0&&t.receipts.delete(e)}}function Uv(e){Yv.delete(e)}function Wv(e,t,n){let r=Vv(e),i=t??``,a=JSON.stringify([`stream`,i]);if(r.receipts.has(a))return;let o=(r.tail?.runId===i?r.tail.text:``)+n;r.tail={runId:i,text:o.slice(-256)},Bv(o).length>0&&Hv(e,r,a)}function Gv(e,t,n){let r=Ji(zm(n));Hv(e,Vv(e),t&&r?JSON.stringify([`final`,t,r]):null)}var Kv,qv,Jv,Yv;function Xv(){return(Xv=e((()=>{Ki(),$c(),B(),ch(),Kv=/https:\/\/github\.com\/[^\s<>()\]}'"`]+/giu,qv=200,Jv=4096,Yv=new WeakMap})))()}function Zv(e){let t=fy.get(e);return t||(t={historyVersion:0,branchVersion:0,subscriptionGeneration:0,pendingSubscriptionReleases:new Set,historyLoad:{phase:`idle`}},fy.set(e,t)),t}function Qv(e){let t=Zv(e),n=t.initialSnapshotHydration;delete t.initialSnapshotHydration,n?.cancel?.()}function $v(e){let t=Zv(e).initialSnapshotHydration;t&&(e.connected?t.readyAt??=Date.now():t.readyAt!==void 0&&Qv(e))}function ey(e){let t=Zv(e),n=t.initialSnapshotHydration;if(!n)return;if(!n.startedBeforeReady||!F(e.sessionKey,n.sessionKey)){Qv(e);return}if(n.wait)return n.wait;let r=n.readyAt??=Date.now(),i=Math.max(0,300-(Date.now()-r));if(i===0){Qv(e);return}return n.wait=new Promise(e=>{let r=r=>{clearTimeout(a),t.initialSnapshotHydration===n&&delete t.initialSnapshotHydration,e(r)};n.complete=()=>r(!0),n.cancel=()=>r(!1);let a=setTimeout(()=>r(!0),i);n.promise.then(()=>r(!0),()=>r(!0))}),n.wait}function ty(e){return e.phase===`pending-connection`||e.phase===`in-flight`}function ny(e,t){let n=Zv(e),r=ty(n.historyLoad);n.historyLoad=t,t.phase===`committed`&&(n.acceptedHistory=t),r!==ty(t)&&e.transcriptLoadingChanged?.()}function ry(e){let t=Zv(e),n=t.historyLoad;if(n.phase===`idle`)return n;let r=kt(e,e.sessionKey)?Dn(e):void 0;return n.sessionKey!==e.sessionKey||n.requestAgentId!==r?(t.historyLoad={phase:`idle`},e.chatLoading=!1):n.phase===`in-flight`&&(!e.connected||n.client!==e.client||n.sessions!==e.sessions||n.connectionEpoch!==e.connectionEpoch)&&(t.historyLoad={phase:`pending-connection`,sessionKey:n.sessionKey,requestAgentId:n.requestAgentId,startup:n.startup},e.chatLoading=!0,e.requestUpdate?.()),t.historyLoad}function iy(e){let t=Zv(e).acceptedHistory;return t&&e.connected&&e.client===t.client&&e.sessions===t.sessions&&e.connectionEpoch===t.connectionEpoch&&e.sessionKey===t.sessionKey&&(!kt(e,e.sessionKey)||Dn(e)===t.requestAgentId)&&t.sessionInfo?.sessionId&&e.currentSessionId===t.sessionInfo.sessionId?t.sessionInfo:void 0}function ay(e,t=e.sessionKey){let n=Zv(e).acceptedHistory,r=e.chatSubmissions?.creation;return E(t)&&n?.sessionId===null&&e.connected&&e.client===n.client&&e.sessions===n.sessions&&e.connectionEpoch===n.connectionEpoch&&e.sessionKey===t&&n.sessionKey===t&&!(r?.sessionKey===t&&!r.admitted)&&!e.hasPendingInitialTurn?.(t)}function oy(e){let t=Zv(e),n=t.acceptedHistory;if(e.currentSessionId&&n&&e.client===n.client&&e.sessions===n.sessions&&(!e.connected||e.connectionEpoch===n.connectionEpoch)&&n.sessionKey===e.sessionKey&&(!kt(e,e.sessionKey)||Dn(e)===n.requestAgentId)&&n.sessionInfo?.sessionId===e.currentSessionId)return!1;let r=t.historyLoad;return r.phase===`idle`?e.chatLoading&&(!e.currentSessionId||!!t.initialSnapshotHydration):r.phase!==`committed`&&r.startup}function sy(e,t,n,r,i){return{version:++Zv(e).historyVersion,sessions:e.sessions,client:t,connectionEpoch:n,sessionKey:r,agentId:i}}function cy(e,t){return Zv(e).historyVersion===t.version&&e.client===t.client&&e.sessions===t.sessions&&e.connected&&e.connectionEpoch===t.connectionEpoch}function ly(e,t){return cy(e,t)&&e.sessionKey===t.sessionKey&&(!kt(e,t.sessionKey)||Dn(e)===t.agentId)}function uy(e,t){Qv(e),Uv(e),kv(e);let n=Zv(e);n.historyVersion+=1,delete n.acceptedHistory,ny(e,{phase:`idle`}),e.chatLoading=!1;let r=np(e,{agentId:t});ap(e,{type:`sessionReset`},{scope:r})}function J(e,t,n=!1){let r=t===null?null:P(t);e.lastError=r,e.chatError=r,n&&e.requestUpdate?.()}function dy(e,t,n){return Qe(e,e.sessionKey,t,n)}var fy;function Y(){return(Y=e((()=>{d(),on(),B(),zv(),Xv(),ip(),fy=new WeakMap})))()}function py(e,t){return e===`source-changed`?R(`chat.queue.editSourceChanged`):e===`full`?R(`chat.queue.full`):t?R(`chat.queue.editStorageFailed`):X}function my(e){let t=ys(e);return t?.command.key===`new`||t?.command.key===`reset`&&!/^soft(?:\s|$)/i.test(t.args)}function hy(e){return!e.intent&&!e.localCommandName&&!e.text.trimStart().startsWith(`/`)}function gy(e,t,n=!1){return ay(e,t)?R(`chat.incognitoExpiredTitle`):_y(e,t,n)}function _y(e,t,n=!1){return e.connected&&e.client&&!e.client.recoveryScopeReady?R(`chat.queue.connectionPending`):n||e.hasPendingInitialTurn?.(t)?R(`chat.queue.initialTurnPending`):null}function vy(e,t){return e.status===`error`?`Chat failed before the run started; try again.`:t===`detached`?`The active run ended before the detached message was accepted.`:`The run ended before the message was accepted.`}function yy(e,t){if(t?.kind!==`delivered`||!t.pending)return;let{sessionKey:n,agentId:r,message:i}=t;if(V(e,n,r)){(!t.sessionId||!e.currentSessionId||t.sessionId===e.currentSessionId)&&Yf(e,Ov(e)?.page.items,t);return}if(e.chatMessagesBySession){let a={sessionKey:n,agentId:r},o=Vh(e.chatMessagesBySession,e,a);op(t,ks(o,t.pendingRunId,!0))&&Nm(e.chatMessagesBySession,e,a,i)}}function by(e,t,n,r){let i=e.client??e,a=e.chatSubmissions,o=Ks(e,n,t),s=s_(e,t,n)?.item;if(r?.inputConsumed&&t){let r=a.readDelivered(o,i);return r&&(r.pending=!1),V(e,n.sessionKey,n.agentId)&&(!s?.sessionId||s.sessionId===e.currentSessionId)&&Qf(e,new Set([t])),!s||o_(e,t,n)?`retired`:`retained`}if(!s)return yy(e,a.readDelivered(o,i)),`retired`;let c=e.connectionEpoch,l=e.connected,u=jp(e),d=()=>e.connected===l&&e.connectionEpoch===c&&u(),f=()=>s_(e,t,n)?.item,p=c=>{if(!d())return`stale`;let l=f();if(!l)return yy(e,a.readDelivered(o,i)),e_(e,s.id)?`stale`:`retired`;if(!Bc(l,s)||!s.sendRunId)return`stale`;yy(e,a.retain({kind:`delivered`,deliveryKey:o,owner:i,sessionKey:s.sessionKey??n.sessionKey,agentId:s.agentId,sessionId:s.sessionId,pendingRunId:s.sendRunId,message:c}));let u=f();return!d()||!u||!Bc(u,s)?`stale`:!r?.retainUntilConsumed&&o_(e,t,n)?`retired`:`retained`},m=e_(e,s.id),h=m&&m.attachmentPayload?.key===s.attachmentPayload?.key&&m.attachments?.length===s.attachments?.length?m:s,g=e=>Ip({...s,attachments:e,runId:s.sendRunId},`complete`),_=g(h.attachments)??g(s.attachments);return _&&(!s.attachmentPayload&&!s.attachmentStorageError||(s.attachments?.length??0)>0)?p(_):lp(e,s,`handoff`).then(t=>{if(!d())return`stale`;if(t.status===`ready`){let e=g(t.update.attachments??s.attachments);if(e)return p(e)}let n=f();if(!n)return e_(e,s.id)?`stale`:`retired`;if(!Bc(n,s))return`stale`;let r=t.status===`failed`?t.reason:`missing`;return t_(e,s.id,e=>Jf({...e,sendState:e.sendState===`held`?`held`:`unconfirmed`},r)),`retained`})}function xy(e,t,n,r,i={}){let a=P(r);if(V(e,t,n)){e.lastError=i.inline?null:a,e.chatError=i.inline?null:a;return}let o=n?f(n):void 0,s=e.sessionsResult?.sessions.find(e=>F(e.key,t)&&(!mn(t)||!o||e.agentId!==void 0&&f(e.agentId)===o));ct({message:`${ze(t,s)}: ${a}`})}function Sy(e,t){let n=(t.senderLabel??`User`).replace(/([\\`*_{}[\]()#+\-.!|>])/g,`\\$1`),r=t.text.trim();return r.includes(`
`)?`> **${n}:**\n${r.split(`
`).map(e=>`> ${e}`).join(`
`)}\n\n${e}`:`> **${n}:** ${r}\n\n${e}`}var Cy,X;function wy(){return(wy=e((()=>{H(),fs(),dc(),lo(),Cs(),on(),Kt(),I(),B(),tt(),Y(),zv(),l_(),ip(),up(),zh(),kh(),Cy=`Reconnected before delivery was confirmed. Check the conversation — retry only if your message didn't arrive.`,X=`Could not store this message for reconnect. Free browser storage or reconnect before sending.`})))()}function Ty(e,t,n=()=>e.requestUpdate()){let r,i,a=!1,o=()=>{clearTimeout(r),r=void 0,i=void 0},s=()=>{let e=Date.now(),n=a&&document.visibilityState!==`hidden`?t().flatMap(t=>{let n=Ja(t),r=n===void 0?void 0:n+_o;return r!==void 0&&r>e?[r]:[]}):[],s=n.length?Math.min(...n):void 0;s!==i&&(o(),s!==void 0&&(i=s,r=setTimeout(c,s-e)))},c=()=>{o(),n(),s()},l=()=>{document.visibilityState===`hidden`?o():c()};return e.addController({hostConnected(){a=!0,document.addEventListener(`visibilitychange`,l),c()},hostDisconnected(){a=!1,document.removeEventListener(`visibilitychange`,l),o()}}),{sync:s}}function Ey(){return(Ey=e((()=>{eo()})))()}function Dy(e){let t=jy.get(e);return t||(t={panes:new Map,listeners:new Set},jy.set(e,t)),t}function Oy(e,t,n){let r=Dy(e);if(JSON.stringify(r.panes.get(t))!==JSON.stringify(n)){n?r.panes.set(t,n):r.panes.delete(t);for(let e of r.listeners)e()}}function ky(e,t){let{listeners:n}=Dy(e);return n.add(t),()=>n.delete(t)}function Ay(e,t,n,r){if(!ci(t)||!n)return{page:t};let i={hello:e.gateway.snapshot.hello,agentsList:e.agents.state.agentsList,assistantAgentId:r},a=Ft(i,n),o=e.sessions.state.result?.sessions.find(e=>Qe(i,n,e.key,e.agentId)),s=i.agentsList?.agents.find(e=>e.id===a.agentId),c=Fs({session:o,agentWorkspace:s?.workspace}),l=[...Dy(e).panes.values()].find(e=>e.sessionKey===a.sessionKey&&e.agentId===a.agentId);return{page:t,title:o?.label||o?.displayName||a.sessionKey,...a,sessionId:o?.sessionId,workspace:c.root??void 0,...l}}var jy;function My(){return(My=e((()=>{Lr(),B(),jy=new WeakMap})))()}function Ny(e){let t=m(e),n=typeof t?.stopReason==`string`?t.stopReason.toLowerCase():``;return Hp(e)!==null||m(t?.openclawAbort)?.aborted===!0||[`aborted`,`cancelled`,`canceled`,`timeout`,`timed_out`].includes(n)}function Py(e){if(Z_(e))return`commentary`;if(_u(e,{phase:`final_answer`}))return`final_answer`;let t=hu(e);if(t)return t;let n=m(e),r=m(n?.__openclaw);return r?.mirrorOrigin===`codex-app-server`&&r.runTerminal===!0&&n?.stopReason===`stop`&&!Ny(e)?`final_answer`:void 0}function Fy(){return(Fy=e((()=>{gu(),ov(),ch()})))()}function Iy(e,t,n,r){let i=Io(e);if(i===`user`&&r)return r.identity?.type===`agent`?ud(r,`chat-avatar assistant`):Nu(Jl(r),Sa(r)??``);if(i===`assistant`){let e=t?.name?.trim()||`Assistant`;return Ly(t?.agentId??`main`,e,t?.avatar,t?.textAvatar??An(t?.avatar))}let a=rr(n),o=ar(n),s=xr(n),c=i===`user`?W`
          <svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18">
            <circle cx="12" cy="8" r="4" />
            <path d="M20 21a8 8 0 1 0-16 0" />
          </svg>
        `:i===`tool`?W`
            <svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18">
              <path
                d="M12 15.5A3.5 3.5 0 0 1 8.5 12 3.5 3.5 0 0 1 12 8.5a3.5 3.5 0 0 1 3.5 3.5 3.5 3.5 0 0 1-3.5 3.5m7.43-2.53a7.76 7.76 0 0 0 .07-1 7.76 7.76 0 0 0-.07-.97l2.11-1.63a.5.5 0 0 0 .12-.64l-2-3.46a.5.5 0 0 0-.61-.22l-2.49 1a7.15 7.15 0 0 0-1.69-.98l-.38-2.65A.49.49 0 0 0 14 2h-4a.49.49 0 0 0-.49.42l-.38 2.65a7.15 7.15 0 0 0-1.69.98l-2.49-1a.5.5 0 0 0-.61.22l-2 3.46a.49.49 0 0 0 .12.64L4.57 11a7.9 7.9 0 0 0 0 1.94l-2.11 1.69a.49.49 0 0 0-.12.64l2 3.46a.5.5 0 0 0 .61.22l2.49-1c.52.4 1.08.72 1.69.98l.38 2.65c.05.24.26.42.49.42h4c.23 0 .44-.18.49-.42l.38-2.65a7.15 7.15 0 0 0 1.69-.98l2.49 1a.5.5 0 0 0 .61-.22l2-3.46a.49.49 0 0 0-.12-.64z"
              />
            </svg>
          `:W`
            <svg viewBox="0 0 24 24" fill="currentColor" width="18" height="18">
              <circle cx="12" cy="12" r="10" />
              <text
                x="12"
                y="16.5"
                text-anchor="middle"
                font-size="14"
                font-weight="600"
                fill="var(--bg, #fff)"
              >
                ?
              </text>
            </svg>
          `,l=i===`user`?`user`:i===`tool`?`tool`:`other`;if(i===`user`&&o){let e=es(o)??o;return Nu({fallback:Ds({name:a}),imageUrl:e,sourceUrl:o.startsWith(`/`)?o:void 0,pending:typeof e!=`string`},a)}return i===`user`&&s?W`<div class="chat-avatar ${l}" role="img" aria-label="${a}">
      ${s}
    </div>`:W`<div class="chat-avatar ${l}">${c}</div>`}function Ly(e,t,n,r=An(n)){let i=n?.trim()||``,a=Il({id:e,name:t,textAvatar:r},`chat-avatar assistant`);if(du(e)||!(i.startsWith(`blob:`)||Pe(i)))return a;let o=es(i)??i,s={imageUrl:o,sourceUrl:i,pending:typeof o!=`string`};return W`<span class=${Tl(`chat-avatar-slot`,s)}>
    ${iu({view:s,fallbackSelector:`.chat-avatar-slot`,className:`chat-avatar assistant`,alt:t})}${a}${Kc(e)}
  </span>`}function Ry(e,t){if(e&&e===t.agentId)return Iy(`assistant`,{agentId:e,name:t.assistantName??`Assistant`,avatar:t.assistantAvatar??null,textAvatar:t.assistantTextAvatar});let n=e?t.agents?.find(t=>t.id===e):void 0;if(!n)return G;let r=n.identity?.name?.trim()||n.id,i=t.senderAgentAvatars?.get(n.id)??qe(n);return Ly(n.id,r,i,An(i)??at(n))}function zy(e){return(e.hello?.snapshot)?.sessionDefaults?.defaultAgentId?.trim()||void 0}function By(e){let t=jt(e.sessionKey);return t?.agentId?t.agentId:mn(e.sessionKey)?Tt(e)||`main`:zy(e)||`main`}function Vy(e){let t=(Xy.get(e)??0)+1;return Xy.set(e,t),t}function Hy(e,t,n,r){return Xy.get(e)===t&&e.sessionKey===n&&By(e)===r}function Uy(e){let t=tb.get(e);t?.get(eb)?.(),t?.delete(eb),e.chatAvatarUrl=null,e.chatAvatarSource=null,e.chatAvatarStatus=null,e.chatAvatarReason=null}function Wy(e,t,n){e.chatAvatarSource=n.source,e.chatAvatarStatus=n.status,e.chatAvatarReason=n.reason,e.chatAvatarUrl=n.url,Zy.set(e,t)}function Gy(e,t,n){let r=tb.get(e);r||(r=new Map,tb.set(e,r)),r.get(t)?.(),r.set(t,n)}function Ky(e){Vy(e);for(let t of tb.get(e)?.values()??[])t();tb.delete(e),Zy.delete(e),Qy.delete(e),$y.delete(e),e.senderAgentAvatars=void 0,Uy(e)}async function qy(e,t){let n=e.client,r=e.connectionEpoch,i=By(e);if(!n||!e.connected)return null;let a=()=>void 0;try{let o=await Ll(n,t);if(!o||!e.connected||e.client!==n||e.connectionEpoch!==r||By(e)!==i)return null;let s=o.avatar?.trim()??``,c=s.startsWith(`/`)?es(s):Pe(s)?s:null;a=as(c);let l=await c;return c!==null&&l===null?(a(),null):{release:a,source:o.avatarSource??null,status:o.avatarStatus??null,reason:o.avatarReason??null,url:l}}catch{return a(),null}}async function Jy(e){if(!e)return;let t=[e.chatMessages,e.agentsList,e.sessionKey,e.assistantAgentId,e.connected,e.client,e.connectionEpoch],n=$y.get(e);if(n&&t.every((e,t)=>e===n[t]))return;$y.set(e,t);let r={};Qy.set(e,r);let i=e.sessionKey,a=By(e),o=e.client,c=e.connectionEpoch,l=e.agentsList?.agents,u=new Set(l?.map(e=>e.id)),d=[];if(e.connected)for(let t of e.chatMessages){if(Yo(t)!==`assistant`)continue;let e=wa(s(t)?.senderSession)?.agentId;if(e&&e!==a&&u.delete(e)&&(d.push(e),d.length===23))break}let f=e.senderAgentAvatars,p=d.length?await Promise.all(d.map(t=>qy(e,t))):[];if(d.length&&(!e.connected||e.client!==o||e.connectionEpoch!==c||e.agentsList?.agents!==l||e.sessionKey!==i||By(e)!==a||Qy.get(e)!==r)){for(let e of p)e?.release();return}let m=tb.get(e);for(let[e,t]of m??[])e!==eb&&!d.includes(e)&&(t(),m?.delete(e));let h=new Map(d.map((t,n)=>{let r=p[n];return r&&Gy(e,t,r.release),[t,r?r.url:f?.get(t)??null]}));(h.size!==(f?.size??0)||[...h].some(([e,t])=>f?.get(e)!==t))&&(e.senderAgentAvatars=h,e.requestUpdate?.())}async function Yy(e){if(!e.connected){Ky(e);return}let t=e.sessionKey,n=e.client,r=e.connectionEpoch,i=Vy(e),a=By(e),o=Zy.get(e)===a;o||Uy(e);let s=await qy(e,a);if(!e.connected||e.client!==n||e.connectionEpoch!==r||!Hy(e,i,t,a)){s?.release();return}s?(Gy(e,eb,s.release),Wy(e,a,s)):o||Uy(e)}var Xy,Zy,Qy,$y,eb,tb;function nb(){return(nb=e((()=>{bi(),fu(),au(),pi(),dl(),He(),ke(),Va(),Ko(),rs(),Ao(),B(),Rf(),Xy=new WeakMap,Zy=new WeakMap,Qy=new WeakMap,$y=new WeakMap,eb=Symbol(`current-chat-avatar`),tb=new WeakMap})))()}function rb(e,t){return t!==`assistant`&&t!==`user`?null:e?.isImported?e.externalSource?`${t}:import:${e.externalSource}`:e.sequence===null?null:`${t}:import-seq:${e.sequence}`:e?.id?`${t}:${e.id}`:null}function ib(e,t){return e.replace(RegExp(`^${uu(t)}(?::|:|-|—)?[ \\t]+`),``)}function ab(e,t){if(e.content.length===0)return null;let n=[];for(let t of e.content){if(t.type!==`text`||typeof t.text!=`string`)return null;n.push(t.text)}return{role:t,senderLabel:(e.senderLabel??``).trim(),senderKey:Ka(e.sender),senderSession:e.senderSession,clientSourcesKey:Pn(e.sourceClients??[]),text:n.join(`
`)}}function ob(e,t){if(e?.role!==`assistant`||t?.role!==`assistant`||!e.text.trim()||!t.text.trim()||!!e.senderLabel==!!t.senderLabel)return!1;let n=e.senderLabel?e:t,r=e.senderLabel?t:e;return n.text===r.text||ib(n.text,n.senderLabel)===r.text}function sb(e){if(!e||!e.role||e.role===`tool`)return null;let t=e.text.trim().replace(/\s+/g,` `);if(!t)return null;let n=[`user`,`assistant`].includes(e.role)?e.senderLabel:``;return JSON.stringify([e.role,n,e.senderKey??``,e.senderSession,e.clientSourcesKey,t])}function cb(e){let t=[],n=null,r=null,i=!1;for(let a of e){if(a.kind!==`message`){t.push(a),n=null,r=null,i=!1;continue}let e=po(a.message),o={kind:`message`,item:a,normalized:e},s=Io(e.role).toLowerCase(),c=j_(a.message),l=c?null:ab(e,s),u=N_(a.message),d=c?null:rb(u,s),f=d===null&&u?.isImported===!0&&u.externalSource===null&&u.sequence===null,p=t[t.length-1];if(d&&r===d&&p?.kind===`message`&&ob(n,l)){l?.senderLabel||(t[t.length-1]=o,n=l);continue}if(p?.kind===`message`&&!f&&!i&&d===r&&l?.role===n?.role){let e=sb(l);if(e&&e===sb(n)){p.item.duplicateCount=(p.item.duplicateCount??1)+1;continue}}t.push(o),n=l,r=d,i=f}return t}function lb(){return(lb=e((()=>{Jn(),Va(),Ko(),Y_()})))()}function ub(e,t){return Py(e)??(t===`none`?`activity`:`reply`)}function db(e){let t=new Set;for(let n of e){if(n.kind!==`group`||n.role!==`user`||!n.sender)continue;let e=Ka(n.sender);e&&t.add(e)}if(t.size<2)return e;let n;for(let t of e){if(t.kind===`stream`){t.replyToSender=n;continue}t.kind===`group`&&(t.role===`user`?n=t.sender:t.role===`assistant`&&g_(t)?n=void 0:t.role===`assistant`&&n&&(t.replyToSender=n))}return e}function fb(e){let t=[],n=null,r=null;for(let i of cb(e)){if(i.kind!==`message`){n&&=(t.push(n),null),t.push(i);continue}let{item:e,normalized:a}=i,o=Io(a.role),s=oc(e.message,a),c={message:e.message,key:e.key,duplicateCount:e.duplicateCount,hasVisibleContent:s===`non-text`||!!Ac(e.message,a).trim()},l=o===`user`||o===`assistant`?a.senderLabel??null:null,u=o===`user`?a.sender:void 0,d=a.timestamp||Date.now(),f=o===`assistant`||o===`tool`?X_(e.message):void 0,p=o===`user`?Am(e.message):null,h=o===`user`?p??P_(e.message):null,g=o===`user`||o===`assistant`,_=e.startsTurn===!0||m(m(e.message)?.__openclaw)?.turnBoundary===!0,v=o===`assistant`&&n?.role===`assistant`&&ub(n.messages[0]?.message,n.visibleContent)!==ub(e.message,s);!n||_||n.role!==o||n.runId!==f||r!==h||v||Pn(n.sourceClients??[])!==Pn(a.sourceClients??[])||g&&(!u?.identity&&n.senderLabel!==l||n.senderSession?.sessionKey!==a.senderSession?.sessionKey||n.senderSession?.label!==a.senderSession?.label||Ka(n.sender)!==Ka(u))?(n&&t.push(n),r=h,n={kind:`group`,key:`group:${o}:${e.key}`,role:o,senderLabel:l,...a.senderSession?{senderSession:a.senderSession}:{},...u?{sender:u}:{},...a.sourceClients?{sourceClients:a.sourceClients}:{},messages:[c],visibleContent:s,timestamp:d,isStreaming:!1,...f?{runId:f}:{}}):((s===`non-text`||n.visibleContent===`none`)&&(n.visibleContent=s),n.messages.push(c))}return n&&t.push(n),db(t)}function pb(e){let t=[],n=[],r=()=>{let[e]=n;if(e){let{runId:r,boundaryId:i}=e;t.push({kind:`stream-run`,key:`stream-run:${e.key}`,parts:n,replyToSender:n.find(e=>e.kind===`stream`)?.replyToSender,...r?{runId:r}:{},...i?{boundaryId:i}:{}}),n=[]}};for(let i of e){if(i.kind===`stream`||i.kind===`reading-indicator`){let e=n[0];e&&(e.runId!==i.runId||e.boundaryId!==i.boundaryId)&&r(),n.push(i);continue}r(),t.push(i)}return r(),t}function mb(e){return e.kind===`group`&&(e.role===`assistant`||e.role===`tool`)&&!h_(e)}function hb(e){if(e.kind!==`group`||e.isStreaming||gb(e,!1))return!1;let t=e.role.toLowerCase();return t===`tool`||t===`assistant`&&!h_(e)&&ub(e.messages[0]?.message,e.visibleContent)!==`final_answer`}function gb(e,t=!0){return e.visibleContent===`non-text`||t&&e.visibleContent===`text`}function _b(e){return e.role.toLowerCase()===`assistant`&&!h_(e)&&gb(e)}function vb(e){return e.kind===`group`&&!e.isStreaming&&_b(e)&&ub(e.messages[0]?.message,e.visibleContent)!==`commentary`}function yb(e){let t=e[0];return!t||t.kind===`stream-run`?[]:t.kind===`group`?t.role.toLowerCase()===`user`?t.messages.map(({message:e})=>e):[]:t.kind===`message`&&v_(t)?[t.message]:[]}function bb(e,t){let[n,r,i,a,...o]=x(t.sessionKey).split(`:`);if(!(n===`agent`&&r&&i===`dashboard`&&a&&o.length===0)||t.searchActive)return e;let s=[],c=[];for(let t of e)t.kind!==`stream-run`&&v_(t)&&c.length>0&&(s.push(c),c=[]),c.push(t);c.length>0&&s.push(c);let{continuationTurnIndexes:l,precedingContinuationTurnIndexes:u}=Rp(s,yb),d=s.map((e,t)=>l.has(t)?void 0:e.findLast(vb)),f=s.map((e,t)=>{let n=d[t];return n?e.lastIndexOf(n):-1});for(let e=s.length-2;e>=0;--e){let t=l.get(e);!d[e]&&t!==void 0&&(d[e]=d[t])}let p=new Set;if(t.runWorking){let e=s.length-1;for(p.add(e);;){let t=u.get(e);if(t===void 0)break;e=t,p.add(e)}}let m=[];for(let[e,n]of s.entries()){if(p.has(e)||n.some(e=>e.kind===`stream-run`||e.kind===`group`&&e.isStreaming)){m.push(...n);continue}let r=f[e]??-1,i=d[e];if(!i){m.push(...n);continue}let a=r>=0?r:n.length-1,o=a;for(;a>0&&mb(n[a-1]);)--a;let c=xb(n);for(;o+1<n.length;){let e=n[o+1];if(!mb(e)||e.runId&&!c.has(e.runId))break;o+=1}let u=[],h=[];for(let e=a;e<=o;e+=1){let t=n[e];e!==r&&hb(t)&&(r<0||e<r||!t.messages.some(({message:e})=>Xs(e).some(Ps)))?u.push(t):h.push(t)}if(!u[0]){m.push(...n);continue}let g=t.session,_=g?.runtimeMs,v=g?.key===t.sessionKey&&i.runId!==void 0&&g.lastRunId===i.runId&&(g.status===`done`||g.status===`failed`||g.status===`timeout`||g.status===`killed`)&&typeof _==`number`&&Number.isFinite(_)&&_>=0?_:null,y=s[l.get(e)??-1]?.[0];m.push(...n.slice(0,a)),m.push({kind:`work-group`,key:`work:${r>=0||!y?i.key:y.key}`,groups:u,durationMs:v}),m.push(...h,...n.slice(o+1))}return m}function xb(e){let t=new Set;for(let n of e){if(n.kind===`stream-run`){n.runId&&t.add(n.runId);continue}if(n.kind!==`group`||n.runId===void 0)continue;let e=n.role.toLowerCase()!==`tool`;(n.isStreaming||gb(n,e))&&t.add(n.runId)}return t}function Sb(e,t={}){if(t.searchActive)return e;let n=e=>{if(e.isStreaming||e.visibleContent===`non-text`||g_(e)||e.messages.some(({message:e,hasVisibleContent:t})=>{let n=m(e);return n?.role===`assistant`&&(t||Py(e)===`final_answer`||Ny(e)||n.stopReason===`error`)}))return!1;let t=e.role.toLowerCase();return t===`tool`||t===`assistant`&&e.visibleContent===`none`&&e.messages.some(({message:e})=>Xs(e).length>0)},r=[],i=[],a=()=>{let[e]=i;e&&(r.push(i.length===1?e:{kind:`activity-run`,key:`activity:${e.key}`,groups:i}),i=[])};for(let t of e){if(t.kind===`group`&&n(t)){i.push(t);continue}a(),r.push(t)}return a(),r}function Cb(){return(Cb=e((()=>{Jn(),qs(),Va(),ec(),Ko(),Qs(),Fy(),lb(),Y_(),ov(),y_(),jh()})))()}function wb(e,t,n,r,i){let a=(n.queue??[]).toSorted(ya),{queue:o,pendingInputs:s}=ep(t,a,n.pendingInputs??[]),c=new Set,l=new Set,u=new Set,d=[],f,p,m=(e,t)=>{if(n.searchOpen&&n.searchQuery?.trim()&&!x_(e,n.searchQuery,n.messageRecovery))for(let e of t)u.add(e.key)};for(let t of s){let r=Dv([t],void 0,a,n.workspaceSyncPendingRunIds,n.workerSetupPending,n.messageRecovery),o=r[0];if(o){if(m(t.message,r),t.state===`queued`){d.push({items:r,runId:t.runId}),i&&t.runId===i&&!u.has(o.key)&&(f=o.key);continue}K_(e,[{item:o,bounds:{afterKey:p}}]),e.splice(e.indexOf(o)+1,0,...r.slice(1));for(let e of r)c.add(e.key);p=r.at(-1).key}}let h=new Map(d.flatMap(e=>e.runId?[[e.runId,e]]:[])),g=new Map(d.map(e=>[e.items[0].key,e])),_=new Set(e.map(e=>e.key));for(let e of o){if(!gv(e))continue;let t=V_(e);if(!t)continue;let i={items:[{kind:`message`,key:e.sendRunId?R_([t])[0].key:`pending-send:${e.id}`,message:t}],runId:e.sendRunId,initial:e.id===n.initialTurnId,local:!0,bypassesQueue:e.queueMode===`steer`||e.queueMode===`interrupt`};m(t,i.items),!f&&!u.has(i.items[0].key)&&!hv(e)&&(f=i.items[0].key);let o=a.indexOf(e),s=r.keys.indexOf(i.items[0].key),c=s<0||i.initial?void 0:r.keys.slice(s+1).find(e=>g.has(e)||_.has(e));c&&_.has(c)&&(i.beforeKey=c);let l=a.slice(o+1).map(e=>e.sendRunId?h.get(e.sendRunId):void 0).find(e=>e!==void 0)??(c?g.get(c):void 0),p=l?d.indexOf(l):-1;d.splice(p<0?d.length:p,0,i)}let v=e.length;for(let t of d.toReversed()){let n=t.local?e.findIndex(e=>{if(!t.runId||e.kind!==`message`)return!1;let n=ea(e.message);return lg(e.message,t.runId)||n?.role===`assistant`&&!n.isImported&&n.runId===t.runId}):-1,r=t.beforeKey?e.findIndex(e=>e.key===t.beforeKey):-1,i=t.initial?0:Math.min(v,n<0?e.length:n,r<0?e.length:r);e.splice(i,0,...t.items),v=t.initial||t.bypassesQueue&&n>=0?v+t.items.length:i,l.add(t.items[0].key)}return r.keys=e.filter(e=>e.kind!==`message`||z_(e.message)).map(e=>e.key),{pendingKeys:l,historicalKeys:c,hiddenKeys:u,activeInputKey:f}}function Tb(){return(Tb=e((()=>{ta(),zv(),wv(),Y_(),ip(),ch()})))()}function Eb(e){return{type:`tool_result`,id:e.callId,name:e.name,text:e.outputText??``,details:e.details,isError:e.isError,exitCode:e.exitCode,__openclaw:{id:e.resultMessageId,toolOutput:e.toolOutput,truncated:e.outputTruncated}}}function Db(e,t){let n=m(e.message);if(!n)return[];let r=n,i=Array.isArray(n.content)?n.content:[],a=e=>{let t=m(e)?.type;return Ln(t)||Fn(t)},o=i.filter(a),s=new Map;if(o.some(e=>!A_(m(e),n))){let e=[...Xs(n)];if(i=i.flatMap(t=>{if(!a(t))return[t];let r=m(t),i=A_(r,n),o=Ln(r.type),c=e.findIndex(e=>o===Object.hasOwn(e,`args`)&&(!i||e.callId===i));if(c<0)return[];let l=e.splice(c,1)[0],u={id:l.callId,name:l.name,details:l.details},d=[...o?[{...r,...u,arguments:l.args}]:[],...!o||l.completed||l.outputText!==void 0?[Eb(l)]:[]];return d.forEach(e=>s.set(e,l)),d}),n={...n,content:i},o=i.filter(e=>a(e)&&A_(m(e),n)),o.length===0)return[]}let c=o.length===0;if(c){let[e]=Xs(n);if(!e?.callId)return[];o=[Eb(e)],s.set(o[0],e)}let l={item:e,originalMessage:r,message:n,index:t,standalone:c,remaining:i.filter(e=>!o.includes(e)&&(!c||m(e)?.type!==`text`))};return o.map(e=>{let t=m(e),i=A_(t,n),a=Ln(t.type),o=n.__openclawToolStreamLive===!0,c=s.get(t)??xs(r,t)[0];return{source:l,id:i,call:a,runId:j(t.runId)??ea(n)?.runId??j(n.runId),name:j(t.name)??j(n.toolName)??j(n.tool_name)??`tool`,rank:a?o?1:2:o?n.__openclawToolStreamResultReceived===!0?2:1:3,block:{...t,id:i,...a?{arguments:c?.args}:{text:c?.outputText,__openclaw:{id:c?.resultMessageId,toolOutput:c?.toolOutput,truncated:c?.outputTruncated}},...c?.details===void 0?{}:{details:c.details},...!a&&c?.isError!==void 0?{isError:c.isError}:{},...!a&&c?.exitCode!==void 0?{exitCode:c.exitCode}:{}}}})}function Ob(e,t){if(!e)return t;let[n,r]=t.rank>=e.rank?[e,t]:[t,e],i=m(n.block.details),a=m(r.block.details);return{...r,name:r.name===`tool`?n.name:r.name,block:{...Object.fromEntries(Object.entries(n.block).filter(([,e])=>e!==void 0)),...Object.fromEntries(Object.entries(r.block).filter(([,e])=>e!==void 0)),...i&&a?{details:{...i,...a}}:{},...r.call?{arguments:r.block.arguments??n.block.arguments}:{text:r.block.text}}}}function kb(e){let t=e.flatMap((e,t)=>e.kind===`message`?Db(e,t):[]);if(t.length===0)return e;let n=new Map;for(let t of e)if(t.kind===`message`){for(let e of Sh(t.message))if(e.runId){let t=n.get(e.id)??new Set;t.add(e.runId),n.set(e.id,t)}}let r=e=>{let t=n.get(e.id);return e.runId??=t?.size===1?t.values().next().value:void 0,wh(e.runId??``,e.id)},i=new Map;for(let e of t){let t=r(e),n=i.get(t)??new Set;e.name!==`tool`&&n.add(e.name.toLowerCase()),i.set(t,n)}let a=new Map,o=new Map;for(let e of t){o.set(e.source.index,e.source);let t=r(e),n=i.get(t),s=e.name===`tool`&&n.size===1?n.values().next().value:e.name.toLowerCase(),c=JSON.stringify([t,s]),l=a.get(c)??{first:e.source.index,attachments:[],projections:[]};l.projections.push(e),e.call?l.call=Ob(l.call,e):l.result=Ob(l.result,e),e.source.message.__openclawToolStreamLive===!0&&(l.live=e.source.message),e.source.standalone&&(l.result?.source===e.source&&(l.attachments=e.source.remaining),e.source.remaining=[]),a.set(c,l)}let s=new Map,c=new Map,l=new Map,u=new Set(o.values());for(let e of a.values()){let t=new Set(e.projections.map(e=>e.source));(t.size>1||e.projections.length>Number(!!e.call)+Number(!!e.result))&&t.forEach(e=>u.delete(e))}for(let e of a.values()){let t=e.call??e.result;if(u.has(t.source))continue;let n=t.source.message,a=m(n.__openclaw),o=Kn(a?.transcriptPosition)?.activity?t.source.index:e.first,s=e.result,d=s!==void 0&&s.rank>1,f=n.messageId??a?.id??s?.source.message.messageId??m(s?.source.message.__openclaw)?.id,p=[...e.call?[{...e.call.block,name:e.call.name}]:[],...s?[{...s.block,name:e.call?.name??s.name}]:[],...e.attachments],h=JSON.stringify([t.runId,!!e.live,d,f,e.live?.__openclawToolStreamDiffStat,e.live?.__openclawToolStreamReceivedAt,(i.get(r(t))?.size??0)>1?t.name:void 0]),g=`${t.source.index}:${h}`,_=[h,r(t),t.name,...e.projections.flatMap(({source:e})=>[e.originalMessage,...Array.isArray(e.originalMessage.content)?e.originalMessage.content:[e.originalMessage.content]])],v=c.get(g),y=new Map;for(let r of[n,e.live,s?.source.message]){let e=Ro(r).filter(e=>(e.toolCallId??e.itemId)===t.id&&!e.suppressChannelProgress);r===s?.source.message&&Array.isArray(m(r)?.activity)&&e.length===0&&y.clear();for(let t of e)(y.get(t.itemId)?.phase!==`end`||t.phase===`end`)&&y.set(t.itemId,t)}if(v){v.inputs.push(..._),v.item.message.content.push(...p),v.item.message.activity=[...Ro(v.item.message),...y.values()],v.index=Math.min(v.index,o);continue}let b={...t.source.item,key:`${t.source.item.key}:invocation:${r(t)}:${t.name}`,message:{...n,role:e.call?`assistant`:n.role,runId:t.runId,content:p,activity:[...y.values()],...f?{messageId:f}:{},...e.live?{__openclawToolStreamLive:!0,__openclawToolStreamResultReceived:d,__openclawToolStreamDiffStat:d?void 0:e.live.__openclawToolStreamDiffStat,__openclawToolStreamReceivedAt:e.live.__openclawToolStreamReceivedAt}:{}}};c.set(g,{item:b,index:o,inputs:_}),l.set(b,{owner:t.source.originalMessage,inputs:_})}for(let{item:e,index:t}of c.values()){let n=s.get(t)??[];n.push(e),s.set(t,n)}let d=e.flatMap((e,t)=>{let n=o.get(t);if(!n||u.has(n))return[e];let r=s.get(t)??[];if(n.remaining.length>0){if(r.length>0){let e=r.map(e=>({message:e.message,blocks:e.message.content}));e.forEach(({message:e})=>{e.content=[]});let t=e[0],i=Array.isArray(n.message.content)?n.message.content:[];for(let r of i){if(n.remaining.includes(r)){t.message.content.push(r);continue}let i=m(r)??{},a=A_(i,n.message);for(let n of e){let e=n.blocks.filter(e=>{let t=m(e);return t?.id===a&&(!i.name||i.name===t?.name)});e.length>0&&(n.message.content.push(...e),n.blocks=n.blocks.filter(t=>!e.includes(t)),t=n)}}e.forEach(e=>e.message.content.push(...e.blocks))}else r.unshift({...n.item,message:{...n.message,content:n.remaining,toolCallId:void 0,tool_call_id:void 0,toolUseId:void 0,tool_use_id:void 0,toolName:void 0,tool_name:void 0}})}return r}),f=new Map;for(let[e,{owner:t,inputs:n}]of l){n.push(e.message.content.length);for(let t of e.message.content){let e=m(t);Ln(e?.type)||Fn(e?.type)?n.push(e?.type,e?.id,e?.name):n.push(t)}let r=jb.get(t)?.get(e.key);r?.inputs.length===n.length&&n.every((e,t)=>e===r.inputs[t])&&(e.message=r.message);let i=f.get(t)??new Map;i.set(e.key,{inputs:n,message:e.message}),f.set(t,i)}for(let[e,t]of f)jb.set(e,t);return d}function Ab(e){let t=[],n=e=>{if(e.length===0)return;let n=[],r;for(let i of e){let a=i.kind===`message`?m(i.message):null;if(i.kind!==`message`||!a||a.__openclawToolStreamLive===!0){t.push(...kb(e));return}r??=a,n.push(i.kind,i.key,a,i.duplicateCount,i.startsTurn),n.push(a.content),Array.isArray(a.content)&&n.push(...a.content)}let i=Mb.get(r),a=i?.inputs.length===n.length&&n.every((e,t)=>e===i.inputs[t])?i:{inputs:n,items:kb(e).map(e=>Object.assign({},e))};Mb.set(r,a);for(let e of a.items)t.push({...e})},r=[];for(let i of e)v_(i)||i.kind===`divider`?(n(r),t.push(i),r=[]):r.push(i);return n(r),t}var jb,Mb;function Nb(){return(Nb=e((()=>{ta(),In(),Gn(),Ic(),Qs(),Y_(),y_(),nh(),jb=new WeakMap,Mb=new WeakMap})))()}function Pb(e,t,n){let r=w_(e,t);return r?`canvas:${r}`:`${n}:canvas`}function Fb(e,t={keys:[]}){let n=[],r=e.toolMessages.filter(e=>m(e)!==null),i=R_(r).map(e=>({projection:{item:e},runId:j(e.message.runId),callId:j(e.message.toolCallId),preview:S_(e.message)})),a=e.queue??[],o=e.streamSegments,s=null,c=()=>s??=_v(e.sessionKey,e.runId??null,e.streamStartedAt,a,o,r),l=e.persistCommentary===!1&&(e.runWorking||e.runActive)?j(c().runId):void 0,u=Wn(e.messages.filter(t=>!ws(t)&&(e.persistCommentary!==!1||!Z_(t)||l!==void 0&&X_(t)===l))),d=e.searchOpen===!0&&!!e.searchQuery?.trim(),f=new Set,p=new Set,h=u.map(m_),g=R_(u),_={previews:[],lastMatchingAssistantIndex:-1},v=g.map((t,n)=>{let r=h[n],i=r&&Io(r.role);return(i===`user`||i===`system`)&&(_={previews:[],lastMatchingAssistantIndex:-1}),i===`assistant`&&r&&(!d||x_(u[n],e.searchQuery??``,e.messageRecovery))&&(_.lastMatchingAssistantIndex=n,_.previews.push(...r.content.flatMap(e=>e.type===`canvas`?[{preview:e.preview,item:t}]:[]))),_}),y=e.compactionStatus,b=y?`divider:compaction:live:${y.runId}:${y.itemId??`manual`}`:void 0,x=!1;for(let[t,r]of g.entries()){let i=r.message,a=r.key,o=m(i)??{},s=m(o.__openclaw);if(s?.kind===`compaction`||lv(i)){let e=y!=null&&uv(i,y),r=fv(s??{},H_(i)??Date.now(),t);n.push({...r,compactionId:r.key,...e&&b?{key:b}:{}}),x||=e;continue}let c=h[t];if(!c)continue;if(s&&s.kind===`reset`){n.push(pv(s,c.timestamp??Date.now(),t));continue}if(Io(c.role)===`system`){let e=Ec(i);e?.trim()&&n.push({kind:`notice`,key:a,text:e,timestamp:c.timestamp});continue}let l=c.role.toLowerCase()===`toolresult`,g=l?S_(i):null;if(g){let e=w_(i,g);e&&p.add(e)}let _=g&&v[t].previews.find(({preview:e})=>Do(e,g.preview));g&&_&&(_.item.message=b_(_.item.message,g.preview,g.text));let S=g!=null&&!_&&(!d||v[t].lastMatchingAssistantIndex>t);if(g&&S&&n.push({kind:`message`,key:Pb(i,g,a),message:T_(g,g.timestamp??E_(u,t))}),!e.showToolCalls&&l)continue;let C=e.searchQuery??``;e.searchOpen&&C.trim()&&!x_(i,C,e.messageRecovery)&&f.add(a),(z_(i,c)||c.role.toLowerCase()===`assistant`)&&n.push(...sv(r,c))}let S=e.runId??(e.stream!==null||a.some(gv)?c().runId:null),C=nv(n.filter(e=>!f.has(e.key))),{pendingKeys:w,historicalKeys:T,hiddenKeys:E,activeInputKey:D}=wb(n,u,e,t,S);n=n.filter(e=>!f.has(e.key)&&!E.has(e.key));let O=()=>n.filter(e=>!T.has(e.key)),k=rv(O()),A=(S?k(S):null)??(D?{afterKey:D}:C),ee=e=>{let{minimum:t,maximum:r}=G_(n,e??void 0),i=n.find((e,n)=>n>=t&&n<r&&w.has(e.key));return i?{...e,beforeKey:i.key}:e??void 0};for(let{projection:e,preview:t}of i){if(!t)continue;let r=w_(e.item.message,t);if(r&&p.has(r))continue;let i=ee(iv(k,e.item.message.runId,S,A)??(!e.item.message.runId&&D?A:void 0)),{minimum:a,maximum:o}=G_(n,i??void 0),s=D_(n,t.timestamp,a,o);if(s){n[s.index]={...s.item,message:b_(s.item.message,t.preview,t.text)};continue}if(d)continue;let c=O_(n,t.timestamp,a,o),l=n[c],u=l?.kind===`message`?H_(l.message):null,f=t.timestamp!=null&&u!=null?Math.min(t.timestamp,u):t.timestamp;n.splice(c,0,{kind:`message`,key:Pb(e.item.message,t,e.item.key),message:T_(t,f)})}n=n.filter(e=>e.kind!==`message`||z_(e.message));let te=[];if(y&&b&&!x){let e=y.startedAt??y.completedAt??Date.now();te.push({item:{...fv({},e,0,y.phase===`complete`?`complete`:`active`),key:b}})}let ne=new Map,M;for(let e of o){let t=j(e.afterBoundaryRunId)??M;t&&ne.set(e,t),M=j(e.boundaryRunId)??M}let re=o.filter(Fo),ie=o.filter(e=>!Fo(e)&&e.boundaryMarker!==!0),ae=ev();for(let e of i)ae.add(e.runId,e.callId,e.projection);let oe=rv(O()),se=(e,t,n)=>{let r=iv(oe,e,S,A)??(!e&&D?A:void 0),i=t?oe(t)?.afterKey:void 0,a=n?oe(n):void 0;return ee(r||i||a?{...r,...a?.afterKey?{afterKey:a.afterKey}:{},...a?.beforeKey?{beforeKey:a.beforeKey}:{},...i?{beforeKey:i}:{}}:void 0)};if(!d){e.archiveNotice&&te.push({item:e.archiveNotice});for(let t of e.guardianNotices??[])te.push({item:dv(t),bounds:se(t.runId)})}let ce=ev(),le=ev();for(let e of ie){let t=j(e.toolCallId),n=j(e.runId),r=j(e.boundaryRunId),i=ne.get(e);r&&ce.add(n,t,r),i&&le.add(n,t,i)}let N=(e,t,n)=>{let r=ne.get(e);te.push({item:{kind:`stream`,key:t,text:n,startedAt:e.ts,isStreaming:!1,...Q_(e.runId),...$_(r??e.runId)},bounds:se(e.runId,e.boundaryRunId,r)})},ue=null,de=Math.max(ie.length,i.length);for(let t=0;t<de;t++){let n=ie[t];if(n){let r=B_(n.text),i=Hc(n),a=i?Ca(r,ue):r;if(i&&(ue=to(ue,r)),a.length>0&&n.persisted!==!0){let r=`stream-seg:${e.sessionKey}:${t}`;N(n,r,a);let i=ae.get(j(n.runId),n.toolCallId?.trim());i&&(i.predecessorKey=r)}}let r=i[t];if(r&&e.showToolCalls){let e=ce.get(r.runId,r.callId),t=le.get(r.runId,r.callId);r.projection.bounds=se(r.runId,e,t),te.push(r.projection)}}for(let t of re){let n=B_(t.text);n.length>0&&N(t,`stream-seg:${e.sessionKey}:${t.itemId}`,n)}for(let t of e.questionPrompts??[]){if(t.status===`pending`)continue;let e={kind:`question`,key:`question:${t.id}`,questionId:t.id,startedAt:t.createdAtMs};te.push({item:e,bounds:t.runId?se(t.runId):void 0})}av(n,i.map(e=>e.projection)),K_(n,te);let fe=e.stream===null&&e.loading===!0&&n.length===0,pe=e.stream!==null&&e.stream.trim().length===0,me=(!y||y.phase===`complete`)&&(e.runWorking===!0&&!fe||pe||a.some(e=>(e.sendState===`submitting`||e.sendState===`sending`)&&gv(e)));e.runWorking!==!0&&e.stream===null&&!me&&vv(e.sessionKey);let he=S?xm(u,S):null,ge=he&&(!M||u.findIndex(e=>P_(e)===M)<=he.index)?he.runId:M,_e=ge??S,ve=ee((_e?rv(O())(_e):null)??(D?{afterKey:D}:null)),ye=e=>{if(ve){let{maximum:t}=G_(n,ve);n.splice(t,0,e)}else n.push(e)};if(e.stream!==null){let t=B_(e.stream),r=Ba(o,B_),i=Ca(t,r);if(i.length>0&&!As(i).shouldSkip){let t=c(),r=e.runId??t.runId;ye({kind:`stream`,key:ge?`${t.key}:after:${ge}`:t.key,text:i,startedAt:W_(n,e.streamStartedAt??Date.now()),isStreaming:!0,...Q_(r),...$_(ge??r)})}}if(me){let t=c(),n=e.runId??t.runId;ye({kind:`reading-indicator`,key:t.key,startedAt:t.startedAt,...Q_(n),...$_(ge??n)})}return fb(Ab(n))}function Ib(){return(Ib=e((()=>{Gn(),jc(),hc(),Va(),wv(),cv(),Cb(),Tb(),Y_(),ov(),Nb(),y_(),jh()})))()}function Lb(e){return e.kind===`group`?[e]:e.kind===`work-group`||e.kind===`activity-run`?e.groups:[]}function Rb(e){if(e.kind===`stream-run`)return e.runId;let t=Lb(e),n=t[0]?.runId;return n&&t.every(e=>e.runId===n)?n:void 0}function zb(e){return Lb(e).some(e=>e.messages.some(({message:e})=>Ny(e)||m(e)?.stopReason===`error`))}function Bb(e){return e.kind===`stream-run`?e.parts.some(e=>e.kind===`reading-indicator`||e.kind===`stream`&&e.isStreaming):Lb(e).some(e=>e.isStreaming)}function Vb(e){let t=e.messages[0]?.message,n=ea(t),r=n?.runId;return r?`send:${r}`:n?.id?`entry:${n.id}`:void 0}function Hb(e,t,n){return`agent-run:${JSON.stringify(n?[e,t,n]:[e,t])}`}function Ub(e,t){return t??e.flatMap(e=>e.kind===`stream-run`?e.parts:[]).find(e=>e.kind===`stream`&&e.key.includes(`:after:`))?.key}function Wb(e){return e.parts.flatMap(Lb)}function Gb(e,t){let n=m(e),r=Py(e),i=n?.stopReason,a=m(n?.__openclaw);return!(Ec(e)?.trim()||tf(e))||Ny(e)||r===`commentary`||i===`toolUse`||i===`error`||a?.mirrorOrigin===`codex-app-server`&&a.runTerminal!==!0?!1:!t||r===`final_answer`||i===`stop`}function Kb(e){let t=e.flatMap(Lb).flatMap(e=>e.role===`assistant`?e.messages:[]).findLast(({message:e})=>Gb(e,!0));if(t)return t;let n=e.at(-1);if(n?.kind!==`group`||n.role!==`assistant`)return null;let r=n.messages.at(-1);return r&&Gb(r.message,!1)?r:null}function qb(e){if(e.outcome.kind!==`active`)return;let t=e.parts.flatMap(e=>e.kind===`stream-run`?e.parts:[]);return t.length>0&&e.parts.every(e=>e.kind===`stream-run`&&e.parts.every(e=>e.kind===`reading-indicator`))?t:void 0}function Jb(e){return e.kind===`group`||e.kind===`work-group`||e.kind===`activity-run`||e.kind===`stream-run`}function Yb(e,t={}){if(t.searchActive)return e;let n=[],r,i,a=new Set,o,s,c=[],l=(e=!1)=>{if(!s||!r||c.length===0)return;let t=Hb(s,r,Ub(c,o)),l=a.has(t)?Hb(s,r,JSON.stringify([i,c[0].key])):t;a.add(t),n.push({kind:`agent-run-frame`,key:l,runId:s,boundaryId:r,outcome:e?{kind:`failed`}:c.some(Bb)?{kind:`active`}:{kind:`completed`,actionOwner:Kb(c)},parts:c}),c=[],s=void 0};for(let t of e){if(!Jb(t)){l(),n.push(t),r=t.kind===`notice`&&t.startsTurn?t.boundaryId:void 0,o=r?void 0:t.key;continue}let e=Lb(t)[0];if(e&&v_(e)){l(),i=e.key,o=void 0;let a=Vb(e);if(e.role===`user`||h_(e)||!a){n.push(t),r=a;continue}r=a}let a=t.kind===`stream-run`?t.boundaryId:void 0;a&&a!==r&&(l(),r=a);let u=Rb(t);if(t.kind===`activity-run`&&!u){l(),n.push(t);let e=t.groups.findLast(v_);e?(r=Vb(e),i=e.key,o=void 0):t.groups.some(e=>e.runId===void 0)&&(r=void 0,o=t.key);continue}if(!r||!u){l(),n.push(t),r=void 0,o=t.key;continue}let d=zb(t);s&&s!==u&&l(),s=u,c.push(t),d&&(l(!0),r=void 0,o=t.key)}return l(),n}function Xb(){return(Xb=e((()=>{ta(),hc(),Fy(),y_(),Ku()})))()}function Zb(e){if(e){hx.delete(e);return}hx.clear(),yv(),gx.clear(),_x.clear()}function Qb(e,t){return e.role===t.role&&e.senderLabel===t.senderLabel&&e.senderSession?.sessionKey===t.senderSession?.sessionKey&&e.senderSession?.agentId===t.senderSession?.agentId&&e.senderSession?.label===t.senderSession?.label&&Pn(e.sourceClients??[])===Pn(t.sourceClients??[])&&JSON.stringify(e.sender)===JSON.stringify(t.sender)&&JSON.stringify(e.replyToSender)===JSON.stringify(t.replyToSender)&&e.isStreaming===t.isStreaming&&e.visibleContent===t.visibleContent&&e.runId===t.runId&&e.messages.length===t.messages.length&&e.messages.every((e,n)=>{let r=t.messages[n];return r!==void 0&&e.key===r.key&&e.message===r.message&&e.duplicateCount===r.duplicateCount&&e.hasVisibleContent===r.hasVisibleContent})}function $b(e,t){if(e.kind!==t.kind||e.key!==t.key)return!1;switch(t.kind){case`group`:return e.kind===`group`&&Qb(e,t);case`message`:return e.kind===`message`&&e.message===t.message&&e.duplicateCount===t.duplicateCount;case`notice`:return e.kind===`notice`&&e.text===t.text&&e.label===t.label&&e.startsTurn===t.startsTurn&&e.boundaryId===t.boundaryId&&e.timestamp===t.timestamp;case`divider`:return e.kind===`divider`&&e.compaction===t.compaction&&e.compactionId===t.compactionId&&e.label===t.label&&e.metric===t.metric&&e.description===t.description&&e.timestamp===t.timestamp;case`stream`:return e.kind===`stream`&&e.text===t.text&&e.startedAt===t.startedAt&&e.isStreaming===t.isStreaming&&JSON.stringify(e.replyToSender)===JSON.stringify(t.replyToSender)&&e.runId===t.runId&&e.boundaryId===t.boundaryId;case`reading-indicator`:return e.kind===`reading-indicator`&&e.startedAt===t.startedAt&&e.runId===t.runId&&e.boundaryId===t.boundaryId;case`question`:return e.kind===`question`&&e.questionId===t.questionId&&e.startedAt===t.startedAt}return!1}function ex(e,t){if(e.length===0||t.length===0)return t;let n=new WeakMap,r=new Map;for(let t of e)if(t.kind===`group`)for(let e of t.messages)e.message&&typeof e.message==`object`&&n.set(e.message,t),r.set(e.key,t);let i=new Set(t.filter(e=>e.kind===`group`).map(e=>e.key)),a=new Set,o=new Map(e.flatMap(e=>e.kind===`divider`&&e.compactionId?[[e.compactionId,e.key]]:[])),s=t.map(e=>{if(e.kind===`divider`&&e.compactionId){let t=o.get(e.compactionId);return t?{...e,key:t}:e}if(e.kind!==`group`)return e;let t=new Map;for(let[i,o]of e.messages.entries()){let s=o.message&&typeof o.message==`object`?n.get(o.message)??r.get(o.key):r.get(o.key);if(!s||a.has(s.key)||s.role!==e.role||s.runId!==e.runId||s.senderLabel!==e.senderLabel||s.senderSession?.sessionKey!==e.senderSession?.sessionKey||s.senderSession?.agentId!==e.senderSession?.agentId||s.senderSession?.label!==e.senderSession?.label||Pn(s.sourceClients??[])!==Pn(e.sourceClients??[])||Ka(s.sender)!==Ka(e.sender))continue;let c=t.get(s);t.set(s,{overlap:(c?.overlap??0)+1,lastMatchIndex:i})}let s=null;for(let[e,n]of t)(!s||n.overlap>s.overlap||n.overlap===s.overlap&&n.lastMatchIndex>s.lastMatchIndex)&&(s={group:e,...n});return!s||s.group.key!==e.key&&i.has(s.group.key)?e:(a.add(s.group.key),e.key===s.group.key?e:{...e,key:s.group.key})}),c=new Map(e.map(e=>[`${e.kind}\u0000${e.key}`,e])),l=s.map(e=>{let t=c.get(`${e.kind}\u0000${e.key}`);return t&&$b(t,e)?t:e});return tx(l,e)?e:l}function tx(e,t){return e===t||e!==void 0&&t!==void 0&&e.length===t.length&&e.every((e,n)=>e===t[n])}function nx(e,t){return e.sessionKey===t.sessionKey&&e.archiveNotice?.key===t.archiveNotice?.key&&e.archiveNotice?.label===t.archiveNotice?.label&&e.runId===t.runId&&e.compactionStatus===t.compactionStatus&&e.locale===t.locale&&e.messages===t.messages&&e.toolMessages===t.toolMessages&&e.guardianNotices===t.guardianNotices&&e.streamSegments===t.streamSegments&&e.streamStartedAt===t.streamStartedAt&&e.queue===t.queue&&e.initialTurnId===t.initialTurnId&&tx(e.pendingInputs,t.pendingInputs)&&e.workspaceSyncPendingRunIds===t.workspaceSyncPendingRunIds&&e.workerSetupPending===t.workerSetupPending&&e.showToolCalls===t.showToolCalls&&e.persistCommentary===t.persistCommentary&&e.runWorking===t.runWorking&&e.runActive===t.runActive&&e.questionPrompts===t.questionPrompts&&e.loading===t.loading&&e.searchOpen===t.searchOpen&&e.searchQuery===t.searchQuery&&e.messageRecovery?.messages===t.messageRecovery?.messages&&e.messageRecovery?.revision===t.messageRecovery?.revision&&e.messageRecovery?.agentId===t.messageRecovery?.agentId}function rx(e){return JSON.stringify([e.sessionKey,e.runId??null,e.streamStartedAt])}function ix(e,t){let n=e.liveStream,r=n?e.items[n.index]:void 0;if(t.stream===null||!n||r?.kind!==`stream`||!r.isStreaming||n.identity!==rx(t))return!1;let i=Ca(B_(t.stream),n.prefix);return i.length===0||As(i).shouldSkip?!1:(e.items[n.index]={...r,text:i},!0)}function ax(e){return e.findIndex(e=>e.kind===`stream`&&e.isStreaming)}function ox(e){let t=hx.get(e.paneId);t||(t=new Map,hx.set(e.paneId,t));let n=Ph(t,e.sessionKey,()=>({input:null,inputOrder:{keys:[]},items:[],liveStream:null}));if(n.input&&nx(n.input,e)){if(n.input.stream===e.stream)return n.items;if(n.input.stream!==null&&ix(n,e))return n.input=e,n.items}n.input?.initialTurnId!==e.initialTurnId&&(n.inputOrder.keys=[]);let r=ex(n.items,Fb(e,n.inputOrder));n.input=e,n.items=r;let i=ax(r);return n.liveStream=i<0?null:{index:i,identity:rx(e),prefix:Ba(e.streamSegments,B_)},r}function sx(e){return vx.get(e)??0}function cx(e,t,n){e.has(t)&&e.get(t)===n||(e.set(t,n),vx.set(e,sx(e)+1))}function lx(e,t){e.delete(t)&&vx.set(e,sx(e)+1)}function ux(e,t,n){let r=new Set(n.map(e=>N_(e)?.id).filter(e=>typeof e==`string`).map(e=>u_(t,e)));for(let t of e.keys())r.has(t)||lx(e,t)}function dx(e){return Ph(gx,e,()=>({expanded:new Map,initialized:new Set}))}function fx(e){return dx(e).expanded}function px(e){for(let[t,n]of _x)if(F(t,e))return t!==e&&(_x.delete(t),yh(_x,e,n)),n;return Ph(_x,e,()=>new Map)}function mx(e,t,n,r=!1){let i=dx(e),{expanded:a,initialized:o,lastSync:s}=i;if(s?.items.deref()===t&&s.isFilteredProjection===r&&s.autoExpandToolCalls===n)return;let c=new Set;for(let e of t)if(e.kind===`group`)for(let t of e.messages){let e=Xs(t.message);for(let r=0;r<e.length;r++){let e=`${t.key}:toolcard:${r}`;c.add(e),!o.has(e)&&(cx(a,e,n),o.add(e))}if(!no(t.message))continue;let r=`toolmsg:${t.key}`;c.add(r),!o.has(r)&&(cx(a,r,n),o.add(r))}if(n&&!s?.autoExpandToolCalls)for(let e of o)cx(a,e,!0);if(!r)for(let e of o)c.has(e)||(o.delete(e),lx(a,e));i.lastSync={items:new WeakRef(t),isFilteredProjection:r,autoExpandToolCalls:n}}var hx,gx,_x,vx;function yx(){return(yx=e((()=>{Jn(),jc(),Va(),Ko(),Qs(),B(),p_(),wv(),Ib(),Y_(),fh(),Cb(),Xb(),hx=new Map,gx=new Map,_x=new Map,vx=new WeakMap})))()}function bx(e){let t=e.captureConnectionScope(),n=()=>!!(t&&e.isConnectionScopeCurrent(t)),r=null,i=new Set;return{isCurrent:n,read:()=>n()?r:null,subscribe(e){return i.add(e),()=>{i.delete(e)}},confirm:e=>{if(!n())return;r=e;let t=[...i];for(let e of t)e()}}}function xx(e,t,n){let r=xn(t),i=/^agent:([^:]+):(.*)$/u.exec(r),o=i?.[2]??r,s=mn(t),c=[a,Lt(e)].includes(o.toLowerCase()),l=vt(e),u=i?.[1],d=c&&f(u??``)===`main`&&l!==`main`&&e.agentsList?.agents!=null&&!e.agentsList.agents.some(e=>f(e.id)===`main`),p=e.agentsList?.scope?e.agentsList.scope===`global`:mn(ht(a,e.hello)),m=(d?l:n?.trim()||u)||(s?Tt(e):l),h=s||c&&p?`global`:c?a:o;return`agent:${f(m)}:${h}`}function Sx(e,t,n){let r=xx(e,t,n);return Ex.get(e.sessions)?.get(r)?.ready}function Cx(e,t,n,r={}){let i=e.sessions,a=xx(e,t,r.agentId),o=Ex.get(i)??new Map;Ex.set(i,o);let s=o.get(a),c=s?.ready,l=s?.receipt.isCurrent()?s.receipt:bx(i),u=r.canDispatch,d=(async()=>{let e=await i.patch(t,n,{agentId:r.agentId,expectedSessionId:r.expectedSessionId,ownsModelOverride:r.ownsModelOverride,canDispatch:u?()=>u(l.read()):void 0,onConfirmed:l.confirm,onRejected:e=>r.onRejected?.(e,l.read()),waitFor:c,...c?{predecessorReceipt:l}:{}});return e&&await r.reconcile?.(e),e})(),f={ready:d.then(e=>e!==null,()=>!1),receipt:l};return o.set(a,f),f.ready.finally(()=>{o.get(a)===f&&o.delete(a)}),d}function wx(e,t){let n=k(e),r=jt(n??``),i=r&&r.agentId!==`main`&&(r.rest===`main`||r.rest===`global`)?r.agentId:void 0,a=i??k(t.agentId);return(n===`global`||i)&&a?{agentId:a}:{}}async function Tx(e,t,n,r={}){let i=await Cx({sessions:e.sessions,assistantAgentId:e.agentId,agentsList:e.defaultAgentId?{defaultId:e.defaultAgentId}:null,hello:null},t,n,{...wx(t,e),...r});if(!i)throw Error(`Session capability is unavailable`);return i}var Ex;function Dx(){return(Dx=e((()=>{I(),B(),Ex=new WeakMap})))()}function Ox(e){Ux.get(e)?.abort(),Ux.delete(e)}function kx(e){Ox(e);let t=Object.keys(e.chatModelSwitchPromises??{}),n=new Set([e.sessionKey,...t]);kt(e,e.sessionKey)&&n.add(`global`);let r=t.length>0,i=e.sessions.state?.modelOverrides??{},a=[...n].some(e=>Object.hasOwn(i,e));if(r||a){e.chatModelSwitchPromises={};for(let t of n)e.sessions.retireModelOverride(t);e.requestUpdate?.()}}function Ax(e){return{...Ut,includeGlobal:!0,includeUnknown:!0,configuredAgentsOnly:!0,includeDerivedTitles:!0,archivedFilter:e.sessionsArchivedFilter??`active`}}function jx(e){return e.sessions.refresh({...Ax(e),...ae(e,e.sessionKey),force:!0})}function Mx(e,t){return e.sessions.refresh({...Ax(e),...Ge(e,t),force:!0})}function Nx(e,t){return e.sessionsResult?.sessions.find(n=>ge(e,n.key,t,n.agentId??e.sessionsResultAgentId))}function Px(e,t){let n=Nx(e,t),r=e.sessions,i=r.captureConnectionScope(),a=e.client,o=ae(e,t).agentId,s=n?.sessionId,c=o??n?.agentId??e.sessionsResultAgentId,l=n=>ge(e,n.key,t,n.agentId??c),u=()=>!!(i&&e.connected&&e.client===a&&e.sessions===r&&r.isConnectionScopeCurrent(i)&&F(e.sessionKey,t)&&ae(e,t).agentId===o),d=()=>u()&&(n?e.sessionsResult?.sessions.some(e=>l(e)&&e.sessionId===s)===!0:!e.sessionsResult?.sessions.some(e=>l(e)&&e.sessionId!==void 0));return{sessionId:s,settings:{...n,...r.settingsPreview(t,o)},agentParams:L(e,t),isCurrent:d,row:n=>{if(!(n?!u()||!ge(e,n.key,t,c):!d()))return e.sessionsResult?.sessions.find(e=>l(e)&&e.sessionId===(s??n?.entry.sessionId))}}}async function Fx(e,t,n,r,i,a){let o=i=>(n.isCurrent()||!!n.row(i))&&Le(e.hello?.auth,{method:`sessions.patch`,params:{key:t,...r},sessionScope:!0,session:n.row(i)}).allowed;J(e,null,!0);let s=null;try{if(!o())return!1;let c=Cx(e,t,r,{...n.agentParams,expectedSessionId:n.sessionId,canDispatch:o,onRejected:(t,r)=>{(n.isCurrent()||n.row(r))&&J(e,`Failed to set ${i}: ${P(t)}`,!0)},reconcile:async()=>jx(e)});return a?.(),s=await c,s!==null}catch{return!1}finally{a?.(s)}}function Ix(e,t,n=e.sessionKey){if(!e.client||!e.connected)return Promise.resolve(!1);let r=Px(e,n),i=t===``?void 0:t===`auto`?`auto`:t===`on`;return r.settings.fastMode===i?Promise.resolve(!0):Fx(e,n,r,{fastMode:i??null},`speed`)}function Lx(e,t){Ux.get(e)?.abort();let n=new AbortController;Ux.set(e,n);let r=e.client,i=e.connectionEpoch,a=e.sessions,o=e.sessionKey,s=L(e,t),c=Nx(e,t),l=c?.sessionId,u=(c=l)=>!n.signal.aborted&&Ux.get(e)===n&&e.connected&&e.client===r&&e.connectionEpoch===i&&e.sessions===a&&e.sessionKey===o&&L(e,t).agentId===s.agentId&&Nx(e,t)?.sessionId===c;return{owner:n,ownsSelection:u,agentScope:s,get expectedSessionId(){return l},activeRow:c,adoptCreatedSession(e){return l!==void 0||!u(e)?!1:(l=e,!0)}}}async function Rx(e,t,n,r,i,a=()=>!0,o=!1){let{owner:s,ownsSelection:c,agentScope:l}=i,u=R(`chat.nativeRuntimeRecovery.reasons.${t.reason}`,{runtime:t.runtimeLabel}),d=()=>J(e,`${u} ${R(`chat.nativeRuntimeRecovery.chooseAnother`)}`,!0),f=()=>c()&&a();try{let a=t.recovery?.sessionId;if(i.expectedSessionId===void 0&&a&&(!c()&&!c(a)||(await Mx(e,{sessionKey:n,...l}),!i.adoptCreatedSession(a)))||!c())return!1;let{confirmNativeRuntimePermissionRecovery:u}=await M(async()=>{let{confirmNativeRuntimePermissionRecovery:e}=await import(`./chat-native-runtime-recovery-ttYYPde6.js`);return{confirmNativeRuntimePermissionRecovery:e}},__vite__mapDeps([14,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url),p=await u(e,n,t,{...l,...r===void 0?{}:{model:r||null},expectedSessionId:i.expectedSessionId,signal:s.signal,retriesMessage:o,canDispatch:f});return!p&&f()&&d(),!c()||!p?!1:(J(e,p.listRefreshError?R(`chat.nativeRuntimeRecovery.refreshFailed`,{error:p.listRefreshError}):null,!0),!0)}catch(t){return c()&&J(e,R(`chat.nativeRuntimeRecovery.failed`,{error:P(t)}),!0),!1}}function zx(e,t){let n=Lx(e,t),r=n.expectedSessionId===void 0,i=n.activeRow?.model,a=n.activeRow?.modelProvider,o=n.activeRow?.agentRuntime?.id,s=So({activeSession:n.activeRow,chatModelCatalog:e.chatModelCatalog,modelOverrides:e.sessions.state.modelOverrides,sessionKey:t,sessionsResult:e.sessionsResult??null})||xe(e.sessionsResult?.defaults?.model,e.sessionsResult?.defaults?.modelProvider,e.chatModelCatalog);return async c=>{if(!await Rx(e,c,t,void 0,n,()=>{let n=Nx(e,t);return r?!(!s||xe(n?.model,n?.modelProvider,e.chatModelCatalog)!==s||n?.agentRuntime?.id!==c.runtimeId||o&&o!==c.runtimeId):!!(s&&n?.model===i&&n?.modelProvider===a&&n?.agentRuntime?.id===o&&o===c.runtimeId)},!0))return;let l=()=>Nx(e,t),u=l(),d=u?.model,f=u?.modelProvider,p=u?.agentRuntime?.id;return()=>{let e=l();return n.ownsSelection()&&e?.model===d&&e?.modelProvider===f&&e?.agentRuntime?.id===p}}}async function Bx(e,t,n=e.sessionKey,r){if(!e.client||!e.connected)return!1;let i=Nx(e,n);if(i?.modelSelectionLocked===!0)return!1;let a=Lx(e,n),{ownsSelection:o,agentScope:s}=a,c=So({activeSession:i,chatModelCatalog:e.chatModelCatalog,modelOverrides:e.sessions.state.modelOverrides,sessionKey:n,sessionsResult:e.sessionsResult??null}),l=i?.runtimeSelectionLocked&&r===null?void 0:r,u=l===void 0||!i?.runtimeSelectionLocked&&(l===null?!mo(i?.agentRuntime):mo(i?.agentRuntime)&&i?.agentRuntime?.id===l);if(c===t&&u)return!0;let d=L(e,n).agentId,f=()=>!kt(e,n)||Tt(e)===d,p={model:t||null,...l===void 0?{}:{agentRuntime:l}},m=()=>o()&&Le(e.hello?.auth,{method:`sessions.patch`,params:{key:n,...p},sessionScope:!0,session:Nx(e,n)}).allowed;if(!m())return!1;J(e,null,!0);let h={},g=()=>{if(e.chatModelSwitchPromises?.[n]===h.current){let t={...e.chatModelSwitchPromises};delete t[n],e.chatModelSwitchPromises=t}},_=(async()=>{try{return await Cx(e,n,p,{...s,expectedSessionId:a.expectedSessionId,ownsModelOverride:f,canDispatch:m,reconcile:()=>jx(e)})!==null}catch(r){if(!o())return!1;let i=r instanceof Yn?ia(r.details):void 0;return i?await Rx(e,i,n,t,a,()=>!l||l===i.runtimeId):(J(e,`Failed to set model: ${P(r)}`,!0),!1)}finally{g(),e.requestUpdate?.()}})();return h.current=_,e.chatModelSwitchPromises={...e.chatModelSwitchPromises,[n]:_},e.requestUpdate?.(),_}function Vx(e,t,n=e.sessionKey){if(!e.client||!e.connected)return Promise.resolve(!1);let r=Px(e,n),i=r.settings.thinkingLevel,a=(zi(t)??t.trim())||void 0;return((typeof i==`string`&&i.trim()?zi(i)??i.trim():void 0)??``)===(a??``)?Promise.resolve(!0):Fx(e,n,r,{thinkingLevel:a??null},`thinking level`,t=>{let n=r.row(t);n&&(e.chatThinkingLevel=n.thinkingLevel??null)})}function Hx(e,t,n=e.sessionKey){if(!e.client||!e.connected)return Promise.resolve(!1);let r=Px(e,n),i=t.trim()||void 0;return(r.settings.contextWindow??``)===(i??``)?Promise.resolve(!0):Fx(e,n,r,{contextWindow:i??null},`context window`)}var Ux;function Wx(){return(Wx=e((()=>{ra(),ki(),Br(),H(),To(),Ie(),Oa(),on(),se(),I(),B(),Y(),Dx(),n(),Ra(),Ux=new WeakMap})))()}async function Gx(e,t){try{let n=t.runId===null||t.sessionAbortable===!0,r=s(await e.request(n?`sessions.abort`:`chat.abort`,{...n?{key:t.sessionKey}:{sessionKey:t.sessionKey},...t.agentId?{agentId:t.agentId}:{},...t.runId===null?t.clearQueued?{clearQueued:!0}:{}:{runId:t.runId,...t.discardPendingInput?{discardPendingInput:!0}:{}}}));return{ok:!0,noActiveRun:r?.aborted===!1||r?.status===`no-active-run`,warning:j(r?.warning)}}catch(e){return{ok:!1,error:e,...e instanceof Yn&&s(e.details)?.errorKind===`state_contention`?{errorKind:`state_contention`}:{}}}}function Kx(e,t){return mn(t)||rn(e)&&Sn(e,t)!==null?{}:{clearQueued:!0}}function qx(e,t){return e.sessionsResult?.sessions.find(n=>Qe(e,t.sessionKey,n.key,n.agentId??e.sessionsResultAgentId??void 0,t.agentId))}function Jx(e,t,n=`run`){let r=e.chatRunSessionAbortable===!0,i=n===`run`?e.chatRunId??null:null,a={sourceClient:t,recoveryScope:e.hello?.auth?.recoveryScope??t.recoveryScope,sessionKey:e.sessionKey,conversation:Ft(e,e.sessionKey),...L(e,e.sessionKey)},o=qx(e,a)?.sessionId,s={...a,...o?{sessionId:o}:{}};return i?{...s,runId:i,...r?{sessionAbortable:!0}:{}}:{...s,runId:null,...Kx(e,e.sessionKey)}}function Yx(){return(Yx=e((()=>{Br(),je(),B()})))()}function Xx(e,t,n={}){return{compact:z(e,{method:`sessions.compact`,requiredScope:`operator.admin`}),abort:z(e,{method:t&&!n.sessionAbortable?`chat.abort`:`sessions.abort`,requiredScope:`operator.write`,sessionScope:!0,session:n.session}),rewind:z(e,{method:`sessions.rewind`,requiredScope:`operator.admin`}),fork:z(e,{method:`sessions.fork`,requiredScope:`operator.write`}),reset:z(e,{method:`sessions.reset`,requiredScope:`operator.admin`}),branchSwitch:z(e,{method:`sessions.branches.switch`,requiredScope:`operator.admin`})}}function Zx(){return(Zx=e((()=>{se()})))()}function Qx(e,t){return J(e,t),e.requestUpdate?.(),!1}function $x(e){if(!e.client?.recoveryScopeReady||!e.client.recoveryScope)return null;let t=e.settings?.gatewayUrl??``,n=e.sessionKey,r=_t(e,n),i=e.currentSessionId??void 0,a=!!e.selectedChatSessionIncognito,o=`${it(t,e.client.recoveryScope)}${JSON.stringify([n,r,i,a])}`,s=`${lt(t)}:${o}`,l=iS.get(e)??new Map;iS.set(e,l);let u=a?void 0:globalThis.sessionStorage;if(!a&&!u)throw Error(R(`chat.goals.recoveryUnavailable`));let d=l.get(s);if(!d){let e=u?.getItem(o);if(e){let t;try{t=JSON.parse(e)}catch{t=`invalid`}let a=c(t)&&`action`in t?Vi:$i;d=t===`expired`?{retired:`expired`,pending:!1}:c(t)&&Wc(a,t)&&t.sessionKey===n&&t.agentId===r&&t.sessionId===i?{params:t,pending:!1}:{retired:`invalid`,pending:!1},d.retired&&u?.setItem(o,JSON.stringify(d.retired)),l.set(s,d)}}return d&&!d.pending&&d.params&&Oe(d.params.issuedAtMs)&&(d.params=void 0,d.retired=`expired`,u?.setItem(o,JSON.stringify(`expired`))),{sessionKey:n,agentId:r,sessionId:i,signature:s,storageKey:o,storage:u,operations:l,operation:d}}function eS(e){try{let t=$x(e)?.operation;return t?{pending:t.pending,retired:t.retired,onCheck:()=>rS(e,void 0,t)}:void 0}catch{return}}async function tS(e,t,n){return t.objective.trim()?t.sessionId&&t.sessionId!==e.currentSessionId?Qx(e,R(`chat.goals.sessionChanged`)):t.action===`edit`?nS(e,{action:`edit`,goalId:t.goalId,objective:t.objective}):e.chatMessage===t.objective&&!!await e.handleSendChat(void 0,{intent:{kind:`session-goal-start`,version:1,issuedAtMs:Date.now()}},n):!1}async function nS(e,t){return rS(e,t)}async function rS(e,t,n){let r=e.client;if(!r||!e.connected||!r.recoveryScopeReady)return Qx(e,R(`chat.goals.offline`));if(!r.recoveryScope)return Qx(e,R(`chat.goals.recoveryUnavailable`));let i;try{i=$x(e)}catch(t){return Qx(e,`${R(`chat.goals.recoveryUnavailable`)} ${P(t)}`)}if(!i)return!1;let{sessionKey:a,agentId:o,sessionId:s,signature:l,storageKey:u,storage:d,operations:f}=i,m=ae(e,a).agentId,{operation:h}=i;if(n&&h!==n)return!1;let g=e.connectionEpoch,_=r.recoveryScope,v=()=>e.client===r&&e.connected&&e.connectionEpoch===g&&r.recoveryScope===_&&(e.currentSessionId??void 0)===s&&V(e,a,o);if(h?.pending)return Qx(e,R(`chat.goals.actionPending`));if(h?.retired){if(t)return!1;let n=e.sessions,i=n.captureConnectionScope(),c=Ft(e,a);if(!i||!c.agentId)return!1;let p=()=>v()&&e.sessions===n&&n.isConnectionScopeCurrent(i)&&$x(e)?.operation===h,m=JSON.stringify(h.retired),g;h.pending=!0,e.requestUpdate?.();try{let t=await n.reconcileMutation(o);if(!p())return!1;g=n.observeRow({key:c.sessionKey,agentId:c.agentId},()=>{},{onInvalidate:()=>{}});let i=g.captureReconcile(),h=await n.describe({key:a,...o?{agentId:o}:{}},{client:r,refresh:!0,timeoutMs:aS});if(!p())return!1;let _=h.session;if(!_||!F(_.key,c.sessionKey)||s&&_.sessionId!==s)return!1;let v=i(_);return!p()||v.status!==`current`||!v.row||s&&v.row.sessionId!==s?!1:t.status===`refreshed`?d&&d.getItem(u)!==m?!1:(d?.removeItem(u),f.delete(l),J(e,null),!0):(t.status===`failed`&&J(e,t.error),!1)}catch(t){return v()&&J(e,P(t)),!1}finally{g?.dispose(),h.pending=!1,e.requestUpdate?.()}}if(h&&t){let n=h.params;if(!n||n.goalId!==t.goalId||(`action`in n?n.action:`clear`)!==t.action||t.action===`edit`&&(!(`objective`in n)||n.objective!==t.objective))return Qx(e,R(`chat.goals.outcomeUnknown`))}if(!h){if(!t)return!1;if(!s||oy(e))return Qx(e,R(`chat.thread.loading`));let n={sessionKey:a,...o?{agentId:o}:{},sessionId:s,goalId:t.goalId,operationId:p(),issuedAtMs:Date.now()};h={params:t.action===`clear`?n:t.action===`edit`?{...n,action:`edit`,objective:t.objective}:{...n,action:t.action},pending:!1};let r=t.action===`clear`?$i:Vi;if(!Wc(r,h.params))return Qx(e,R(`chat.goals.invalidRequest`));try{d?.setItem(u,JSON.stringify(h.params))}catch(t){return Qx(e,`${R(`chat.goals.recoveryUnavailable`)} ${P(t)}`)}f.set(l,h)}let y=h.params;if(!y)return!1;let b=e=>{let t=JSON.parse(d?.getItem(u)??`null`);c(t)&&t.operationId===y.operationId&&(e?d?.setItem(u,JSON.stringify(e)):d?.removeItem(u))};h.pending=!0,J(e,null),e.requestUpdate?.();try{let t=await r.request(`action`in y?`sessions.goal.update`:`sessions.goal.clear`,y,{timeoutMs:aS});f.delete(l);try{b()}catch{}if(v()){if(t.replayed)return Mx(e,{sessionKey:a,agentId:o}).catch(t=>{v()&&(J(e,P(t)),e.requestUpdate?.())}),!0;let n=e.sessionsResult?.sessions.find(e=>F(e.key,a)&&e.sessionId===s&&(e.agentId===void 0||e.agentId===m));n?.goal?.id===y.goalId&&(!t.goal||t.goal.updatedAt>=n.goal.updatedAt)&&(m&&s&&e.sessions.patchRowLocal(n.key,{goal:t.goal},{agentId:m,sessionId:s}),t.status===`started`&&t.runId&&Yp(e,t.runId,Date.now()))}return!0}catch(t){let n=t instanceof Yn&&c(t.details)?t.details:null,r=n?.reason,i=typeof r==`string`&&(n?.code===`GOAL_OPERATION_REJECTED`&&oS.has(r)||r.startsWith(`goal-`)&&oS.has(r.slice(5)));if(i){let e=r===`expired`||r===`goal-expired`?`expired`:void 0;e?(h.params=void 0,h.retired=e):f.delete(l);try{b(e)}catch{}}return v()&&J(e,i?P(t):`${R(`chat.goals.outcomeUnknown`)} ${P(t)}`),!1}finally{h.pending=!1,e.requestUpdate?.()}}var iS,aS,oS;function sS(){return(sS=e((()=>{Gc(),ca(),Br(),H(),$a(),Ee(),on(),I(),B(),o(),Y(),Wx(),Lp(),fo(),iS=new WeakMap,aS=3e4,oS=new Set([`expired`,`operation-conflict`,`session-rebound`,`goal-rebound`,`capacity`,`invalid`])})))()}function cS(e,t,n=()=>!0){return{slot:e,combo:t,available:n}}var lS;function uS(){return(uS=e((()=>{Pt(),lS={terminal:cS(`terminal`,gt.terminalPanel,e=>e.state?.terminalAvailable===!0),browser:cS(`browser`,gt.browserPanel,e=>e.state?.browserPanelAvailable===!0),workspace:cS(`workspace`,gt.workspaceFiles),companion:cS(`companion`,gt.sideChat),desktop:cS(`desktop`,gt.desktopPanel,e=>e.desktopAvailable===!0),discussion:cS(`discussion`,gt.discussionPanel,e=>e.discussion!=null&&e.discussionAvailable===!0),dashboard:cS(`dashboard`,gt.dashboardPanel,e=>e.dashboardAvailable()),detail:cS(`detail`,gt.reviewPanel),conversation:void 0,"link-reader":void 0,portal:void 0}})))()}function dS(e,t){return e?W`<a
        class="rail-header__action"
        href=${e}
        target="_blank"
        rel="noopener"
        aria-label=${t}
        title=${t}
        >${U.externalLink}</a
      >`:void 0}function fS(e){let t=e?.state,n=e&&{...e,dashboardAvailable:()=>e.dashboard!==G},r=(e,r,i,a,o)=>({slot:e,label:R(`chat.sidePanel.${r}`),icon:i,available:!!(n&&(e===`portal`?t&&ua({hello:t.hello,client:t.client,phase:t.connected?`connected`:`stopped`},`portal.list`,`operator.write`):lS[e]?.available(n))),content:a,loading:tu(r===`conversation`||r===`companion`?`chat`:r===`portal`?`browser`:r===`dashboard`?`board`:r,R(r===`desktop`?`desktop.connecting`:`common.loading`)),empty:{description:R(`chat.sidePanel.${r}Empty`)},headerAction:o,shortcut:lS[e]?.combo}),i=t?.terminalAvailable?W`<openclaw-terminal-panel
        embedded
        .tabsInHeader=${e?.terminalTabsInHeader??!1}
        .client=${t.connected?t.client:null}
        .available=${t.terminalAvailable}
        .agentId=${e?.agentId??null}
        .sessionKey=${t.sessionKey}
        .themeMode=${e?.themeMode??`dark`}
        .basePath=${t.basePath}
      ></openclaw-terminal-panel>`:null,a=t?.browserPanelAvailable?W`<openclaw-browser-panel
        embedded
        data-chat-autotype-exempt
        .client=${t.connected?t.client:null}
        .available=${t.browserPanelAvailable}
        .remoteAvailable=${Fr({phase:t.connected?`connected`:`offline`,hello:t.hello})}
        .presented=${e?.browserPresented??!1}
        .tabsInHeader=${e?.browserTabsInHeader??!1}
        .refreshOnPresentation=${e?.browserRefreshOnPresentation??!0}
        .sessionKey=${t.sessionKey}
        .preferredTab=${e?.preferredBrowserTab}
        .sessionTabs=${e?.sessionBrowserTabs??[]}
        .resourceBasePath=${t.resourceBasePath}
        .authToken=${yr(t)}
      ></openclaw-browser-panel>`:null,o=e?W`<openclaw-chat-session-rail
        embedded
        .presented=${e.companionPresented}
        .focusRequest=${e.companionFocusRequest}
        .sessionKey=${t?.sessionKey}
        .digest=${e.digest}
        .running=${!!e.activeRunId}
        .activeRunId=${e.activeRunId}
        .startedAt=${e.startedAt}
        .lastReadAt=${e.lastReadAt}
        .pullRequests=${e.pullRequests}
        .companion=${e.companion}
        .connected=${t?.connected===!0}
        .sendShortcut=${t?.settings.chatSendShortcut??`enter`}
        .onSubmit=${e.onCompanionSubmit}
        .onDraftChange=${e.onCompanionDraftChange}
        .onAttachmentsChange=${e.onCompanionAttachmentsChange}
        .uploadConfig=${t?.uploadConfig}
        .attachmentLimits=${Cu(t?.hello?.policy)}
        .onVisibilityChange=${e.onCompanionVisibilityChange}
      ></openclaw-chat-session-rail>`:null,s=t&&e?.desktopAvailable?W`<openclaw-desktop-panel
          embedded
          data-chat-autotype-exempt
          .client=${t.connected?t.client:null}
          .available=${e.desktopAvailable}
          .presented=${e?.desktopPresented??!1}
          .refreshOnPresentation=${e?.desktopRefreshOnPresentation??!0}
          .requestedSource=${e?.desktopSource??null}
          .sessionKey=${t.sessionKey}
          .onFocusTargetChange=${e?.onDesktopFocusTargetChange}
        ></openclaw-desktop-panel>`:null,c=e?.discussion?W`<openclaw-session-discussion
        .sessionKey=${e.discussion.sessionKey}
        .canOpen=${e.discussion.canOpen}
        .sourceGeneration=${e.discussionSourceGeneration}
        .loadInfo=${e.discussion.loadInfo}
        .openDiscussion=${e.discussion.openDiscussion}
        .onStateChange=${e.discussion.onStateChange}
      ></openclaw-session-discussion>`:null,l=t?W`<openclaw-portals-page
        embedded
        .presented=${e?.portalPresented??!1}
        .requestedPortalId=${t.sidebarLayout.columns.flatMap(e=>e.panels).find(e=>e.slot===`portal`)?.portalId??null}
        .requestedEnvironmentId=${t.sidebarLayout.columns.flatMap(e=>e.panels).find(e=>e.slot===`portal`)?.environmentId??null}
      ></openclaw-portals-page>`:null,u=t?Gu(t):null,d=t?.sidebarContent??(t?kd(t):null),f=t&&e&&u?W`<openclaw-chat-files-panel
          .tabsInHeader=${ot(t.sidebarLayout)?.slot!==`workspace`}
          .previews=${u.previews}
          .activeId=${u.activePreviewId}
          .browser=${e.workspace}
          .renderDetail=${e.renderDetail}
          .onSelect=${e=>Bu(t,e)}
          .onClose=${e=>ef(t,e)}
        ></openclaw-chat-files-panel>`:e?.workspace??null,p=new Map((e?.pluginPanels??[]).map(e=>[`plugin:${e.key}`,e]));for(let e of t?.sidebarLayout.columns??[])for(let{slot:t}of e.panels)t.startsWith(`plugin:`)&&!p.has(t)&&p.set(t,void 0);return[r(`conversation`,`conversation`,U.messageSquare,G),r(`detail`,`review`,U.diff,d?.kind===`loading`?tu(`review`,R(`common.loading`)):d?.kind===`unavailable`?W`<div class="callout danger review-unavailable" role="alert">
              <strong>${R(`chat.detailPanel.unavailable`)}</strong>
              <span>${d.message}</span>
            </div>`:d&&e?e.renderDetail(d):null),r(`terminal`,`terminal`,U.terminal,i),r(`browser`,`browser`,U.globe,a),{slot:`link-reader`,label:R(`linkReader.title`),icon:U.link,available:!!e?.linkReaders?.length,content:t?W`<openclaw-link-reader-panel
            embedded
            data-chat-autotype-exempt
            .client=${t.connected?t.client:null}
            .available=${t.connected}
            .readers=${e?.linkReaders??gi}
            .agentId=${e?.agentId??void 0}
            .sessionKey=${t.sessionKey}
            .presented=${e?.linkReaderPresented??!1}
            .tabsInHeader=${e?.linkReaderTabsInHeader??!0}
            .onClose=${e?.onCloseLinkReader}
          ></openclaw-link-reader-panel>`:null,loading:tu(`files`,R(`linkReader.loadingPreview`)),empty:{description:R(`linkReader.urlPlaceholder`)}},r(`portal`,`portal`,U.globe,l),r(`workspace`,`files`,U.fileText,f),r(`companion`,`companion`,U.messageSquarePlus,o,e?W`<openclaw-tooltip .content=${R(`chat.rail.clear`)}>
            <button
              class="rail-header__action chat-session-rail__clear"
              type="button"
              aria-label=${R(`chat.rail.clear`)}
              ?disabled=${!e.connected||e.companion.turns.some(e=>e.status===`pending`)}
              @click=${e.onClearCompanion}
            >
              ${U.trash}
            </button>
          </openclaw-tooltip>`:void 0),r(`desktop`,`desktop`,U.monitor,s,dS(e?.desktopFocusHref,R(`desktop.openWindow`))),r(`discussion`,`discussion`,U.messageSquare,c,dS(e?.discussionOpenUrl,R(`chat.sessionDiscussion.openExternal`))),r(`dashboard`,`dashboard`,U.layoutDashboard,e?.dashboard??null),...[...p].map(([n,r])=>({slot:n,label:r?.value.label??n.slice(7),icon:U.plug,available:r!==void 0,content:r?sn(`panels`,r.key,{sessionKey:t?.sessionKey??``,agentId:e?.agentId??void 0},G,e?.isPluginPanelPresented(n)):null,loading:tu(`files`,R(`common.loading`)),empty:{description:r?.value.label??R(`pluginTabs.unavailableSubtitle`)}}))]}function pS(e){return e.filter(e=>e.available).map(e=>e.slot)}function mS(e,t=`content`){let n={};for(let r of e){let e=r[t];e!=null&&(n[r.slot]=e)}return n}function hS(){return(hS=e((()=>{bi(),kr(),ii(),Ar(),mi(),ql(),H(),Lc(),fa(),Qt(),uS(),Kf(),Ju(),Sd(),Lh(),hs()})))()}function gS(e,t){let n=SS[e];if(!n)return;let[r,i]=n;if(customElements.get(r)){CS.delete(e);return}let a=CS.get(e)??{listeners:new Set};return CS.set(e,a),a.error===void 0?(a.listeners.add(t),a.pending||=qr(r,i).catch(e=>{a.error=si({error:e,stale:sr(e),onRetry:()=>void ur()})}).finally(()=>{delete a.pending,a.listeners.forEach(e=>e()),a.listeners.clear()}),null):a.error}function _S(e){let{layout:t,state:n}=e;return{activatePanel:r=>{let i=t.columns[0]?.panels.find(e=>e.id===r)?.slot;i===`dashboard`&&!Je(t,`dashboard`)?e.openPanelSlot(i):n.updateSidebarLayout(ph(t,r)),n.updateSidebarActivePanel(r)},togglePanelExpanded:e=>{n.updateSidebarLayout(sg(t,e),{dashboardPresentation:`personal`}),n.updateSidebarActivePanel(e)},closeSlot:t=>{if(t===`conversation`){e.setPanelOpen(!1);return}t===`discussion`&&e.forgetDiscussionUrl(),e.closePanelSlot(t)},openSlot:e.openPanelSlot,reorderPanel:(e,r,i)=>n.updateSidebarLayout(og(t,e,r,i)),resizePanel:e.resizePanel,setOpen:e.setPanelOpen}}function vS(e){let t=`chat-panel-${encodeURIComponent(e.presentationId)}`,n=e.panelDefinitions??fS(),r=e.layout.open===!0,i=e.layout.columns.length>0?gS(`region`,e.requestUpdate):void 0,a=null;for(let t of e.layout.columns[0]?.panels??[]){let r=gS(t.slot,e.requestUpdate);r!==void 0&&(a??={...e.panelTemplates},a[t.slot]=r??n.find(e=>e.slot===t.slot)?.loading)}let o=e.availableWidth>0?e.availableWidth:1/0,s=e.narrow||o<680,c=ot(e.layout),l=!c||c.slot===`conversation`,u=e.layout.columns[0],d=e.layout.columns[0]?.activePanelId,f=e.layout.columns[0]?.panels.find(e=>e.id===d)?.slot,p=n.find(e=>e.slot===f)?.loading;return W`<div
    class="sidebar-region ${s?`sidebar-region--narrow`:``} ${e.layout.expanded?`sidebar-region--expanded`:``} ${e.layout.expanded&&e.layout.expandedSide?`sidebar-region--expanded-side`:``} sidebar-region--${ce(e.layout)} ${r?`sidebar-region--open`:``}"
    style=${Ci({"--side-panel-width":`${u?.width??480}px`,"--side-panel-height":`${u?.height??360}px`})}
  >
    <div class="sidebar-region__header">${e.header??G}</div>
    ${i===void 0?W`<openclaw-chat-sidebar-region
            .panelIdPrefix=${t}
            .conversationTab=${e.conversationTab}
            .layout=${e.layout}
            .fetchFavicon=${e.fetchFavicon}
            .panelDefinitions=${n}
            .panelTemplates=${a??e.panelTemplates}
            .panelActions=${e.panelActions}
            .availableSlots=${e.availableSlots}
            .callbacks=${e.callbacks}
            .narrow=${e.narrow}
            .availableWidth=${e.availableWidth}
          ></openclaw-chat-sidebar-region>`:i===null?p??null:null}
    <div
      id=${`${t}-conversation`}
      class="sidebar-region__primary"
      role="region"
      aria-label=${R(`chat.sidePanel.conversation`)}
      data-region=${l?`main`:`side`}
      ?hidden=${!Je(e.layout,`conversation`)}
    >
      ${e.primary}
    </div>
    <div class="sidebar-region__right-runtime">${i??null}</div>
  </div>`}function yS(e){let t=e.layout;return e.board.available?e.board.face===`dashboard`&&t.columns.length===0&&(t=Ch(t,`dashboard`)):t=bh(t,`dashboard`),Se(t,e.paneWidth)??t}function bS(e,t){return t||!e.client||!e.connected?null:async t=>{if(!e.client||!e.connected)return null;let n=e.client,r=await n.request(`chat.message.get`,{sessionKey:t.sessionKey,...t.agentId?{agentId:t.agentId}:{},messageId:t.messageId,maxChars:t.maxChars??xS});return e.connected&&e.client===n?r:null}}var xS,SS,CS;function wS(){return(wS=e((()=>{bi(),wi(),Qn(),hr(),zr(),H(),hS(),Lh(),n(),xS=5e5,SS={region:[`openclaw-chat-sidebar-region`,()=>M(()=>import(`./chat-sidebar-region.runtime-BeUv-jNa.js`),__vite__mapDeps([15,1,2,3,4,5,6,7,8,16,17,9,12,10,11,13,18]),import.meta.url)],terminal:[`openclaw-terminal-panel`,()=>M(()=>import(`./terminal-panel-registration-D5VvSsFk.js`),__vite__mapDeps([19,20,1,2,3,4,5,6,7,8,21,22,16,23,17,24,25,9,12,10,11,13]),import.meta.url)],"link-reader":[`openclaw-link-reader-panel`,()=>M(()=>import(`./link-reader-panel-DdSQDdBY.js`),__vite__mapDeps([26,1,2,3,4,5,6,7,8,22,16,27,9,12,10,11,13]),import.meta.url)],browser:[`openclaw-browser-panel`,()=>M(()=>import(`./browser-panel-BZcARBB-.js`),__vite__mapDeps([28,29,1,2,3,4,5,6,7,8,21,22,16,30,23,17,9,10,11,12,13]),import.meta.url)],desktop:[`openclaw-desktop-panel`,()=>M(()=>import(`./desktop-panel-YZcYHBlM.js`),__vite__mapDeps([31,32,1,2,3,4,5,6,7,8,21,22,30,33,9,10,11,12,13]),import.meta.url)],portal:[`openclaw-portals-page`,()=>M(()=>import(`./portals-page-BjP25pFE.js`),__vite__mapDeps([34,1,2,3,4,5,6,7,8,9,10,11,12,13,35]),import.meta.url)],companion:[`openclaw-chat-session-rail`,()=>M(()=>import(`./chat-session-rail-RNyFzpdR.js`),__vite__mapDeps([36,1,2,3,4,5,6,7,8,17,9,10,11,12,13,37]),import.meta.url)],discussion:[`openclaw-session-discussion`,()=>M(()=>import(`./session-discussion-panel-CrbgRdV1.js`),__vite__mapDeps([38,1,2,3,4,5,6,7,8,17,9,10,11,12,13]),import.meta.url)]},CS=new Map})))()}function TS(e){let t=Wt(e.sessionKey),n=bS(e,!!t);return{catalogKey:t,chatProps:{fullMessageAgentId:L(e,e.sessionKey).agentId,loadFullAssistantMessage:n}}}function ES(){return(ES=e((()=>{me(),I(),wS()})))()}function DS(e){let t=e.modelSelectionPolicy,n=t?.restricted?So(e)||t.defaultModel:e.catalogInitialized===!1?void 0:e.activeSession?.model??e.agentModel,r=OS(e),i=AS(n,t?.restricted?void 0:e.activeSession?.modelProvider,e.chatModelCatalog,e.onSetup,{retired:e.catalogRetired===!0,error:e.catalogError,modelSelectionPolicy:t});return{modelSetupRequired:r,modelUnavailableBanner:i,requiredReason:r?R(`modelSetup.required.body`):i?.text}}function OS(e){return e.catalog||e.catalogRetired||e.catalogInitialized===!1||e.modelSelectionPolicy?.restricted||!e.connected||!e.agentsLoaded||!e.selectedAgentFound?!1:!e.agentModel?.trim()}function kS(e,t=R(`modelSetup.required.body`)){return{kind:`above-composer`,text:`${t} ${R(`modelSetup.commandHint`)}`,actionLabel:R(`modelSetup.required.action`),onAction:e}}function AS(e,t,n,r,i){if(i?.retired)return{kind:`above-composer`,text:R(i.error?`chat.modelControls.modelsUnavailable`:`chat.modelControls.loadingModels`)};if(i?.modelSelectionPolicy?.restricted&&i.modelSelectionPolicy.defaultModel===null&&!Lo(e,t,n))return{kind:`above-composer`,text:R(n.some(e=>e.manualSelectionAllowed!==!1)?`chat.modelControls.selectionRequired`:`chat.modelControls.noPermittedModels`)};let a=Fc(va(e,t,n));return a?kS(r,a):void 0}function jS(){return(jS=e((()=>{H(),Oa()})))()}var MS,NS;function PS(){return(PS=e((()=>{bi(),su(),H(),Cc(),Cs(),B(),n(),MS=M(()=>import(`./composer-draft-store.runtime-v4vUYxIm.js`),__vite__mapDeps([39,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url),NS=class extends u{constructor(...e){super(...e),this.identity=``,this.entries=[],this.drafts=[],this.error=``,this.busy=!1,this.generation=0}static{this.properties={host:{attribute:!1},identity:{type:String}}}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),this.unsubscribe=ss(()=>void this.refresh())}disconnectedCallback(){this.generation++,this.unsubscribe?.(),super.disconnectedCallback()}updated(e){(e.has(`identity`)||e.has(`host`))&&this.refresh()}owner(){let e=this.host;return!e?.connected||e.selectedChatSessionIncognito||!e.client?.recoveryScopeReady||!e.client.recoveryScope?null:{gatewayOwner:Ms(e.settings.gatewayUrl).gatewayOwner,recoveryScope:e.client.recoveryScope}}async refresh(){let e=++this.generation,t=this.host,n=this.owner();this.drafts=[];try{let r=t?bs(t):null;if(this.entries=r?.entries??[],this.error=r?.blocked?R(`chat.outboxRecoveryFull`):``,n){let t=await(await MS).prepareDurableComposerRecovery(n);if(e!==this.generation||!this.isConnected)return;if(t.status===`storage-failed`)throw Error(`storage-failed`);this.drafts=t.entries}}catch{if(e!==this.generation||!this.isConnected)return;this.error=R(`chat.outboxRecoveryStorageFailed`)}this.requestUpdate()}async recover(e){let t=this.host,n=this.owner();if(!t||!n||this.busy)return;let r=this.identity,i=t.client,a=t.currentSessionId,o=t.connectionEpoch,s=()=>this.isConnected&&this.host===t&&this.identity===r&&t.client===i&&t.currentSessionId===a&&t.connectionEpoch===o&&JSON.stringify(this.owner())===JSON.stringify(n)&&!t.chatMessage&&!t.chatGoalDraftMode&&!t.chatReplyTarget&&!t.chatAttachments.length&&!t.chatQueue.length;this.busy=!0,this.error=``,this.requestUpdate();try{if(!s()){this.error=R(`chat.outboxRecoveryConflict`);return}let i=Ft(t,t.sessionKey),a=sc(t,i),o={...n,scopeKey:`chat:v3:${N(i)}`},c=await MS,l=await c.readDurableComposerDraft(o);if(l.status===`storage-failed`){this.error=R(`chat.outboxRecoveryStorageFailed`);return}if(!a||l.status===`found`||!s()){this.error=R(`chat.outboxRecoveryConflict`);return}if(!await hl({title:R(`chat.outboxRecoveryTitle`),message:R(`chat.outboxRecoveryConfirm`),details:`${i.sessionKey}${i.agentId?` (${i.agentId})`:``}`,confirmLabel:R(`chat.outboxRecoveryRestore`)})||!s())return;let u=await c.readDurableComposerDraft(o);if(!s()||JSON.stringify(u)!==JSON.stringify(l)){this.error=R(`chat.outboxRecoveryConflict`);return}let d=`id`in e?Ys(t,e,a,l.revision??0):(await c.restoreDurableComposerRecovery(o,e,l.revision??0,l.writeId,()=>s()&&JSON.stringify(sc(t,i))===JSON.stringify(a),a.revision)).status;d===`restored`||d===`persisted`?(this.host===t&&this.identity===r&&this.dispatchEvent(new CustomEvent(`outbox-restored`,{bubbles:!0})),await this.refresh()):this.error=R(d===`conflict`?`chat.outboxRecoveryConflict`:`chat.outboxRecoveryStorageFailed`)}catch{this.error=R(`chat.outboxRecoveryStorageFailed`)}finally{this.busy=!1,this.requestUpdate()}}render(){if(!this.entries.length&&!this.drafts.length&&!this.error)return G;let e=[...this.entries,...this.drafts];return W`<details class="chat-outbox-recovery">
      <summary>
        ${e.length?R(`chat.outboxRecoveryTitle`):R(`chat.outboxRecoveryFailedTitle`)}${e.length?W` <span class="chat-outbox-recovery__count">${e.length}</span>`:G}
      </summary>
      <div class="chat-outbox-recovery__content">
        ${e.length?W`<p>${R(`chat.outboxRecoveryDescription`)}</p>`:G}
        ${this.error?W`<p class="chat-outbox-recovery__error" role="alert">${this.error}</p>`:G}
        ${e.map(e=>W`<div class="chat-outbox-recovery-row">
            <p>
              ${`id`in e?[e.session.draft,...(e.session.queue??[]).map(e=>e.text)].filter(Boolean).join(` · `).slice(0,240):e.text.slice(0,240)}
            </p>
            <p>
              ${`id`in e?R(`chat.outboxRecoveryMessages`,{count:String(e.session.queue?.length??0)}):e.attachmentNames.join(`, `).slice(0,240)}
            </p>
            <button
              class="btn"
              ?disabled=${this.busy||!this.owner()}
              @click=${()=>void this.recover(e)}
            >
              ${R(`chat.outboxRecoveryRestore`)}
            </button>
          </div>`)}
      </div>
    </details>`}},customElements.define(`openclaw-chat-outbox-recovery`,NS)})))()}function FS(e,t){let n=1,r=t.length;if(r>LS)return!1;for(let t of e){let e=t.browserAnnotation;if(e&&(n+=1,r+=e.modelContext.length,n>IS||r>LS))return!1}return!0}var IS,LS;function RS(){return(RS=e((()=>{IS=4,LS=8e3})))()}function zS(e,t,n,r={}){if(!t.browserAnnotation)return!1;let i=t.browserAnnotation.modelContext,a=e.getOwner(),o=e.getSessionKey(),s=e.getAttachments(),c=s.findIndex(e=>e.id===t.id);if(c<0)return!1;e.setAttachments(s.filter(e=>e.id!==t.id)),e.requestUpdate(),e.focusComposer();let l=r.releasePayload??_n,u=!1,d=()=>{u||(u=!0,l(t.id))},f=r.presentToast??ct;return f({message:n.removed,actionLabel:n.undo,onAction:()=>{if(u)return;if(e.getOwner()!==a||e.getSessionKey()!==o){d();return}let r=e.getAttachments();if(r.some(e=>e.id===t.id)){u=!0;return}if(!FS(r,i)){d(),f({message:n.undoUnavailable});return}u=!0;let s=Math.min(c,r.length);e.setAttachments([...r.slice(0,s),t,...r.slice(s)]),e.requestUpdate(),e.focusRestoredAnnotation(t.id)},onDismiss:e=>{e!==`action`&&d()}})||d(),!0}function BS(){return(BS=e((()=>{tt(),Ig(),RS()})))()}function VS(e){Zv(e).branchVersion+=1}function HS(e){VS(e),e.chatBranchesConnectionEpoch=null}function US(e){return F(e.chatBranchesSessionKey,e.sessionKey)?e.chatBranches??[]:[]}async function WS(e){let t=e.sessions,n=e.client,r=e.sessionKey;if(!t?.listBranches||!n||!e.connected)return;let i=Zv(e),a=++i.branchVersion,o=e.connectionEpoch,s=L(e,r);try{let c=await t.listBranches(r,s);if(i.branchVersion!==a||e.client!==n||!e.connected||e.connectionEpoch!==o||!V(e,r,s.agentId))return;e.chatBranches=c,e.chatBranchesSessionKey=r,e.chatBranchesConnectionEpoch=o}catch{}finally{i.branchVersion===a&&e.requestUpdate?.()}}function GS(){return(GS=e((()=>{I(),B(),Y()})))()}function KS(e,t){return mn(t)?Tt(e):Sn(e,t)}function qS(e,t){return Zv(e).subscriptionGeneration===t.generation&&e.client===t.client&&e.connectionEpoch===t.connectionEpoch&&e.connected&&e.sessionKey.trim()===t.requestedKey&&KS(e,t.requestedKey)===(t.requestedAgentId??null)}async function JS(e){let t=Zv(e).pendingSubscriptionReleases;t.size!==0&&await Promise.all([...t].map(async n=>{try{await e.sessions.unsubscribeMessages(n),t.delete(n)}catch{}}))}async function YS(e,t,n){let r=$S;for(let i=0;i<eC;i+=1)try{await e(t);return}catch(e){if(n?.()||i+1===eC)throw e;await new Promise(e=>{globalThis.setTimeout(e,r)}),r=Math.min(r*2,3e4)}}function XS(e){let t=Zv(e);t.subscriptionGeneration+=1,t.subscriptionReady=Promise.resolve(!1);let n=new Set(t.pendingSubscriptionReleases);t.pendingSubscriptionReleases.clear(),e.chatSessionMessageSubscription&&n.add(e.chatSessionMessageSubscription),e.chatSessionMessageSubscriptionRequestedKey=null,e.chatSessionMessageSubscription=null,e.chatSessionApprovalQueue=[];let r=e.sessions;if(!r?.unsubscribeMessages)return;let i=r.unsubscribeMessages.bind(r);for(let e of n)YS(i,e).catch(()=>void 0)}function ZS(e,t){let n=Zv(e),r=e.client,i=e.connectionEpoch,a=e.sessionKey.trim(),o=KS(e,a),s=QS(e,t),c=n.subscriptionGeneration,l=s.then(t=>t&&r!==null&&qS(e,{generation:c,client:r,connectionEpoch:i,requestedKey:a,requestedAgentId:o})&&e.chatSessionMessageSubscriptionRequestedKey===a&&e.chatSessionMessageSubscription!=null);return n.subscriptionReady=l,l}async function QS(e,t){if(!e.client||!e.connected)return!1;let n=e.client,r=e.connectionEpoch,i=e.sessionKey.trim();if(!i)return!1;let a=ee(e.chatSessionMessageSubscriptionRequestedKey),o=e.chatSessionMessageSubscription??null,s=ee(o?.key),c=a??s,l=KS(e,i),u=l!==null&&c===i&&(o?.agentId??null)!==l;u&&(e.chatSessionApprovalQueue=[],e.requestUpdate?.());let d=Zv(e),f=++d.subscriptionGeneration;await JS(e);let p=c!==null&&c!==i,m=o!==null&&(t?.force===!0||p||u),h=t?.force===!0||p||u||s===null||a===null,g=()=>qS(e,{generation:f,client:n,connectionEpoch:r,requestedKey:i,requestedAgentId:l}),_=()=>{let t=d.subscriptionError;if(!(!t||d.pendingSubscriptionReleases.size>0)){d.subscriptionError=void 0;for(let n of[`sessionsError`,`lastError`,`chatError`])e[n]===t&&(e[n]=null);e.requestUpdate?.()}},v=t=>{let n=P(t);d.subscriptionError=n,e.sessionsError=n,J(e,n),e.requestUpdate?.()};if(!m&&!h)return g()&&o&&F(o.key,i)&&(o.agentId??null)===l&&_(),g()&&o!==null;try{let t=Promise.resolve();m&&o&&(t=e.sessions.unsubscribeMessages(o));let n=h&&g()?e.sessions.subscribeMessages(i,{agentId:l??void 0,...ni(e.hello?.auth??null)?{includeApprovals:!0}:{}}):Promise.resolve(null),[r,a]=await Promise.allSettled([t,n]);if(r.status===`rejected`){if(a.status===`fulfilled`&&a.value)try{await YS(e.sessions.unsubscribeMessages.bind(e.sessions),a.value,g)}catch(t){return g()?(o&&d.pendingSubscriptionReleases.add(o),e.chatSessionMessageSubscriptionRequestedKey=i,e.chatSessionMessageSubscription=a.value,v(`${P(r.reason)}; replacement release failed: ${P(t)}`),!0):(d.pendingSubscriptionReleases.add(a.value),!1)}return g()&&v(r.reason),!1}let s=a.status===`fulfilled`?a.value:null;if(!s){if(g()&&m&&(e.chatSessionMessageSubscriptionRequestedKey=null,e.chatSessionMessageSubscription=null),a.status===`rejected`)throw a.reason;return!1}if(!g()){try{await YS(e.sessions.unsubscribeMessages.bind(e.sessions),s)}catch{d.pendingSubscriptionReleases.add(s)}return!1}return e.chatSessionMessageSubscriptionRequestedKey=i,e.chatSessionMessageSubscription=s,e.chatSessionApprovalQueue=s.includeApprovals?$h(s.approvalReplay,s.key,s.agentId??void 0):[],_(),!0}catch(e){return g()&&v(e),!1}}var $S,eC;function tC(){return(tC=e((()=>{Pr(),on(),B(),Y(),Hh(),$S=250,eC=3})))()}function nC(e,t){if(!(e instanceof Yn)||e.gatewayCode!==`UNAVAILABLE`||!e.retryable)return!1;let n=e.details;if(!n||typeof n!=`object`)return!0;let r=n.method;return typeof r!=`string`||r===t}function rC(e){let t=typeof e.retryAfterMs==`number`?e.retryAfterMs:aC;return Math.min(Math.max(t,100),oC)}function iC(e){return new Promise(t=>{setTimeout(t,e)})}var aC,oC;function sC(){return(sC=e((()=>{Br(),aC=500,oC=5e3})))()}function cC(e){return`kind`in e}function lC(e){let t=e?.totalMessages,n=typeof t==`number`&&Number.isSafeInteger(t)&&t>=0?t:void 0,r=e?.nextOffset;return e?.hasMore===!0&&typeof r==`number`&&Number.isSafeInteger(r)&&r>0?{hasMore:!0,nextOffset:r,...n===void 0?{}:{totalMessages:n}}:{hasMore:!1,...n===void 0?{}:{totalMessages:n},...e?.completeSnapshot===!0?{completeSnapshot:!0}:{}}}function uC(e){return ee(e.sessionInfo?.sessionId)??ee(e.sessionId)}function dC(e){let t=e.totalMessages;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<0)return null;let n=t-(e.hasMore?e.nextOffset:t)+1;return Number.isSafeInteger(n)&&n>0?n:null}function fC(e){if(!e.previousSessionId||e.previousSessionId!==e.nextSessionId||e.previousMessages.length===0)return null;let t=e.previousPagination.totalMessages,n=e.nextPagination.totalMessages,r=dC(e.previousPagination),i=dC(e.nextPagination);if(typeof t!=`number`||typeof n!=`number`||r===null||i===null||n<t||i>t+1||i<=r)return null;let a=e.previousMessages.filter(e=>{let t=na(e);return t!==null&&t<i});if(a.length===0)return null;let o=n-r+1;return{messages:[...a,...e.nextMessages],pagination:r>1?{hasMore:!0,nextOffset:o,totalMessages:n}:{hasMore:!1,totalMessages:n}}}function pC(e,t){t!==void 0&&uh(e,t??void 0);let n=ah(e);if(!e.chatMessagesBySession)return;let r=e.sessionKey,i=kt(e,r)?Dn(e):void 0;gh(e.chatMessagesBySession,e,{sessionKey:r,agentId:i},{...n===void 0?{}:{deltaCursor:n},...e.chatDisplayedLeafEntryId===void 0?{}:{displayedLeafEntryId:e.chatDisplayedLeafEntryId},messages:e.chatMessages,pagination:e.chatHistoryPagination,sessionId:e.currentSessionId??null})}function mC(e,t,n){if(delete e.chatHistoryCursor,!e.chatMessagesBySession)return;let r=Qh(e.chatMessagesBySession,e,{sessionKey:t,agentId:n});if(r?.deltaCursor===void 0)return;let{deltaCursor:i,...a}=r;gh(e.chatMessagesBySession,e,{sessionKey:t,agentId:n},a)}function hC(){return(hC=e((()=>{ta(),B(),zh()})))()}function gC(e){if(cC(e)&&e.kind===`reset`||!e.activity||!e.messages)return e;let t=new Map(e.activity.map(e=>[e.messageId,e.items])),n=e=>{let n=s(e),r=n?.messageId??s(n?.__openclaw)?.id,i=typeof r==`string`?t.get(r):void 0;return n&&i?{...n,activity:i}:e};return{...e,messages:e.messages.map(t=>{if(!cC(e))return n(t);let r=s(t);return r?{...r,message:n(r.message)}:t})}}function _C(e,t,n,r){let i=e.ownerRequestCounts.get(t),a=(i?.get(n)??0)+r;if(a<=0){i?.delete(n),i?.size===0&&e.ownerRequestCounts.delete(t);return}i||(i=new Map,e.ownerRequestCounts.set(t,i)),i.set(n,a)}async function vC(e,t,n,r){for(;;)try{return await t()}catch(t){if(!n())throw t;if(r()&&nC(t,e)){if(await iC(rC(t)),!n())throw t;continue}throw t}}function yC(e,...[t,n,r,i,a,o,s,c,l=[],u={limit:80,maxBytes:TC}]){let d=kC.get(t);d||(d=new WeakMap,kC.set(t,d));let f=e??t,p=d.get(f);p||(p={ownerRequestCounts:new WeakMap,requests:new Map},d.set(f,p));let m=p.requests,h=m.get(n),g=(p.ownerRequestCounts.get(o)?.get(n)??0)>0,_={...s,retryDeadlineMs:Date.now()+OC};if(!h||g){let o={sessionKey:i,...a?{agentId:a}:{},...c===void 0?{}:{cursor:c},...u,...l.length?{inputRunIds:l}:{}},s=new AbortController,d=new Set([_]),f=vC(r,async()=>{let n=new Map([...d].map(e=>[e,e.captureRun?.()])),i=e?{owner:e,reconcile:e.captureReconcile()}:void 0;return{...gC(await t.request(r,o,{signal:s.signal})),observation:i,consumersAtIssue:n}},()=>[...d].some(e=>e.isCurrent()),()=>[...d].some(e=>e.isCurrent()&&Date.now()<e.retryDeadlineMs)).finally(()=>{m?.get(n)?.promise===f&&m.delete(n)});h={controller:s,consumers:d,promise:f},m.set(n,h)}else h.consumers.add(_);_C(p,o,n,1);let v=new AbortController,y=setTimeout(()=>{v.abort(Error(R(`chat.historyRequestTimedOut`)))},Math.max(0,_.retryDeadlineMs-Date.now())),b=h;return Ea({controller:b.controller,promise:b.promise,subscribers:b.consumers},_,v.signal,()=>{clearTimeout(y),_C(p,o,n,-1),b.consumers.size===0&&m.get(n)===b&&m.delete(n)}).then(({consumersAtIssue:e,observation:t,...n})=>t?{...n,observation:{...t,run:e.get(_)}}:n)}async function bC(e,t,n,r,i){let a=`chat.history`,o=await yC(null,e,`prefetch\u0000${a}\u0000${t}\u0000${i===void 0?`page`:`cursor:${i}`}`,a,t,void 0,n,{isCurrent:r},i,void 0,EC);if(cC(o))return o;let s=o.sessionInfo;return{kind:`snapshot`,snapshot:{...o.deltaCursor===void 0?{}:{deltaCursor:o.deltaCursor},...Object.hasOwn(s??{},`activeLeafEntryId`)?{displayedLeafEntryId:s?.activeLeafEntryId?.trim()||null}:{},messages:vs(o.messages),pagination:lC(o),sessionId:uC(o)}}}async function xC(e,t,n,r){let i=gC(await e.request(`chat.history`,{sessionKey:t,...n?{agentId:n}:{},limit:DC,offset:r}));return{...i,messages:vs(i.messages)}}async function SC(e,t){if(!e.client||!e.connected)return;let n=e.client,r=e.sessionKey,i=kt(e,r)?Dn(e):void 0,a=sy(e,n,e.connectionEpoch,r,i),o=await xC(n,r,i,t);if(ly(e,a))return o}async function CC(e,t){if(!e.client||!e.connected)return;let n=e.client,r=e.connectionEpoch,i=e.sessionKey,a=Zv(e).historyVersion,o=kt(e,i)?Dn(e):void 0,s=await xC(n,i,o,t);return{claim:{client:n,connectionEpoch:r,sessionKey:i,historyVersion:a,...o?{agentId:o}:{}},requestedOffset:t,result:s}}function wC(e,t){let n=t.claim,r=e.chatHistoryPagination;return e.client===n.client&&e.connected&&e.connectionEpoch===n.connectionEpoch&&Zv(e).historyVersion===n.historyVersion&&e.sessionKey===n.sessionKey&&(!kt(e,n.sessionKey)||Dn(e)===n.agentId)&&r.hasMore&&r.nextOffset===t.requestedOffset}var TC,EC,DC,OC,kC;function AC(){return(AC=e((()=>{H(),ec(),B(),sC(),hC(),Y(),TC=262144,EC={limit:20,maxBytes:65536},DC=1e3,OC=6e4,kC=new WeakMap})))()}function jC(e,t){if(e.chatRunId!==t.runId)return;let n=e.chatRunStartup;if(n?.runId===t.runId){if(t.state===`status`&&t.phase!==`retrying`&&n.state===`activity`||n.seq!==void 0&&(t.seq===void 0?t.state===`status`:t.seq<=n.seq))return;if(t.state===`activity`&&t.seq===void 0&&n.seq!==void 0){e.chatRunStartup={...t,seq:n.seq};return}}e.chatRunStartup=t}function MC(e,t){if(e)return e.phase===`retrying`?e.message:R(PC[e.phase]);switch(t?.phase){case`reconnecting`:return R(`connection.reconnecting`);case`pending`:case`requested`:case`provisioning`:return R(`chat.startupStatus.provisioningEnvironment`);case`syncing`:return R(`chat.startupStatus.preparingWorkspace`);case`starting`:return R(`newSession.starting`);case`active`:case`sending`:return R(`chat.composer.sendingMessage`);default:return}}function NC(e){return e?.state===`status`?e:null}var PC;function FC(){return(FC=e((()=>{H(),_a(),Hs(),PC={waiting_for_state:`chat.startupStatus.waitingForState`,preparing_workspace:`chat.startupStatus.preparingWorkspace`,naming_worktree:`chat.startupStatus.namingWorktree`,creating_worktree:`chat.startupStatus.creatingWorktree`,running_setup:`chat.startupStatus.runningSetup`,provisioning_environment:`chat.startupStatus.provisioningEnvironment`,preparing_context:`chat.startupStatus.preparingContext`,memory_flushing:`chat.startupStatus.memoryFlushing`,starting_model:`chat.startupStatus.startingModel`}})))()}function IC(e,t,n={}){return Bh(e,t,{...n,persistCommentary:n.persistCommentary??LC(t),isHiddenAssistantMessage:xc,isHiddenStreamText:gc})}function LC(e){return e.settings?.chatPersistCommentary!==!1}function RC(e,t){if(e.chatRunId===t.runId&&Array.isArray(t.events))for(let n of t.events)n&&n.runId===t.runId&&mg(e,n)}function zC(e){return typeof e==`string`&&e&&!gc(e)?e:null}function BC(e){let t=new Set;for(let n of e.events??[]){let r=n.data.itemId;n.runId===e.runId&&n.stream===`item`&&n.data.kind===`preamble`&&typeof r==`string`&&r.trim()&&t.add(r.trim())}return t}function VC(e,t,n){for(let[r,i]of Object.entries(e))if(r!==n&&t[r]!==i)return!1;for(let[r,i]of Object.entries(t))if(r!==n&&e[r]!==i)return!1;return!0}function HC(e,t){let n=Object.entries(e);return n.length===Object.keys(t).length&&n.every(([e,n])=>t[e]===n)}function UC(e,t){return e.chatMessages.some(e=>{let n=ea(e),r=m(m(e)?.__openclaw);return n?.role===`assistant`&&!n.isImported&&(n.id!==null||n.sequence!==null)&&n.runId===t&&r?.runTerminal===!0})}function WC(e,t,n){return Xf(e,np(e,{sessionKey:t,...n?{agentId:n}:{}})).runs}function GC(e,t){return!e||t?.startsWith(e)?t??e:!t||e.startsWith(t)?e:t}function KC(e){let{state:t,run:n,sessionInfo:r,historyRun:i,previousRunProjections:a,runProjectionsBeforeApply:o,currentRunProjections:c,resetStream:l,activeStreamBeforeReset:u}=e,d=n?.runId?.trim();if(!d||!n){if(!r)return;let e=t.chatRunId?.trim(),n=r.lastRunId??(e&&UC(t,e)?e:void 0),i=n?c[n]:void 0;if(n&&(r.status===`done`||r.status===`failed`||r.status===`killed`||r.status===`timeout`)&&r.hasActiveRun!==!0&&!S(r)&&(!t.chatRunId||t.chatRunId===n)&&!t.chatQueue.some(e=>e.sendState===`sending`&&e.sendRunId&&e.sendRunId!==n)&&(r.status!==`killed`&&!i||t.chatRunId===n||cp(t)===n)&&HC(a,o)){let e=Xf(t).entries.findLast(e=>e.identity?.runId===n&&!e.identity.isImported&&e.identity.role===`custom`&&s(e.message)?.customType===`run-failed-before-reply`),a=s(s(e?.message)?.details),o=a?.errorKind,c=o===`state_contention`?o:void 0,l=Ts(e?.message),u=c&&l&&typeof a?.diagnostic==`string`?`${l}\n\n${a.diagnostic}`:l,d=ap(t,{type:`runTerminal`,runId:n,...c?{errorKind:c}:{},status:r.status===`done`?`completed`:r.status===`timeout`?`timeout`:`error`,errorMessage:r.status===`failed`||r.status===`timeout`?u??r.lastRunError:r.lastRunError});tp(t,n);let f=d.runs[n];f?.errorMessage?(t.chatRunError?.runId!==n||!i?.errorMessage)&&Im(t,f.errorMessage,n,f.errorKind===`state_contention`?f.errorKind:void 0):f?.status===`completed`&&t.chatRunError?.runId&&t.chatRunError.runId!==n&&(t.chatRunError=null),Qp(t,r,{publishRunStatus:!1})}return}let f=c[d],p=t.chatRunId===d&&f?.status===`streaming`&&VC(a,c,d),m=p||t.chatRunId===d&&(u!==null||t.chatStreamSegments?.some(e=>!e.runId||e.runId===d)),h=r?.activeRunIds,g=S(r??{})&&(!Array.isArray(h)||h.includes(d))&&(!f||f.status===`streaming`),_=!!(t.chatRunId&&t.chatRunId!==d&&Array.isArray(h)&&!h.includes(t.chatRunId)&&i?.runId===t.chatRunId&&i.sessionId===r?.sessionId&&i.isCurrent()&&!t.chatQueue.some(e=>e.sendState===`sending`&&e.sendRunId&&e.sendRunId!==d));if(g&&(l&&(!t.chatRunId||_)&&HC(a,o)||p)){let e=t.chatRunId!==d;Yp(t,d,Date.now()),e&&r&&bp(t,d,r),t.chatRunSessionAbortable=n?.sessionAbortable===!0}if(!g||t.chatRunId!==d)return;let v=typeof n.startedAt==`number`&&Number.isFinite(n.startedAt)?n.startedAt:null,y=_?null:p?GC(zC(Ts(f?.message)),u):u;t.chatStream=GC(zC(n.text),y),t.chatStreamStartedAt=v??t.chatStreamStartedAt??Date.now();let b=m?null:xm(t.chatMessages,d),x=t.chatStream===null?null:cm(t.chatMessages,t.chatStream,d,b?.index,BC(n)),C=t.chatStream?.slice(0,t.chatStream.length-(x?.length??0))??``,w=Ba(t.chatStreamSegments??[]);(b||to(w,C)!==w)&&(t.chatStreamSegments=[...t.chatStreamSegments??[],{text:C,ts:t.chatStreamStartedAt,runId:d,...b?{boundaryRunId:b.runId}:{},...C?{persisted:!0}:{boundaryMarker:!0}}]);let T=n.events?.findLast(e=>e.runId===d&&e.stream===`run_status`),E=T?.data.phase,D=E===`waiting_for_state`||E===`preparing_workspace`||E===`naming_worktree`||E===`creating_worktree`||E===`running_setup`||E===`provisioning_environment`||E===`preparing_context`||E===`memory_flushing`||E===`starting_model`;n.text&&(t.chatRunStartup?.state!==`status`||t.chatRunStartup.phase!==`retrying`)?jC(t,{state:`activity`,runId:d}):T&&D&&jC(t,{state:`status`,runId:d,phase:E,seq:T.seq}),RC(t,n)}function qC(){return(qC=e((()=>{ta(),hc(),ec(),FC(),ip(),Lp(),jh(),ng(),Vp()})))()}function Z(e){return f(jt(e.sessionKey)?.agentId??L(e,e.sessionKey).agentId??Tt(e))}function JC(){return(JC=e((()=>{I(),B()})))()}async function YC(e,t,n,r,i,a,o,s,c,l){let u=sy(e,t,n,i,a),d=()=>e.sessions===r&&ly(e,u),f=()=>{let t=e.chatRunId,n=e.currentSessionId,r=e.chatRunLifecycleGeneration??0;return d()&&t&&n?{runId:t,sessionId:n,isCurrent:()=>d()&&e.chatRunId===t&&(e.chatRunLifecycleGeneration??0)===r&&e.currentSessionId===n}:void 0},p=Ep(),m=e.chatMessages,h=WC(e,i,a),g=e.chatHistoryPagination,_=e.currentSessionId??null,v=e.chatDisplayedLeafEntryId,y=e.chatRunId,b=(t,n={})=>gp(e,`control-ui.chat.history`,{phase:t,durationMs:wp(Ep()-p),sessionKey:e.sessionKey,activeRunId:e.chatRunId,requestSessionKey:i,requestAgentId:a,previousRunId:y,...n},{console:!1,maxBufferedEventsForType:30});b(`start`,{method:o}),e.resetChatInputHistoryNavigation?.(),e.chatLoading=!0;let x=n=>yC(r,t,`${l}${n===void 0?`page`:`cursor:${n}`}`,o,i,a,e,{isCurrent:d,captureRun:f},n,c);try{let n=Zv(e),r=n.subscriptionReady;for(;r;){let t=await r;if(!d())return;if(r===n.subscriptionReady){if(!t){n.subscriptionError&&(ny(e,{phase:`failed`,sessionKey:i,requestAgentId:a,startup:o===`chat.startup`,message:n.subscriptionError,retryable:!1}),e.requestUpdate?.());return}break}r=n.subscriptionReady}J(e,null);let l=await x(s);if(!d()){b(`stale`,{reason:`apply-version`});return}if(cC(l)&&l.kind===`reset`&&(mC(e,i,a),l=await x(),!d())){b(`stale`,{reason:`reset-fallback-version`});return}if(cC(l)&&l.kind===`delta`){let t=WC(e,i,a),n=e.chatRunId?e.chatStream:null,r=S(l.sessionInfo);for(let t of l.messages)vm(e,t,r,{kind:`history-delta`});let o=Xf(e);return Object.hasOwn(l.sessionInfo,`activeLeafEntryId`)&&(e.chatDisplayedLeafEntryId=l.sessionInfo.activeLeafEntryId?.trim()||null),e.currentSessionId=l.sessionInfo.sessionId?.trim()||_,qf(e,{...o,scope:{...o.scope,...np(e)}}),Fv(e,l.pendingInputs,{queriedRunIds:c,receipts:!_||_===e.currentSessionId?l.inputReceipts:void 0}),e.chatThinkingLevel=l.sessionInfo.thinkingLevel??null,e.chatQueueModeOverride=l.sessionInfo.queueMode,e.chatEffectiveQueueMode=l.sessionInfo.effectiveQueueMode,KC({state:e,run:l.inFlightRun,sessionInfo:l.sessionInfo,historyRun:l.observation.run,previousRunProjections:h,runProjectionsBeforeApply:t,currentRunProjections:o.runs,resetStream:!e.chatRunId||e.chatRunId===y,activeStreamBeforeReset:n}),pC(e,l.deltaCursor??null),b(`applied`,{messageCount:l.messages.length,visibleMessageCount:l.messages.length,resetStream:!1}),{messages:e.chatMessages,deltaCursor:l.deltaCursor,pendingInputs:l.pendingInputs,inputReceipts:l.inputReceipts,sessionInfo:l.sessionInfo,...l.inFlightRun?{inFlightRun:l.inFlightRun}:{},...l.metadata?{metadata:l.metadata}:{},observation:l.observation}}if(cC(l))throw Error(`chat history page request returned a cursor reset`);let u=l,f=WC(e,i,a),p=Array.isArray(u.messages)?u.messages:[],C=lC(u),w=uC(u),T=vs(p),E=Jp({host:e,previousMessages:m,sessionKey:i,visibleMessages:T}),D=Object.hasOwn(u.sessionInfo??{},`activeLeafEntryId`)?u.sessionInfo?.activeLeafEntryId?.trim()||null:v??null,O=fC({nextMessages:T,nextPagination:C,nextSessionId:w,previousMessages:u.windowReset!==!0&&(!_||!w||_===w)&&(v===void 0||v===D)?E:[],previousPagination:g,previousSessionId:_}),k=O?.messages??T,A=np(e,{sessionKey:i,agentId:a,sessionId:w,...Object.hasOwn(u.sessionInfo??{},`activeLeafEntryId`)?{activeLeafEntryId:D}:{}});e.chatSubmissions?.observeInitialSession(i,t,w);let j=ap(e,{type:`snapshotLoaded`,messages:k,options:{shouldIncludeMessage:ds}},{scope:A,runActive:u.sessionInfo&&(typeof u.sessionInfo.hasActiveRun==`boolean`||u.sessionInfo.status!==void 0)?S(u.sessionInfo):void 0});Object.hasOwn(u.sessionInfo??{},`activeLeafEntryId`)&&(e.chatDisplayedLeafEntryId=D),e.chatHistoryPagination=O?.pagination??C,e.currentSessionId=w,Fv(e,u.pendingInputs,{queriedRunIds:c,receipts:!_||_===w?u.inputReceipts:void 0}),pC(e,u.deltaCursor??null),e.reconnectResumeSessionId&&e.reconnectResumeSessionId!==e.currentSessionId&&(e.reconnectResumeSessionId=null),e.chatThinkingLevel=u.sessionInfo?.thinkingLevel??u.thinkingLevel??null,e.chatVerboseLevel=u.verboseLevel??null,e.chatQueueModeOverride=u.sessionInfo?.queueMode,e.chatEffectiveQueueMode=u.sessionInfo?.effectiveQueueMode;let ee=e.chatRunId?e.chatStream:null,te=!e.chatRunId||e.chatRunId===y;if(te){let t={persistCommentary:e.chatRunId?!0:LC(e),isHiddenAssistantMessage:xc,isHiddenStreamText:gc},n=Fp(e,t),r=_h(e.chatMessages,e,t);Yh(e.chatMessages,e,t);let i=Pm(e);e.chatRunId&&(n||i.length>0)&&(e.chatRunStartup?.state!==`status`||e.chatRunStartup.phase!==`retrying`)&&jC(e,{state:`activity`,runId:e.chatRunId});let a=ag(e.chatMessages,e),o=i.length>0&&i.every(e=>a.has(e)),s=a.size>0,c=i.length===0||o;!n||r?(e.chatRunId&&r&&_m(e,{runId:e.chatRunId,persisted:!0}),c?Xh(e,{preserveStreamSegments:e.chatRunId!==null}):fm(e,a),e.chatRunId||(e.chatStream=null,e.chatStreamStartedAt=null),b(`stream-reset`,{messageCount:p.length,visibleMessageCount:T.length})):e.chatRunId?s&&(yp(e,IC(e.chatMessages,e,{includeCurrent:!1,requirePersistedTool:!o,persistCommentary:!0})),oh(e,t.isHiddenStreamText)||(e.chatStreamStartedAt=null),Yh(e.chatMessages,e,t),o?Xh(e,{preserveStreamSegments:!0}):fm(e,a)):(yp(e,IC(e.chatMessages,e)),Xh(e),e.chatStream=null,e.chatStreamStartedAt=null)}return KC({state:e,run:u.inFlightRun,sessionInfo:u.sessionInfo,historyRun:u.observation.run,previousRunProjections:h,runProjectionsBeforeApply:f,currentRunProjections:j.runs,resetStream:te,activeStreamBeforeReset:ee}),b(`applied`,{messageCount:p.length,visibleMessageCount:T.length,resetStream:te}),u}catch(t){if(!d()){b(`stale`,{reason:`error-version`});return}b(`error`);let n=We(t);n&&(uy(e,a),e.chatThinkingLevel=null,e.chatVerboseLevel=null),ny(e,{phase:`failed`,sessionKey:i,requestAgentId:a,startup:o===`chat.startup`,message:n?pt(`existing chat history`):P(t),retryable:t instanceof Yn&&t.retryable}),e.requestUpdate?.()}finally{cy(e,u)&&(e.chatLoading=!1)}}function XC(){return(XC=e((()=>{Br(),ec(),on(),dt(),AC(),hC(),Y(),qC(),zv(),FC(),ip(),hp(),Lm(),jh(),ng(),mm(),ch(),nh()})))()}async function ZC(e,t={}){let n=e.sessionKey,r=kt(e,n)?Dn(e):void 0,i=t.startup===!0,a=e.chatSubmissions?.creation?.sessionKey===n||e.hasPendingInitialTurn?.(n),o=Zv(e);if(!e.client||!e.connected){ny(e,{phase:`pending-connection`,sessionKey:n,requestAgentId:r,startup:i}),e.chatLoading=!0,e.requestUpdate?.();return}let s=i?`chat.startup`:`chat.history`,c=e.client,l=e.sessions,u=e.connectionEpoch,d=i?ey(e):void 0;if(d){let i=o.historyVersion;if(e.chatLoading=!0,e.requestUpdate?.(),!await d||!e.connected||e.client!==c||e.sessions!==l||e.connectionEpoch!==u||!F(e.sessionKey,n)||kt(e,n)&&Dn(e)!==r)return;if(n=e.sessionKey,o.historyVersion!==i){let e=o.historyLoad;if(e.phase===`idle`)return;if(e.phase===`in-flight`&&t.supersedeInFlight!==!0&&e.startup&&e.client===c&&e.sessions===l&&e.connectionEpoch===u&&e.sessionKey===n&&e.requestAgentId===r)return e.promise}}let f=ah(e),p=f===void 0?`page`:`cursor:${f}`,m=jv(e),h=JSON.stringify([u,s,n,r??``,80,m]),g=`${h}${p}`,_=o.historyLoad;if(_.phase===`in-flight`&&_.sessionKey===n&&_.requestAgentId===r&&_.client===c&&_.sessions===l&&_.connectionEpoch===u){if(_.refresh)return _.refresh.startup||=i,_.refresh.deferBranches&&=t.deferBranches===!0,_.refresh.promise;if(t.supersedeInFlight!==!0&&_.key===g)return _.promise;let a=++o.historyVersion,s={startup:i||_.startup,deferBranches:t.deferBranches===!0,promise:Promise.resolve(void 0)};return s.promise=_.promise.then(()=>{if(!(o.historyVersion!==a||!e.connected||e.client!==c||e.sessions!==l||e.connectionEpoch!==u||e.sessionKey!==n||kt(e,n)&&Dn(e)!==r))return ZC(e,s)}),_.refresh=s,s.promise}let v=YC(e,c,u,l,n,r,s,f,m,h).then(s=>{let d=o.historyLoad;return d.phase===`in-flight`&&d.promise===v&&(s?(t.deferBranches!==!0&&(!F(e.chatBranchesSessionKey,n)||e.chatBranchesConnectionEpoch!==u)&&WS(e),ny(e,{phase:`committed`,sessions:l,client:c,connectionEpoch:u,sessionKey:n,requestAgentId:r,sessionInfo:s.sessionInfo,sessionId:uC(s)??(a?void 0:null)})):e.sessionKey===n&&(!kt(e,n)||Dn(e)===r)&&(!e.connected||d.client!==e.client||d.sessions!==e.sessions||d.connectionEpoch!==e.connectionEpoch)?(ny(e,{phase:`pending-connection`,sessionKey:n,requestAgentId:r,startup:i}),e.chatLoading=!0):(ny(e,{phase:`idle`}),e.chatLoading=!1),e.requestUpdate?.()),s});return ny(e,{phase:`in-flight`,sessions:l,client:c,connectionEpoch:u,key:g,promise:v,sessionKey:n,requestAgentId:r,startup:i}),v}function QC(e){let t=ry(e);if(t.phase===`pending-connection`||t.phase===`failed`&&t.retryable)return ZC(e,{startup:t.startup,deferBranches:!0})}function $C(e,t,n){if(!t||e.client!==n||!e.connected)return;e.agentsList=t,e.agentsError=null;let r=typeof e.agentsSelectedId==`string`&&e.agentsSelectedId.trim()?f(e.agentsSelectedId):void 0;r&&t.agents.some(e=>f(e.id)===r)||(e.agentsSelectedId=typeof t.defaultId==`string`&&t.defaultId.trim()?t.defaultId:t.agents[0]?.id??null)}function ew(){return(ew=e((()=>{B(),GS(),XC(),AC(),hC(),Y(),zv(),zh()})))()}function tw(e,t,n){return{owner:n,paneId:e,scopeKey:N(Ft(t,t.sessionKey))}}function nw(e,t,n,r){let i=e.chatAttachmentHandoff.consume(tw(t,n,r));if(!i)return;let a=i.draftRevision===void 0||i.draftRevision>=_d(n,n.sessionKey);a&&i.draftRevision!==void 0&&(n.chatMessage=i.message??``,n.chatMentions=i.mentions,n.chatGoalDraftMode=i.goalMode??null,n.chatReplyTarget=i.replyTarget??null);let o=new Set(n.chatAttachments.map(e=>e.id));n.chatAttachments=[...n.chatAttachments,...a?i.attachments.filter(e=>!o.has(e.id)):[]];let s=Object.entries(i.fallbacks).filter(([e])=>Object.hasOwn(n.chatComposerFallbackByScope,e)).flatMap(([,e])=>e.attachments);n.chatComposerFallbackByScope={...i.fallbacks,...n.chatComposerFallbackByScope};let c=n.chatComposerFallbackByScope[tw(t,n,r).scopeKey];a&&c?.storageFailed&&(n.lastError=Wu,n.chatError=Wu),Og([...s,...a?[]:i.attachments],[n.chatAttachments,...Object.values(n.chatComposerFallbackByScope).map(e=>e.attachments)])}function rw(e,t,n,r,i){let a=[...n.chatAttachments];e.chatAttachmentHandoff.prepare({reviewPrivateDraft:Kd,...tw(t,n,r),attachments:a,fallbacks:n.chatComposerFallbackByScope,message:n.chatMessage,mentions:n.chatMentions,goalMode:n.chatGoalDraftMode,replyTarget:n.chatReplyTarget,draftRevision:i,incognito:Df(n,Ft(n,n.sessionKey))})}function iw(e){if(e){en(e.chatAttachments);for(let t of Object.values(e.chatComposerFallbackByScope))en(t.attachments),t.attachments=[];e.chatAttachments=[]}}function aw(e,t,n,r,i){if(!i||r===i)return r;if(n){let e=e=>(en(e.filter(e=>e.browserAnnotation)),e.filter(e=>!e.browserAnnotation));n.chatAttachments=e(n.chatAttachments);for(let t of Object.values(n.chatComposerFallbackByScope))t.attachments=e(t.attachments);n.requestUpdate?.()}return e.chatAttachmentHandoff.clearPane(t),i}function ow(e,t,n){let r=new Set(lm(t,n).map(e=>e.id));for(let t of e.querySelectorAll(`openclaw-chat-pane`))r.has(t.paneId)&&t.resumeStagedAttachments?.()}function sw(e,t,n,r){let i=Nh(n).find(e=>e.id!==r),a=[...t.querySelectorAll(`openclaw-chat-pane`)].filter(e=>e.paneId===r);for(let e of a)e.discardStagedAttachments?.();return e.chatAttachmentHandoff.clearPane(r),i}var cw,lw;function uw(){return(uw=e((()=>{Cs(),B(),Ig(),df(),Ed(),zu(),qp(),cw=new WeakMap,lw=class{constructor(e,t){this.context=e,this.host=t,this.ownsComposer=!0,this.custody=Symbol(`chat-composer-custody`);let n=cw.get(e);n||(n=new Set,cw.set(e,n)),this.presentations=n,this.scope=this.currentScope(),n.add(this)}claim(){if(!this.host.presented())return;let e=this.currentScope();this.otherRegion(e).find(e=>e.ownsComposer)?.transferTo(this),this.ownsComposer||=(this.host.resume(!0),!0),this.scope=e,this.presentations.delete(this),this.presentations.add(this)}captureOwner(){let e=this.currentScope();if(!e)return;let t=this.custody;return{resolveOwner:()=>{let n=[this,...[...this.presentations].toReversed()];for(let r of n){if(!this.presentations.has(r)||!r.ownsComposer||r.custody!==t)continue;let n=r.currentScope();if(n&&(n.owner===e.owner||n.owner.recoveryScopeReady)&&r.matchesScope({...e,owner:n.owner}))return r.host.state()}},retainedAttachmentIds:e=>this.context.chatAttachmentHandoff.retainedAttachmentIds(e)}}dispose(){if(this.ownsComposer){let e=this.otherRegion(this.currentScope()),t=e.find(e=>e.host.presented())??e[0];t&&this.transferTo(t)}this.presentations.delete(this)}currentScope(){let e=this.host.state(),t=this.host.owner(),n=t?.recoveryScope;return e&&t&&e.client===t&&n?{owner:t,gatewayOwner:Ms(e.settings.gatewayUrl).gatewayOwner,recoveryScope:n,scopeKey:N(Ft(e,e.sessionKey))}:null}otherRegion(e){return[...this.presentations].toReversed().filter(t=>t.host.region()!==this.host.region()&&t.matchesScope(e))}matchesScope(e){let t=this.scope,n=this.currentScope();return!!(e&&t&&n&&n.owner===e.owner&&t.gatewayOwner===e.gatewayOwner&&t.recoveryScope===e.recoveryScope&&t.scopeKey===e.scopeKey&&(n.owner===t.owner||n.owner.recoveryScopeReady)&&n.gatewayOwner===t.gatewayOwner&&n.recoveryScope===t.recoveryScope&&n.scopeKey===t.scopeKey)}transferTo(e){let t=this.host.state(),n=e.host.state();if(!t||!n||!this.matchesScope(e.currentScope()))return;this.host.pause(),e.host.pause();let r=t.chatAttachments,i=t.chatComposerFallbackByScope;Og([n.chatAttachments,...Object.values(n.chatComposerFallbackByScope).map(e=>e.attachments)].flat(),[r,...Object.values(i).map(e=>e.attachments)]),n.chatMessage=t.chatMessage,n.chatMentions=t.chatMentions,n.chatGoalDraftMode=t.chatGoalDraftMode,n.chatReplyTarget=t.chatReplyTarget,n.chatQueuedEdit=t.chatQueuedEdit,n.chatAttachments=r,n.chatComposerFallbackByScope=i,t.chatMessage=``,t.chatMentions=[],t.chatGoalDraftMode=null,t.chatReplyTarget=null,t.chatQueuedEdit=null,t.chatAttachments=[],t.chatComposerFallbackByScope={},e.host.adoptAttachmentReads(this.host.takeAttachmentReads()),this.ownsComposer=!1,e.ownsComposer=!0,e.custody=this.custody,e.scope=e.currentScope(),e.host.resume(),t.requestUpdate?.(),n.requestUpdate?.()}}})))()}function dw(e,t,n){let r=et.get(e);!r&&n&&(r=new Map,et.set(e,r));let i=r?.get(t);if(!i&&n&&(i=[],r?.set(t,i)),i){let e=Date.now();be(i,t=>t.expiresAt<=e)}return i}function fw(e,t,n,r){let i=dw(e,t,!0);be(i,e=>F(e.sessionKey,n));let a=e.gateway.snapshot.client,o=Tr(e.gateway,{gatewayUrl:e.gateway.connection.gatewayUrl,recoveryScope:a?.recoveryScope||void 0}),s={sessionKey:n,value:{...r},isCurrent:()=>e.gateway.snapshot.client===a&&o(),expiresAt:Date.now()+fe};for(i.push(s),globalThis.setTimeout(()=>{dw(e,t,!1)},fe);i.length>Cw;)i.shift()}function pw(e,t,n){let r=dw(e,t,!1),i=r?.findIndex(e=>e.isCurrent()&&F(e.sessionKey,n));return!r||i===void 0||i<0?null:r.splice(i,1)[0].value}function mw(e,t,n){be(dw(e,t,!1),e=>F(e.sessionKey,n))}function hw(e,t){let n=et.get(e);n&&n.get(t)&&(n.delete(t),n.size===0&&et.delete(e))}function gw(e,t){let n=m(e);if(!n)return null;for(let e of t){let t=n[e];if(typeof t==`string`&&t.trim())return t.trim()}return null}function _w(e){let t=m(e)?.result;if(t===void 0)return null;try{return JSON.stringify(t)||null}catch{return null}}function vw(e,t){return/^[a-z0-9]$/iu.test(t)&&e.matches(`wa-dropdown, [data-chat-autotype-shortcuts][open]`)&&e.querySelector(`[data-shortcut="${t.toLowerCase()}"]:not([disabled])`)!==null}function yw(e){return e.composedPath().some(t=>t instanceof HTMLElement&&(t.matches(kw)||vw(t,e.key)||e.key===` `&&t.matches(Aw)))}function bw(e,t){return[...(e instanceof Element?e.closest(`openclaw-app`)??e:e).querySelectorAll(`wa-dropdown`)].some(e=>e.open===!0&&!e.closest(`[inert]`)&&(jw.has(t)||vw(e,t)))}function xw(e,t=[]){let n=!1;return e.querySelectorAll(Dw).forEach(e=>{t.includes(e)||(e.open=!1,n=!0)}),n}function Sw(e,t){if(t.defaultPrevented||t.isComposing||t.metaKey||t.ctrlKey||t.altKey||bw(e,t.key)||t.key.length!==1||yw(t)||document.openClawModalLayers?.size||document.querySelector(`dialog[open], [aria-modal='true']`))return;let n=e.querySelector(Ow);!n||n.disabled||n.readOnly||(n.focus({preventScroll:!0}),t.stopImmediatePropagation())}var Cw,ww,Tw,Ew,Dw,Ow,kw,Aw,jw,Mw,Nw;function Pw(){return(Pw=e((()=>{lr(),B(),Tn(),Cw=4,ww=1200,Tw=new Set([`ArrowUp`,`PageUp`,`Home`]),Ew=new WeakMap,Dw=`.chat-controls__inline-select[open], .context-usage details[open], .agent-chat__attach-menu[open], .chat-pr__checks[open]`,Ow=`.agent-chat__composer-combobox > textarea`,kw=`input, textarea, select, [contenteditable]:not([contenteditable='false']), [role='combobox'], [role='textbox'], [data-chat-autotype-exempt]`,Aw=`a[href], button, summary, [role='button'], [role='checkbox'], [role='link'], [role='listbox'], [role='menu'], [role='menuitem'], [role='menuitemcheckbox'], [role='menuitemradio'], [role='option'], [role='radio'], [role='switch'], [role='tab']`,jw=new Set([` `,`Enter`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`ArrowUp`,`Escape`]),Mw=`Start a new session after the active run or queued messages finish.`,Nw=`Session list is still refreshing. Try New Chat again in a moment.`})))()}function Fw(e){e.updateComplete.then(()=>{e.querySelector(Ow)?.focus({preventScroll:!0})})}function Iw(e,t,n,r){if(!e||!t||n.defaultPrevented||!(n instanceof CustomEvent))return!1;if(!yn(e.uploadConfig))return ct({message:qt()}),!1;let i=n.detail;if(!i||typeof i.modelContext!=`string`||typeof i.dataUrl!=`string`||!i.card)return!1;if(!FS(e.chatAttachments,i.modelContext))return n.rejection=`limit`,!1;let a=Cf(i.dataUrl,i.fileName||`annotation`,Cu(e.hello?.policy),id(e.chatAttachments)+r);return a?(n.preventDefault(),e.chatAttachments=[...e.chatAttachments,{...a,browserAnnotation:{modelContext:i.modelContext,title:i.card.title,displayUrl:i.card.displayUrl,markedRegionCount:i.card.markedRegionCount,inspectedElement:i.card.inspectedElement}}],e.requestUpdate?.(),!0):!1}function Lw(){return(Lw=e((()=>{tt(),Dt(),RS(),Pw(),Kf(),_f()})))()}function Rw(e,t,n){let r=jt(t)?.agentId??n?.trim();if(Wt(t)){r&&e.agentSelection.set(r,{background:!0});return}let i=ht(t,e.gateway.snapshot.hello),a=Xr();(a.sessionKey!==i||a.lastActiveSessionKey!==i)&&br({sessionKey:i,lastActiveSessionKey:i}),(e.gateway.snapshot.sessionKey!==i||r&&e.agentSelection.state.selectedId!==r)&&Wr({selection:e.agentSelection,gateway:e.gateway,sessionKey:i,agentId:r,background:!0})}function zw(e){return!e.chatLoading&&!e.chatSending&&!e.chatRunId&&e.chatStream===null&&(e.chatQueue.length===0||ay(e))}function Q(e){let t=(e.sessionsResult?.sessions??[]).find(t=>ge(e,t.key,e.sessionKey,t.agentId));if(!t||!mn(t.key))return t;let n=Z(e);if(!(e.sessionsResultAgentId&&f(e.sessionsResultAgentId)!==n))return t.observerDigest?.agentId&&f(t.observerDigest.agentId)!==n?{...t,observerDigest:void 0}:t}function Bw(e){let t=Z(e);if(e.chatAvatarUrl)return e.chatAvatarUrl;let n=Yl({agentId:t}).avatar;if(n)return n;let r=(e.chatAvatarStatus??e.assistantAvatarStatus)===`none`&&(e.chatAvatarReason??e.assistantAvatarReason)===`missing`,i=e.assistantAvatar;if(!r&&i&&Pe(i)&&e.assistantAgentId===t)return i;let a=e.agentsList?.agents?.find(e=>e.id===t)?.identity,o=a?.avatarUrl??a?.avatar;return typeof o==`string`&&Pe(o)?o:null}function Vw(){return(Vw=e((()=>{Yr(),au(),Vr(),ke(),me(),I(),B(),JC(),Y()})))()}function Hw(e,t,n){if(n!==`dashboard`)return Ch(t,n);let r=Xr().sidebarSessionLayouts?.[Mt(e,e.sessionKey)],i=r?r.dashboardPresentationOverride:null,a={...t,dashboardPresentationOverride:i};return r&&i===void 0?Ch(a,n):Th(a,i??Q(e)?.boardPresentation??`split`)}function Uw(e,t){t===`workspace`&&af(e)}function Ww(e){let{state:t,sidebarLayout:n}=e,r=e=>Je(n,e),i=r=>{e.updateSidebarLayout(Hw(t,n,r)),r===`companion`&&e.setObserverVisibility(!0)},a=r=>{r===`companion`&&e.setObserverVisibility(!1),Uw(t,r),e.updateSidebarLayout(bh(n,r))},o=e=>r(e)?a(e):i(e);return{closePanelSlot:a,openPanelSlot:i,sessionWorkspace:{...Hd(t,{draftScope:e.presentationId,draftContext:{sessionTitle:e.sessionTitle,paneLabel:e.paneLabel},expanded:Je(n,`workspace`),narrowLayout:!1,presented:e.presented}),collapsed:!r(`workspace`),narrowLayout:!1,onToggleCollapsed:()=>o(`workspace`),onToggleTerminal:t.terminalAvailable?()=>o(`terminal`):void 0,onToggleBrowser:t.browserPanelAvailable?()=>o(`browser`):void 0,onToggleDesktop:oi(e.gatewaySnapshot)?()=>o(`desktop`):void 0}}}function Gw(){return(Gw=e((()=>{ii(),Vr(),B(),Vw(),Ju(),Sd(),Lh()})))()}function Kw(e){if(e.restartingKey===e.row?.key)return{kind:`busy`,message:R(e.row?.repositoryWorkspaceId&&e.row.placement?.state!==`failed`?`sessionsView.dispatchingSession`:`sessionsView.restartingSession`)};if(e.reclaimingKey===e.row?.key)return{kind:`busy`,message:R(`sessionsView.stoppingSession`)};if(e.moving)return{kind:`busy`,message:R(`sessionsView.finishingSessionMove`)};if(e.workspaceResultReconciling)return{kind:`busy`,message:R(`sessionsView.syncingCloudFilesComposer`)};if(Jw(e.row))return{kind:`dispatch-required`};switch(e.row?.placement?.state){case`requested`:case`provisioning`:case`syncing`:case`starting`:return{kind:`setup`,startup:{sessionKey:e.row.key,phase:e.row.placement.state,startedAt:e.row.placement.createdAtMs}};case`draining`:case`reconciling`:return{kind:`busy`,message:R(`sessionsView.finishingSessionMove`)};case`failed`:return{kind:`failed`,...e.row.placement.recoveryAction?{recoveryAction:e.row.placement.recoveryAction}:{}};default:return{kind:`ready`}}}function qw(e){let t=Zw(e),n=e.workspaceResultReconciling&&e.row?.placement?.state===`active`&&!t.moving&&!t.restarting&&e.reclaimingKey!==e.row.key,r=Kw({...e,moving:t.moving,workspaceResultReconciling:n}),i=r.kind===`setup`&&!e.startupPending,a=!e.startupPending&&r.kind===`busy`?r.message:null,o=e.row?.placement,s=!e.startupPending&&r.kind===`failed`&&o?.state===`failed`&&o.retryOnSend===!0,c=o&&`terminalReason`in o?o.terminalReason:void 0,l=o?.state===`failed`?o.recoveryError:c,u={state:r,blocksSend:r.kind!==`ready`&&!n&&!i&&!s,busyMessage:a,startup:r.kind===`setup`?r.startup:null,diskSpace:o?.state===`active`?o.diskSpace:void 0,workerRuntimeInstall:o?.state===`active`||o?.state===`provisioning`?o.workerRuntimeInstall:void 0,runError:l&&!t.restarting?{summary:R(`chat.cloudWorkerFailed`,{error:l})}:null,failedUnavailableMessage:R(`sessionsView.failedSessionUnavailable`)};if(e.startupPending||!e.row||s)return{...u,disabledBanner:void 0};let d=r.kind===`dispatch-required`;if(!d&&(r.kind!==`failed`||!r.recoveryAction))return{...u,disabledBanner:void 0};let f=d||r.recoveryAction===`restart`;return{...u,disabledBanner:{kind:`above-composer`,title:R(d?`sessionsView.repositoryWorkerRequiredTitle`:`sessionsView.failedSessionTitle`),text:R(d?`sessionsView.repositoryWorkerRequiredPrompt`:f?`sessionsView.failedSessionRestartPrompt`:`sessionsView.failedSessionStopPrompt`),icon:`warning`,actionLabel:R(d?`sessionsView.chooseWorker`:f?`sessionsView.restartSession`:`sessionsView.stopCloudWorker`),actionStyle:`primary`,disabledReason:f?t.recoveryDisabledReason:t.reclaimDisabledReason,onAction:f?e.onRecover:e.onReclaim}}}function Jw(e){return!(!e?.repositoryWorkspaceId||e.placement&&e.placement.state!==`local`)}function Yw(e,t){let n=e.placement,r=t?.phase===`failed`?void 0:t?.targetKind;n?.state===`active`&&(r=n.runner?.kind===`device`?`device`:`profile`);let i,a;if(r===`device`||r===`auto-device`)i=R(`sessionsView.runsOnDevice`),a=`sessionsView.stopDeviceWorker`;else if(r===`profile`){let e=n&&n.state!==`local`&&n.state!==`requested`?n:void 0;i=e?.providerId&&e.profileId?`${e.providerId} · ${e.profileId}`:R(`newSession.runsOn`,{place:R(`newSession.cloud`)}),a=`sessionsView.stopCloudWorker`}else i=R(`sessionsView.runsOnWorker`),a=`sessionsView.stopWorker`;return{label:i,stopLabel:R(a),confirmMessage:R(`${a}Confirm`,{session:e.label||e.key}),confirmLabel:R(`${a}ConfirmAction`)}}function Xw(e){if(!e)return null;let t=e.placement;if(t&&t.state!==`local`){if(t.state!==`active`)return null;if(t.runner?.kind===`device`){let e=j(t.runner.deviceId);return t.runner.status===`available`&&e?`node:${e}`:null}return j(t.environmentId)??null}let n=j(e.execNode);return n?`node:${n}`:`gateway`}function Zw(e){let t=e.movingKey===e.row?.key||e.row?.placementMove!==void 0&&e.row.placementMove.error===void 0,n=e.reclaimingKey===e.row?.key,r=e.restartingKey===e.row?.key,i=Ml(e.row?.placement),a=z(e.gatewaySnapshot,{method:`sessions.move`,requiredScope:`operator.write`}),o=z(e.gatewaySnapshot,{method:`sessions.reclaim`,requiredScope:`operator.write`}),s=z(e.gatewaySnapshot,{method:`sessions.dispatch`,requiredScope:`operator.write`}),c=e.row?.placement?.state,l=Jw(e.row),u=c===`failed`?e.row?.placement?.recoveryAction:void 0,d=c===`active`?e.row?.placement?.runner:void 0,f=d?.kind===`device`&&d.status===`offline`,p=t?R(`common.loading`):n?R(`sessionsView.actionUnavailable`):c===`active`?a.allowed?void 0:a.reason:R(`sessionsView.actionUnavailable`),m=r?R(`common.loading`):t||n||!l&&u!==`restart`?R(`sessionsView.actionUnavailable`):e.row?.archived?R(`chat.archivedSessionDisabled`):s.allowed||!l&&o.allowed?void 0:s.reason;return{moving:t,restarting:r,moveDisabledReason:p,reclaimDisabledReason:n?R(`common.loading`):r?R(`sessionsView.actionUnavailable`):f?R(`sessionsView.offlineDeviceStopUnavailable`):i?.blocksActiveRun&&e.row?.hasActiveRun===!0?R(`sessionsView.activeRun`):i?o.allowed?void 0:o.reason:R(`sessionsView.actionUnavailable`),recoveryDisabledReason:m}}function Qw(){return(Qw=e((()=>{cu(),H(),_a(),Es(),se(),Hs(),Dc()})))()}function $w(e){if(!e)return null;let t=e.state===`active`?e.runner:void 0;return[e.state,e.generation,`environmentId`in e?e.environmentId:void 0,`activeOwnerEpoch`in e?e.activeOwnerEpoch:void 0,`providerId`in e?e.providerId:void 0,`profileId`in e?e.profileId:void 0,t?.kind,t?.deviceId,t?.status]}function eT(e){return JSON.stringify([e?.sessionId,e?.execNode,e?.archived===!0,$w(e?.placement)])}var tT;function nT(){return(nT=e((()=>{ii(),Ul(),nl(),Rc(),me(),I(),B(),Qw(),Lh(),tT=class{constructor(){this.owner=null,this.generation=0,this.pendingProbes=0,this.reconciliationFailed=!1}syncPane(e){let t=e.state(),n=t?.client,r=t?.sessionKey,i=t?.connectionEpoch,a=t?L(t,t.sessionKey).agentId:void 0,o=e.observation(),s=o?.row??void 0;this.sync(t&&n&&r&&t.connected&&o?.isCurrent()&&e.isPresented()&&!Wt(r)?{client:n,sessions:t.sessions,observation:o,sessionKey:r,agentId:a,connectionEpoch:t.connectionEpoch,desktopAvailable:oi(e.gateway),browserAvailable:Fr(e.gateway),placement:s?.placement,sessionId:s?.sessionId,execNode:s?.execNode,archived:s?.archived,browserTab:[...gs(t.chatMessages,t.chatToolMessages).values()].at(-1),layout:()=>t.sidebarLayout,commit:(t,n)=>e.commit(t,n),requestUpdate:()=>e.requestUpdate(),isCurrent:()=>e.isConnected()&&e.state()===t&&t.client===n&&t.sessionKey===r&&L(t,t.sessionKey).agentId===a&&t.connectionEpoch===i&&t.connected&&e.observation()===o&&o.isCurrent()&&eT(o.row??void 0)===eT(s)&&e.isPresented()}:null)}invalidate(){this.generation+=1,this.signature=void 0,this.pendingProbes=0,this.reconciliation=void 0,this.reconciliationFailed=!1,this.probeCurrent=void 0,this.requestProbeUpdate=void 0}reconcileObservation(e){let t=this.owner;if(!t?.isCurrent()||!t.observation.isCurrent())return;let n=t.layout(),r=t.desktopAvailable&&(this.desktop!==void 0||!n.columns.some(e=>e.panels.some(e=>e.slot===`desktop`))),i=!this.dismissed(n)&&t.browserAvailable&&t.browserTab!==void 0;(r||i)&&this.reconcile(async()=>(await this.readSession(t),e.requestUpdate(),await e.updated(),t.observation.isCurrent()))}readSession(e){let t=this.descriptorRead;if(t?.observation===e.observation&&t.current())return t.promise;let n=this.generation,r=()=>n===this.generation&&e.isCurrent()&&e.observation.isCurrent(),i={observation:e.observation,current:r,promise:Promise.resolve(null)};return i.promise=(async()=>{for(;r();){let t=e.observation.captureReconcile(),{session:n}=await e.sessions.describe({key:e.sessionKey,...e.agentId?{agentId:e.agentId}:{}},{client:e.client});if(!r())return null;let i=t(n??void 0);if(i.status===`current`)return i.row;if(i.status===`retired`)return null}return null})().finally(()=>{this.descriptorRead===i&&(this.descriptorRead=void 0)}),this.descriptorRead=i,i.promise}reconcile(e){let t=this.probeCurrent;if(!t?.())return;let n=this.reconciliationFailed&&this.pendingProbes===0,r=this.requestProbeUpdate,i=Promise.resolve().then(()=>t()?e():!1).catch(()=>!1);this.reconciliation=i,this.reconciliationFailed=!1,i.then(e=>{this.reconciliation===i&&(this.reconciliationFailed=!e,!e&&this.desktop&&(this.desktop.source=null,r?.()),e&&(this.reconciliation=void 0,n&&t()&&this.pendingProbes===0&&(this.signature=void 0,r?.())))})}async afterReconciliation(e,t){let n;for(;e()&&(n=this.reconciliation);){let e=await n;if(this.reconciliation===n&&!e)return}return e()?t():void 0}trackProbe(e,t){this.pendingProbes+=1,e.finally(()=>{this.generation===t&&--this.pendingProbes})}desktopSource(e,t,n,r,i){if(this.desktop?.sessionKey===t&&this.desktop.agentId===n)return this.desktop.client===e&&this.desktop.observation.isCurrent()&&this.desktop.connectionEpoch===r&&this.desktop.resourceIdentity===eT(i)?this.desktop.source:null}sync(e){let t=this.owner;if(this.owner=e,!e){this.invalidate();return}let n=eT(e),r=JSON.stringify([e.sessionKey,e.agentId,e.connectionEpoch,n,e.desktopAvailable,e.browserAvailable,e.browserTab,e.layout().resourceAutoOpenDismissed]);if(this.client===e.client&&this.signature===r&&t?.observation===e.observation)return;(this.reconciliationFailed||this.probeCurrent&&!this.probeCurrent())&&(this.reconciliation=void 0,this.reconciliationFailed=!1),this.client=e.client,this.signature=r;let i=++this.generation;this.pendingProbes=0,this.desktop&&(this.desktop.sessionKey!==e.sessionKey||this.desktop.agentId!==e.agentId?this.desktop=void 0:(this.desktop.client!==e.client||this.desktop.connectionEpoch!==e.connectionEpoch||this.desktop.resourceIdentity!==n)&&(this.desktop={...this.desktop,client:e.client,connectionEpoch:e.connectionEpoch,resourceIdentity:n,source:null}));let a=e.layout().columns.some(e=>e.panels.some(e=>e.slot===`desktop`));if(this.dismissed(e.layout())&&(!this.desktop||!a)){this.desktop=void 0;return}let o=()=>i===this.generation&&e.isCurrent()&&(!this.dismissed(e.layout())||this.desktop!==void 0&&e.layout().columns.some(e=>e.panels.some(e=>e.slot===`desktop`)));this.probeCurrent=o,this.requestProbeUpdate=e.requestUpdate,e.desktopAvailable&&(this.desktop||!a)&&this.trackProbe(this.discoverDesktop(e,o),i),!this.dismissed(e.layout())&&e.browserAvailable&&e.browserTab&&this.trackProbe(this.discoverBrowser(e,e.browserTab,o),i)}dismissed(e){return e.resourceAutoOpenDismissed===!0||e.open===!1&&De(e).some(e=>e.slot!==`conversation`)}publishDesktop(e,t){let n=e.layout().columns.some(e=>e.panels.some(e=>e.slot===`desktop`));if(this.dismissed(e.layout())&&!n||!this.desktop&&(t===null||n))return;let r=this.desktop?.source!==t;this.desktop={client:e.client,observation:e.observation,sessionKey:e.sessionKey,agentId:e.agentId,connectionEpoch:e.connectionEpoch,resourceIdentity:eT(e),source:t},t!==null&&this.reveal(e,`desktop`),r&&e.requestUpdate()}reveal(e,t){let n=e.layout();if(this.dismissed(n)||n.columns.some(e=>e.panels.some(e=>e.slot===t)))return;let r=Ch(n,t);n.open&&jn(n)&&(r.columns[0].activePanelId=n.columns[0].activePanelId),ot(n)?.slot!==void 0&&ot(n)?.slot!==`conversation`&&(r.open=n.open),r.expanded=n.expanded,r.expandedSide=n.expandedSide,e.commit(r,t)}async discoverDesktop(e,t){try{let n=await this.readSession(e),r=await this.afterReconciliation(t,()=>{if(!n||!F(n.key,e.sessionKey)||n.archived){this.publishDesktop(e,null);return}let t=Xw(n);if(!t||t===`gateway`||_l({id:t}).kind===`environment`&&!n.sessionId){this.publishDesktop(e,null);return}return t});if(!r)return;let i=await gl(e.client,{target:Promise.resolve(r),isCurrent:t,recoverToPicker:!1});await this.afterReconciliation(t,()=>{let t=i?.environments.find(e=>e.id===r);if(!t||t.status!==`available`||t.desktop!==!0){this.publishDesktop(e,null);return}if(t.type===`worker`&&(t.worker?.state!==`attached`||!n?.sessionId||!t.worker.attachedSessionIds.includes(n.sessionId))){this.publishDesktop(e,null);return}this.publishDesktop(e,r)})}catch{await this.afterReconciliation(t,()=>{this.publishDesktop(e,null)})}}async discoverBrowser(e,t,n){try{let r=await this.readSession(e);if(!r||r.archived)return;let i=await this.afterReconciliation(n,()=>Qc(Nl(e.client,t.tab,n)));await this.afterReconciliation(n,()=>{i?.running&&i.tabs.some(e=>e.targetId===t.tab.targetId&&!e.urlUnavailableReason)&&this.reveal(e,`browser`)})}catch{}}}})))()}function rT(e){return e.chatRunId?!0:!!e.sessionsResult?.sessions.some(t=>t.key===e.sessionKey&&S(t))}function iT(e,t,n,r){e.chatMessagesBySession&&tg(e.chatMessagesBySession,e,{sessionKey:t,agentId:n},r)}function aT(e,t){return e.client===t.client&&e.connectionEpoch===t.connectionEpoch&&V(e,t.sessionKey,t.agentId)}function oT(e,t,n){n&&Object.hasOwn(n.sessionInfo??{},`activeLeafEntryId`)&&n.sessionInfo?.activeLeafEntryId===null&&e.client===t.client&&e.connectionEpoch===t.connectionEpoch&&e.connected&&V(e,t.sessionKey,t.agentId)&&delete e.chatDisplayedLeafEntryId}async function sT(e){if(!e.client||!e.connected)return`failed`;let t=e.client,n=e.connectionEpoch,r=e.sessionKey,i=L(e,r),a={client:t,connectionEpoch:n,sessionKey:r,agentId:i.agentId},o=e.chatRunId,s=e.chatSubmissions?.readInitial(r,t),c=rT(e);try{let a=await e.sessions.reset(r,i);if(a===`not-started`)return J(e,`Gateway was unavailable before chat history could be cleared.`),Np(e),`failed`;if(s&&tr(s),iT(e,r,i.agentId),a===`uncertain`||e.client!==t||e.connectionEpoch!==n||!e.connected){let a={client:e.client,connectionEpoch:e.connectionEpoch,sessionKey:r,agentId:i.agentId},o=!1;if(e.client&&e.connected&&V(e,r,i.agentId)){uy(e,i.agentId);let a=await ZC(e);o=!!a,oT(e,{client:t,connectionEpoch:n,sessionKey:r,agentId:i.agentId},a)}return aT(e,a)&&(J(e,o?`The clear request may have completed. Current history was refreshed; review it before resuming queued messages.`:`The clear request may have completed. Cached history was cleared, but current history could not be refreshed; reconnect and review it before resuming queued messages.`),Np(e)),`uncertain`}}catch(t){return aT(e,a)&&(J(e,P(t)),Np(e)),`failed`}if(!V(e,r,i.agentId))return`completed`;uy(e,i.agentId),e.chatRunError=null,e.chatReplyTarget=null,sm(e,{outcome:c?`interrupted`:void 0,sessionStatus:`killed`,runId:o,sessionKey:r,clearLocalRun:!0,clearChatStream:!0,clearToolStream:!0,clearRunStatus:!c});let l=await ZC(e);return oT(e,{client:t,connectionEpoch:n,sessionKey:r,agentId:i.agentId},l),aT(e,a)&&Np(e),`completed`}async function cT(e,t,n){if(!e.client||!e.connected)return null;let r=e.sessionKey,i=L(e,r),a=e.client,o=e.connectionEpoch,s=()=>e.connected&&e.client===a&&e.connectionEpoch===o,c=()=>V(e,r,i.agentId),l=()=>s()&&c(),u=()=>yd(e.chatMessage,e.chatAttachments,e.chatGoalDraftMode,e.chatMentions,e.chatReplyTarget),d=u(),f=n.readSignal,p=gd(e,r,i.agentId);try{let a=await e.sessions.rewind(r,t,i),o=a.editorText??``;return iT(e,r,i.agentId,`cache-eviction`),c()&&(uy(e,i.agentId),await Promise.all([ZC(e),WS(e)])),!s()||!p()||u()!==d||(Hu(e,r,{agentId:i.agentId,draft:o,mentions:[],goalMode:null,replyTarget:null,expectedDraftRevision:pd(e,r,i.agentId)}),!c())?null:(e.chatGoalDraftMode=null,e.chatReplyTarget=null,e.chatAttachments=Ag(e.chatAttachments,a.editorAttachments),e.handleChatDraftChange(o,[]),n.readSignal===f&&n.abortReads(),a)}catch(t){return l()&&(J(e,P(t)),Np(e)),null}}async function lT(e,t){if(!e.client||!e.connected)return!1;let n=e.sessionKey,r=L(e,n),i=e.client,a=e.connectionEpoch,o=()=>e.connected&&e.client===i&&e.connectionEpoch===a,s=()=>V(e,n,r.agentId),c=()=>o()&&s();try{return await e.sessions.switchBranch(n,t,r),iT(e,n,r.agentId,`cache-eviction`),s()?(uy(e,r.agentId),await Promise.all([ZC(e),WS(e)]),c()):!1}catch(t){return c()&&(J(e,P(t)),Np(e)),!1}}function uT(){return(uT=e((()=>{yi(),on(),I(),Ig(),GS(),Y(),ew(),zu(),Ld(),Lp(),Qm(),zh()})))()}function dT(e,t,n){let r=n??Ft(e,t),i=N(r),a=new Set([i]);for(let t of Object.keys(e.chatComposerFallbackByScope)){let n=uc(t);n&&e.chatComposerFallbackByScope[t]?.awaitingDefaults&&N(Ft(e,n.sessionKey,n.agentId))===i&&a.add(t)}let o=[...a].map(t=>({fallback:e.chatComposerFallbackByScope[t],scopeKey:t})).filter(e=>e.fallback!==void 0),s=o.toSorted((e,t)=>t.fallback.sequence-e.fallback.sequence)[0];if(!s)return{scopeKey:i};let c=s.scopeKey,l=s.fallback;if(gn(e)&&delete l.awaitingDefaults,o.length===1&&c===i)return{fallback:l,scopeKey:i};let u=l;if(c!==i&&l.draftRetry){let n=pd(e,t,r.agentId),i=_d(e,t,r.agentId);l.draftRetry.draftRevision>i&&(u={...l,draftRetry:{...l.draftRetry,expectedDraftRevision:n}})}let d={...e.chatComposerFallbackByScope};for(let e of o)delete d[e.scopeKey];return d[i]=u,Og(o.flatMap(e=>e.fallback.attachments),[e.chatAttachments,...Object.values(d).map(e=>e.attachments)]),e.chatComposerFallbackByScope=d,{fallback:u,scopeKey:i}}function fT(e,t,n){let r=++vT;return e.chatComposerFallbackByScope={...e.chatComposerFallbackByScope,[N(t)]:{...gn(e)?{}:{awaitingDefaults:!0},...Df(e,t)?{incognito:!0}:{},message:n.message,...n.mentions?.length?{mentions:n.mentions.map(e=>({...e}))}:{},...n.goalMode?{goalMode:n.goalMode}:{},...n.replyTarget?{replyTarget:{...n.replyTarget}}:{},attachments:[...n.attachments],storageFailed:n.draftRetry!==void 0,sequence:r,...n.draftRetry?{draftRetry:n.draftRetry}:{}}},{sequence:r}}function pT(e,t){return e.message===t.message&&JSON.stringify(e.mentions??[])===JSON.stringify(t.mentions??[])&&JSON.stringify(e.replyTarget??null)===JSON.stringify(t.replyTarget??null)&&e.attachments.length===t.attachments.length&&e.attachments.every((e,n)=>e.id===t.attachments[n]?.id)}function mT(e,t,n){let{fallback:r,scopeKey:i}=dT(e,t.sessionKey,t);if(r&&pT(r,n))return{sequence:r.sequence};if(r?.storageFailed&&!r.message.trim()&&!r.replyTarget&&r.attachments.length===0)return e.chatComposerFallbackByScope={...e.chatComposerFallbackByScope,[i]:{...r,message:n.message,mentions:n.mentions,replyTarget:n.replyTarget?{...n.replyTarget}:void 0,attachments:[...n.attachments]}},{sequence:r.sequence};if(!(r&&(r.storageFailed||r.message.trim()||r.replyTarget||r.attachments.length>0)))return fT(e,t,n)}function hT(e,t,n){let{fallback:r}=dT(e,t.sessionKey,t);return r&&pT(r,n)?{sequence:r.sequence}:void 0}function gT(e,t){return Object.values(e.chatComposerFallbackByScope).some(e=>e.sequence===t.sequence)}function _T(e,t){if(!t)return!1;let n=Object.entries(e.chatComposerFallbackByScope).filter(([,e])=>e.sequence===t.sequence);if(n.length===0)return!1;let r={...e.chatComposerFallbackByScope};for(let[e]of n)delete r[e];return e.chatComposerFallbackByScope=r,!0}var vT;function yT(){return(yT=e((()=>{Cs(),B(),Ig(),Ed(),zu(),vT=0})))()}var bT,xT,ST,CT;function wT(){return(wT=e((()=>{Wo(),B(),Pw(),qp(),bT=`openclaw:queued-edit-retention-change`,xT=3,ST=5e3,CT=class{constructor(e,t){this.host=e,this.bindings=t,this.sessionsByPane=new Map,this.unbound=new Set,this.pendingAtFocus=new WeakSet,this.preview=null,this.refreshRetention=()=>{this.host.requestUpdate()},this.removeSession=(e,t,n,r=!1)=>{let i=this.bindings.context();if(i&&$r(i,t)){this.host.requestUpdate();return}let a=this.findPane(e,t);r||a?.discardStagedAttachments?.();let o=this.sessionsByPane.get(e),s=o&&[...o.keys()].find(e=>F(e,t));s!==void 0&&o?.delete(s),i&&!r&&mw(i,e,t),this.preview?.paneId===e&&F(this.preview.sessionKey,t)&&this.cancelPreview();let c=Xp(this.bindings.layout(),e)?.pane.sessionKey;c&&F(c,t)?this.bindings.selectReplacement(e,t,n):this.host.requestUpdate()},this.handleNavigationIntent=e=>{if(!(e instanceof CustomEvent)||(this.cancelPreview(),!this.bindings.presented()))return;let t=e.detail,n=this.bindings.layout(),r=Xp(n,n.activePaneId)?.pane;if(window.location.href!==this.bindings.routeHref()&&(!r||!this.unbound.has(r.id)))return;if(r&&this.unbound.has(r.id)&&(!mn(t.sessionKey)||t.agentId)){e.preventDefault(),t.commit()&&this.bindings.presented()&&this.bindings.layout()===n&&this.bindings.adoptNavigation(r.id,t.sessionKey,t.agentId);return}let i=[...this.sessionsByPane.get(r?.id??``)?.keys()??[]].find(e=>F(e,t.sessionKey));if(!r||!i||this.findPane(r.id,i)?.routeFace!==t.face||F(r.sessionKey,i))return;this.present(r.id,i,!0);let a={...t,href:window.location.href,paneId:r.id,sessionKey:i};this.preview=a,this.previewFrame=requestAnimationFrame(()=>{this.preview===a&&(this.previewFrame=requestAnimationFrame(()=>{this.previewFrame=void 0,this.preview===a&&(window.location.href!==a.href||!a.commit())&&this.cancelPreview()}))}),this.previewTimer=window.setTimeout(this.cancelPreview,ST),e.preventDefault()},this.cancelPreview=()=>{let e=this.bindings.layout(),t=this.preview?.paneId??e.activePaneId;this.clearPreviewWork(),this.preview=null;let n=Xp(e,t)?.pane;n&&this.present(n.id,n.sessionKey)}}get unboundPaneIds(){return this.unbound}restore(e){this.unbound.clear(),this.pendingAtFocus=new WeakSet;for(let t of e)mn(t.sessionKey)&&this.unbound.add(t.id);this.unbound.has(this.bindings.layout().activePaneId)&&this.capturePendingNavigation()}bindPane(e){this.unbound.delete(e)}capturePendingNavigation(){let e=this.bindings.context();if(!e)return;let{matches:t,pendingMatches:n}=e.router.getState();this.pendingAtFocus=new WeakSet([...t,...n].filter(e=>e.isFetching||e.status===`pending`).map(e=>e.abortController))}wasPendingAtFocus(){return this.bindings.context()?.router.getState().matches.some(e=>this.pendingAtFocus.has(e.abortController))===!0}connect(){this.host.addEventListener(bT,this.refreshRetention),window.addEventListener(`popstate`,this.cancelPreview),window.addEventListener(qo,this.handleNavigationIntent)}disconnect(){this.sessionsByPane.clear(),this.unbound.clear(),this.pendingAtFocus=new WeakSet,this.host.removeEventListener(bT,this.refreshRetention),window.removeEventListener(`popstate`,this.cancelPreview),window.removeEventListener(qo,this.handleNavigationIntent),this.cancelPreview()}suspend(){this.cancelPreview()}settleRoute(){this.preview&&this.cancelPreview()}retain(e){for(let t of this.unbound)e.some(e=>e.id===t&&mn(e.sessionKey))||this.unbound.delete(t);let t=e.filter(e=>!this.unbound.has(e.id)),n=new Set(t.map(e=>e.id));for(let e of this.sessionsByPane.keys())n.has(e)||this.sessionsByPane.delete(e);return new Map(t.map(e=>[e.id,this.retainPane(e)]))}retainPane(e){let t=this.sessionsByPane.get(e.id);t||(t=new Map,this.sessionsByPane.set(e.id,t));let n=Array.from({length:xT},()=>void 0);for(let[e,r]of t)n[r]=e;let r=[...t.keys()].find(t=>t===e.sessionKey||F(t,e.sessionKey))??e.sessionKey,i=t.get(r);if(i===void 0){if(i=n.indexOf(void 0),i<0){let r=[...t].find(([t])=>!this.findPane(e.id,t)?.hasQueuedMessageEdit);if(r){let[n,a]=r;this.findPane(e.id,n)?.prepareForEviction?.(),t.delete(n),i=a}else i=n.length}n[i]=r}t.delete(r),t.set(r,i);for(let[i,a]of t){if(t.size<=xT)break;i===r||this.findPane(e.id,i)?.hasQueuedMessageEdit||(this.findPane(e.id,i)?.prepareForEviction?.(),t.delete(i),n[a]=void 0)}for(;n.length>xT&&n.at(-1)===void 0;)n.pop();return n}discardPane(e){this.unbound.delete(e);let t=this.bindings.context();t&&(hw(t,e),t.chatAttachmentHandoff.clearPane(e)),this.sessionsByPane.delete(e)}findPane(e,t){return[...this.host.querySelectorAll(`openclaw-chat-pane`)].find(n=>n.paneId===e&&F(n.sessionKey??``,t))}present(e,t,n=!1){let r=lm(this.bindings.layout(),this.bindings.narrow()).some(t=>t.id===e);for(let i of this.host.querySelectorAll(`openclaw-chat-pane`)){if(i.paneId!==e)continue;let a=F(i.sessionKey??``,t),o=this.bindings.presented()&&r&&a;if(i.classList.toggle(`chat-pane-cache__pane--visible`,a),i.visuallyPresented=o,n){i.toggleAttribute(`inert`,!0);continue}i.toggleAttribute(`inert`,!o),i.setAttribute(`aria-hidden`,o?`false`:`true`),i.presented=o}}clearPreviewWork(){this.previewFrame!==void 0&&(cancelAnimationFrame(this.previewFrame),this.previewFrame=void 0),this.previewTimer!==void 0&&(window.clearTimeout(this.previewTimer),this.previewTimer=void 0)}}})))()}async function TT(){return!customElements.get(`openclaw-board-view`)&&(OT??=M(()=>import(`./board-view-3OMPWlN8.js`),__vite__mapDeps([40,1,2,3,4,5,6,7,8,41,42,43,44,9,12,10,11,13,45]),import.meta.url),await OT,!0)}function ET(e){return W`
    <div class="board-session-surface__board">
      <openclaw-board-view
        .active=${e.active}
        .session=${e.session}
        .snapshot=${e.snapshot}
        .activeTabId=${e.activeTabId}
        .pageWidgetName=${e.pageWidgetName??``}
        .widgetFrameUrl=${e.widgetFrameUrl}
        .callbacks=${e.callbacks}
        .canMutate=${e.canMutate}
        .canGrant=${e.canGrant}
      ></openclaw-board-view>
    </div>
  `}function DT(e){return W`
    <div class="board-session-surface" ?hidden=${!e.active} ?inert=${!e.active}>
      ${ET(e)}
    </div>
  `}var OT;function kT(){return(kT=e((()=>{bi(),n(),OT=null})))()}function AT(e){let t=m(e)?.messageId;return typeof t==`string`&&t?t:null}function jT(){return(jT=e((()=>{})))()}function MT(e,t){return{content:R(e,{error:P(t)}),failed:!0}}function NT(e){if(e.isCurrent?.()===!1)throw Error(`The Gateway connection changed. Retry the command.`)}function PT(e,t){NT(e);let n=z(e.readSessionAccessSnapshot?.()??e.sessionAccessSnapshot,t);if(!n.allowed)throw Error(n.reason)}async function FT(e,t,n,r){return PT(e,{method:`sessions.patch`,params:{key:t,...wx(t,e),...n}}),await Tx(e,t,n,r)}async function IT(e,t,n,r,i){switch(n){case`help`:return LT();case`new`:return{content:R(`chat.commandResults.startingNewThread`),action:`new-session`};case`reset`:return{content:R(`chat.commandResults.resettingThread`),action:`reset`};case`stop`:return{content:R(`chat.commandResults.stoppingCurrentRun`),action:`stop`};case`clear`:return{content:R(`chat.commandResults.chatHistoryCleared`),action:`clear`};case`compact`:return await RT(t,i);case`model`:return await zT(e,t,r,i);case`think`:return await BT(e,t,r,i);case`fast`:return await UT(e,t,r,i);case`verbose`:return await VT(e,t,r,i);case`usage`:return await WT(t,i);case`agents`:return await GT(e);case`steer`:case`redirect`:return await nE(e,t,r,i,n);default:return{content:R(`chat.commandResults.unknownCommand`,{command:`/${n}`})}}}function LT(){let e=[`**${R(`chat.commandResults.help.availableCommands`)}**\n`],t=``;for(let n of pc){let r=n.category??`session`;r!==t&&(t=r,e.push(`**${tc(r)}**`));let i=n.args?` ${n.args}`:``,a=n.executeLocal?``:` *(${R(`chat.commandResults.help.agentCommand`)})*`;e.push(`\`/${n.name}${i}\` — ${zs(n)}${a}`)}return e.push(`\n${R(`chat.commandResults.help.openMenu`)}`),{content:e.join(`
`)}}async function RT(e,t){try{let n=wx(e,t);PT(t,{method:`sessions.compact`,requiredScope:`operator.admin`});let r=await t.sessions.compact(e,n);if(r?.ok!==!0){let e=typeof r?.reason==`string`?Ne(r.reason):``;return{content:e?R(`chat.commandResults.compaction.failedWithReason`,{reason:e}):R(`chat.commandResults.compaction.failed`),failed:!0}}return r?.compacted?{action:`refresh`}:typeof r?.reason==`string`&&r.reason.trim()?{content:R(`chat.commandResults.compaction.skippedWithReason`,{reason:Ne(r.reason)}),action:`refresh`}:{content:R(`chat.commandResults.compaction.skipped`),action:`refresh`}}catch(e){return{content:R(`chat.commandResults.compaction.failedWithReason`,{reason:P(e)}),failed:!0}}}async function zT(e,t,n,r){if(!n)try{let{session:n,defaults:i,models:a}=await tE(e,r,t),o=n?.model||i?.model||`default`,s=a.filter(e=>e.available!==!1&&e.manualSelectionAllowed!==!1).map(e=>e.id),c=[R(`chat.commandResults.model.current`,{model:`\`${o}\``})];if(s.length>0){let e=s.length>10?R(`chat.commandResults.model.more`,{count:String(s.length-10)}):``;c.push(`${R(`chat.commandResults.model.available`,{models:s.slice(0,10).map(e=>`\`${e}\``).join(`, `)})}${e}`)}return{content:c.join(`
`)}}catch(e){return MT(`chat.commandResults.model.getFailed`,e)}try{let e=n.trim();return await FT(r,t,{model:e},{ownsModelOverride:r.ownsModelOverride}),{content:R(`chat.commandResults.model.set`,{model:`\`${e}\``}),action:`refresh`,modelChanged:!0}}catch(e){return MT(`chat.commandResults.model.setFailed`,e)}}async function BT(e,t,n,r){let i=n.trim();if(!i)try{let{session:n,defaults:i,models:a}=await tE(e,r,t);return{content:YT(R(`chat.commandResults.thinking.current`,{level:fc(n,i,a)}),Go(n,i,a))}}catch(e){return MT(`chat.commandResults.thinking.getFailed`,e)}if(Oi(i))try{return await FT(r,t,{thinkingLevel:null}),{content:R(`chat.commandResults.thinking.reset`),action:`refresh`}}catch(e){return MT(`chat.commandResults.thinking.resetFailed`,e)}try{let{session:e,defaults:n}=await QT(r,t),a=r.chatModelCatalog??r.modelCatalog??[],o=ts(i,e,n,a);return o?Zo(e,n,o,a)===!1?{content:R(`chat.commandResults.thinking.unsupported`,{level:i,options:Go(e,n,a)})}:(await FT(r,t,{thinkingLevel:o}),{content:R(`chat.commandResults.thinking.set`,{level:`**${o}**`}),action:`refresh`}):{content:R(`chat.commandResults.thinking.unrecognized`,{level:i,options:Go(e,n,a)})}}catch(e){return MT(`chat.commandResults.thinking.setFailed`,e)}}async function VT(e,t,n,r){let i=n.trim();if(!i)try{let e=await ZT(r,t);return{content:YT(R(`chat.commandResults.verbose.current`,{level:Bi(e?.verboseLevel)??`off`}),`on, full, off`)}}catch(e){return MT(`chat.commandResults.verbose.getFailed`,e)}let a=Bi(i);if(!a)return{content:R(`chat.commandResults.verbose.unrecognized`,{level:i})};try{return await FT(r,t,{verboseLevel:a}),{content:R(`chat.commandResults.verbose.set`,{level:`**${a}**`}),action:`refresh`}}catch(e){return MT(`chat.commandResults.verbose.setFailed`,e)}}function HT(e){return R(`chat.commandResults.fast.options`,{seconds:String(e?.fastAutoOnSeconds??60)})}async function UT(e,t,n,r){let i=x(n);if(!i||i===`status`)try{let e=await ZT(r,t);return{content:YT(Aa(e),HT(e))}}catch(e){return MT(`chat.commandResults.fast.getFailed`,e)}if(Oi(i))try{return await FT(r,t,{fastMode:null}),{content:R(`chat.commandResults.fast.reset`),action:`refresh`}}catch(e){return MT(`chat.commandResults.fast.resetFailed`,e)}let a=Bo(i);if(a===void 0)return{content:R(`chat.commandResults.fast.unrecognized`,{mode:n.trim()})};try{return await FT(r,t,{fastMode:a}),{content:R(a===`auto`?`chat.commandResults.fast.setAuto`:a?`chat.commandResults.fast.enabled`:`chat.commandResults.fast.disabled`),action:`refresh`}}catch(e){return MT(`chat.commandResults.fast.setFailed`,e)}}async function WT(e,t){try{let n=eE(await XT(t),e);if(!n)return{content:R(`chat.commandResults.usage.noActiveThread`)};let r=Number.isFinite(n.inputTokens),i=Number.isFinite(n.outputTokens),a=r?n.inputTokens??0:0,o=i?n.outputTokens??0:0,s=r||i?a+o:null,c=Number.isFinite(n.totalTokens)?n.totalTokens??null:s,l=n.totalTokensFresh!==!1,u=xa(n),d=u.tokens,f=c!==null&&l&&d>0?Math.round(c/d*100):null,p=s===null?R(`chat.commandResults.usage.notAvailable`):`${l?``:`~`}${Ze(s)}`,m=[`**${R(`chat.commandResults.usage.title`)}**`,R(`chat.commandResults.usage.inputTokens`,{count:`**${Ze(a)}**`}),R(`chat.commandResults.usage.outputTokens`,{count:`**${Ze(o)}**`}),R(`chat.commandResults.usage.totalTokens`,{count:`**${p}**`})];return f!==null&&m.push(R(u.fromLastPrompt?`chat.commandResults.usage.promptBudget`:`chat.commandResults.usage.context`,{percent:`**${f}%**`,total:Ze(d)})),n.model&&m.push(R(`chat.commandResults.usage.model`,{model:`\`${n.model}\``})),{content:m.join(`
`)}}catch(e){return MT(`chat.commandResults.usage.failed`,e)}}async function GT(e){try{let t=await e.request(`agents.list`,{}),n=t?.agents??[];if(n.length===0)return{content:R(`chat.commandResults.agents.none`)};let r=[R(`chat.commandResults.agents.title`,{count:String(n.length)}),``];for(let e of n){let n=e.id===t?.defaultId,i=e.identity?.name||e.name||e.id,a=n?` *(${R(`chat.commandResults.agents.default`)})*`:``,o=e.agentRuntime?.id?R(`chat.commandResults.agents.runtime`,{runtime:`\`${e.agentRuntime.id}\``}):``;r.push(`- \`${e.id}\` — ${i}${a}${o}`)}return{content:r.join(`
`)}}catch(e){return MT(`chat.commandResults.agents.failed`,e)}}function KT(e,t){let n=jt(k(e)??``)?.agentId??k(t.agentId);return n?{agentId:n}:{}}function qT(e,t){let n=k(e);return jt(n??``)?.agentId??k(t.agentId)??(n===`main`?k(t.defaultAgentId)??`main`:void 0)}function JT(e,t){let n=new Set([e]);if(t&&t!==`main`){let r=`agent:${t}:${a}`,i=`agent:${t}:global`;(e===r||e===i)&&n.add(`global`)}if(t===`main`){let t=`agent:${ut}:main`;e===`main`?n.add(t):e===t&&n.add(a)}return n}function YT(e,t){return`${e}\n${R(`chat.commandResults.options`,{options:t})}`}async function XT(e,t){let n=await e.sessions.list(t);if(!n)throw Error(R(`chat.commandResults.sessionUnavailable`));return n}async function ZT(e,t){return(await QT(e,t)).session}async function QT(e,t){return $T(e,t,await XT(e,KT(t,e)))}function $T(e,t,n){let r=qT(t,e),i=k(e.defaultAgentId)??`main`,a=k(e.sessionsResultAgentId),o=e.sessionsResult&&r&&a===r?eE(e.sessionsResult,t):void 0;return{session:eE(n,t)??o,defaults:!r||r===i?n.defaults:void 0}}function eE(e,t){let n=k(t),r=jt(n??``)?.agentId??(n===`main`?`main`:void 0),i=n?JT(n,r):new Set;return e?.sessions?.find(e=>{let t=k(e.key);return t?i.has(t):!1})}async function tE(e,t,n){let r=t.chatModelCatalog??t.modelCatalog,i=qT(n,t),[a,o]=await Promise.all([XT(t,KT(n,t)),r?Promise.resolve(r):Ss(e,{agentId:i,sessionKey:n}).then(e=>e.models)]);return{...$T(t,n,a),models:o}}async function nE(e,t,n,r,i){try{let a=n.trim();if(!a)return{content:R(`chat.commandResults.${i}.usage`)};NT(r);let o=await e.request(`chat.send`,{sessionKey:t,...wx(t,r),message:a,...i===`steer`?{deliver:!1,queueMode:`steer`}:{queueMode:`interrupt`},idempotencyKey:p()}),s=gg(o?.status);if(s===`timeout`||s===`error`)return{content:R(`chat.commandResults.${i}.${s===`timeout`?`timeout`:`failed`}`),failed:!0};let c={content:R(`chat.commandResults.${i}.succeeded`)};return(s===`started`||s===`in_flight`)&&(i===`steer`?c.pendingCurrentRun=!0:c.trackRunId=typeof o?.runId==`string`?o.runId:void 0),c}catch(e){return MT(`chat.commandResults.${i}.requestFailed`,e)}}function rE(){return(rE=e((()=>{ki(),H(),fs(),Oa(),Uo(),on(),Ke(),Tc(),se(),B(),o(),yg(),Dx()})))()}function iE(e,t){let n=t===null?null:P(t);e.lastError=n,e.chatError=n}function aE(e){return{client:e.client??null,hello:e.hello??null,phase:e.connected?`connected`:`offline`}}function oE(e,t){let n=Xx(aE(e),!1,{session:e.sessionsResult?.sessions.find(t=>V(e,t.key,t.agentId??e.sessionsResultAgentId??void 0))})[t];return n.allowed?!0:(iE(e,n.reason),!1)}function sE(e){return!e.client||!e.connected?null:{client:e.client,connectionEpoch:e.connectionEpoch,sessionKey:e.sessionKey,agentId:_t(e,e.sessionKey)}}function cE(e,t){return e.connected&&e.client===t.client&&e.connectionEpoch===t.connectionEpoch}function lE(e,t){return cE(e,t)&&V(e,t.sessionKey,t.agentId)}function uE(e,t){return cE(e,t)?!kt(e,t.sessionKey)||Tt(e)===t.agentId:!1}function dE(e,t){if(!lE(e,t))return{allowed:!1,reason:`The Gateway connection changed. Retry the command.`};let n=z(aE(e),{method:`chat.send`,requiredScope:`operator.admin`});return n.allowed?{allowed:!0}:n}function fE(e,t){let n=dE(e,t);return n.allowed?!0:(iE(e,n.reason),!1)}function pE(e){return iE(e,`The Gateway connection changed. Retry the command.`),`failed`}function mE(e,t){return JSON.stringify([e??null,t??null])}function hE(e){let t=DE.get(e);return t||(t=new Map,DE.set(e,t)),t}async function gE(e,t,n){try{let r=await e.request(`commands.list`,{...t?{agentId:t}:{},...n?{sessionKey:n}:{},includeArgs:!0,scope:`text`});return Array.isArray(r?.commands)?ns(ha(r)):void 0}catch{return}}function _E(e,t,n){let r=yc(e,{agentId:t,sessionKey:n});if(Array.isArray(r?.commands))return Promise.resolve(ns(ha(r)));let i=hE(e),a=mE(t,n),o=i.get(a),s=Date.now();if(o?.commands&&o.expiresAt>s)return Promise.resolve(o.commands);if(o?.inFlight)return o.inFlight;let c={commands:o?.commands,expiresAt:o?.expiresAt??0},l=gE(e,t,n).then(e=>(e&&i.get(a)===c&&(c.commands=e,c.expiresAt=Date.now()+EE),e??o?.commands??io())).finally(()=>{i.get(a)===c&&delete c.inFlight});return c.inFlight=l,i.set(a,c),l}function vE(e,t){TE+=1,DE.get(e)?.delete(mE(t.agentId,t.sessionKey))}function yE(e){if(!Array.isArray(e.result?.commands))return!1;let t=ns(ha(e.result));return TE+=1,Js(t),!0}async function bE(e){let t=++TE,n=e.agentId?.trim();if(!e.client){if(t!==TE||e.shouldApply?.()===!1)return;Js(io());return}let r=await _E(e.client,n,e.sessionKey);t===TE&&e.shouldApply?.()!==!1&&Js(r)}function xE(e){return![`stop`,`export-session`,`steer`,`redirect`,`new`].includes(e)}async function SE(e,t){let n=t?.sessionKey??e.sessionKey,r=t?()=>V(e,t.sessionKey,t.agentId):()=>e.sessionKey===n||F(e.sessionKey,n);if(!r())return`deferred`;if(!e.confirmConversationReset)return`confirmed`;let i=await e.confirmConversationReset();return r()?i?e.chatRunId?`deferred`:`confirmed`:`cancelled`:t?`deferred`:`cancelled`}async function CE(e,t,n,r){switch(t){case`stop`:return oE(e,`abort`)?(await Kp(e,{scope:`session`}),`completed`):`failed`;case`new`:return e.createChatSession?await e.createChatSession()?`completed`:`cancelled`:(iE(e,`New Chat is unavailable.`),`failed`);case`reset`:{let t=sE(e);if(!t||!fE(e,t))return`failed`;let i=await SE(e);return i===`confirmed`?fE(e,t)?(await r.sendResetMessage(n?`/reset ${n}`:`/reset`,{previousDraft:r.previousDraft,restoreDraft:r.restoreDraft,target:t}),`completed`):`failed`:i}case`clear`:{if(!oE(e,`reset`))return`failed`;let t=sE(e);if(!t)return`failed`;let n=await SE(e);return n===`confirmed`?lE(e,t)?oE(e,`reset`)?await sT(e):`failed`:pE(e):n}case`compact`:if(!oE(e,`compact`))return`failed`;break;case`export-session`:return n.trim()?(iE(e,R(`chat.commandResults.exportPathUnsupported`)),`failed`):(iE(e,null),await e.exportCurrentChat?.()===`empty`&&(wE(e,R(`chat.commandResults.emptyExport`)),Np(e,!1,!1,{contentChanged:!0})),`completed`)}if(!e.client||!e.connected)return iE(e,`Gateway not connected`),wE(e,`Cannot run \`/${t}\`: Control UI is not connected to the Gateway.`),Np(e,!1,!1,{contentChanged:!0}),`failed`;let i=sE(e);if(!i)return`failed`;let a=()=>lE(e,i),o;try{o=await IT(i.client,i.sessionKey,t,n,{sessions:e.sessions,sessionAccessSnapshot:aE(e),readSessionAccessSnapshot:()=>aE(e),isCurrent:a,chatModelCatalog:e.chatModelCatalog,sessionsResult:e.sessionsResult,sessionsResultAgentId:e.sessionsResultAgentId,defaultAgentId:vt(e),agentId:i.agentId,ownsModelOverride:()=>uE(e,i)})}catch(n){return a()&&(iE(e,P(n)),wE(e,`Command \`/${t}\` failed unexpectedly.`),Np(e,!1,!1,{contentChanged:!0})),`failed`}return o.content&&a()&&wE(e,o.content),o.failed?(a()&&(iE(e,o.content||`Command /${t} failed.`),Np(e,!1,!1,{contentChanged:!!o.content})),`failed`):(o.trackRunId&&a()&&(e.chatRunId=o.trackRunId,e.chatStream=``,e.chatSending=!1),o.pendingCurrentRun&&e.chatRunId&&a()&&Qg(e,`/${t} ${n}`.trim(),e.chatRunId,ko(e.hello,e.client?.instanceId,e.selfUser)??void 0),o.modelChanged&&a()&&await e.refreshCurrentSessionTools?.(),o.action===`refresh`&&a()&&await e.refreshCurrentChat?.(),a()&&Np(e,!1,!1,{contentChanged:!!o.content}),`completed`)}function wE(e,t){yp(e,[...e.chatMessages,{role:`system`,content:t,timestamp:Date.now()}])}var TE,EE,DE;function OE(){return(OE=e((()=>{H(),Os(),fs(),is(),on(),se(),I(),B(),rE(),uT(),l_(),Zx(),ip(),Lp(),Qm(),TE=0,EE=6e4,DE=new WeakMap})))()}function kE(e){return(e?.appliedConfigHash??e?.configRevisionHash??e?.hash??null)||JSON.stringify(m(m(e?.runtimeConfig)?.mcp)?.servers??null)}var AE;function jE(){return(jE=e((()=>{bi(),Pr(),ll(),er(),Al(),H(),yo(),we(),Gs(),on(),fa(),se(),I(),B(),Rh(),Wx(),Dx(),Af(),rd(),Oo(),AE=class e{constructor(e){this.notify=e,this.patchTokens=new Map,this.effectiveTools=null,this.effectiveToolsErrorKey=null,this.effectiveToolsRequest=null,this.client=null,this.addDialogOpen=!1,this.addScope=`session`,this.addBusy=!1,this.addError=null,this.skillCatalog=new vu(e),this.library=new bd(e)}static async addMcpServer(e){let t=e.scope===`session`?{...e.config,enabled:!1}:e.config,n=`config`;try{let r=await e.patchGlobal(t);if(!r.ok)return{...r,stage:n};if(e.scope===`everywhere`)return{ok:!0};n=`session`;let i=await e.loadSessionOverrides();if(!i.ok)return{...i,stage:n};let a=zc(i.overrides,`mcpServers`,e.name,!0,!1),o=await e.patchSession(a);return o.ok?o:{...o,stage:n}}catch(e){return{ok:!1,error:P(e),stage:n}}}loadSkills(e,t,n){let r=e.runtimeConfig.state;!r.configSnapshot&&!r.configLoading&&e.runtimeConfig.ensureLoaded().catch(()=>void 0);let i=t.client,a=t.connectionEpoch;this.skillCatalog.load(i,a,n,()=>t.connected&&t.client===i&&t.connectionEpoch===a)}effectiveToolsKeys(e,t,n){let r=st({chatModelCatalog:t.chatModelCatalog,sessions:e.sessions,sessionsResult:t.sessionsResult},{agentId:n,sessionKey:t.sessionKey});return{cacheKey:`${r}\0config=${kE(e.runtimeConfig.state.configSnapshot??null)}`,requestKey:r}}loadEffectiveTools(e,t,n,r=!1){let i=t.client,a=t.sessionKey,{cacheKey:o,requestKey:s}=this.effectiveToolsKeys(e,t,n);if(!t.connected||!i||this.effectiveTools?.key===o||this.effectiveToolsRequest?.key===o||!r&&this.effectiveToolsErrorKey===o)return;let c=Symbol(`composer-effective-tools-request`),l=t.connectionEpoch;this.effectiveToolsRequest={key:o,owner:c};let u={chatModelCatalog:t.chatModelCatalog,client:i,connected:!0,sessions:e.sessions,sessionsResult:t.sessionsResult,toolsEffectiveError:null,toolsEffectiveLoading:!1,toolsEffectiveLoadingKey:null,toolsEffectiveResult:null,toolsEffectiveResultKey:null},d=()=>this.effectiveToolsRequest?.owner===c&&this.client===i&&t.client===i&&t.connected&&this.connectionEpoch===l&&t.connectionEpoch===l&&t.sessionKey===a&&this.effectiveToolsKeys(e,t,n).cacheKey===o;this.effectiveToolsErrorKey=null,this.notify(),Me(u,{agentId:n,sessionKey:a},{isCurrent:d}).then(()=>{d()&&(u.toolsEffectiveResult&&u.toolsEffectiveResultKey===s?this.effectiveTools={key:o,result:u.toolsEffectiveResult}:u.toolsEffectiveError&&(this.effectiveToolsErrorKey=o))}).catch(()=>{d()&&(this.effectiveToolsErrorKey=o)}).finally(()=>{this.effectiveToolsRequest?.owner===c&&(this.effectiveToolsRequest=null,this.client===i&&this.connectionEpoch===l&&this.notify())})}async patch(e,t,n){if(!t.connected||!t.client)return{ok:!1,error:R(`chat.composer.menu.offlineBlocked`)};let r=z(e.gateway.snapshot,{method:`sessions.patch`,params:{key:t.sessionKey,toolOverrides:n}});if(!r.allowed)return{ok:!1,error:r.reason};let i=t.sessionKey;if(this.patchTokens.has(i))return{ok:!1,error:R(`chat.composer.menu.savingBlocked`)};let a=t.client,o=Symbol(i);this.patchTokens.set(i,o);let s=()=>this.client===a&&t.client===a&&t.sessionKey===i&&this.patchTokens.get(i)===o;t.lastError=null,t.chatError=null,this.notify();try{if(!await Cx(t,i,{toolOverrides:n},L(t,i)))throw Error(R(`chat.composer.menu.offlineBlocked`));return{ok:!0}}catch(e){let n=P(e);if(s()){try{await jx(t)}catch{}s()&&(t.lastError=n,t.chatError=n,t.requestUpdate?.())}return{ok:!1,error:n}}finally{this.patchTokens.get(i)===o&&(this.patchTokens.delete(i),this.client===a&&this.notify())}}closeAddDialog(){this.addBusy||(this.addDialogOpen=!1,this.addError=null,this.notify())}addServerBlockedReason(e,t,n,r){let i=fi(e.gateway.snapshot);return!t.connected||!t.client?R(`chat.composer.menu.offlineBlocked`):i.canAdmin?r===`everywhere`?null:n?this.patchTokens.has(t.sessionKey)?R(`chat.composer.menu.savingBlocked`):null:R(`common.loading`):R(`chat.composer.menu.adminBlocked`)}async loadCurrentSessionOverrides(e,t,n){let r=()=>e.sessionKey===t&&ae(e,t).agentId===n;if(!r())return{ok:!1,error:R(`mcpServers.sessionChanged`)};try{await jx(e)}catch(e){return{ok:!1,error:P(e)}}if(!r())return{ok:!1,error:R(`mcpServers.sessionChanged`)};let i=e.sessions.state;if(i.error)return{ok:!1,error:i.error};let a=i.result?.sessions.find(e=>F(e.key,t));return!a||(i.agentId??void 0)!==n?{ok:!1,error:R(`mcpServers.sessionUnavailable`)}:{ok:!0,overrides:a.toolOverrides}}async submitAddServer(t,n,r,i){if(this.addBusy)return;let a=this.addServerBlockedReason(t,n,r,this.addScope);if(a){this.addError=a,this.notify();return}let o=i.name.trim();if(!Ho.test(o)){this.addError=R(`mcpServers.nameInvalid`),this.notify();return}let s=ba(i.target,i.transport);if(!s){this.addError=R(`mcpServers.targetInvalid`),this.notify();return}this.addBusy=!0,this.addError=null,this.notify();let c=n.sessionKey,l=ae(n,c).agentId,u;try{u=await e.addMcpServer({scope:this.addScope,name:o,config:s,patchGlobal:e=>Us(t.runtimeConfig,{buildPatch:t=>Ia(t,o,e),note:`composer connectors: add MCP server ${o}`}),loadSessionOverrides:()=>this.loadCurrentSessionOverrides(n,c,l),patchSession:e=>this.patch(t,n,e)})}finally{this.addBusy=!1}if(!u.ok){let e=Ne(u.error);this.addError=u.stage===`session`?R(`mcpServers.sessionEnableFailed`,{error:e}):e,this.notify();return}this.addDialogOpen=!1,this.notify()}renderAddServerDialog(e,t,n){if(!this.addDialogOpen)return G;let r=this.addServerBlockedReason(e,t,n,`everywhere`),i=this.addServerBlockedReason(e,t,n,this.addScope),a=R(`chat.composer.menu.addMcpServerTitle`),o=R(`chat.composer.menu.addMcpServerDescription`),s=R(this.addScope===`session`?`chat.composer.menu.scopeSessionHint`:`chat.composer.menu.scopeEverywhereHint`);return W`
      <openclaw-modal-dialog
        label=${a}
        description=${o}
        @modal-cancel=${e=>{if(this.addBusy){e.preventDefault();return}this.closeAddDialog()}}
      >
        <div class="exec-approval-card mcp-server-dialog">
          <div class="exec-approval-header">
            <div>
              <div class="exec-approval-title">${a}</div>
              <div class="exec-approval-sub">${o}</div>
            </div>
          </div>
          <div class="mcp-server-dialog__scope">
            <span>${R(`chat.composer.menu.scopeLabel`)}</span>
            ${Hl({value:this.addScope,options:[{value:`session`,label:R(`chat.composer.menu.scopeSession`)},{value:`everywhere`,label:R(`chat.composer.menu.scopeEverywhere`)}],ariaLabel:R(`chat.composer.menu.scopeLabel`),disabled:this.addBusy||r!==null,onChange:e=>{this.addScope=e,this.addError=null,this.notify()}})}
            <span class="mcp-server-dialog__scope-hint">${s}</span>
          </div>
          ${ml({busy:this.addBusy,disabled:i!==null,blockedReason:i,autofocus:!0,onSubmit:r=>void this.submitAddServer(e,t,n,r),onCancel:()=>this.closeAddDialog()})}
          ${this.addError?W`<div class="mcp-server-message mcp-server-message--error" role="alert">
                  ${this.addError}
                </div>`:G}
        </div>
      </openclaw-modal-dialog>
    `}props(e,t,n,r,i=!1,a=!1){(this.client!==t.client||this.connectionEpoch!==t.connectionEpoch)&&(this.client=t.client,this.connectionEpoch=t.connectionEpoch,this.skillCatalog.synchronize(t.client,t.connectionEpoch),this.patchTokens.clear(),this.effectiveTools=null,this.effectiveToolsErrorKey=null,this.effectiveToolsRequest=null);let o=t.client,s=t.connectionEpoch,c=t.sessionKey,l=()=>t.connected&&t.client===o&&t.connectionEpoch===s&&t.sessionKey===c;this.library.synchronize(o&&t.connected?{client:o,connectionEpoch:s,sessionKey:c,agentId:r,isCurrent:l}:null),a&&!this.library.result&&!this.library.loading&&!this.library.error&&this.library.load();let u=ua(e.gateway.snapshot,`skills.library.activate`,`operator.write`,{requireAdvertisement:!1}),d=e.runtimeConfig.state.configSnapshot?.runtimeConfig??null,f=fi(e.gateway.snapshot),p=t.connected&&!!t.client,m=da(e.gateway.snapshot,`tools.effective`)===!0;m&&i&&this.loadEffectiveTools(e,t,r);let h=m?this.effectiveToolsKeys(e,t,r).cacheKey:null,g=h!==null&&this.effectiveTools?.key===h?this.effectiveTools.result:null,_=h!==null&&this.effectiveToolsRequest?.key===h,v=h!==null&&this.effectiveToolsErrorKey===h,y=p&&n!==void 0&&d!==null,b=z(e.gateway.snapshot,{method:`sessions.patch`,params:{key:t.sessionKey,toolOverrides:null}}),x=p?y?b.allowed?this.patchTokens.has(t.sessionKey)?R(`chat.composer.menu.savingBlocked`):null:b.reason:R(`common.loading`):R(`chat.composer.menu.offlineBlocked`),S=x??(g?null:R(v?`chat.composer.menu.toolAccess.loadFailed`:`common.loading`)),C=p?f.canAdmin?null:R(`chat.composer.menu.adminBlocked`):R(`chat.composer.menu.offlineBlocked`);return{basePath:t.basePath,skills:this.skillCatalog.rows(r,n?.toolOverrides),skillsLoading:this.skillCatalog.isLoading(r),skillsError:this.skillCatalog.hasError(r),mcpServers:go(d)??[],toolsEffectiveResult:g,toolsEffectiveLoading:_,toolsEffectiveError:v,toolAccessMutationBlockedReason:S,webSearchBaseEnabled:Rd(d),mutationBlockedReason:x,canAdmin:f.canAdmin&&p,adminBlockedReason:C,addServerDialog:this.renderAddServerDialog(e,t,n),library:{result:this.library.result,loading:this.library.loading,busy:this.library.busy,error:this.library.error,notice:this.library.notice,canWrite:u,onReload:()=>{l()&&this.library.load(!0)},onRead:(e,t)=>{l()&&this.library.openRead(e,t)},onActivate:(e,t,n)=>{l()&&u&&this.library.activate(e,t,n)}},libraryDialog:this.library.read?ih({read:this.library.read,file:this.library.selectedFile,onFile:e=>{this.library.selectedFile=e,this.notify()},onClose:()=>{this.library.closeRead(),this.notify()}}):G,onLoadSkills:()=>{l()&&(this.loadSkills(e,t,r),this.library.load(!0))},onPatchToolOverrides:n=>void this.patch(e,t,n),onNavigate:(t,n)=>e.navigate(t,n),onAddServer:()=>{f.canAdmin&&p&&(this.addDialogOpen=!0,this.addScope=`session`,this.addError=null,this.notify())},...m?{onOpenToolAccess:()=>this.loadEffectiveTools(e,t,r,!0)}:{}}}}})))()}function ME(e){return e?[e.id,e.identity?.type,e.identity?.id,e.name,e.email,e.avatarUrl]:null}function NE(e,t){let{users:n}=Qo(e),r=Jr({snapshotUser:t.selfUser,presenceEntries:e?.presence,presenceInstanceId:t.selfInstanceId});return JSON.stringify([n.length>=2,ME(r),n.filter(e=>e.watchedSessions.includes(t.sessionKey)).map(ME)])}function PE(e,t,n){return e===t||NE(e,n)===NE(t,n)}function FE(){return(FE=e((()=>{eo()})))()}function IE(e,t){return t?(e.selectedChatSessionArchived=t.archived===!0,e.selectedChatSessionIncognito=t.incognito===!0,e.chatQueueModeOverride=t.queueMode,e.chatEffectiveQueueMode=t.effectiveQueueMode,!0):!1}async function LE(e,t,n){let r=await Jc(e,t,n);if(r?.blob&&(r.artifact.type!==`image`||!HE.test(r.blob.type.split(`;`,1)[0]?.trim().toLowerCase()??``)))return null;if(r?.encoding===`base64`&&r.artifact.type===`image`&&HE.test(r.artifact.mimeType??``)&&r.data)return{url:`data:${r.artifact.mimeType};base64,${r.data}`};let i=typeof r?.url==`string`?r.url.trim():``;if(!i)return null;let a=typeof r?.expiresAt==`string`?r.expiresAt.trim():void 0;return{url:i,...a?{expiresAt:a}:{},...r?.blob?{blob:r.blob}:{}}}function RE(e){e.lastError=null,e.lastErrorCode=null,e.chatError=null}function zE(e,t){let n=ry(e),r=t&&n.phase===`failed`?n.message:null;return{submitDisabledReason:t?r??R(`chat.thread.loading`):null,submitPending:t&&n.phase!==`failed`}}function BE(e,t,n){return co(e.settings.chatFollowUpMode,jo(n.configSnapshot?.runtimeConfig,{configNeedsApply:n.configNeedsApply,effectiveMode:e.chatEffectiveQueueMode,sessionMetadataLoaded:t!==void 0||e.chatEffectiveQueueMode!==void 0,sessionMode:e.chatQueueModeOverride}))}var VE,HE,UE;function WE(){return(WE=e((()=>{Fl(),H(),Xa(),Y(),VE=256,HE=/^image\/(?:png|jpeg|gif|webp|avif)$/u,UE=class{constructor(){this.lastBlocked=new Map}reset(){this.lastBlocked.clear()}resolve(e){if(e.catalog)return!1;if(e.session){let t=e.session.visibility===`draft`?e.session.sharingRole!==`admin`&&e.session.sharingRole!==`owner`:e.session.visibility!==void 0&&e.session.visibility!==`shared`&&e.session.sharingRole===`viewer`;return this.remember(e.sessionKey,t),t}return e.listLoading?this.lastBlocked.get(e.sessionKey)===!0:!1}remember(e,t){if(this.lastBlocked.delete(e),this.lastBlocked.set(e,t),this.lastBlocked.size<=VE)return;let n=this.lastBlocked.keys().next().value;n&&this.lastBlocked.delete(n)}}})))()}function GE(){return{realtimeTalkActive:!1,realtimeTalkStatus:`idle`,realtimeTalkDetail:null,realtimeTalkInputNotice:null,realtimeTalkUseSystemDefault:null,realtimeTalkInputLevel:new jm,realtimeTalkConversation:[],realtimeTalkVideoStream:null,realtimeTalkCameraDevices:[],realtimeTalkVideoCapable:!1,realtimeTalkVideoPending:!1,realtimeTalkCameraError:!1,realtimeTalkSession:null,realtimeTalkVoiceController:null,realtimeTalkConversationState:ig()}}function KE(e){e.realtimeTalkConversationState=ig(),e.realtimeTalkConversation=[]}function qE(e,t={}){let n=e.realtimeTalkSession;e.realtimeTalkVoiceController?.dispose(),e.realtimeTalkVoiceController=null,e.realtimeTalkSession=null,e.realtimeTalkUseSystemDefault=null,e.realtimeTalkActive=!1,e.realtimeTalkStatus=`idle`,e.realtimeTalkDetail=null,e.realtimeTalkInputNotice=null,e.realtimeTalkInputLevel.set(0),e.realtimeTalkVideoStream=null,e.realtimeTalkCameraDevices=[],e.realtimeTalkVideoCapable=!1,e.realtimeTalkVideoPending=!1,e.realtimeTalkCameraError=!1,t.preserveConversation?(e.realtimeTalkConversationState=Fh(e.realtimeTalkConversationState),e.realtimeTalkConversation=e.realtimeTalkConversationState.entries):KE(e),n?.stop()}function JE(e){e.realtimeTalkStatus===`error`&&qE(e)}function YE(e,t=()=>!0){let n=0,r=()=>e.realtimeTalkStatus===`error`,i=t=>{e.settings=br({talkCameraAutoEnable:t})},a=t=>{e.realtimeTalkDetail=P(t),e.realtimeTalkCameraError=!0,e.requestUpdate()},o=async t=>{let n=await Zh(()=>!1);e.realtimeTalkSession===t&&(e.realtimeTalkCameraDevices=n.devices,e.requestUpdate())},s=async(t,n={})=>{let o=e.realtimeTalkSession;if(o&&e.realtimeTalkVideoCapable&&!e.realtimeTalkVideoPending&&!r()){e.realtimeTalkVideoPending=!0,e.realtimeTalkCameraError=!1,e.realtimeTalkDetail=null,e.requestUpdate(),t||i(!1);try{t&&await o.switchCamera(Xr().realtimeTalkVideoDeviceId),await o.setVideoEnabled(t)}catch(t){if(e.realtimeTalkSession!==o||r())return;n.disableAutoEnableOnFailure&&i(!1),e.realtimeTalkVideoStream=null,a(t)}finally{e.realtimeTalkSession===o&&(e.realtimeTalkVideoPending=!1,e.requestUpdate())}}};e.resetRealtimeTalkConversation=()=>{KE(e)};let c=async(l=!1,u)=>{if(e.realtimeTalkUseSystemDefault=null,!t())return;if(!e.client||!e.connected){e.lastError=`Gateway not connected`,e.chatError=e.lastError,e.requestUpdate();return}let d=Xr(),f=l?void 0:d.realtimeTalkInputDeviceId?.trim()||void 0,{client:p,sessionKey:m}=e,h=u?e.realtimeTalkSession?.getTransport():void 0;if(u&&!h)throw Error(R(`chat.voice.selectionFailed`));if(u){let r=e.realtimeTalkSession,i=e.realtimeTalkVoiceController;e.realtimeTalkSession=null;let a=r?.stop();if(e.realtimeTalkVideoStream=null,e.realtimeTalkCameraDevices=[],e.realtimeTalkConversationState=Fh(e.realtimeTalkConversationState),e.realtimeTalkConversation=e.realtimeTalkConversationState.entries,n+=1,e.requestUpdate(),await a,e.realtimeTalkVoiceController!==i||e.client!==p||e.sessionKey!==m||!e.connected||!t())return}else{n=0,e.realtimeTalkVoiceController?.dispose();let t=new em({client:p,sessionKey:m,isCurrent:()=>e.realtimeTalkVoiceController===t&&e.client===p&&e.sessionKey===m&&e.connected,currentCall:()=>e.realtimeTalkSession,restart:e=>c(l,e),cancel:t=>{qE(e,{preserveConversation:!0}),e.realtimeTalkStatus=`error`,e.realtimeTalkDetail=t,e.requestUpdate()}});e.realtimeTalkVoiceController=t}let g=e.realtimeTalkVoiceController,_=u?`voice-${n}:`:``,v=u?e.realtimeTalkConversation.length:0,y=d.realtimeTalkVideoDeviceId?.trim()||void 0,b=d.talkCameraAutoEnable===!0,x=!1;e.realtimeTalkActive=!0,e.realtimeTalkStatus=`connecting`,e.realtimeTalkDetail=null,e.realtimeTalkInputNotice=null,e.realtimeTalkVideoCapable=!1,e.realtimeTalkVideoPending=!1,e.realtimeTalkCameraError=!1,e.realtimeTalkInputLevel.set(0),u||e.resetRealtimeTalkConversation();let S=t=>(...n)=>{e.realtimeTalkSession===C&&t(...n)},C=new qh(p,m,{onStatus:S((t,n)=>{e.realtimeTalkStatus=t,e.realtimeTalkDetail=t===`error`&&n?Ne(n):n??null,e.realtimeTalkCameraError=!1,e.realtimeTalkActive=t!==`idle`,(t===`idle`||t===`error`)&&(e.realtimeTalkInputNotice=null,e.realtimeTalkInputLevel.set(0)),e.requestUpdate(),t===`error`&&g?.failed(C),t===`listening`&&e.realtimeTalkVideoCapable&&b&&!x&&(x=!0,s(!0,{disableAutoEnableOnFailure:!0}))}),onInputNotice:S(t=>{e.realtimeTalkInputNotice=Ne(t),e.requestUpdate()}),onVideoCapability:S(t=>{e.realtimeTalkVideoCapable=t,e.requestUpdate()}),onInputLevel:S(t=>{e.realtimeTalkInputLevel.set(t)}),onTranscript:S(t=>{e.realtimeTalkConversationState=Kh(e.realtimeTalkConversationState,t.itemId===void 0?t:{...t,itemId:`${_}${t.itemId}`,order:t.order===void 0?void 0:v+t.order}),e.realtimeTalkConversation=e.realtimeTalkConversationState.entries,e.requestUpdate()}),onTranscriptOrder:S(t=>{e.realtimeTalkConversationState=xh(e.realtimeTalkConversationState,t.map(({itemId:e,order:t})=>({itemId:`${_}${e}`,order:v+t}))),e.realtimeTalkConversation=e.realtimeTalkConversationState.entries,e.requestUpdate()}),onVideoStream:S(t=>{if(t&&e.realtimeTalkStatus===`error`){C.setVideoEnabled(!1).catch(()=>void 0);return}e.realtimeTalkVideoStream=t,t&&(i(!0),e.realtimeTalkDetail=null,e.realtimeTalkCameraError=!1,o(C)),e.requestUpdate()}),onVideoError:S(e=>{r()||a(e)}),onTalkEvent:S(t=>{e.client===p&&e.sessionKey===m&&(t.type===`session.ready`?g?.ready(C):t.type===`session.closed`&&g?.failed(C))})},u?{voice:u.voice,voiceChangeId:u.changeId,transport:h}:{},{inputDeviceId:f,videoDeviceId:y});e.realtimeTalkSession=C;try{return await C.start(),e.realtimeTalkSession===C?C:void 0}catch(t){if(e.realtimeTalkSession!==C)return;if(u)throw t;let n=P(t);if(qE(e),e.realtimeTalkStatus=`error`,e.realtimeTalkDetail=n,t instanceof rg){let t=async()=>{if(e.realtimeTalkUseSystemDefault===t){if(e.realtimeTalkUseSystemDefault=null,!e.connected||e.client!==p||e.sessionKey!==m){e.requestUpdate();return}await c(!0)}};e.realtimeTalkUseSystemDefault=t}e.requestUpdate()}};e.toggleRealtimeTalk=async()=>{if(e.realtimeTalkSession||e.realtimeTalkActive){qE(e),e.requestUpdate();return}await c()},e.toggleRealtimeTalkCamera=async()=>{let t=e.realtimeTalkVideoStream===null;await s(t)},e.switchRealtimeTalkCamera=async()=>{let t=e.realtimeTalkSession,n=e.realtimeTalkVideoStream,i=e.realtimeTalkCameraDevices;if(!t||!n||i.length<2||e.realtimeTalkVideoPending)return;let o=n.getVideoTracks()[0]?.getSettings?.().deviceId?.trim()||Xr().realtimeTalkVideoDeviceId?.trim(),s=i[(i.findIndex(e=>e.deviceId===o)+1)%i.length];if(s){e.realtimeTalkVideoPending=!0,e.realtimeTalkCameraError=!1,e.realtimeTalkDetail=null,e.requestUpdate();try{await t.switchCamera(s.deviceId),e.realtimeTalkSession===t&&(e.settings=br({realtimeTalkVideoDeviceId:s.deviceId}))}catch(n){e.realtimeTalkSession===t&&!r()&&a(n)}finally{e.realtimeTalkSession===t&&(e.realtimeTalkVideoPending=!1,e.requestUpdate())}}}}function XE(){return(XE=e((()=>{Vr(),H(),on(),hh(),sh(),Mp(),um(),pm()})))()}function ZE(e,t=e.sessionKey,n=Dn(e)){let r=Yt(t),i=mn(t),a=(e,t)=>!!r&&Yt(e.key)===r&&(!i||(e.agentId??t)===n),o=e.sessionsResult?.sessions.find(t=>a(t,e.sessionsResultAgentId))??e.sessions?.state?.result?.sessions.find(t=>a(t,e.sessions?.state?.agentId));return o&&(e.sessions?.projectRows?.([o])[0]??o)}function QE(e,t=e.sessionKey,n=Dn(e)){let r=$g(e,t,n).filter(e=>!e.pendingRunId&&e.sendState!==`held`&&e.sendState!==`executing-command`).map(e=>({id:e.id,update:e=>({...e,sendState:`held`,sendError:R(`chat.providerReview.queuedInputHeld`)})}));return r.length===0||q(e).update(e,r)!==null}function $E(){return($E=e((()=>{H(),wo(),B(),Kg(),l_(),La()})))()}function eD(e){let t=cD.get(e)??{attempts:new Map,timers:new Map};return cD.set(e,t),t}function tD(e,t){return!t.host.connected||t.host.client!==e||t.connectionEpoch!==t.host.connectionEpoch}function nD(e){return!(e instanceof Yn)||!e.retryable?null:Math.min(Math.max(e.retryAfterMs??oD,100),sD)}function rD(e,t,n,r,i){let a=e.client;if(!e.connected||!a)return;let o=eD(a);if(o.timers.has(t))return;let s=(o.attempts.get(t)??0)+1,c=i?g({initialMs:n,maxMs:sD,factor:2,jitter:0},s):n;i?o.attempts.set(t,s):o.attempts.delete(t);let l={timer:setTimeout(()=>{o.timers.delete(t),tD(a,l)||r(l.host)},c),suppressGenericWake:i,connectionEpoch:e.connectionEpoch,host:e};o.timers.set(t,l)}function iD(e,t,n,r){let i=e.client;if(!i)return!1;let a=eD(i),o=a.timers.get(t);if(!o)return!1;let s=tD(i,o);return!s&&n&&(o.connectionEpoch=e.connectionEpoch,o.host=e),!r&&!s&&o.suppressGenericWake?!0:(clearTimeout(o.timer),a.timers.delete(t),(r||s)&&a.attempts.delete(t),!1)}function aD(e,t){let n=eD(e);n.timers.has(t)||n.attempts.delete(t)}var oD,sD,cD;function lD(){return(lD=e((()=>{v(),Br(),oD=500,sD=3e4,cD=new WeakMap})))()}function uD(e,t,n,r,i=!0){rD(e,N(t),n,e=>void pD(e,t,r),i)}async function dD(e,t,n,r,i=!1){let a=e.client,o=e.connectionEpoch;if(!a||!e.connected)return`blocked`;let s=(n.sendAttempts??0)===0&&n.sendRequestStartedAtMs===void 0;if(s&&n.queueMode&&n.sendState!==`unconfirmed`)return`send`;if(s){let n=!mn(t.sessionKey)||e.sessions.state.agentId===t.agentId?e.sessions.state.result?.sessions.find(e=>F(e.key,t.sessionKey)):void 0;if(n&&S(n))return`blocked`}let c=[e,t,n,a,o,n=>uD(e,t,n,r)],l=()=>e.connected&&e.client===a&&e.connectionEpoch===o,u;try{u=await M(()=>import(`./chat-outbox-receipts-Cg60kvyq.js`),__vite__mapDeps([46,1,4,2,3,5,6,7,8,9,10,11,12,13]),import.meta.url)}catch(n){return l()&&(xy(e,t.sessionKey,t.agentId,P(n)),e.requestUpdate?.()),`blocked`}if(!l())return`blocked`;let{readCurrentStoredChatHistory:d,isInterruptedChatInput:f}=u,p=await d(...c);if(typeof p!=`string`&&f(p,n)&&(n.queueMode===`steer`||n.queueMode===`interrupt`||!(V(e,t.sessionKey,t.agentId)&&Ah(e))))return`send`;if(p===`blocked`||p===`continue`||n.sendState===`unconfirmed`&&!i)return p===`continue`?`continue`:`blocked`;if(V(e,t.sessionKey,t.agentId)&&Ah(e))return`blocked`;if((n.sendAttempts??0)>0){let r=await d(...c);return r===`blocked`||r===`continue`?r:Yg(e,e=>{let t=e.chatQueue.find(e=>e.id===n.id);return t?.sendState===`sending`&&Bc(t,{...n,sendState:`sending`})})?`blocked`:i?`send`:(t_(e,n.id,e=>({...e,sendError:`Reconnected before delivery was confirmed. Check the conversation — retry only if your message didn't arrive.`,sendState:`unconfirmed`}))&&xy(e,t.sessionKey,t.agentId,Cy,{inline:!n.localCommandName}),`blocked`)}return`send`}async function fD(e,t,n){for(;;){let r=e.host;if(ZE(r,t.sessionKey,t.agentId)?.providerReview)return QE(r,t.sessionKey,t.agentId),`blocked`;if(!r.connected||!r.client||gy(r,t.sessionKey))return`blocked`;let i=ja(r,t);if(!i)return`empty`;let a=i.queue.find(t=>e.freshAdmissions.has(t.id)&&(t.queueMode||!t.intent&&e.pendingOptions.get(t.id)?.allowActiveRunSend))??i.queue.find(t=>e.freshAdmissions.has(t.id)||t.sendState!==`failed`||t.localCommandName);if(!a)return`empty`;let o=e.freshAdmissions.has(a.id),s=o?e_(r,a.id)??a:a;if(s.sendState===`failed`&&!o)return`empty`;if(!o&&q(r).hasPendingSubmission(i,a)||s.sendState===`held`||s.sendState===`unconfirmed`&&(!s.sendRunId||s.localCommandName)||s.sendState===`waiting-model`&&!e.pendingOptions.has(s.id)||rm(r,s.id))return q(r).syncHost(r),`blocked`;let c=V(r,i.sessionKey,i.agentId);if(s.localCommandName){let t=(e,t)=>t_(r,s.id,n=>({...n,sendError:t,sendState:e}));if(!c||Ah(r))return e.waitingForVisibleOwner=!c,e.freshAdmissions.delete(s.id),e.pendingOptions.delete(s.id),`blocked`;if(q(r).syncHost(r),s.localCommandName===`reset`){if((s.sendAttempts??0)>0||s.sendRequestStartedAtMs!==void 0)return t(`unconfirmed`,Cy),`blocked`;let a=sE(r);if(!a)return t(`failed`,`The Gateway connection changed. Retry the command.`),`blocked`;let o=dE(r,a);if(!o.allowed)return t(`failed`,o.reason),n.setChatError(r,o.reason),`blocked`;let c=await SE(r,{sessionKey:i.sessionKey,...i.agentId?{agentId:i.agentId}:{}});if(c===`deferred`)return t(`waiting-idle`),`blocked`;if(c===`cancelled`){if(!q(r).remove(r,s.id))return`blocked`;continue}let l=dE(r,a);if(!l.allowed)return t(`failed`,l.reason),n.setChatError(r,l.reason),`blocked`;e.pendingOptions.set(s.id,{...e.pendingOptions.get(s.id),target:a});let u=await n.sendQueuedChatMessage(r,s.id,e.pendingOptions.get(s.id),i.sessionKey);if(e.outcomes.set(s.id,u),e.pendingOptions.delete(s.id),u!==`sent`)return`blocked`;continue}let a=e.freshAdmissions.delete(s.id);if(e.pendingOptions.delete(s.id),!a){let e=await dD(r,i,s,n);if(e===`blocked`)return`blocked`;if(e===`continue`)continue}if(gy(r,i.sessionKey))return`blocked`;let o=t(`executing-command`);if(!o)return`blocked`;let l=r.client,u=r.connectionEpoch,d=()=>r.connected&&r.client===l&&r.connectionEpoch===u&&V(r,i.sessionKey,i.agentId),f=(e,n=!1)=>{let a=t(`failed`,e);return(!a||n)&&xy(r,i.sessionKey,i.agentId,a?e:X),`blocked`};try{let e=await CE(r,o.localCommandName??s.localCommandName,o.localCommandArgs??``,{sendResetMessage:(e,t)=>n.sendResetSlashCommand(r,e,t)});if(e===`deferred`)return t(`waiting-idle`),`blocked`;if(e===`failed`){let e=d(),t=(e?r.lastError:null)??`Command /${s.localCommandName} failed.`,n=!V(r,i.sessionKey,i.agentId);return f(t,!e&&n)}if(e===`uncertain`){let e=ja(r,i),t=e?.queue.findIndex(e=>e.id===s.id)??-1,a=t>=0?e?.queue[t+1]:void 0;if(a&&!t_(r,a.id,e=>({...e,sendError:_D,sendState:`unconfirmed`})))return n.setChatError(r,X),`blocked`}if(!q(r).remove(r,s.id))return xy(r,i.sessionKey,i.agentId,X),`blocked`;if(e===`uncertain`)return`blocked`;d()&&n.setChatError(r,null)}catch(e){return f(P(e),!0)}continue}if(mn(i.sessionKey)&&!i.agentId)return e.freshAdmissions.delete(s.id),e.pendingOptions.delete(s.id),`blocked`;let l=e.freshAdmissions.delete(s.id),u=e.pendingOptions.get(s.id),d=l&&s.sendState===`unconfirmed`;if(!l||d||!c){let e=await dD(r,i,a,n,d);if(e===`blocked`)return`blocked`;if(e===`continue`)continue}let f=ja(r,t),p=l?e_(r,s.id):f?.queue.find(e=>e.id===s.id);if(!f||!p||!Bc(p,s)){e.pendingOptions.delete(s.id);continue}q(r).syncHost(r);let m=await n.sendQueuedChatMessage(r,s.id,c?u:{...u,routingSessionKey:void 0},i.sessionKey);if(e.outcomes.set(s.id,m),e.pendingOptions.delete(s.id),m===`pending`){let n=ja(r,t)?.queue.find(e=>e.id===s.id);if(!n||n.orderKey!==s.orderKey)continue;return!u?.pendingSettings&&e.freshAdmissions.size===0&&(e.rerun=!1),`blocked`}}}async function pD(e,t,n,r,i,a){let o=e.client;if(!e.connected||!o)return;let s=N(t),c=vD.get(o)??new Map;vD.set(o,c);let l=V(e,t.sessionKey,t.agentId);if(iD(e,s,l,r))return;let u=c.get(s);if(u){let n=u.host===e,s=!u.owner.host.connected||u.owner.host.client!==o||u.owner.connectionEpoch!==u.owner.host.connectionEpoch;return(!u.host.connected||u.host.client!==o||!V(u.host,t.sessionKey,t.agentId)&&l)&&(u.host=e,u.rerun||=u.waitingForVisibleOwner===!0&&l),u.rerun||=(a??n)||!!r||s,r&&i&&u.pendingOptions.set(r,i),r&&u.freshAdmissions.add(r),!r&&u.pendingOptions.size?void 0:(await u.promise,r?u.outcomes.get(r):void 0)}let d={owner:{host:e,connectionEpoch:e.connectionEpoch},freshAdmissions:new Set(r?[r]:[]),host:e,outcomes:new Map,pendingOptions:new Map(r&&i?[[r,i]]:[]),promise:Promise.resolve(),rerun:!1};c.set(s,d),d.promise=(async()=>{do d.rerun=!1,d.waitingForVisibleOwner=!1,d.owner={host:d.host,connectionEpoch:d.host.connectionEpoch},await fD(d,t,n);while(d.rerun)})();try{return await d.promise,aD(o,s),r?d.outcomes.get(r):void 0}finally{c.get(s)===d&&c.delete(s)}}async function mD(e,t,n){let r=e.client;if(!e.connected||!r)return;q(e).syncHost(e,{requestUpdate:!1});let i=n?rt(n.payload):void 0;if(n&&!i)return;let a=Fa(e).filter(e=>!i||F(e.sessionKey,i.key)&&(!mn(e.sessionKey)||i.agentId!==null&&e.agentId===f(i.agentId))),o=gD.get(r)??new WeakSet;gD.set(r,o);let s=n?!o.has(n):void 0;n&&a.length>0&&o.add(n),await Promise.allSettled(a.filter(e=>!n||s||vD.get(r)?.has(N(e))).map(n=>pD(e,n,t,void 0,void 0,s)))}async function hD(e,t){let n=Fa(e).find(t=>V(e,t.sessionKey,t.agentId));n&&await pD(e,n,t,void 0,void 0,!0)}var gD,_D,vD;function yD(){return(yD=e((()=>{lo(),Vo(),Cs(),on(),I(),B(),Mn(),OE(),Kg(),lD(),$E(),l_(),wy(),Gm(),Lp(),n(),gD=new WeakMap,_D=`A preceding /clear may have completed. Review the current conversation before retrying.`,vD=new WeakMap})))()}function bD(e,t,n,r,i){return JSON.stringify([t,e.sessionKey,yd(n.trim(),r,void 0,i)])}function xD(e,t,n,r,i,a=`none`){return yd(e.chatMessage,e.chatAttachments,void 0,e.chatMentions,e.chatReplyTarget)===yd(t,n,void 0,r,i)?(e.chatMessage=``,e.chatMentions=[],e.chatReplyTarget=null,a!==`all`&&(e.chatAttachments=a===`annotations`?e.chatAttachments.filter(e=>e.browserAnnotation||e.selectionAnnotation):[]),sp(e),{previousAttachments:n,previousDraft:t,previousMentions:r,previousReplyTarget:i}):{}}function SD(e){return e.map(e=>{let t=Sg(e);return{...e,...t?{dataUrl:t}:{}}})}function CD(e){return`chatComposerFallbackByScope`in e&&typeof e.chatComposerFallbackByScope==`object`&&e.chatComposerFallbackByScope!==null?e:void 0}function wD(e,t,n){let r=CD(e);return{client:e.client,clientGeneration:e.client?.connectionGeneration,owner:e.captureComposerRecoveryOwner?.(),...n?{composer:{...n,goalMode:e.chatGoalDraftMode,...r?{fallbackOwnership:hT(r,t,{message:n.draft,mentions:n.mentions,replyTarget:n.replyTarget,attachments:n.attachments})}:{}}}:{},connectionEpoch:e.connectionEpoch,scope:t}}function TD(e,t){return e.client===t.client&&e.connectionEpoch===t.connectionEpoch&&e.client?.connectionGeneration===t.clientGeneration}function ED(e,t){return TD(e,t)&&V(e,t.scope.sessionKey,t.scope.agentId)}function DD(e,t){let n=t.composer?.fallbackOwnership,r=t.owner?t.owner.resolveOwner():e;if(!r||!TD(e,t)||r.client!==t.client)return!1;let i=CD(r);return i?_T(i,n):!1}function OD(e,t){let n=t.composer?.fallbackOwnership,r=t.owner?t.owner.resolveOwner():e,i=r&&CD(r);return!!(n&&i&&gT(i,n))}function kD(e,t,n){let r=t.owner?.resolveOwner(),i=[];for(let t of r&&r!==e?[e,r]:[e]){i.push(t.chatAttachments);for(let e of Object.values(CD(t)?.chatComposerFallbackByScope??{}))i.push(e.attachments)}let a=t.owner?.retainedAttachmentIds(n??[]);Og(n?.filter(e=>!a?.has(e.id))??[],i)}function AD(e,t){let n=t?.filter(e=>e.browserAnnotation||e.selectionAnnotation);return!!(n?.length&&n.length===e.chatAttachments.length&&n.every((t,n)=>t.id===e.chatAttachments[n]?.id&&t.browserAnnotation===e.chatAttachments[n]?.browserAnnotation&&t.selectionAnnotation===e.chatAttachments[n]?.selectionAnnotation))}function jD(e,t){let n=t.composer;if(!n)return!0;if(!TD(e,t))return n.attachments.length===0||OD(e,t);let r=t.owner?t.owner.resolveOwner():e;if(!r)return!1;if(r.client!==t.client)return n.attachments.length===0||OD(e,t);let i=CD(r);if(r.canRestoreComposer?.()===!1||!V(r,t.scope.sessionKey,t.scope.agentId)){if(!i)return n.attachments.length===0;let e=mT(i,t.scope,{message:n.draft,mentions:n.mentions,replyTarget:n.replyTarget,attachments:n.attachments});return n.fallbackOwnership=e,n.attachments.length===0||e!==void 0}if(r.chatAttachments.length>0&&!AD(r,n.attachments))return DD(e,t),n.attachments.length===0;let a=ND(r,{previousAttachments:n.attachments,previousDraft:n.draft,previousMentions:n.mentions,previousReplyTarget:n.replyTarget,previousGoalDraftMode:n.goalMode});a.draft&&(r.chatMessage=n.draft,r.chatMentions=n.mentions??[],r.chatReplyTarget=n.replyTarget??null),a.attachments&&(r.chatAttachments=n.attachments);let o=n.attachments.length===0||a.attachments;return a.complete||DD(e,t),r!==e&&r.requestUpdate?.(),o}function MD(e,t,n,r){if(!n){jD(e,t)||kD(e,t,r);return}TD(e,t)&&DD(e,t),OD(e,t)||kD(e,t,r)}function ND(e,t){let n=!e.chatMessage.trim()&&!e.chatReplyTarget&&(!e.chatGoalDraftMode||e.chatGoalDraftMode===t.previousGoalDraftMode)&&(e.chatAttachments.length===0||AD(e,t.previousAttachments)),r=!!(t.previousAttachments?.length&&n),i=t.previousDraft!=null&&n;return{attachments:r,draft:i,complete:(!t.previousDraft?.trim()||i)&&(!t.previousAttachments?.length||r)}}function PD(e,t,n){let r=ND(e,n),i=q(e).remove(e,t.id);return i?(r.draft&&(e.chatMessage=n.previousDraft??``,e.chatMentions=n.previousMentions??[],e.chatReplyTarget=n.previousReplyTarget??null),r.attachments&&(e.chatAttachments=n.previousAttachments??[]),r.attachments||en(i_(e,i.attachments)),!0):!1}function FD(e,t,n={}){let r=ND(e,n);return e.canRestoreComposer?.()===!0&&V(e,t.sessionKey??e.sessionKey,t.agentId)&&(n.previousDraft!==void 0||n.previousAttachments!==void 0)&&r.complete&&PD(e,t,n)}function ID(){return(ID=e((()=>{I(),Ig(),yT(),Kg(),l_(),Ld(),mp()})))()}function LD(e){let t=e.indexOf(`,`);if(!e.startsWith(`data:`)||t<0)return null;let[n,...r]=e.slice(5,t).split(`;`);if(!n||r.pop()!==`base64`||r.some(e=>!/^[^=]+=[\s\S]*$/.test(e)))return null;let i=e.slice(t+1);return i&&!/[\r\n\u2028\u2029]/.test(i)?{mimeType:n,content:i}:null}function RD(e){return e?.length?e.map(e=>{let t=Sg(e),n=t?LD(t):null;if(!n)throw Error(R(`chat.sendErrors.outboxPayloadMissing`));return{type:n.mimeType.startsWith(`image/`)?`image`:`file`,mimeType:n.mimeType,fileName:e.fileName,...e.origin?{origin:e.origin}:{},content:n.content}}):void 0}function zD(){return(zD=e((()=>{H(),Ig()})))()}async function BD(e,t){t.attachments?.length&&fn(e.uploadConfig);let n=UD(e,t);if(ZE(e,n.sessionKey,n.selectedAgentId)?.providerReview)throw Error(R(`chat.providerReview.pausedBody`));let r=t.sessionId??(t.intent?void 0:n.sessionId),i=!(t.intent||!r||e.reconnectResumeSessionId!==r),a=await e.client.request(`chat.send`,{sessionKey:n.sessionKey,...mn(n.sessionKey)&&n.selectedAgentId?{agentId:n.selectedAgentId}:{},...r?{sessionId:r}:{},...i?{__controlUiReconnectResume:!0}:{},message:t.message,...t.workContext?{workContext:t.workContext}:{},...t.mentions?.length?{mentions:t.mentions}:{},...t.intent?{intent:t.intent}:{},deliver:!1,...t.replyToId?{replyToId:t.replyToId}:{},...t.queueMode?{queueMode:t.queueMode}:{},...t.expectedLeafEntryId===void 0?{}:{expectedLeafEntryId:t.expectedLeafEntryId},idempotencyKey:t.runId,attachments:RD(t.attachments)});return i&&(e.reconnectResumeSessionId=null),_g(a,t.runId)}function VD(e){if(!(e.chatLoading||oy(e)))return e.chatDisplayedLeafEntryId===null?null:e.chatDisplayedLeafEntryId?.trim()||void 0}function HD(e){return e instanceof Yn&&s(e.details)?.reason===WD}function UD(e,t){let n=t.sessionKey??e.sessionKey,r=t.agentId?f(t.agentId):Dn(e),i=e.currentSessionId,a=n===e.sessionKey&&(!mn(n)||r!==void 0&&r===Dn(e))&&typeof i==`string`&&i.trim()?i.trim():void 0;return{sessionKey:n,...r?{selectedAgentId:r}:{},...a?{sessionId:a}:{}}}var WD;function GD(){return(GD=e((()=>{Br(),H(),B(),Dt(),zD(),Y(),$E(),yg(),WD=`active-leaf-changed`})))()}function KD(e,t,n,r=t.sendSubmittedAtMs,i={}){r!=null&&gp(e,`control-ui.chat.send`,{phase:n,durationMs:wp(Ep()-r),runId:t.sendRunId,sessionKey:t.sessionKey,agentId:t.agentId,sendAttempts:t.sendAttempts??0,sendState:t.sendState,...i},{console:!1,maxBufferedEventsForType:40})}function qD(e,t){if(!t||typeof t!=`object`)return;let n=t,r=$D.find(e=>e===n.phase),i=j(n.runId);if(!r||!i)return;let a=e.chatSendTimingsByRun?.get(i),o=Ep(),s=b(n.ackToPhaseMs),c=b(n.receivedToPhaseMs),l=b(n.dispatchStartedToPhaseMs),u=b(n.postDispatchMs),d=a?.submittedAtMs===void 0?s:wp(o-a.submittedAtMs);if(d===void 0)return;let f=r===`first-assistant-event`&&d>=eO,p={};for(let e of[`provider`,`model`,`agentRunId`]){let t=j(n[e]);t&&(p[e]=t)}gp(e,`control-ui.chat.send`,{phase:`server-${r}`,durationMs:d,runId:i,sessionKey:a?.sessionKey??j(n.sessionKey),agentId:a?.agentId??j(n.agentId),sendAttempts:a?.sendAttempts??0,sendState:a?.sendState,ackStatus:a?.ackStatus,serverPhase:r,...s===void 0?{}:{serverAckToPhaseMs:s},...c===void 0?{}:{serverReceivedToPhaseMs:c},...l===void 0?{}:{serverDispatchStartedToPhaseMs:l},...u===void 0?{}:{serverPostDispatchMs:u},...p,...f?{slow:!0}:{}},{console:f,warn:f,maxBufferedEventsForType:40})}function JD(e,t,n,r){(e.chatSendTimingsByRun??=new Map).set(n,{runId:n,sessionKey:t.sessionKey,agentId:t.agentId,sendAttempts:t.sendAttempts??0,sendState:t.sendState,submittedAtMs:t.sendSubmittedAtMs??r,requestStartedAtMs:r})}function YD(e,t,n,r,i){let a=e.chatSendTimingsByRun??=new Map,o=a.get(t),s=o?.submittedAtMs??r.sendSubmittedAtMs??i,c={...o??{sendAttempts:r.sendAttempts??0,sendState:r.sendState,submittedAtMs:s,requestStartedAtMs:i},runId:n.runId,sessionKey:o?.sessionKey??r.sessionKey,agentId:o?.agentId??r.agentId,ackAtMs:Ep(),ackStatus:n.status};n.runId!==t&&a.delete(t),a.set(n.runId,c)}function XD(e){let t=e.serverTiming;return{...typeof t?.receivedToAckMs==`number`?{serverReceivedToAckMs:t.receivedToAckMs}:{},...typeof t?.loadSessionMs==`number`?{serverLoadSessionMs:t.loadSessionMs}:{},...typeof t?.prepareAttachmentsMs==`number`?{serverPrepareAttachmentsMs:t.prepareAttachmentsMs}:{}}}function ZD(e){return typeof e.sendSubmittedAtMs==`number`&&(e.sendState===`waiting-model`||e.sendState===`waiting-idle`||e.sendState===`submitting`||e.sendState===`sending`||e.sendState===`waiting-reconnect`)}function QD(e,t,n=t.sendSubmittedAtMs){let r=t.sessionKey??e.sessionKey,i=t.sendRunId;i&&n!=null&&Sp(e,()=>{if(!V(e,r,t.agentId))return;let a=$g(e,r,t.agentId).find(e=>e.id===t.id&&e.sendRunId===i);a&&ZD(a)&&KD(e,a,`pending-painted`,n)})}var $D,eO;function tO(){return(tO=e((()=>{T(),I(),l_(),hp(),$D=[`dispatch-started`,`model-selected`,`agent-run-started`,`first-assistant-event`,`dispatch-completed`,`post-dispatch-completed`],eO=1500})))()}function nO(e,t,n,r,i=Ep(),a,o,s,c,l,u,d,f){let m=xo(t,d),h=!!(n&&n.length>0);if(!m.text&&!h)return null;let g=_s(e,e.sessionKey),_=ko(e.hello,e.client?.instanceId,e.selfUser);return{item:{id:p(),text:l?t:m.text,...m.mentions?{mentions:m.mentions}:{},...f?{workContext:f}:{},createdAt:Date.now(),...s===void 0?{}:{orderKey:s},attachments:h?n:void 0,refreshSessions:r,sendAttempts:0,sendRunId:p(),sendState:a,...c?{queueMode:c}:{},...l?{intent:l,...e.currentSessionId?{sessionId:e.currentSessionId}:{}}:{},...l&&u!==void 0?{expectedLeafEntryId:u}:{},sendSubmittedAtMs:i,...g.scope,..._?{sender:_}:{},...o?{replyToId:o}:{}},admission:g}}function rO(e,t){let n=t.sendSubmittedAtMs??Ep(),r=q(e).keep(e,{sessionKey:t.sessionKey,agentId:t.agentId},t);return KD(e,r,`pending-visible`,n),(r.sendState===`waiting-model`||r.sendState===`waiting-reconnect`)&&KD(e,r,r.sendState,n),QD(e,r,n),Np(e,!0,!0,{source:`manual`}),r}function iO(e){return e.connected&&e.client?`waiting-idle`:`waiting-reconnect`}function aO(e,t=!0){let n=e.client,r=e.connectionEpoch;return()=>(!t||e.connected)&&e.client===n&&e.connectionEpoch===r}function oO(e,t,n){return n?.expectedLeafEntryId===void 0?n?.routingSessionKey&&V(e,t.sessionKey??e.sessionKey,t.agentId)?VD(e):void 0:n.expectedLeafEntryId}function sO(e,t,n,r){let i=t.sessionKey??n;if(!e.connected||!e.client||!V(e,i,t.agentId)||!e.chatLoading&&!oy(e))return;let a=aO(e),o=e.sessions,s=ry(e);return s.phase===`failed`?Promise.resolve(null):(s.phase===`in-flight`?s.promise:ZC(e,{startup:oy(e),deferBranches:!0})).then(n=>{let s=e_(e,t.id);return!n||!a()||e.sessions!==o||!V(e,i,t.agentId)||!s||!Bc(s,t)||rm(e,t.id)?null:{item:s,expectedLeafEntryId:oO(e,s,r)}})}function cO(e,t,n,r){return t===`memory`?q(e).change(e,n,r,!0):t_(e,n,r)}function lO(e,t,n){return(r,i)=>cO(e,t,n,e=>e.sendState===`held`?e:{...e,sendError:i,sendState:r})}function uO(e,t,n,r,i){let a=i?.routingSessionKey??r,o=lO(e,n,t.id),s=(n=t.agentId)=>V(e,a,n),c=e_(e,t.id);if(!c)return`failed`;if(c.sendState===`held`||c.sendState===`unconfirmed`&&!c.sendRunId||ay(e,a))return`pending`;if(c.workContextUnavailable){let t=R(`chat.messages.attachedContext.restoreFailed`);return o(`failed`,t),xy(e,a,c.agentId,t),`failed`}if(ZE(e,a,c.agentId)?.providerReview)return QE(e,a,c.agentId),`pending`;let l=!!(c.queueMode||i?.allowActiveRunSend);return gy(e,a)||i?.routingSessionKey&&!s(c.agentId)||!l&&s(c.agentId)&&(Ah(e)||Mh(e))?o(iO(e))?`pending`:(J(e,X),`failed`):c}function dO(e,t,n=t.sessionKey??e.sessionKey){return e.connected&&!!e.client&&!e.chatLoading&&!oy(e)&&!ay(e,n)&&!Ah(e)&&!Sx(e,n,t.agentId)&&V(e,n,t.agentId)&&e.chatQueue[0]?.id===t.id}function fO(e,t){e.chatSendingScopeKey===N(t)&&(e.chatSendingScopeKey=null,e.chatSending=!1)}function pO(e,t,n,r,i){let a=Uu(n,e.hello?.policy);if(a===void 0)return!1;let o=lO(e,i?.storageMode??`durable`,t.id);return FD(e,t,i)||o(`failed`,a),xy(e,r,t.agentId,a),!0}function mO(e,t,n,r,i,a,o){let s=n.id,{sessionKey:c}=a,l=i?.storageMode??`durable`,u=lO(e,l,s),d=HD(r),f=d?R(`chat.sendErrors.activeLeafChanged`):hd(r);if(e_(e,s)?.sendState===`held`)return KD(e,n,`failed`,n.sendSubmittedAtMs,{error:f}),`pending`;if(r instanceof ri)return FD(e,n,i)||u(`failed`,f),xy(e,c,n.agentId,f),KD(e,n,`failed`,n.sendSubmittedAtMs,{error:f}),`failed`;if(!d&&(r instanceof Yn?r.retryable:/gateway (?:not connected|closed)|websocket|disconnected/i.test(f))){let a=r instanceof Error&&!(r instanceof Yn)&&r.message===`gateway not connected`,u=nD(r),d=a||u!==null,p=d?{sendAttempts:t.sendAttempts,sendRequestStartedAtMs:t.sendRequestStartedAtMs}:{};if(l===`memory`){let t=d&&FD(e,n,i);return t||cO(e,l,s,e=>({...e,...p,sendError:d?f:Cy,sendState:d?`failed`:`unconfirmed`})),xy(e,c,n.agentId,t?f:X),KD(e,n,`failed`,n.sendSubmittedAtMs,{error:t?f:X}),t?`failed`:`pending`}if(!t_(e,s,e=>({...e,...p,sendError:f,sendState:`waiting-reconnect`}))){let t=a&&FD(e,n,i);return t||t_(e,s,e=>({...e,sendError:X,sendState:`failed`})),xy(e,c,n.agentId,X),KD(e,n,`failed`,n.sendSubmittedAtMs,{error:X}),t?`failed`:`pending`}return V(e,c,n.agentId)&&J(e,u===null?`Message will send when the Gateway reconnects.`:`The Gateway asked us to retry this message shortly.`),u!==null&&o(u),KD(e,n,`waiting-reconnect`,n.sendSubmittedAtMs,{error:f}),`pending`}fO(e,a);let p=i?.restoreOnTerminalFailure===!0&&FD(e,n,i);return p||u(`failed`,f),V(e,c,n.agentId)&&d&&Promise.all([ZC(e),WS(e)]),xy(e,c,n.agentId,f,{inline:l===`durable`&&!p}),KD(e,n,`failed`,n.sendSubmittedAtMs,{error:f}),`failed`}async function hO(e,t,n,r){let i=n;for(;await i;){let n=Sx(e,t,r);if(!n||n===i)return!0;i=n}return!1}async function gO(e,t,n){let r=t.id,i=aO(e),a=t,o=a.sessionKey??n,s=jp(e,Ft(e,o,a.agentId)),c=await lp(e,{...a,sessionKey:o}),l=e_(e,r);if(!i()||!s()||!l||!Bc(l,a)||rm(e,r))return c.status===`ready`&&!a.attachmentPayload&&dp(c.update),`pending`;if(c.status===`failed`){let t=Jf(l,c.reason);return t_(e,r,()=>t),xy(e,o,a.agentId,t.sendError),`failed`}let u={...a,...c.update};return u.attachmentPayload?.key!==a.attachmentPayload?.key&&u.sendState===`unconfirmed`?(t_(e,r,()=>u),`pending`):(!a.attachmentPayload||a.attachmentStorageError)&&!t_(e,r,()=>u)?(a.attachmentPayload||dp(c.update),`pending`):u}function _O(){return(_O=e((()=>{Br(),H(),Ua(),is(),Pa(),lo(),Cs(),I(),B(),o(),GS(),Y(),ew(),Kg(),lD(),$E(),l_(),ID(),GD(),wy(),tO(),Dx(),Kf(),Ru(),up(),hp(),Gm(),Lp(),Qm(),oo()})))()}async function vO(e,t,n,r,i,a){let o=i?.routingSessionKey??r,s=lO(e,n,t.id),c=(n=t.agentId)=>V(e,o,n),l=new Set,u=i?.pendingSettings??Sx(e,o,t.agentId),d=u?e_(e,t.id):t;for(;u&&!l.has(u);){if(d?.sendState===`held`||d?.sendState===`unconfirmed`&&!d.sendRunId)return`pending`;d?.sendState!==`waiting-model`&&(d=s(`waiting-model`),d||J(e,X)),e.requestUpdate?.();let n=await u;if(l.add(u),d=e_(e,t.id),!d)return`failed`;if(d.sendState===`held`||d.sendState===`unconfirmed`&&!d.sendRunId)return`pending`;if(!n)return!(c(d.agentId)&&FD(e,d,i))&&!s(`failed`,`Chat settings update was interrupted. Review and retry when ready.`)&&J(e,X),e.requestUpdate?.(),`failed`;u=Sx(e,o,d.agentId)}return l.size&&(d=s(iO(e))),d?(l.size&&e.requestUpdate?.(),a(d)):(J(e,X),`failed`)}async function yO(e,t,n,r=e.sessionKey,i=!0){let a=n?.storageMode??`durable`,o=e_(e,t),s=o?.localCommandName===`reset`&&!!n?.target;if(!o||o.pendingRunId||o.localCommandName&&!s)return`failed`;let c=o.sessionKey??r,l=o.agentId,u=()=>!n?.canDispatch||n.canDispatch()?!0:(lO(e,a,t)(`failed`,Za),xy(e,c,l,Za),!1);if(!u())return`failed`;let d=oO(e,o,n),f=sO(e,o,r,n);if(f){let e=await f;if(!u())return`failed`;if(!e)return`pending`;({item:o,expectedLeafEntryId:d}=e)}if(a===`durable`&&(o.attachments?.length||o.attachmentPayload||o.attachmentStorageError)){let t=await gO(e,o,r);if(!u())return`failed`;if(typeof t==`string`)return t;o=t}return vO(e,o,a,o.sessionKey??r,n,t=>u()?bO(e,o,t,n,r,d,s,i):`failed`)}async function bO(e,t,n,r,i,a,o,s){let c=t.id,l=r?.storageMode??`durable`,u=t.sessionKey??i,d=r?.routingSessionKey??u,f=uO(e,n,l,u,r);if(typeof f!=`string`&&t.attachmentPayload&&(f={...f,attachments:t.attachments}),typeof f==`string`)return f;if(!f.sendRunId||!f.sendState){let t=f.sessionKey??i;f=cO(e,l,f.id,n=>({...n,sendAttempts:n.sendAttempts??0,sendRunId:n.sendRunId??p(),sendState:e.connected&&e.client?`sending`:`waiting-reconnect`,sessionKey:t,agentId:n.agentId??_t(e,t)}))??`pending`}if(typeof f==`string`)return J(e,X),f;o&&(f={...f,refreshSessions:!0,text:f.localCommandArgs?`/reset ${f.localCommandArgs}`:`/reset`});let m=xo(f.text,f.mentions),h=f.intent?f.text:m.text,g=(t.attachmentPayload?t.attachments:f.attachments)??[];if(!h&&g.length===0)return q(e).remove(e,c),`sent`;let _=f.sessionKey??e.sessionKey,v=lO(e,l,c);if(r?.target){let t=dE(e,r.target);if(!t.allowed)return v(`failed`,t.reason),xy(e,_,f.agentId,t.reason),`failed`}if(!e.connected||!e.client){let t=v(`waiting-reconnect`);return!t&&FD(e,f,r)?`failed`:(t||(v(`failed`,X),xy(e,_,f.agentId,X)),`pending`)}if(pO(e,f,g,_,r))return`failed`;let y=aO(e),b=f.sendRunId??p(),x=Date.now(),S=Ep(),C=cO(e,l,c,e=>({...e,sendAttempts:(e.sendAttempts??0)+1,sendError:void 0,sendRunId:b,sendState:`sending`,sendRequestStartedAtMs:S,sessionKey:_,agentId:f.agentId}));if(!C)return xy(e,_,f.agentId,X),`pending`;JD(e,C,b,S),KD(e,C,`request-start`,C.sendSubmittedAtMs);let w={sessionKey:_,...f.agentId?{agentId:f.agentId}:{}},T=()=>V(e,_,f.agentId),E=s&&T()?zx(e,d):void 0;T()&&(e.chatSendingScopeKey=N(w),e.chatSending=!0,e.chatRunId||(Bp(e),e.providerPolicyNotice=null),J(e,null),sm(e,{clearRunStatus:!0,clearIndicators:!e.chatRunId}));try{if(r?.canDispatch&&!r.canDispatch())return v(`failed`,Za),xy(e,_,f.agentId,Za),`failed`;let t=f.intent?f.expectedLeafEntryId:a,n=await BD(e,{message:h,workContext:f.workContext,mentions:m.mentions,attachments:g.length?g:void 0,runId:b,sessionKey:_,agentId:f.agentId,...f.sessionId?{sessionId:f.sessionId}:{},...f.intent?{intent:f.intent,sessionId:f.sessionId}:{},...f.queueMode?{queueMode:f.queueMode}:{},...f.queueMode!==`steer`&&t!==void 0?{expectedLeafEntryId:t}:{},...f.replyToId?{replyToId:f.replyToId}:{}});if(!y())return`pending`;if(YD(e,b,n,C,S),KD(e,C,`ack`,C.sendSubmittedAtMs,{ackStatus:n.status,requestDurationMs:wp(Ep()-S),...XD(n)}),vg(n)){if(n.stopReason===`restart`&&l===`durable`)return v(`waiting-reconnect`),`pending`;let t=vy(n,`chat`);fO(e,w);let i=r?.restoreOnTerminalFailure===!0&&FD(e,f,r);if(i||v(`failed`,t),T()){let t=np(e,{sessionKey:_,agentId:f.agentId});ap(e,{type:`sendFailed`,runId:b},{scope:t});let r=e.chatRunId===n.runId;sm(e,{outcome:`interrupted`,sessionStatus:n.status===`error`?`failed`:`killed`,runId:n.runId,sessionKey:_,clearIndicators:r,clearLocalRun:r,clearChatStream:r,clearToolStream:r,publishRunStatus:!1,armLocalTerminalReconcile:(!e.chatRunId||r)&&n.runId===b})}return xy(e,_,f.agentId,t,{inline:l===`durable`&&!i}),KD(e,C,`failed`,C.sendSubmittedAtMs,{error:t,ackStatus:n.status}),`failed`}let i=l===`memory`||n.messageSeq!==void 0||n.status===`ok`&&!hy(f),o=!1;if(i&&(q(e).remove(e,c),o=l===`durable`&&e_(e,c)!==null),T()){if(i){let t=np(e,{sessionKey:_,agentId:f.agentId}),r=Ip({...f,text:h,mentions:m.mentions,attachments:g,createdAt:x,runId:b});r&&ap(e,{type:`sendPending`,runId:b,message:r},{scope:t}),n.runId!==b&&ap(e,{type:`sendAcknowledged`,previousRunId:b,runId:n.runId},{scope:t})}if(n.status===`ok`)sm(e,{outcome:`done`,sessionStatus:`done`,runId:n.runId,sessionKey:_,clearLocalRun:!0,clearChatStream:!0,clearToolStream:!0,publishRunStatus:!1,armLocalTerminalReconcile:!0}),ZC(e).then(()=>hD(e,SO));else if(pu(n.status)){(!e.chatRunId||f.queueMode===`interrupt`)&&Yp(e,n.runId,x);let t=f.sessionId&&e.sessionsResult?.sessions.some(e=>e.sessionId===f.sessionId&&[`requested`,`provisioning`,`syncing`,`starting`].includes(e.placement?.state??``));f.queueMode!==`steer`&&n.messageSeq===void 0&&t&&ZC(e,{deferBranches:!0})}}if(f.refreshSessions){let t={sessionKey:_,agentId:f.agentId};n.status===`ok`?Mx(e,t):pu(n.status)&&e.refreshSessionsAfterChat.set(n.runId,t)}return Mg(i_(e,g)),o?(xy(e,_,f.agentId,X),`pending`):i?`sent`:`pending`}catch(n){if(!y())return`pending`;let a=n instanceof Yn?ia(n.details):void 0;if(a){let t=hd(n);fO(e,w);let o=v(`failed`,t);KD(e,f,`failed`,f.sendSubmittedAtMs,{error:t});let u=s?await E?.(a):void 0;if(u?.()&&y()&&T()){let t=e_(e,c);if(!o||!t||!Bc(o,t))return`failed`;if(cO(e,l,c,e=>({...e,sendRunId:p(),sendError:void 0,sessionId:a.recovery?.sessionId,sendState:`sending`})))return await yO(e,c,{...r,canDispatch:u,allowActiveRunSend:!0},i,!1)}let d=FD(e,f,r);return xy(e,_,f.agentId,T()&&e.chatError||t,{inline:l===`durable`&&!d}),`failed`}return mO(e,t,f,n,r,w,t=>uD(e,w,t,SO))}finally{y()&&fO(e,w)}}async function xO(e,t,n={}){let r=t.sessionKey??e.sessionKey,i=n.storageMode??`durable`,a=n.routingSessionKey??r,o=aO(e,!1),s=t.agentId??_t(e,a)??void 0,c={...n,routingSessionKey:a,storageMode:i},l;if(i===`memory`)l=await yO(e,t.id,c,r);else{let n=Fa(e).find(e=>e.queue.some(e=>e.id===t.id));if(!n)return`pending`;let o=async o=>{let s=V(e,a,o.agentId);if(s&&!o.queueMode&&!c.allowActiveRunSend&&(Ah(e)||Mh(e))){let a=uO(e,o,i,r,c);if(typeof a==`string`)return a===`pending`&&n.queue[0]?.id!==t.id&&pD(e,n,SO),a}return!e.connected||!e.client?`pending`:(s?await pD(e,n,SO,t.id,{...c,pendingSettings:void 0}):await pD(e,n,SO))??`pending`},s=t.localCommandName?void 0:c.pendingSettings??Sx(e,a,t.agentId);l=s?await vO(e,t,i,r,{...c,pendingSettings:s},o):await o(t)}return l===`sent`&&V(e,r,s)&&(sp(e),n.restoreDraft&&n.previousDraft?.trim()&&(e.chatMessage=n.previousDraft,e.chatMentions=n.previousMentions??[],e.chatReplyTarget=n.previousReplyTarget??null),n.restoreAttachments&&n.previousAttachments?.length&&(e.chatAttachments=n.previousAttachments)),o()&&V(e,a,s)&&Np(e,!0,!0),l===`sent`&&V(e,r,s)&&!e.chatRunId&&hD(e,SO),l}var SO;function CO(){return(CO=e((()=>{ra(),mu(),Br(),Pa(),lo(),Vo(),Cs(),I(),o(),Ig(),OE(),Y(),ew(),yD(),Kg(),l_(),yg(),ID(),_O(),GD(),wy(),tO(),Wx(),Dx(),Ru(),ip(),mp(),hp(),Lp(),Qm(),kh(),SO={sendQueuedChatMessage:yO,async sendResetSlashCommand(e,t,n){let r=nO(e,t,void 0,!0,void 0,iO(e)),i=r?rO(e,r.item):void 0;if(!r||!i||!r_(e,r.admission,i)){i&&PD(e,i,{previousDraft:n.previousDraft}),J(e,X);return}await xO(e,i,{previousDraft:n.previousDraft,restoreDraft:n.restoreDraft,routingSessionKey:e.sessionKey,target:n.target})},setChatError:J}})))()}function wO(e){return!!(e.sendRunId&&!e.localCommandName&&(e.sendState===`unconfirmed`||e.sendState===`held`&&((e.sendAttempts??0)>0||e.sendRequestStartedAtMs!==void 0)))}async function TO(e,t){if(!(ZE(e)?.providerReview||oy(e))){if(e_(e,t)?.intent){J(e,R(`chat.goals.admissionImmutable`));return}if(rm(e,t)){J(e,hm);return}if(!t_(e,t,e=>({...e,queueMode:`steer`}))){J(e,X);return}await DO(e,t)}}function EO(e,t,n){let r=q(e),i=r.locate(e,t);if(!i||!ho(i.item))return`noop`;if(rm(e,t))return J(e,Zp),`rejected`;let a=r.snapshot(e,i.scope),o=Co(a).find(e=>e.some(e=>e.id===t)),s=o?.findIndex(e=>e.id===t)??-1,c=o?.findIndex(e=>e.id===n)??-1;if(s<0||c<0||s===c)return`noop`;if(o.slice(Math.min(s,c),Math.max(s,c)+1).some(t=>rm(e,t.id)))return J(e,Zp),`rejected`;let l=Co(o,t=>!rm(e,t.id)).find(e=>e.some(e=>e.id===t)),u=l?.findIndex(e=>e.id===n)??-1,d=vo(l??[],t,u);if(d.length===0)return`noop`;let f=new Map(d.map(e=>[e.id,e])),p=new Set(l.map(e=>e.id));if(a.map(e=>f.get(e.id)??e).toSorted(ya).some((e,t)=>!p.has(e.id)&&a[t]?.id!==e.id))return`noop`;if(q(e).update(e,d.map(e=>({id:e.id,update:t=>({...t,orderKey:e.orderKey})})))===null)return J(e,X),`rejected`;for(let t of[`lastError`,`chatError`])e[t]===`A queued message is being edited in another pane. Finish or cancel that edit before reordering it.`&&(e[t]=null);return`moved`}async function DO(e,t,n){if(ZE(e)?.providerReview||oy(e)||n&&!n())return;let r=e.chatQueue.find(e=>e.id===t);if(ay(e,r?.sessionKey??e.sessionKey))return;let i=r?.sendState===`failed`&&!r.localCommandName,a=r!==void 0&&wO(r);if(rm(e,t)){J(e,om);return}if(!r||r.pendingRunId||r.sendState===`executing-command`||r.sendState===`submitting`||r.sendState===`sending`||r.sendState===`waiting-model`)return;let o=q(e),s=o.locate(e,r.id);if(!s)return;if(!s.durable){let i=q(e).hasVolatile(e,r.id);if(!r_(e,{scope:s.scope,awaitingDefaults:!gn(e)},r)){if(i&&!r.localCommandName&&r.sendRunId&&(r.sendState===`failed`||r.sendState===`unconfirmed`||r.sendState===`held`)&&dO(e,r)){let r=q(e).change(e,t,e=>OO(e,void 0));if(!r){J(e,X);return}await xO(e,r,{routingSessionKey:r.sessionKey??e.sessionKey,storageMode:`memory`,canDispatch:n});return}J(e,X);return}}let c=t_(e,t,t=>OO(t,iO(e)));if(!c){J(e,X);return}let l=o.locate(e,c.id);if(!l?.durable){J(e,X);return}let u=l.scope,d=c.queueMode||i||a,f=pD(e,u,SO,d?c.id:void 0,d?{routingSessionKey:e.sessionKey,canDispatch:n,...i?{allowActiveRunSend:!0}:{}}:void 0);e.chatSending&&e.chatSendingScopeKey===N(u)||(await f,e.chatRunId||hD(e,SO))}var OO,kO,AO;function jO(){return(jO=e((()=>{H(),$a(),B(),o(),Y(),yD(),Kg(),$E(),l_(),CO(),_O(),wy(),zu(),Gm(),fo(),OO=(e,t)=>{let n=wO(e);return{...e,sendAttempts:n?e.sendAttempts:0,sendError:e.sendState===`failed`?e.sendError:void 0,sendRequestStartedAtMs:n?e.sendRequestStartedAtMs:void 0,sendRunId:e.sendState===`failed`&&e.queueMode!==`steer`&&!e.intent?p():e.sendRunId,sendState:n?`unconfirmed`:t}},kO=(e,t)=>mD(e,SO,t),AO=e=>hD(e,SO)})))()}function MO(e,t){let n=t.flatMap(e=>{let t=e.browserAnnotation?.modelContext.trim();return t?[t]:[]});if(n.length===0)return e;let r=n.join(`

`);return e?`${r}\n\n${e}`:r}async function NO(e,t,n){let r=null;if(e.client&&e.connected&&(t.trim()||n.attachments?.length)){ED(e,n.recovery)&&J(e,null);try{r=await BD(e,{message:t.trim(),attachments:n.attachments,runId:p(),expectedLeafEntryId:VD(e)})}catch(t){if(ED(e,n.recovery)){let n=HD(t);J(e,n?R(`chat.sendErrors.activeLeafChanged`):hd(t)),n&&Promise.all([ZC(e),WS(e)])}}}let i=r?.status===`ok`||r?.status===`started`||r?.status===`in_flight`;MD(e,n.recovery,i,n.attachments),vg(r)&&ED(e,n.recovery)&&J(e,vy(r,`detached`))}function PO(){return(PO=e((()=>{H(),o(),GS(),Y(),ew(),yg(),ID(),GD(),wy(),Ru()})))()}function FO(){return new Promise(e=>{let t=new MessageChannel;t.port1.addEventListener(`message`,()=>{t.port1.close(),t.port2.close(),e()},{once:!0}),t.port1.start(),t.port2.postMessage(void 0)})}async function IO(e,t,n,r){let i=n.yieldToInput&&typeof MessageChannel<`u`,a=i&&n.isCurrent()&&e.connected&&e.client&&!e.chatLoading&&!oy(e)&&!n.pendingSettings&&t.sendState===`waiting-idle`&&(t.queueMode||n.allowActiveRunSend&&!t.intent||!Ah(e)&&!Mh(e)&&e.chatQueue.find(e=>e.sendState!==`failed`||e.localCommandName)?.id===t.id),o=i&&e.connected&&n.isCurrent()?q(e).beginSubmission(e,t.id,{inline:!!a,isCurrent:()=>e.connected&&n.isCurrent()}):void 0;try{let a=t;if(i){await FO();let r=n.isCurrent()&&V(e,t.sessionKey,t.agentId)?e_(e,t.id):null;if(!r||!Bc(t,{...r,sendState:r.sendState===`submitting`?`waiting-idle`:r.sendState,orderKey:t.orderKey}))return`pending`;a=r}return await r(a)}finally{o?.release()}}async function LO(e,t,n,r){let i=t;if(r){let e=RO.get(r)??p();RO.set(r,e),i=`${t}\0${e}`}let a=e.chatSubmitGuards??=new Set;if(!a.has(i)){a.add(i);try{return await n()}finally{a.delete(i)}}}var RO;function zO(){return(zO=e((()=>{lo(),I(),o(),Y(),Kg(),l_(),Lp(),RO=new WeakMap})))()}async function BO(e,t){let n=Sx(e,t);return n&&!await hO(e,t,n)?!1:e.sessionKey===t}async function VO(e,t,n,r){if(ZE(e)?.providerReview&&!bm(t??e.chatMessage)){J(e,R(`chat.providerReview.pausedBody`));return}if(oy(e)&&(n?.intent||n?.resumeQueuedMessageEditId||!$o(t??e.chatMessage)))return;let i=e.chatMessage,a=e.chatMentions?.map(e=>({...e})),o=e.chatReplyTarget?{...e.chatReplyTarget}:null,s=e.chatGoalDraftMode,c=n?.intent,l=t??e.chatMessage,u=t==null?a:n?.mentionsOverride,d=xo(l,u),f=c?l:d.text,p=Ep(),m=e.sessionKey,h=e.client,g=e.connectionEpoch,_=jp(e),v=VD(e),y=SD(t==null?e.chatAttachments:n?.attachmentsOverride??[]),b=(n=`none`)=>t==null?xD(e,i,y,a,o,n):{},x=y.length>0;if(x&&!yn(e.uploadConfig)){J(e,qt());return}if(c){if(u?.length){J(e,R(`chat.mentions.unsupported`));return}if(!e.connected||!e.client){J(e,R(`chat.goals.offline`));return}if(Ah(e)||Mh(e)){J(e,R(`chat.goals.busy`));return}if(y.some(e=>e.browserAnnotation)){J(e,R(`chat.goals.annotationUnsupported`));return}if(!f.trim())return}let S=n?.resumeQueuedMessageEditId,C=S?Fm(e):null;if(S!=null&&C?.id!==S)return;let w=S!=null&&C?.id===S,T=w?C.revision:null,E=c?null:ys(f);if(d.mentions?.length&&(E||/^\/(?:btw|side)(?::|\s|$)/i.test(f))){J(e,R(`chat.mentions.unsupported`));return}if(w&&(E||bm(f))){J(e,`Queued-row edits cannot run commands or stop aliases. Cancel this edit and send the command from the composer.`);return}let D=E||c?f:MO(f,y),O=E?y.filter(e=>!e.browserAnnotation&&!e.selectionAnnotation):y,k=()=>{let t=Uu(O,e.hello?.policy);return t!==void 0&&(ct({message:t}),!0)};if(!D&&!x)return;if(!c){if(bm(f)&&(f.startsWith(`/`)||Em(e))){if(e.connected&&!oE(e,`abort`))return;e.chatRunError=null,t??kp(e,f),await Kp(e,{scope:`session`});return}e.chatRunError=null;let r=E;if(/^\/(?:btw|side)(?::|\s|$)/i.test(f)){let n=Xo(f);await LO(e,bD(e,`local`,D,[]),async()=>{t??(kp(e,f),b(`all`)),await e.openSessionCompanion?.(n)});return}let s=r?.command.clientPresentation,c=e.dispatchClientPresentation;if(e.connected&&r?.args===``&&s?.when===`no-arguments`&&!x&&e.chatReplyTarget==null&&c&&await LO(e,bD(e,`local`,D,[]),async()=>{if(e.sessionKey!==m)return`not-handled`;let n=!1;try{n=await c(s.action)}catch{}return n?(e.sessionKey===m&&(t??(b(),kp(e,D))),`handled`):`not-handled`})!==`not-handled`)return;if(r?.command.key===`approve`&&(Ah(e)||oy(e))){await LO(e,bD(e,`detached`,D,y),async()=>{if(!await BO(e,m)||k())return;let n=b(`annotations`);t??kp(e,f);let r=Ft(e,m);Np(e,!0,!1,{source:`manual`}),await NO(e,D,{attachments:O.length?O:void 0,recovery:wD(e,r,n.previousDraft===void 0?void 0:{draft:n.previousDraft,mentions:n.previousMentions,replyTarget:n.previousReplyTarget,attachments:n.previousAttachments??[]})})});return}let l=r?.command.key===`model`&&Mi(r.args);if(r?.command.executeLocal&&!l){if(xE(r.command.key)){if(gy(e,m)){e.requestUpdate?.();return}await LO(e,bD(e,`local`,D,y),async()=>{let n=_s(e,e.sessionKey);t??(kp(e,f),b(`all`));let s=Zg(e,D,my(D),{args:r.args,name:r.command.key},ko(e.hello,e.client?.instanceId,e.selfUser)??void 0);if(s){if(s.sendState=iO(e),!r_(e,n,s)){q(e).remove(e,s.id),t??(e.chatMessage=i,e.chatMentions=a??[],e.chatReplyTarget=o,e.chatAttachments=y),J(e,X);return}Np(e,!0,!1,{source:`manual`}),await xO(e,s,{routingSessionKey:e.sessionKey})}});return}let s=r.command.key===`redirect`,c=async()=>{if(s&&!await BO(e,m))return;let a=t==null?i:void 0,o,c=Ft(e,m);if(t==null&&(kp(e,f),r.command.key!==`export-session`)){let e=b();a=e.previousDraft,e.previousDraft!==void 0&&(o={draft:e.previousDraft,mentions:e.previousMentions,replyTarget:e.previousReplyTarget,attachments:e.previousAttachments??[]})}let l=wD(e,c,o);(r.command.key===`steer`||r.command.key===`redirect`)&&Np(e,!0,!1,{source:`manual`});let u=await CE(e,r.command.key,r.args,{previousDraft:a,restoreDraft:!!(t&&n?.restoreDraft),sendResetMessage:(t,n)=>SO.sendResetSlashCommand(e,t,n)});r.command.key===`export-session`&&u===`completed`&&t==null&&ED(e,l)&&b(`all`),u===`failed`&&(t!=null||ED(e,l))&&n?.onLocalCommandSendRejected?.(),u===`failed`||u===`cancelled`?MD(e,l,!1,l.composer?.attachments):u===`completed`&&MD(e,l,!0,l.composer?.attachments)};s?await LO(e,bD(e,`local`,D,y),c):await c();return}}if(k())return;let{replyTargetOverride:A=o}=n??{},j=w?null:A,ee=w?C.replyToId:j?.sourceMessageId?.trim()||void 0,te=j&&!ee&&!c?Sy(D,j):D,ne=!c&&!f.startsWith(`/`)&&!f.startsWith(`!`)&&!Ni(te)?w?C.source.workContext:e.getWorkContext?.():void 0,M=ne?Un(ne):void 0,re=te.length-f.length,ie=d.mentions?.map(e=>({profileId:e.profileId,start:e.start+re,end:e.end+re})),ae=bD(e,S?`queued-edit`:c?`goal`:`message`,M?`${te}\n\n${Rn(M)}`:te,y,ie),oe=!1;return await LO(e,ae,async()=>{if(e.chatLoading&&(c||E||w)){if(!await ZC(e))return;v=VD(e)}if(e.sessionKey!==m)return;let i=_t(e,m),a=()=>_()&&e.client===h&&e.connectionEpoch===g&&e.sessionKey===m&&V(e,m,i);if(!V(e,m,i)){J(e,R(`mcpServers.sessionUnavailable`));return}if(c&&(Ah(e)||Mh(e))){J(e,R(`chat.goals.busy`));return}let o=Fm(e);if(w&&(o!==C||o.revision!==T))return;if(gy(e,m)){e.requestUpdate?.();return}let l=Sx(e,m),u=Mh(e)||oy(e),d=S&&o?.id===S?o:null,y=d?d.source.queueMode??`queue`:n?.followUpMode??e.chatFollowUpMode??Nr(e.settings?.chatFollowUpMode),x=!c&&u&&y!==`queue`?y:void 0,k=!!(c||u&&y!==`queue`),A=nO(e,te,O.length?O:void 0,!!c||my(D),p,l?`waiting-model`:iO(e),ee,d?.orderKey,x,c,v,ie,M);if(!A)return;let j=A.item;if(j.asyncQuestionItemId=d?.source.asyncQuestionItemId??n?.asyncQuestionItemId,j.attachments?.length){let t=await lp(e,j),n=Fm(e);if(!a()||w&&(n!==C||n.revision!==T)){t.status===`ready`&&dp(t.update);return}if(t.status===`failed`){J(e,$f(t.reason));return}j={...j,...t.update};let r=gy(e,m);if(r||c&&(Ah(e)||Mh(e))){dp(j),r?e.requestUpdate?.():J(e,R(`chat.goals.busy`));return}l??=Sx(e,m),j.sendState=l?`waiting-model`:iO(e)}let ne=b(E?`annotations`:`none`);t??kp(e,f),j=rO(e,j);let re=q(e).admit(e,A.admission,j,d?{id:d.id,expected:d.source}:void 0),ae=re===`admitted`;d&&Hm(e,ae,j.attachments,d);let se=!ae&&!j.attachments?.length&&(!d||!d.sourceWasDurable)&&!Fm(e)&&!l&&dO(e,j,m);if(!ae&&!se){dp(j),PD(e,j,{...ne,previousGoalDraftMode:s}),J(e,py(re,!!d));return}J(e,null),n?.onOutboxAdmitted?.();let ce=await IO(e,j,{yieldToInput:ae&&!!r,isCurrent:a,allowActiveRunSend:k,pendingSettings:l},r=>xO(e,r,{...ne,previousGoalDraftMode:s,...k?{allowActiveRunSend:!0}:{},...v===void 0?{}:{expectedLeafEntryId:v},...l?{pendingSettings:l}:{},restoreAttachments:!!(t&&n?.restoreDraft),restoreDraft:!!(t&&n?.restoreDraft),restoreOnTerminalFailure:!!(E||c),routingSessionKey:m,storageMode:se?`memory`:`durable`})),le=e_(e,j.id);oe=ce!==`failed`,ce===`pending`&&le?.sendState===`waiting-idle`&&e.sessionKey===m&&V(e,m,le.agentId)&&(Ah(e)||Mh(e))&&KD(e,le,`queued-busy`,p)},r),oe}function HO(){return(HO=e((()=>{Fi(),Li(),Nn(),Vr(),H(),$a(),yo(),fs(),Ya(),is(),Pa(),Cs(),I(),B(),tt(),Dt(),OE(),Y(),ew(),Kg(),$E(),l_(),ID(),CO(),PO(),_O(),GD(),wy(),tO(),Dx(),zO(),Kf(),mp(),up(),hp(),Gm(),Lp(),Qm(),fo(),Oo()})))()}function UO(e,t){let n=Ov(e),r=n?.queuedInputs.find(e=>`pending-input:${e.id}`===t&&e.queued&&e.state===`queued`),i=e.client;if(!n||!r?.runId)return!1;if(!i||!e.connected)return!0;let a=e.connectionEpoch,o=()=>Ov(e)===n&&e.client===i&&e.connected&&e.connectionEpoch===a;return Gx(i,{sessionKey:n.sessionKey,agentId:n.agentId,runId:r.runId,...Df(e,n)?{}:{discardPendingInput:!0}}).then(async t=>{if(o()){if(!t.ok){e.chatError=P(t.error),e.requestUpdate?.();return}await ZC(e,{supersedeInFlight:!0})}}),!0}function WO(e){e.imageLightboxRequestVersion+=1;let t=e.imageLightbox;return e.imageLightbox=null,t?.release?.(),e.imageLightboxRequestVersion}async function GO(e){if(!e.client||!e.connected)return;let t=e.client,n=e.sessionKey.trim(),r=By({sessionKey:n,assistantAgentId:e.assistantAgentId,agentsList:e.agentsList,hello:e.hello});if(!r)return;let i=++e.assistantIdentityRequestVersion;try{let a=await Ll(t,r);if(e.client!==t||!e.connected||e.assistantIdentityRequestVersion!==i||e.sessionKey.trim()!==n||By(e)!==r||!a)return;e.assistantAgentId!==(a.agentId??null)&&kt(e,e.sessionKey)&&kx(e),e.assistantName=a.name,e.assistantAvatar=a.avatar,e.assistantAvatarSource=a.avatarSource??null,e.assistantAvatarStatus=a.avatarStatus??null,e.assistantAvatarReason=a.avatarReason??null,e.assistantAgentId=a.agentId??null,e.requestUpdate?.()}catch{}}function KO(e,t,n,r=new Map){let i=Xr(),a=n.sessionKey?.trim()||i.sessionKey,o=Mt({agentsList:e.agents.state.agentsList,hello:e.gateway?.snapshot.hello},a),s=ti(),c=e.config.current,l={uploadConfig:e.config,captureComposerRecoveryReload:()=>{let t=cr(e.gateway);return()=>ur({timeoutMs:0,...t})},sessions:e.sessions,hasPendingInitialTurn:t=>e.placementStartup.hasPendingTurn(t),chatSubmissions:e.chatSubmissions,settings:i,password:``,onboarding:!1,assistantName:c.assistantIdentity.name,assistantAvatar:null,assistantAvatarStatus:null,assistantAvatarReason:null,assistantAvatarSource:null,assistantIdentityRequestVersion:0,userName:s.name,userAvatar:s.avatar,embedSandboxMode:c.embedSandboxMode,allowExternalEmbedUrls:c.allowExternalEmbedUrls,automaticallyFetchFavicons:c.automaticallyFetchFavicons,client:null,connected:!1,connectionEpoch:0,mediaPolicyEpoch:0,hello:null,selfUser:null,canvasPluginSurfaceUrl:null,terminalAvailable:!1,browserPanelAvailable:!1,assistantAgentId:e.agentSelection.state.selectedId,sessionKey:a,chatLoading:!1,chatHistoryPagination:{hasMore:!1},chatSending:!1,chatMessage:``,chatMessages:[],chatDisplayedLeafEntryId:void 0,chatBranches:[],chatBranchesSessionKey:null,chatBranchesConnectionEpoch:null,chatToolMessages:[],guardianNotices:[],providerPolicyNotice:null,chatThinkingLevel:null,chatVerboseLevel:null,chatQueueModeOverride:void 0,chatEffectiveQueueMode:void 0,chatAttachments:[],chatRunId:null,chatRunUsageById:new Map,chatStream:null,chatStreamStartedAt:null,chatRunStartup:null,lastError:null,chatError:null,chatRunError:null,agentsError:null,chatStreamSegments:[],chatRunStatus:null,compactionStatus:null,fallbackStatus:null,observerDigest:null,knownAgentRunIds:new Set,waitingApprovalStatuses:new Map,waitingApprovalResolvedIds:new Set,chatAvatarUrl:null,chatAvatarSource:null,chatAvatarStatus:null,chatAvatarReason:null,chatModelSwitchPromises:{},chatModelPickerOpenSessionKey:null,chatModelsLoading:!1,chatModelCatalog:[],chatModelCatalogInitialized:bt(e.gateway.snapshot.client),chatModelSelectionPolicy:void 0,chatModelCatalogRetired:!1,chatModelCatalogError:null,chatAccountSelection:null,modelAuthStatusRequestVersion:0,modelAuthStatusResult:null,modelAuthStatusError:null,sessionsResult:null,sessionsResultAgentId:null,sessionsLoading:!1,sessionsError:null,sessionsArchivedFilter:`active`,selectedChatSessionArchived:!1,selectedChatSessionIncognito:!1,agentsList:e.agents.state.agentsList,agentsSelectedId:e.agentSelection.state.selectedId,refreshSessionsAfterChat:new Map,pendingAbort:null,pendingSessionMessageReloadSessionKey:null,chatSubmitGuards:new Set,chatGoalDraftMode:null,chatSendTimingsByRun:new Map,chatQueue:[],chatComposerFallbackByScope:{},chatSendingScopeKey:null,chatMessagesBySession:r,eventLogBuffer:[],dispatchClientPresentation:t=>Vl(e,t),basePath:e.basePath,resourceBasePath:e.resourceBasePath,chatNewMessagesBelow:!1,chatLocalInputHistoryBySession:{},chatInputHistorySessionKey:null,chatInputHistoryItems:null,chatInputHistoryIndex:-1,chatDraftBeforeHistory:null,chatStreamRenderFrame:null,chatLastScrollTop:0,chatLastScrollHeight:0,chatHasAutoScrolled:!1,chatUserNearBottom:!0,chatFollowLocked:!1,chatReadingHistory:!1,sidebarLayout:Ht(i.sidebarSessionLayouts?.[o]),sidebarContent:null,sidebarFocusPanelId:i.sidebarSessionActivePanels?.[o]??``,sidebarFocusVersion:0,imageLightbox:null,imageLightboxRequestVersion:0,toolStreamById:new Map,toolStreamOrder:[],activityEventSeqById:new Map,toolStreamSyncTimer:null,...GE(),renderLifecycle:t,requestUpdate:()=>t.invalidate(),transcriptLoadingChanged:()=>n.dispatchEvent(new CustomEvent(xt,{bubbles:!0,composed:!0})),sessionWorkspaceState:void 0,querySelector:n.querySelector.bind(n)};l.resetToolStream=()=>Bp(l),l.resetChatInputHistoryNavigation=()=>sp(l),l.resetChatScroll=()=>eh(l),l.scrollToBottom=e=>{eh(l),Np(l,!0,!!e?.smooth,{source:`manual`})},l.handleChatScroll=e=>Jh(l,e),l.handleChatDraftChange=(e,t)=>Dp(l,e,t),l.handleChatInputHistoryKey=e=>Ap(l,e),l.applySettings=e=>{let n={...l.settings,...e};l.settings=br({chatShowThinking:n.chatShowThinking,chatShowToolCalls:n.chatShowToolCalls,chatPersistCommentary:n.chatPersistCommentary,chatSendShortcut:n.chatSendShortcut}),t.invalidate()},YE(l,()=>!ZE(l)?.providerReview),l.loadAssistantIdentity=()=>GO(l),l.handleSendChat=(t,n,r)=>{let i=t??l.chatMessage,a=ys(i)!==null||bm(i)&&Em(l);return Kl({connected:l.connected,directComposerSend:t===void 0&&n===void 0&&Rl(),message:i,hasAttachments:l.chatAttachments.length>0,isCommand:a})&&Pl(e),VO(l,t,n,r)},l.handleAbortChat=async e=>{await Kp(l,e),t.invalidate()},l.removeQueuedMessage=e=>{if(UO(l,e))return;if(rm(l,e)){J(l,Om),t.invalidate();return}let n=a_(l,e,{discard:!0});n===`removed`?(J(l,null),kO(l)):n===`rejected`&&J(l,X),t.invalidate()},l.retryQueuedChatMessage=async e=>{await DO(l,e),t.invalidate()},l.steerQueuedChatMessage=async e=>{await TO(l,e),t.invalidate()},l.moveQueuedChatMessage=(e,n)=>{EO(l,e,n),t.invalidate()},l.editQueuedChatMessage=e=>{if(pg(l,e)===`unavailable`)J(l,Sm);else for(let e of[`lastError`,`chatError`])l[e]===`A queued message is being edited in another pane. Finish or cancel that edit before editing it here.`&&(l[e]=null);t.invalidate()},l.updateQueuedChatMessageEdit=(e,n)=>{qm(l,e,n),t.invalidate()},l.submitQueuedChatMessageEdit=()=>{let e=Fm(l);e&&l.handleSendChat(e.draftText,{attachmentsOverride:[...e.attachments],mentionsOverride:e.mentions,resumeQueuedMessageEditId:e.id}).then(()=>t.invalidate(),()=>t.invalidate())},l.cancelQueuedChatMessageEdit=()=>{zp(l)&&kO(l),t.invalidate()};let u=new Set,d=``;return l.updateSidebarLayout=(e,n)=>{let r=Mt(l,l.sessionKey),i=JSON.stringify([l.settings.gatewayUrl,r]);i!==d&&(u.clear(),d=i);let a=Ht(e),o=l.sidebarLayout,s=(e,t)=>e.columns.some(e=>e.panels.some(e=>e.slot===t));n?.automaticResource&&!s(o,n.automaticResource)&&s(a,n.automaticResource)&&u.add(n.automaticResource);for(let e of u){let t=a.columns.flatMap(e=>e.panels).find(t=>t.slot===e);(!t||e===`desktop`&&t.environmentId!==void 0)&&u.delete(e)}(o.resourceAutoOpenDismissed||n?.persist!==!1&&(o.open&&!a.open||s(o,`desktop`)&&!s(a,`desktop`)||s(o,`browser`)&&!s(a,`browser`)))&&(a.resourceAutoOpenDismissed=!0);let c=n?.dashboardPresentation===`personal`?Up(a):void 0;if(c){let e=Q(l);a.dashboardPresentationOverride=e&&c===(e.boardPresentation??`split`)?null:c}if((l.sidebarContent?.kind===`loading`||l.sidebarContent?.kind===`unavailable`)&&!a.columns.some(e=>e.panels.some(e=>e.slot===`detail`))&&(l.sidebarContent=null),l.sidebarLayout=a,n?.persist===!1){t.invalidate();return}let f=a;for(let e of u)f=bh(f,e);l.settings=br({sidebarSessionLayouts:Gt(Xr().sidebarSessionLayouts,r,f,{geometryOnly:n?.geometryOnly,dashboardPresentationOverride:c?a.dashboardPresentationOverride:void 0})}),a.dashboardPresentationOverride=l.settings.sidebarSessionLayouts?.[r]?.dashboardPresentationOverride,t.invalidate()},l.updateSidebarActivePanel=e=>{let n=e.trim();if(!n)return;l.sidebarFocusPanelId=n,l.sidebarFocusVersion+=1;let r=l.sidebarLayout.columns.flatMap(e=>e.panels).find(e=>e.id===n)?.slot;if((r===`desktop`||r===`browser`)&&u.has(r)){t.invalidate();return}l.settings=br({sidebarSessionActivePanels:Ve(Xr().sidebarSessionActivePanels,Mt(l,l.sessionKey),n)}),t.invalidate()},l.handleOpenSidebar=e=>{let t=e?.fileTab??(e?.kind===`attachment`?{id:`attachment:${e.sourceIdentity??e.src??crypto.randomUUID()}`,label:e.title}:e?.kind===`file`?{id:`file:${e.path}`,label:e.name}:null),r=t?`workspace`:`detail`,i=Ch(l.sidebarLayout,r),a=i.columns.flatMap(e=>e.panels).find(e=>e.slot===r);a&&(i=ph(i,a.id));let o=n.getBoundingClientRect?.().width??0,s=o>0&&o>=680?Se(i,o)??i:i;t&&e?ed(l,t.id,t.label,e):l.sidebarContent=e,l.updateSidebarLayout(s),a&&l.updateSidebarActivePanel(a.id)},l.handleCloseSidebar=e=>{e===`workspace`&&af(l),l.updateSidebarLayout(bh(l.sidebarLayout,e))},l.beginImageOpen=()=>{let e=WO(l);return t.invalidate(),e},l.handleOpenImage=(e,n)=>{if((n??l.beginImageOpen())!==l.imageLightboxRequestVersion){e.release?.();return}let r=e.kind===`video`,i=e=>r?Cd(e,`video`):At(e,window.location.href,{allowDataImage:!0}),a=i(e.src),o=e.originalSrc?i(e.originalSrc):void 0;if(!a||e.originalSrc&&!o){e.release?.();return}l.imageLightbox={...e,src:a,...o?{originalSrc:o}:{}},t.invalidate()},l.handleCloseImage=()=>{WO(l),t.invalidate()},l}function qO(){return(qO=e((()=>{au(),Bl(),mr(),$l(),Vr(),hr(),fs(),on(),Cn(),Ct(),B(),Yx(),nb(),nn(),Y(),ew(),zv(),$E(),l_(),XE(),jO(),HO(),wy(),Wx(),Vw(),Ud(),Ju(),Ed(),mp(),Gm(),Lp(),Qm(),$e(),Lh()})))()}function JO(e){let t=e.chatStreamRenderFrame;t!=null&&(e.chatStreamRenderFrame=null,typeof globalThis.cancelAnimationFrame==`function`&&globalThis.cancelAnimationFrame(t))}function YO(e,t=`immediate`){if(globalThis.document?.visibilityState===`hidden`||t===`immediate`||typeof globalThis.requestAnimationFrame!=`function`){JO(e),e.requestUpdate?.();return}if(e.chatStreamRenderFrame!=null)return;let n=0;n=globalThis.requestAnimationFrame(()=>{e.chatStreamRenderFrame===n&&(e.chatStreamRenderFrame=null,e.requestUpdate?.())}),e.chatStreamRenderFrame=n}var XO;function ZO(){return(ZO=e((()=>{vi(),H(),Cs(),B(),tt(),Ig(),tC(),Kg(),zv(),XE(),qO(),Kf(),yf(),Ku(),Ju(),Sd(),df(),Ed(),zu(),Gm(),Qm(),XO=class{constructor(e,t,n){this.host=e,this.onStateChange=t,this.onQueuedMessageDiscarded=n,this.previousChatLoading=!1,this.previousChatMessages=[],this.previousChatToolMessages=[],this.previousChatStreamSegments=[],this.previousGuardianNotices=[],this.previousChatStream=null,this.previousRealtimeConversation=[],this.scrollAfterUpdate=!1,this.scrollContentChangedAfterUpdate=!1,this.forceScrollAfterUpdate=!1,this.cleanups=[],this.renderLifecycleConnected=!1,this.attachmentReadsValue=new zd(()=>this.stateValue?.requestUpdate?.()),this.composerPersistence=new ad(()=>this.stateValue),e.addController(this)}get state(){return this.stateValue}get attachmentReads(){return this.attachmentReadsValue}takeAttachmentReads(){let e=this.attachmentReadsValue;return this.attachmentReadsValue=new zd(()=>this.stateValue?.requestUpdate?.()),e}adoptAttachmentReads(e,t){this.attachmentReadsValue.abortReads(),this.attachmentReadsValue=e,e.retarget(this.attachmentInputProps(t),()=>t.requestUpdate?.())}attachmentInputProps(e){let t=this.attachmentReads,n=t.readSignal;return{uploadConfig:e.uploadConfig,attachmentReads:t,attachments:e.chatAttachments,attachmentLimits:Cu(e.hello?.policy),getAttachments:()=>e.chatAttachments,pendingAttachmentReads:t.pendingReads,getPendingAttachmentReads:()=>t.pendingReads,readSignal:n,onPendingReadsChange:r=>{r===1&&n===t.readSignal&&Iu(e),t.updatePending(n,r)},onAttachmentsChange:t=>{e.chatAttachments=t,e.requestUpdate?.()}}}createRenderLifecycle(){this.cancelRenderLifecycleScope();let e={cancellations:new Set};return this.renderLifecycleScope=e,{invalidate:()=>{this.requestUpdateForScope(e)},afterCommit:(t,n)=>this.afterCommit(e,t,n)}}attach(e){this.stateValue&&this.stateValue!==e&&(this.privateDraftReview?.controller.abort(),XS(this.stateValue),td(this.stateValue.requestUpdate),this.attachmentReads.abortReads(),this.composerPersistence.stop(),JO(this.stateValue),Jm(this.stateValue),qE(this.stateValue)),this.stateValue=e;let t=Ov(e)?.page;this.previousPendingInputs=t,e.canRestoreComposer=()=>this.stateValue===e&&this.composerPersistence.active,this.previousChatLoading=e.chatLoading,this.previousChatMessages=e.chatMessages,this.previousChatToolMessages=e.chatToolMessages,this.previousChatStreamSegments=e.chatStreamSegments,this.previousGuardianNotices=e.guardianNotices,this.previousChatStream=e.chatStream,this.previousRealtimeConversation=e.realtimeTalkConversation;let n=e.renderLifecycle;e.requestUpdate=()=>n.invalidate(),this.cleanups.push(q(e).subscribe(e,t=>{this.stateValue===e&&this.onQueuedMessageDiscarded?.(t)})),this.cleanups.push($n(()=>this.stateValue!==e||!e.chatQueuedEdit&&!this.hasPrivateDraft(e),()=>{if(!e.chatQueuedEdit&&this.hasPrivateDraft(e)){ct({message:R(`chat.privateDraftReload.blocked`),actionLabel:R(`chat.privateDraftReload.review`),onAction:()=>void this.reviewPrivateDraft(e)});return}let t=e.chatQueuedEdit,n=e.client;ct({message:R(`chat.queue.reloadBlocked`),actionLabel:e.reviewQueuedMessageEdit?R(`chat.queue.reviewEdit`):void 0,onAction:()=>{this.stateValue===e&&e.client===n&&t&&Fm(e)===t&&e.reviewQueuedMessageEdit?.()}})}));let r=e.handleSendChat;e.handleSendChat=async(e,t,i)=>{let a=r(e,t,i);n.invalidate();try{return await a}finally{n.invalidate()}};let i=e.handleChatDraftChange;e.handleChatDraftChange=(e,t)=>{i(e,t),this.composerPersistence.schedule()};let a=e.handleChatInputHistoryKey;e.handleChatInputHistoryKey=t=>{let n=a(t);return n.handled&&(this.composerPersistence.schedule(),e.renderLifecycle.invalidate()),n}}hasPrivateComposerInput(e){return Df(e,Ft(e,e.sessionKey))&&!!(e.chatMessage||e.chatAttachments.length||e.chatGoalDraftMode||e.chatReplyTarget||e.chatMentions?.length||this.attachmentReads.pendingReads)}privateFallback(e){return Object.entries(e.chatComposerFallbackByScope).find(([t,n])=>{let r=uc(t);return(n.incognito||r&&Df(e,r))&&!!(n.message||n.attachments.length||n.goalMode||n.replyTarget||n.mentions?.length)})}hasPrivateDraft(e){return this.hasPrivateComposerInput(e)||!!this.privateFallback(e)}async reviewPrivateDraft(e){if(this.stateValue!==e||this.privateDraftReview||!this.hasPrivateDraft(e))return;let t=Yd(e),n=this.hasPrivateComposerInput(e)?void 0:this.privateFallback(e),{sessionKey:r,connectionEpoch:i}=e,a=n?.[1].message??e.chatMessage,o=n?n[1].mentions:e.chatMentions,s=n?n[1].goalMode:e.chatGoalDraftMode,c=n?n[1].replyTarget:e.chatReplyTarget,l=[...n?.[1].attachments??e.chatAttachments],u=this.attachmentReads,d=n?0:u.pendingReads,f=e.captureComposerRecoveryReload?.(),p={controller:new AbortController,isCurrent:()=>this.stateValue===e&&e.client===t.client&&gf(e,t)&&e.sessionKey===r&&e.connectionEpoch===i&&(n?e.chatComposerFallbackByScope[n[0]]===n[1]:e.chatMessage===a&&e.chatMentions===o&&e.chatGoalDraftMode===s&&e.chatReplyTarget===c&&this.attachmentReads===u&&u.pendingReads===d&&e.chatAttachments.length===l.length&&l.every((t,n)=>e.chatAttachments[n]===t))};this.privateDraftReview=p;try{if(!p.isCurrent()||p.controller.signal.aborted||!await Kd({text:a,attachments:l,hasGoal:!!s,pendingReads:d,isCurrent:p.isCurrent,signal:p.controller.signal})||!p.isCurrent())return;if(n){let t={...e.chatComposerFallbackByScope};delete t[n[0]],e.chatComposerFallbackByScope=t}else u.abortReads(),e.chatAttachments=[],e.chatGoalDraftMode=null,e.chatReplyTarget=null,e.handleChatDraftChange(``,[]);let t=e.captureComposerRecoveryOwner?.()?.retainedAttachmentIds(l);Og(l.filter(e=>!t?.has(e.id)),[e.chatAttachments,...Object.values(e.chatComposerFallbackByScope).map(e=>e.attachments)]),e.requestUpdate?.(),await f?.()}catch{p.isCurrent()&&ct({message:R(`chat.privateDraftReload.unavailable`)})}finally{this.privateDraftReview===p&&(this.privateDraftReview=void 0),!p.isCurrent()&&this.stateValue===e&&e.client===t.client&&e.sessionKey===r&&this.hasPrivateDraft(e)&&ct({message:R(`chat.privateDraftReload.changed`),actionLabel:R(`chat.privateDraftReload.review`),onAction:()=>void this.reviewPrivateDraft(e)})}}addCleanup(e){this.cleanups.push(e)}isRenderLifecycleScopeActive(e){return this.renderLifecycleConnected&&this.renderLifecycleScope===e}requestUpdateForScope(e){return this.isRenderLifecycleScopeActive(e)?(this.privateDraftReview&&!this.privateDraftReview.isCurrent()&&this.privateDraftReview.controller.abort(),this.composerPersistence.persistChangedState(),this.captureRenderLifecycleChanges(),this.onStateChange?.(),this.host.requestUpdate(),!0):!1}cancelRenderLifecycleScope(){let e=this.renderLifecycleScope;if(e){this.renderLifecycleScope=void 0;for(let t of e.cancellations)t()}}afterCommit(e,t,n){if(!this.isRenderLifecycleScopeActive(e))return n?.(),()=>void 0;let r=!0,i=!1,a,o=()=>{r&&(r=!1,a=void 0,e.cancellations.delete(s))},s=()=>{if(r){r=!1,e.cancellations.delete(s);try{a?.()}finally{a=void 0,i||n?.()}}};return e.cancellations.add(s),this.requestUpdateForScope(e)?(this.host.updateComplete.then(()=>{if(r){if(!this.isRenderLifecycleScopeActive(e)){s();return}i=!0;try{let n=t(o);typeof n==`function`?r&&this.isRenderLifecycleScopeActive(e)?a=n:n():o()}catch(e){throw o(),e}}},s),s):(s(),s)}captureRenderLifecycleChanges(){let e=this.stateValue;if(!e)return;let t=Ov(e)?.page,n=this.previousPendingInputs!==t||this.previousChatMessages!==e.chatMessages||this.previousChatToolMessages!==e.chatToolMessages||this.previousChatStreamSegments!==e.chatStreamSegments||this.previousGuardianNotices!==e.guardianNotices||this.previousRealtimeConversation!==e.realtimeTalkConversation,r=this.previousChatStream!==e.chatStream,i=this.previousChatLoading!==e.chatLoading,a=this.previousChatLoading&&!e.chatLoading,o=this.previousChatStream==null&&typeof e.chatStream==`string`;this.previousPendingInputs=t,this.previousChatLoading=e.chatLoading,this.previousChatMessages=e.chatMessages,this.previousChatToolMessages=e.chatToolMessages,this.previousChatStreamSegments=e.chatStreamSegments,this.previousGuardianNotices=e.guardianNotices,this.previousChatStream=e.chatStream,this.previousRealtimeConversation=e.realtimeTalkConversation,(n||r||i)&&(this.scrollAfterUpdate=!0,this.scrollContentChangedAfterUpdate||=n||r,this.forceScrollAfterUpdate||=a||o||!e.chatHasAutoScrolled)}handleTranscriptResize(){this.stateValue&&this.renderLifecycleConnected&&vh(this.stateValue,!1,!1,{source:`resize`})}hostConnected(){this.renderLifecycleConnected=!0,this.cancelRenderLifecycleScope()}hostUpdated(){let e=this.stateValue;if(!this.scrollAfterUpdate)return;let t=this.forceScrollAfterUpdate,n=this.scrollContentChangedAfterUpdate;this.scrollAfterUpdate=!1,this.scrollContentChangedAfterUpdate=!1,this.forceScrollAfterUpdate=!1,e&&vh(e,t,e.chatHasAutoScrolled,{contentChanged:n})}stopChatEffects(){for(this.privateDraftReview?.controller.abort();this.cleanups.length>0;)this.cleanups.pop()?.();let e=this.stateValue;e&&(XS(e),td(e.requestUpdate),JO(e),Jm(e),WO(e),(e.sidebarContent?.kind===`loading`||e.sidebarContent?.kind===`unavailable`)&&(e.sidebarContent=null),af(e),bu(e),qE(e),e.resetToolStream?.())}hostDisconnected(){this.renderLifecycleConnected=!1,this.cancelRenderLifecycleScope(),this.attachmentReads.abortReads(),this.composerPersistence.stop(),this.stopChatEffects(),this.stateValue=void 0,this.previousPendingInputs=void 0,this.scrollAfterUpdate=!1,this.scrollContentChangedAfterUpdate=!1,this.forceScrollAfterUpdate=!1}}})))()}function QO(e,t){if(!t||e.defaultPrevented||e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||!e.deltaY||Math.abs(e.deltaX)>Math.abs(e.deltaY))return;let n=e.composedPath();if(n.includes(t))return;for(let t of n){if(t===e.currentTarget)break;if(!(t instanceof HTMLElement))continue;let n=getComputedStyle(t),r=e.deltaY<0?t.scrollTop>0:t.scrollTop+t.clientHeight<t.scrollHeight-1;if(/^(auto|scroll)$/.test(n.overflowY)&&(t.scrollHeight>t.clientHeight&&(!t.closest(`.chat-footer__context`)||r)||n.overscrollBehaviorY===`contain`||n.overscrollBehaviorY===`none`))return}let r=new WheelEvent(`wheel`,{deltaX:e.deltaX,deltaY:e.deltaY,deltaMode:e.deltaMode,cancelable:!0});if(!t.dispatchEvent(r))return;e.preventDefault();let i=getComputedStyle(t),a=e.deltaMode===WheelEvent.DOM_DELTA_PAGE?t.clientHeight:e.deltaMode===WheelEvent.DOM_DELTA_LINE?Number.parseFloat(i.lineHeight)||Number.parseFloat(i.fontSize)*1.2:1;t.scrollBy({top:e.deltaY*a,behavior:`instant`})}function $O(e){if(e.defaultPrevented||!ek.has(e.key))return!1;let t=e.key!==` `&&e.key!==`ArrowUp`&&e.key!==`ArrowDown`&&!e.shiftKey&&!e.altKey&&!e.metaKey,n=vn(),r=t&&!e.ctrlKey&&n,i=e.key===`ArrowUp`||e.key===`PageUp`||e.key===`Home`||e.key===` `&&e.shiftKey,a=!1;for(let o of e.composedPath()){if(o===e.currentTarget)break;if(o instanceof HTMLElement){if(o instanceof HTMLMediaElement&&o.controls&&!e.key.startsWith(`Page`))return!1;if(o instanceof HTMLInputElement){if(o.type===`range`){if(e.key!==` `)return!1}else if([`button`,`checkbox`,`color`,`file`,`image`,`reset`,`submit`].includes(o.type)){if(e.key===` `)return!1}else if(!r&&!(t&&!e.ctrlKey&&e.key.startsWith(`Page`)))return!1}if(o instanceof HTMLSelectElement&&(o.multiple||o.size>1||!r&&(!t||!e.ctrlKey||n||e.key.startsWith(`Page`)))||o instanceof HTMLTextAreaElement&&!r||!a&&o.hasAttribute(`contenteditable`)&&(a=!0,!o.matches(`[contenteditable="false" i]`)&&!r)||e.key===` `&&o.matches(`button, summary`)||/^(auto|scroll)$/.test(getComputedStyle(o).overflowY)&&(i?o.scrollTop>0:o.scrollTop<o.scrollHeight-o.clientHeight))return!1}}return!0}var ek;function tk(){return(tk=e((()=>{Pt(),ek=new Set([`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `])})))()}var $;function nk(){return(nk=e((()=>{r(),Ti(),hi(),_i(),Xl(),wl(),Yc(),B(),ro(),Xt(),mc(),Ot(),jE(),nn(),Y(),FE(),WE(),ZO(),Vw(),qu(),of(),Hf(),If(),Lp(),Qm(),mt(),$=class extends hn{connectedCallback(){this.paneLifecycleRoot=this.closest(`openclaw-app-shell`)??this.parentElement,document.addEventListener(`visibilitychange`,this.handleVisibilityChange),super.connectedCallback(),this.addEventListener(xt,this.synchronizeForegroundTranscript),this.paneLifecycleRoot?.dispatchEvent(new Event($t))}async scheduleUpdate(){for(;this.hasUpdated&&this.isConnected&&document.visibilityState===`hidden`;)await new Promise(e=>{this.hiddenUpdateResume=e});await super.scheduleUpdate()}disconnectedCallback(){this.removeEventListener(xt,this.synchronizeForegroundTranscript),this.context?.connectionBootstrap.setForegroundPane(this,null),this.hiddenUpdateResume?.(),document.removeEventListener(`visibilitychange`,this.handleVisibilityChange),super.disconnectedCallback();let e=this.paneLifecycleRoot;this.paneLifecycleRoot=null,this.conversationVisible=!1,e?.dispatchEvent(new Event($t))}get visuallyPresented(){return this.visuallyPresentedValue}set visuallyPresented(e){let t=this.visuallyPresentedValue;if(e===t)return;let n=this.conversationPresented;this.visuallyPresentedValue=e,this.requestUpdate(`visuallyPresented`,t),this.notifyConversationPresentation(n)}get conversationPresented(){return this.presented&&this.visuallyPresented&&this.conversationVisible}setConversationVisible(e){let t=this.conversationPresented;this.conversationVisible=e,this.notifyConversationPresentation(t)}notifyConversationPresentation(e){e!==this.conversationPresented&&this.dispatchEvent(new Event($t,{bubbles:!0,composed:!0}))}get presented(){return this.presentedValue}set presented(e){let t=this.presentedValue;if(e===t)return;let n=this.conversationPresented;this.headerPresentationGeneration+=1,this.presentedValue=e,this.progressCard.hostUpdate(),this.requestUpdate(`presented`,t),this.presentedChanged(e),this.notifyConversationPresentation(n),this.synchronizeForegroundTranscript()}presentedChanged(e){}get transcriptLoading(){let e=this.state?ry(this.state).phase:`idle`;return e===`pending-connection`||e===`in-flight`}get transcriptReady(){if(!this.state?.connected||this.state.client!==this.context?.gateway.snapshot.client)return!1;let e=this.state?ry(this.state).phase:`idle`;return e===`committed`||e===`failed`}get headerOutcomeOwner(){return`${this.connectionGeneration}:${this.headerPresentationGeneration}`}ownsHeaderOutcome(e){return this.presented&&e===this.headerOutcomeOwner}get selected(){return this.activeValue}get active(){return this.activeValue&&(!this.context||Ir(this.context).current===this.inputRegion)}set active(e){let t=this.activeValue;e!==t&&(this.activeValue=e,this.requestUpdate(`active`,t),this.activeChanged(this.active),this.synchronizeForegroundTranscript())}activeChanged(e){}retireHeaderSessionMutations(){this.headerSessionMutationAbortController.abort(),this.headerSessionMutationAbortController=new AbortController}get runActivity(){let e=this.state;return e?.connected?{client:e.client,agentId:Z(e),working:Mh(e),completion:e.chatRunStatus}:null}resolveChatReadTarget(){let e=this.state;if(!e)return;let t=Ft(e,e.sessionKey);if(t.agentId)return t;let n=iy(e);return n&&jt(n.key)?Ft(e,n.key):n?.agentId&&(n.key===`global`||n.key===`unknown`)?{sessionKey:n.key,agentId:n.agentId}:void 0}isCurrentSessionArchived(e){return e.selectedChatSessionArchived||e.sessionsResult?.sessions.some(t=>t.archived===!0&&F(t.key,e.sessionKey))===!0}get presencePayload(){return this.presencePayloadValue}set presencePayload(e){let t=this.presencePayloadValue;this.presencePayloadValue=e;let n=this.context?.gateway.snapshot;PE(t,e,{sessionKey:this.state?.sessionKey??this.sessionKey,selfUser:n?.selfUser,selfInstanceId:n?.client?.instanceId})||this.requestUpdate(`presencePayload`,t)}constructor(){super(),this.paneLifecycleRoot=null,this.handleVisibilityChange=()=>{if(this.progressCard.hostUpdate(),document.visibilityState!==`hidden`){this.hiddenUpdateResume?.();return}let e=this.state;if(!e)return;let t=nf(this.presentationId).composerTextarea?.value,n=t!==void 0&&t!==e.chatMessage;n&&e.handleChatDraftChange(t),(n||e.chatStreamRenderFrame!=null)&&YO(e)},this.minutePoll=new so(this,6e4,()=>this.requestUpdate(),!0,`visible`),this.paneId=`single`,this.presentationId=`single`,this.sessionKey=``,this.routeLoadingSkeleton=!1,this.inputRegion=`page`,this.compact=!1,this.visuallyPresentedValue=!0,this.conversationVisible=!1,this.activeValue=!1,this.headerPresentationGeneration=0,this.presentedValue=!0,this.synchronizeForegroundTranscript=()=>{this.context?.connectionBootstrap.setForegroundPane(this,this.state&&this.isConnected&&this.selected&&this.presented&&this.inputRegion===`page`?{sessionKey:ft(this.state,{sessionKey:this.state.sessionKey}),client:this.state.client,ready:this.transcriptReady||iy(this.state)!==void 0}:null)},this.focusComposer=!1,this.dashboardExpanded=!1,this.narrow=!1,this.mergedChrome=!1,this.navDrawerOpen=!1,this.onboarding=!1,this.publishedRunActivity=null,this.chatState=new XO(this,()=>{let e=this.runActivity;(e?.client!==this.publishedRunActivity?.client||e?.agentId!==this.publishedRunActivity?.agentId||e?.working!==this.publishedRunActivity?.working||e?.completion!==this.publishedRunActivity?.completion)&&(this.publishedRunActivity=e,this.dispatchEvent(new Event(zt,{bubbles:!0})))},e=>jd(this.presentationId).transcriptRenderContext.onAsyncQuestionDiscard?.(e)),this.composerCapabilities=new AE(()=>this.requestUpdate()),this.transcript=new wd(this,()=>this.paneId,{visuallyPresented:()=>this.visuallyPresented,onViewportResize:()=>this.chatState.handleTranscriptResize(),canFollowEnd:()=>this.state!==void 0&&Um(this.state),onReaderScroll:e=>this.state&&dm(this.state,e)}),this.progressCard=new lu(this,{gateway:()=>this.context?.gateway,target:()=>this.initialProgressCardTarget()}),this.questionPromptState=sl(()=>{this.questionPrompts=xl(this.questionPromptState),this.requestUpdate()}),this.questionPrompts=[],this.paneWidth=1/0,this.paneResizeObserver=null,this.connectedClient=null,this.boardProviderLifecycleConnected=!1,this.connectionGeneration=0,this.headerSessionMutationAbortController=new AbortController,this.headerEditing=!1,this.headerRenameValue=``,this.headerPlatform=null,this.headerCopiedAction=null,this.continueInTerminalDialog=null,this.headerPlacementMovingKey=null,this.headerPlacementReclaimingKey=null,this.headerPlacementRestartingKey=null,this.sessionSharingStates=new Map,this.sessionSharingHydrationTargets=new Map,this.sessionParticipationTracker=new UE,this.resetConfirmationOpen=!1,this.deferredSessionHydrationRequestVersion=0,this.observedBoardPresence=new Map,this.swarmHydrator=null,this.sessionDiscussionStates=new Map,this.sessionDiscussionOpenUrls=new Map,this.pendingPanelToggleRequests=new Map,this.sessionDiscussionProbes=new Set,this.sessionDiscussionPanels=new Map,this.headerRenameInitialValue=``,this.headerRenameSession=null,this.headerCopiedTimer=null,this.composerPrefillAttentionTimer=null,this.composerPrefillAttentionTarget=null,this.headerWorktreePaths=new Map,this.headerBranches=new Map,this.nativeDraftCleanup=null,this.unreadPatchGuard=new Ha,this.sessionSuggestions=[],this.sessionSuggestionBusyIds=new Set,this.sessionSuggestionsRequestVersion=0,this.sessionSuggestionsRefreshQueued=!1,this.sessionSuggestionTargetSignature=``,this.typingActors=new Map,this.typingTimers=new Map,this.sessionPullRequests=[],this.githubRepo=null,this.sessionPullRequestsStatus=`ready`,this.githubPublication=null,this.dismissedSessionPullRequestIds=new Set,this.dismissedWorkspaceConflictRefs=new Map,this.catalogMessages=[],this.catalogLoading=!1,this.loadingOlder=!1,this.catalogSession=null,this.catalogHost=null,this.catalogLoadGeneration=0,this.catalogRequestedSessionKey=null,this.olderLoadGeneration=0,this.historyObserver=null,this.historyObserverRoot=null,this.historyObserverSentinel=null,this.historyObserverBootstrap=!1,this.historyObserverArmed=!1,this.historyAutoLoadBlocked=!1,this.historyIntentConsumed=!1,this.historyIntentTimer=null,this.historyTouchY=null,this.transcriptScrollTop=null,this.olderCursorsSeen=new Set,Wl(this),new pn(this).effect(()=>this.ownerDocument,xu).watch(()=>this.context&&Ir(this.context),(e,t)=>e.subscribe(t),()=>this.activeChanged(this.active)).watch(()=>this.context?.overlays,(e,t)=>e.subscribe(e=>{this.state&&this.reconcileWaitingApprovalSnapshot(e.approvalQueue),t()})).watch(()=>this.context?.runtimeConfig,(e,t)=>e.subscribe(()=>{this.refreshSwarmRoster(),t()})).watch(()=>this.context?.theme,(e,t)=>e.subscribe(t)).watch(()=>this.context?.plugins,(e,t)=>e.subscribe(t)).watch(()=>this.resolveBoardProvider(),(e,t)=>{let n=e.snapshot$.subscribe(t),r=e.loadError$.subscribe(t);return()=>{n(),r()}}).effect(()=>this.resolveBoardProvider(),e=>e.events.subscribe(e=>this.handleBoardCommand(e)))}},A([re({context:di,subscribe:!0})],$.prototype,`context`,void 0),A([K({attribute:!1})],$.prototype,`paneId`,void 0),A([K({attribute:!1})],$.prototype,`paneLabel`,void 0),A([K({attribute:!1})],$.prototype,`presentationId`,void 0),A([K({attribute:!1})],$.prototype,`chatMessagesBySession`,void 0),A([K({attribute:!1})],$.prototype,`sessionSnapshotStore`,void 0),A([K({attribute:!1})],$.prototype,`sessionKey`,void 0),A([K({attribute:!1})],$.prototype,`routeLoadingSkeleton`,void 0),A([K({attribute:!1})],$.prototype,`agentId`,void 0),A([K({attribute:!1})],$.prototype,`inputRegion`,void 0),A([K({attribute:!1})],$.prototype,`compact`,void 0),A([K({attribute:!1})],$.prototype,`workContext`,void 0),A([K({attribute:!1})],$.prototype,`draft`,void 0),A([K({attribute:!1})],$.prototype,`focusComposer`,void 0),A([K({attribute:!1})],$.prototype,`dashboardExpanded`,void 0),A([K({attribute:!1})],$.prototype,`routeFace`,void 0),A([K({attribute:!1})],$.prototype,`onFaceChange`,void 0),A([K({attribute:!1})],$.prototype,`onFocusPane`,void 0),A([K({attribute:!1})],$.prototype,`onSessionDeleted`,void 0),A([K({attribute:!1})],$.prototype,`presentationTitle`,void 0),A([K({attribute:!1})],$.prototype,`narrow`,void 0),A([K({attribute:!1})],$.prototype,`mergedChrome`,void 0),A([K({attribute:!1})],$.prototype,`navDrawerOpen`,void 0),A([K({attribute:!1})],$.prototype,`onboarding`,void 0),A([K({attribute:!1})],$.prototype,`onOpenSplitView`,void 0),A([K({attribute:!1})],$.prototype,`onSplitDown`,void 0),A([K({attribute:!1})],$.prototype,`onSplitRight`,void 0),A([K({attribute:!1})],$.prototype,`onClosePane`,void 0),A([K({attribute:!1})],$.prototype,`boardProvider`,void 0),A([xi()],$.prototype,`paneWidth`,void 0),A([xi()],$.prototype,`headerEditing`,void 0),A([xi()],$.prototype,`headerRenameValue`,void 0),A([xi()],$.prototype,`headerPlatform`,void 0),A([xi()],$.prototype,`headerCopiedAction`,void 0),A([xi()],$.prototype,`headerPlacementMovingKey`,void 0),A([xi()],$.prototype,`headerPlacementReclaimingKey`,void 0),A([xi()],$.prototype,`headerPlacementRestartingKey`,void 0),A([xi()],$.prototype,`sessionSharingStates`,void 0),A([xi()],$.prototype,`resetConfirmationOpen`,void 0),A([xi()],$.prototype,`catalogMessages`,void 0),A([xi()],$.prototype,`catalogLoading`,void 0),A([xi()],$.prototype,`loadingOlder`,void 0)})))()}function rk(e){return JSON.stringify([e.question,e.answer,e.ts])}function ik(e,t){let n=e.turns.flatMap(e=>e.attachments??[]),r=[...e.responses],i=t.map(e=>({exchange:e,key:rk(e)}));for(;r.length;){let e=0;if(r.every(([,t])=>(e=i.findIndex((n,r)=>r>=e&&n.key===t)+1,e>0)))break;r.shift()}let a=i.map(({exchange:e,key:t},n)=>{let i=r[0]?.[1]===t?r.shift():void 0;return{turn:i?.[0]??{status:`answered`,...e},key:t,position:n,fresh:!i}}),o=[...a],s=new Map,c=new Set(a.filter(({turn:t,fresh:n})=>!n&&!e.turns.includes(t)).map(({turn:e})=>e)),l=[...c,...e.turns].flatMap(e=>{let t=o.findIndex(({turn:t,fresh:n})=>e.status===`answered`?e===t:e.status===`failed`&&e.question===t.question&&n),n=t<0?void 0:o.splice(t,1)[0];return n&&(Object.assign(e,n.turn),delete e.attachments,n.turn=e,s.set(e,n.position)),!n&&e.status===`answered`?[]:[e]});for(let{turn:e,position:t}of o){let n=l.findLastIndex(e=>(s.get(e)??1/0)<t),r=l.findIndex((e,t)=>t>n&&e.status===`answered`);s.set(e,t),l.splice(r<0?l.length:r,0,e)}e.turns=l.filter(e=>!c.has(e)).slice(-24),Og(n,[e.turns.flatMap(e=>e.attachments??[])]),e.responses=new Map(a.slice(-24).map(({turn:e,key:t})=>[e,t]))}function ak(e,t){return`${t?.trim()??``}\0${e.trim()}`}function ok(e){let t=e.flatMap(e=>e.selectionAnnotation?[qd(e.selectionAnnotation)]:[]);return t.length?t.join(`

`):void 0}function sk(e,t,n,r,i,a){let o=ok(i??[]),s=i?.filter(e=>!e.selectionAnnotation);return s?.length&&fn(a),e.request(`sessions.companion.ask`,{sessionKey:t,...r?{agentId:r}:{},question:n,...o?{selectionContext:o}:{},...s?.length?{attachments:RD(s)}:{}},{timeoutMs:dk})}function ck(e,t,n){return e.request(`sessions.companion.state`,{sessionKey:t,...n?{agentId:n}:{}})}function lk(e,t,n){return e.request(`sessions.companion.reset`,{sessionKey:t,...n?{agentId:n}:{}})}var uk,dk,fk;function pk(){return(pk=e((()=>{Gi(),y(),H(),tt(),Dt(),zD(),Ig(),yf(),Wd(),uk=`SESSION_COMPANION_BUSY`,dk=7e4,fk=class{constructor(e=()=>{}){this.notify=e,this.threads=new Map,this.hydrationTokens=new Map,this.submissionTokens=new Map}view(e,t){return this.get(e,t)}setDraft(e,t,n){let r=this.get(e,n);r.draft!==t&&(r.draft=t,r.draftRevision+=1,this.notify())}setAttachments(e,t,n){if((ok(t)?.length??0)>16e3)return ct({message:R(`chat.rail.selectionTooLong`)}),!1;let r=this.get(e,n);return r.attachments=t,this.notify(),!0}async hydrate(e,t,n){let r=e.trim();if(!r)return;let i=ak(r,n),a=this.get(r,n),o=Symbol(i);this.hydrationTokens.set(i,o),a.loading=!0,this.notify();try{for(;this.submissionTokens.has(i)||a.pendingResets.size;)await Promise.all([this.submissionTokens.get(i)?.promise,...[...a.pendingResets].map(e=>e.promise)]);if(this.hydrationTokens.get(i)!==o)return;let e=a.revision,n=await t(r);for(;a.pendingResets.size;)await Promise.all([...a.pendingResets].map(e=>e.promise));if(this.hydrationTokens.get(i)!==o||a.revision!==e)return;ik(a,n.exchanges),a.revision+=1,this.notify()}catch{}finally{this.hydrationTokens.get(i)===o&&(this.hydrationTokens.delete(i),a.loading=!1,this.notify())}}async submit(e,t,n,r){let i=e.trim(),a=typeof t==`string`?t.trim():t.question;if(!i||!a)return;let o=ak(i,r),s=this.get(i,r);if(s.turns.some(e=>e.status===`pending`)||s.attachmentReads?.pendingReads||typeof t!=`string`&&(!s.turns.includes(t)||t.status!==`failed`))return;let c=typeof t==`string`?s.attachments:t.attachments,u={question:a,status:`pending`,...c?.length?{attachments:c}:{}};if(typeof t==`string`){let e=[...s.turns,u];for(let t of e.slice(0,-24))en(t.attachments??[]);s.turns=e.slice(-24),s.attachments=[],s.draft=``,s.draftRevision+=1}else s.turns=s.turns.map(e=>e===t?u:e);s.revision+=1;let d=ne();this.submissionTokens.set(o,d),this.notify();try{let e=await n(i,a,u.attachments);if(this.submissionTokens.get(o)!==d)return;en(u.attachments??[]),delete u.attachments,Object.assign(u,{status:`answered`,answer:e.answer,ts:e.ts}),s.responses.set(u,rk({question:a,...e})),s.responses=new Map([...s.responses].slice(-24))}catch(e){if(this.submissionTokens.get(o)!==d)return;let t=l(l(e).details),n=_(t,`reason`)??null,r=n===`image-input-unsupported`,i=t.code===uk?`busy`:n===`context-unavailable`?`history-unavailable`:n===`session-missing`?`missing`:n===`rate-limited`?`rate-limited`:r?`image-unsupported`:n===`utility-model-unavailable`?`model-unavailable`:`unavailable`;Object.assign(u,{status:`failed`,hint:i,retryable:r||!!l(e).retryable||n===null})}finally{d.resolve(),this.submissionTokens.get(o)===d&&(this.submissionTokens.delete(o),s.revision+=1,this.notify())}}async reset(e,t,n){let r=e.trim();if(!r)return;let i=ak(r,n),a=this.get(r,n),o=new Set([...a.turns,...a.responses.keys()]),s=a.draftRevision,c=a.attachmentReads,l=[...c?.project(a.attachments??[])??[]],u=new Set([...(a.attachments??[]).map(({id:e})=>e),...l.map(({attachment:e})=>e.id)]),d=this.submissionTokens.get(i),f=this.hydrationTokens.get(i),p=ne();a.pendingResets.add(p);try{if(await t(r),this.threads.get(i)!==a)return;let e=[...a.attachments??[],...a.turns.flatMap(e=>e.attachments??[])];a.turns=a.turns.filter(e=>!o.has(e)),a.responses=new Map([...a.responses].filter(([e])=>!o.has(e))),a.draftRevision===s&&(a.draft=``,a.draftRevision+=1);for(let e of l)c?.remove(e);a.attachments=(a.attachments??[]).filter(({id:e})=>!u.has(e)),d&&this.submissionTokens.get(i)===d&&(this.submissionTokens.delete(i),d.resolve()),f&&this.hydrationTokens.get(i)===f&&(this.hydrationTokens.delete(i),a.loading=!1),Og(e,[a.attachments??[],a.turns.flatMap(e=>e.attachments??[])]),a.revision+=1,this.notify()}finally{a.pendingResets.delete(p),p.resolve()}}retire(e,t){let n=e?ak(e,t):null;for(let[e,t]of this.threads)if(!(n&&n!==e)){t.attachmentReads?.abortReads(),en(t.attachments??[]);for(let e of t.turns)en(e.attachments??[])}for(let e of[this.threads,this.hydrationTokens,this.submissionTokens])n?e.delete(n):e.clear();this.notify()}get(e,t){let n=ak(e,t),r=this.threads.get(n);return r||(r={turns:[],loading:!1,draft:``,attachments:[],attachmentReads:new zd(this.notify),revision:0,draftRevision:0,pendingResets:new Set,responses:new Map},this.threads.set(n,r)),r}}})))()}var mk;function hk(){return(hk=e((()=>{Gi(),H(),Ya(),me(),tt(),Dt(),nk(),pk(),Vw(),qu(),Wd(),Lh(),mk=class extends ${constructor(...e){super(...e),this.sessionCompanionHydrationKey=``,this.sessionCompanionFocusGeneration=0,this.sessionCompanionPresented=!1,this.sessionCompanionThreads=new fk(()=>{this.requestUpdate()}),this.setSessionObserverVisibility=e=>{let t=this.state;t?.connected&&t.client&&un(t.client,e).catch(()=>void 0),this.requestUpdate()},this.submitSessionCompanionQuestion=async e=>{let t=this.state;if(!t||!t.sessionKey)return;let{sessionKey:n,client:r,connected:i}=t,a=Z(t);this.requestSessionRail(`open`);let o=typeof e==`string`?e:e.question;if(o.trim()){if(!i||!r){this.sessionCompanionThreads.setDraft(n,o,a);return}if((typeof e==`string`?this.sessionCompanionThreads.view(n,a).attachments:e.attachments)?.some(e=>!e.selectionAnnotation)&&!yn(t.uploadConfig)){ct({message:qt()});return}await this.sessionCompanionThreads.submit(n,e,(e,n,i)=>sk(r,e,n,a,i,t.uploadConfig),a)}},this.stageSessionCompanionAttachment=(e,t)=>{let n=this.state;if(!n||n.sessionKey!==t||!e.selectionAnnotation)return!1;let r=Z(n),i=this.sessionCompanionThreads.view(t,r),a=[...i.attachments??[],e];if(qd({...e.selectionAnnotation,comment:``}).length>16e3)ct({message:R(i.draft.trim()?`chat.rail.selectionTooLong`:`chat.rail.selectionQuoteOnly`)});else if(!this.sessionCompanionThreads.setAttachments(t,a,r))return!1;return i.draft.trim()||this.sessionCompanionThreads.setDraft(t,Ta(e.selectionAnnotation.text)??``,r),this.requestSessionRail(`open`),!0}}selectedSessionRailMode(e){let t=this.state;return t?.sessionKey===e&&Je(t.sidebarLayout,`companion`)?`expanded`:`hidden`}restorePaneSidebarLayout(e){if(!this.compact)return e;let t=e.columns[0]?.panels.find(e=>e.slot===`conversation`);return{...t?rh(e,t.id):e,open:!1,expanded:!1}}setChatSidePanelOpen(e,t){let n=this.state;if(!n)return;let r=t??n.sidebarLayout,i=Bm(r,e);r.columns[0]?.panels.some(e=>e.slot===`companion`)&&this.setSessionObserverVisibility(Je(i,`companion`)),this.commitSidebarLayout(i,ot(r)?.slot===`dashboard`?{dashboardPresentation:`personal`}:void 0)}requestSessionRail(e){let t=this.state;if(!t)return;let n=this.selectedSessionRailMode(t.sessionKey)===`expanded`;if(e===`toggle`&&n){this.commitSidebarLayout(bh(t.sidebarLayout,`companion`)),this.setSessionObserverVisibility(!1);return}this.commitSidebarLayout(Ch(t.sidebarLayout,`companion`)),this.setSessionObserverVisibility(!0)}syncSessionCompanionPresentation(e){(this.sessionCompanionPresented!==e||!e&&this.sessionCompanionFocusRequest!==void 0)&&(this.sessionCompanionPresented=e,e&&this.state?this.sessionCompanionFocusRequest??=this.captureSessionCompanionFocus(this.state).requestFocus:(this.sessionCompanionFocusGeneration+=1,this.sessionCompanionFocusRequest=void 0))}captureSessionCompanionFocus(e){let t=e.sessionKey,n=Z(e),r=this.connectionGeneration,i=this.sessionCompanionFocusGeneration,a=nf(this.presentationId),o=a.editRevision,s=e.chatMessage,c=()=>this.state===e&&e.sessionKey===t&&Z(e)===n&&this.connectionGeneration===r&&this.sessionCompanionFocusGeneration===i&&a.editRevision===o&&e.chatMessage===s&&this.sessionCompanionPresented&&(this.ownerDocument.activeElement===this.ownerDocument.body||this.contains(this.ownerDocument.activeElement))&&this.isConnected&&this.active&&this.visuallyPresented&&this.presented,l=()=>(this.sessionCompanionFocusRequest===l&&(this.sessionCompanionFocusRequest=void 0,this.requestUpdate()),c());return{ownsFocus:c,requestFocus:l}}async openSessionCompanion(e,t){let{ownsFocus:n,requestFocus:r}=this.captureSessionCompanionFocus(e);this.sessionCompanionFocusRequest=r,this.requestUpdate(),await this.submitSessionCompanionQuestion(t),n()&&(this.sessionCompanionFocusRequest=r,this.requestUpdate())}hydrateSessionCompanion(e){let t=this.state;if(!t?.connected||!t.client||!e||Wt(e))return;let n=Z(t),r=`${this.connectionGeneration}\0${n}\0${e}`;this.sessionCompanionHydrationKey!==r&&(this.sessionCompanionHydrationKey=r,this.sessionCompanionThreads.hydrate(e,e=>ck(t.client,e,n),n))}}})))()}var gk,_k;function vk(){return(vk=e((()=>{Ai(),su(),H(),bn(),on(),se(),B(),tt(),hk(),pk(),Vw(),Id(),gk=`session.members.listEvidence`,_k=class extends mk{constructor(...e){super(...e),this.clearSessionCompanion=async()=>{let e=this.captureConnectionScope(),t=e?.state.sessionKey;if(!e||!t)return;let n=Z(e.state);await this.sessionCompanionThreads.reset(t,t=>lk(e.client,t,n),n).catch(n=>{this.presented&&this.isConnectionScopeCurrent(e)&&e.state.sessionKey===t&&this.publishHeaderError(n)})}}setSessionSharingState(e,t){this.sessionSharingStates=new Map(this.sessionSharingStates).set(e,t)}sessionSharingAgentId(e){return e===`global`?this.state?Z(this.state):void 0:jt(e)?.agentId}sessionSharingCacheKey(e){return`${this.sessionSharingAgentId(e)??``}\0${e}`}currentSessionSharingRow(e,t){let n=e.state.sessionsResult?.sessions.find(e=>F(e.key,t.key));if(!n||!Nf(t)||!Nf(n))return null;if(n===t)return n;let r=t.sessionId?.trim(),i=n.sessionId?.trim();return r&&i&&r===i?n:null}async loadSessionSharing(e,t=!1){let n=this.captureConnectionScope(),r=n?this.currentSessionSharingRow(n,e):null;if(!n||!r||!z(n.context.gateway.snapshot,{method:gk,requiredScope:`operator.read`}).allowed)return;let i=this.sessionSharingCacheKey(r.key),a=this.sessionSharingStates.get(i);if(a?.loading&&!t)return;let o={...a,loading:!0,error:void 0},s=()=>this.sessionSharingStates.get(i)===o,c=()=>{if(!s())return;let e=new Map(this.sessionSharingStates);e.delete(i),this.sessionSharingStates=e};this.setSessionSharingState(i,o);let l;try{l={loading:!1,result:await n.client.request(gk,{sessionKey:r.key,...this.sessionSharingAgentId(r.key)?{agentId:this.sessionSharingAgentId(r.key)}:{}})}}catch(e){l={loading:!1,error:P(e)}}if(!this.ownsHeaderOutcomeScope(n)||!this.currentSessionSharingRow(n,r)||!s()){this.isConnectionScopeCurrent(n)&&c();return}this.setSessionSharingState(i,l)}failSharing(e,t,n,r){this.ownsHeaderOutcomeScope(e)&&(this.setSessionSharingState(t,{...this.sessionSharingStates.get(t)??{loading:!1},loading:!1,error:P(r)}),F(this.state?.sessionKey,n)&&this.publishHeaderError(r,e.headerOutcomeOwner))}async setSessionPublicShare(e,t){let n=this.captureConnectionScope(),r=n?this.currentSessionSharingRow(n,e):null,i=r?.sessionId;if(!n||!r||!i)return;let a=()=>z(n.context.gateway.snapshot,{method:`session.publicShare.set`,requiredScope:`operator.write`}).allowed,o=()=>this.ownsHeaderOutcomeScope(n)&&this.currentSessionSharingRow(n,r)?.sessionId===i&&F(n.state.sessionKey,r.key),s=this.sessionSharingCacheKey(r.key),c=this.sessionSharingStates.get(s);if(!a()||!o()||c?.loading)return;let l={...c,loading:!0,error:void 0};this.setSessionSharingState(s,l);try{if(t&&(!o()||!a()||!await hl({title:R(`chat.sessionSharing.publicConfirmTitle`),message:R(`chat.sessionSharing.publicConfirmMessage`),confirmLabel:R(`chat.sessionSharing.publicConfirmEnable`),danger:!0}))||!o()||!a())return;let e=await n.client.request(`session.publicShare.set`,{sessionKey:r.key,agentId:this.sessionSharingAgentId(r.key),expectedSessionId:i,enabled:t});if(!o()){this.sessionSharingHydrationTargets.delete(s);return}this.setSessionSharingState(s,{loading:!1,...c?.result?{result:{...c.result,publicShare:e.publicShare}}:{}}),ct({message:R(t?`chat.sessionSharing.publicEnabled`:`chat.sessionSharing.publicDisabled`)}),await this.loadSessionSharing(r,!0)}catch(e){o()&&this.failSharing(n,s,r.key,e)}finally{this.sessionSharingStates.get(s)===l&&this.setSessionSharingState(s,{...c,loading:!1})}}async copySessionPublicLink(e){let t=this.captureConnectionScope(),n=t?this.currentSessionSharingRow(t,e):null;if(!t||!n)return;let r=this.sessionSharingStates.get(this.sessionSharingCacheKey(e.key))?.result?.publicShare,i=n.sessionId;if(!r||!i)return;let a=()=>this.ownsHeaderOutcomeScope(t)&&this.currentSessionSharingRow(t,n)?.sessionId===i;try{let e=t.context.gateway,n=e.snapshot.hello?.controlUiUrl,i=n??t.client.gatewayUrl??e.connection.gatewayUrl,o=new URL(i||window.location.href);o.protocol=o.protocol.replace(/^ws/u,`http`);let s=Ii({basePath:n?o.pathname:t.context.basePath,token:r.token}),c=await Jt(new URL(s,o.origin).href,a);a()&&ct({message:R(c?`common.copied`:`common.copyFailed`)})}catch(e){a()&&this.publishHeaderError(e)}}async setSessionVisibility(e,t){let n=this.captureConnectionScope(),r=n?this.currentSessionSharingRow(n,e):null;if(!n||!r||t===r.visibility)return;let i=this.sessionSharingAgentId(r.key),a=this.sessionSharingCacheKey(r.key),o={sessionKey:r.key,visibility:t,...i?{agentId:i}:{}};if(z(n.context.gateway.snapshot,{method:`session.visibility.set`,requiredScope:`operator.write`}).allowed)try{if(await n.client.request(`session.visibility.set`,o),!this.ownsHeaderOutcomeScope(n)||!this.currentSessionSharingRow(n,r))return;let e=await n.sessions.reconcileMutation(i),t=this.currentSessionSharingRow(n,r);if(!this.ownsHeaderOutcomeScope(n)||!t)return;if(e.status===`failed`){this.failSharing(n,a,r.key,e.error);return}await this.loadSessionSharing(t,!0)}catch(e){if(!this.ownsHeaderOutcomeScope(n)||!this.currentSessionSharingRow(n,r))return;this.failSharing(n,a,r.key,e)}}async setSessionMember(e,t,n){let r=this.captureConnectionScope(),i=r?this.currentSessionSharingRow(r,e):null;if(!r||!i)return;let a=this.sessionSharingAgentId(i.key),o=this.sessionSharingCacheKey(i.key),s=n?`session.members.add`:`session.members.remove`,c={sessionKey:i.key,identityId:t,...a?{agentId:a}:{}};if(z(r.context.gateway.snapshot,{method:s,requiredScope:`operator.write`}).allowed)try{if(await r.client.request(s,c),!this.ownsHeaderOutcomeScope(r)||!this.currentSessionSharingRow(r,i)||(await this.loadSessionSharing(i,!0),!this.ownsHeaderOutcomeScope(r)||!this.currentSessionSharingRow(r,i)))return;let e=await r.sessions.reconcileMutation(a);e.status===`failed`&&this.ownsHeaderOutcomeScope(r)&&this.currentSessionSharingRow(r,i)&&this.failSharing(r,o,i.key,e.error)}catch(e){if(!this.ownsHeaderOutcomeScope(r)||!this.currentSessionSharingRow(r,i))return;this.failSharing(r,o,i.key,e)}}captureConnectionScope(){let e=this.state;if(!e?.client)return null;let t={context:this.context,state:e,client:e.client,generation:this.connectionGeneration,headerOutcomeOwner:this.headerOutcomeOwner,sessions:this.context.sessions};return this.isConnectionScopeCurrent(t)?t:null}isConnectionScopeCurrent(e){return this.isConnected&&this.context===e.context&&this.state===e.state&&e.state.connected&&e.state.client===e.client&&this.connectedClient===e.client&&e.context.gateway.snapshot.phase===`connected`&&e.context.gateway.snapshot.client===e.client&&this.connectionGeneration===e.generation}ownsHeaderOutcomeScope(e){return this.isConnectionScopeCurrent(e)&&this.ownsHeaderOutcome(e.headerOutcomeOwner)}}})))()}function yk(e,t){let n=rt(e);if(!n||!ve(t,n.key,n.agentId??void 0))return;let r=m(m(e)?.message);if(j(r?.role)?.toLowerCase()!==`user`)return;let i=Vn(m(r?.__openclaw)?.senderIdentity);return i?.type===`profile`?i.id:void 0}function bk(){return(bk=e((()=>{Hn(),Ce(),B()})))()}var xk,Sk,Ck,wk,Tk,Ek;function Dk(){return(Dk=e((()=>{Br(),H(),on(),fa(),eo(),I(),B(),Pw(),vk(),Vw(),bk(),Id(),xk=2500,Sk=1e4,Ck=3e4,wk=300,Tk=250,Ek=class extends _k{constructor(...e){super(...e),this.typingActiveIds=new Set,this.typingViews=[]}syncSelectedSessionSharing(e){let t=e?.sessionId?.trim();if(!e||!t||!this.presented||!Nf(e))return;let n=this.sessionSharingCacheKey(e.key);if(this.sessionSharingHydrationTargets.get(n)===t&&this.sessionSharingStates.has(n))return;this.sessionSharingHydrationTargets.set(n,t);let r=new Map(this.sessionSharingStates);r.delete(n),this.sessionSharingStates=r,this.loadSessionSharing(e,!0)}suggestionMatchesCurrentSession(e){let t=this.state;return!!(t?.connected&&ve({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello,sessionKey:t.sessionKey},e.sessionKey,e.agentId))}hasMultipleIdentities(){return Eo(this.presencePayload)}resetSessionSuggestions(){this.sessionSuggestionsRequestVersion+=1,this.sessionSuggestionsRefreshQueued=!1,this.sessionSuggestions=[],this.sessionSuggestionRole=void 0,this.sessionSuggestionBusyIds.clear(),this.sessionSuggestionAddOperation=void 0,this.sessionSuggestionEditOperation=void 0}syncSessionSuggestionTarget(e,t){let n=t?`${e}\0${t.key}\0${t.sessionId??``}\0${t.visibility??`shared`}\0${t.sharingRole??`owner`}`:``;n!==this.sessionSuggestionTargetSignature&&(this.sessionSuggestionTargetSignature=n,this.resetSessionSuggestions(),this.clearTypingActors(),this.refreshSessionSuggestions())}refreshSessionSuggestions(){if(this.sessionSuggestionsRefreshPromise)return this.sessionSuggestionsRefreshVersion!==this.sessionSuggestionsRequestVersion&&(this.sessionSuggestionsRefreshQueued=!0),this.sessionSuggestionsRefreshPromise;let e=++this.sessionSuggestionsRequestVersion;this.sessionSuggestionsRefreshVersion=e;let t=this.loadSessionSuggestions(e).finally(()=>{this.sessionSuggestionsRefreshPromise===t&&(this.sessionSuggestionsRefreshPromise=void 0,this.sessionSuggestionsRefreshVersion=void 0,this.sessionSuggestionsRefreshQueued&&(this.sessionSuggestionsRefreshQueued=!1,this.refreshSessionSuggestions()))});return this.sessionSuggestionsRefreshPromise=t,t}async loadSessionSuggestions(e){let t=this.sessionSuggestionTargetSignature,n=this.captureConnectionScope(),r=n?Q(n.state):void 0;if(!n||!r||!this.hasMultipleIdentities()||!da(n.context.gateway.snapshot,`session.suggestions.list`)){this.sessionSuggestions=[],this.sessionSuggestionRole=void 0,this.requestUpdate();return}let i=n.state.sessionKey;try{let r=await n.client.request(`session.suggestions.list`,{sessionKey:i,...L(n.state,i)});if(!this.isConnectionScopeCurrent(n)||n.state.sessionKey!==i||e!==this.sessionSuggestionsRequestVersion||t!==this.sessionSuggestionTargetSignature)return;this.sessionSuggestions=r.suggestions,this.sessionSuggestionRole=r.role,this.requestUpdate()}catch{e===this.sessionSuggestionsRequestVersion&&t===this.sessionSuggestionTargetSignature&&(this.sessionSuggestions=[],this.sessionSuggestionRole=void 0,this.requestUpdate())}}handleSessionSuggestionEvent(e){if(!this.hasMultipleIdentities()||!this.suggestionMatchesCurrentSession(e.suggestion))return;let t=this.sessionSuggestionsRefreshPromise!==void 0||this.sessionSuggestionRole!==void 0;this.sessionSuggestionsRequestVersion+=1;let n=this.context.gateway.snapshot.selfUser?.id;(this.sessionSuggestionRole!==`viewer`||e.suggestion.author.id===n)&&(this.sessionSuggestions=e.action===`added`?[...this.sessionSuggestions.filter(t=>t.id!==e.suggestion.id),e.suggestion].toSorted((e,t)=>e.createdAt-t.createdAt||e.id.localeCompare(t.id)):e.suggestion.author.id===n?this.sessionSuggestions.map(t=>t.id===e.suggestion.id?e.suggestion:t):this.sessionSuggestions.filter(t=>t.id!==e.suggestion.id),this.sessionSuggestionBusyIds.delete(e.suggestion.id),this.requestUpdate(),t&&this.refreshSessionSuggestions())}async addCurrentSessionSuggestion(){let e=this.captureConnectionScope(),t=e?.state.chatMessage??``;if(!e||!t.trim()||this.sessionSuggestionAddOperation||!this.hasMultipleIdentities())return;if(e.state.chatMentions?.length||e.state.chatAttachments.length>0){e.state.chatError=R(e.state.chatMentions?.length?`chat.mentions.unsupported`:`chat.sessionSuggestions.attachmentsUnsupported`),e.state.lastError=e.state.chatError,e.state.requestUpdate?.();return}let n=e.state.sessionKey,r=Symbol(`session-suggestion-add`);this.sessionSuggestionAddOperation=r,this.requestUpdate();try{let i=await e.client.request(`session.suggestions.add`,{sessionKey:n,text:t,...L(e.state,n)});if(this.sessionSuggestionAddOperation!==r||!this.isConnectionScopeCurrent(e)||e.state.sessionKey!==n)return;e.state.chatMessage===t&&!e.state.chatMentions?.length&&e.state.handleChatDraftChange(``,[]),this.sessionSuggestions=[...this.sessionSuggestions.filter(e=>e.id!==i.suggestion.id),i.suggestion]}catch(t){this.sessionSuggestionAddOperation===r&&this.isConnectionScopeCurrent(e)&&(e.state.chatError=P(t),e.state.lastError=e.state.chatError)}finally{this.sessionSuggestionAddOperation===r&&(this.sessionSuggestionAddOperation=void 0,this.requestUpdate())}}async resolveCurrentSessionSuggestion(e,t){let n=this.captureConnectionScope();if(!n||this.sessionSuggestionBusyIds.has(e.id)||t===`edit`&&this.sessionSuggestionEditOperation!==void 0||!this.suggestionMatchesCurrentSession(e)||this.isCurrentSessionArchived(n.state)&&t!==`dismiss`)return;let r=n.state.sessionKey,i=this.sessionSuggestionTargetSignature,a=()=>this.isConnectionScopeCurrent(n)&&n.state.sessionKey===r&&this.sessionSuggestionTargetSignature===i,o=t===`edit`?{text:n.state.chatMessage,mentions:n.state.chatMentions?.map(e=>({...e}))}:void 0,s=t===`edit`?Symbol(`session-suggestion-edit`):void 0;s&&(this.sessionSuggestionEditOperation=s),this.sessionSuggestionBusyIds.add(e.id),t===`edit`&&(n.state.handleChatDraftChange(e.text,[]),queueMicrotask(()=>this.querySelector(Ow)?.focus({preventScroll:!0}))),this.requestUpdate();try{let i=await n.client.request(`session.suggestions.resolve`,{sessionKey:r,id:e.id,resolution:t,...L(n.state,r)});if(!a())return;this.sessionSuggestions=i.suggestion.author.id===this.context.gateway.snapshot.selfUser?.id?[...this.sessionSuggestions.filter(t=>t.id!==e.id),i.suggestion].toSorted((e,t)=>e.createdAt-t.createdAt||e.id.localeCompare(t.id)):this.sessionSuggestions.filter(t=>t.id!==e.id)}catch(r){a()&&(t===`edit`&&r instanceof Yn&&o!==void 0&&n.state.chatMessage===e.text&&!n.state.chatMentions?.length&&n.state.handleChatDraftChange(o.text,o.mentions??[]),n.state.chatError=P(r),n.state.lastError=n.state.chatError)}finally{a()&&(this.sessionSuggestionEditOperation===s&&(this.sessionSuggestionEditOperation=void 0),this.sessionSuggestionBusyIds.delete(e.id),this.requestUpdate())}}clearTypingActors(){this.clearTypingRequest();for(let e of this.typingTimers.values())window.clearTimeout(e);this.typingTimers.clear(),this.typingActors.clear(),this.typingActiveIds.clear(),this.refreshTypingPresentation()}pruneTypingActors(){let e=this.state;if(!e||this.typingActors.size===0)return;let t=Ft(e,e.sessionKey),n=wn(t.sessionKey,t.agentId),r=new Set(Qo(this.presencePayload).users.flatMap(e=>e.identity?.type===`profile`&&e.watchedSessions.includes(n)?[e.identity.id]:[])),i=!1;for(let e of this.typingActors.keys())r.has(e)||(this.removeTypingActor(e),i=!0);i&&this.refreshTypingPresentation()}handleSessionTypingEvent(e){let t=this.context.gateway.snapshot.selfUser?.id,n=this.state,r=n?Q(n):void 0;if(!this.hasMultipleIdentities()||e.actor.id===t||!n||r?.sessionId!==e.sessionId||!ve({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello,sessionKey:n.sessionKey},e.sessionKey,e.agentId))return;let i=this.typingTimers.get(e.actor.id);if(i!==void 0&&(window.clearTimeout(i),this.typingTimers.delete(e.actor.id)),!e.typing){this.removeTypingActor(e.actor.id),this.refreshTypingPresentation();return}let a=e.preview?Sk:xk,o=Date.now(),s=o+Ck,c={label:e.actor.label??e.actor.id,retireAt:e.preview?s:o+a,...e.preview?{preview:e.preview}:{}};this.typingActiveIds.add(e.actor.id),this.typingActors.set(e.actor.id,c);let l=()=>{if(this.typingActors.get(e.actor.id)!==c)return;this.typingTimers.delete(e.actor.id);let t=s-Date.now();if(!c.preview||t<=0){this.removeTypingActor(e.actor.id);let t=Date.now();for(let[e,n]of this.typingActors)n.retireAt<=t&&this.removeTypingActor(e)}else{if(!c.paused)for(let e of this.typingActiveIds){let t=this.typingActors.get(e);t?.preview&&t.retireAt-Ck+Sk<=Date.now()&&(t.paused=!0,this.typingActiveIds.delete(e))}let n=t-wk;n<=0&&(c.exitDurationMs=t),this.typingTimers.set(e.actor.id,window.setTimeout(l,n>0?n:t))}this.refreshTypingPresentation()};this.typingTimers.set(e.actor.id,window.setTimeout(l,a)),this.refreshTypingPresentation()}clearTypingActorForSessionMessage(e){let t=this.state;if(!t)return;let n=yk(e,{agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello,sessionKey:t.sessionKey});n&&this.removeTypingActor(n)&&this.refreshTypingPresentation()}removeTypingActor(e){return this.typingActors.get(e)?(this.typingActiveIds.delete(e),window.clearTimeout(this.typingTimers.get(e)),this.typingTimers.delete(e),this.typingActors.delete(e)):!1}refreshTypingPresentation(){let e=[];for(let[t,n]of this.typingActors)if(e.push({id:t,label:n.label,...n.preview?{preview:n.preview}:{},...n.paused?{paused:!0}:{},...n.exitDurationMs===void 0?{}:{exitDurationMs:n.exitDurationMs}}),e.length===2)break;let t=0;for(let n of this.typingActiveIds){if(n===e[0]?.id||n===e[1]?.id)continue;let r=this.typingActors.get(n);r&&(t+=1,e.length<7&&e.push({id:n,label:r.label}))}let n=t>5?{several:!0}:void 0;e.length===this.typingViews.length&&e.every((e,t)=>{let n=this.typingViews[t];return n?.id===e.id&&n.label===e.label&&n.preview===e.preview&&n.paused===e.paused&&n.exitDurationMs===e.exitDurationMs})&&n?.several===this.typingOverflow?.several||(this.typingViews=e,this.typingOverflow=n,this.requestUpdate())}typingActorViews(){return this.typingViews}sendTypingState(e,t){let n=this.captureConnectionScope(),r=n?Q(n.state):void 0;if(!n||!r?.sessionId||!this.hasMultipleIdentities()){this.clearTypingRequest();return}let i=n.state.sessionKey,{sessionId:a,sharingRole:o,visibility:s}=r,c=()=>{let r=Q(n.state);if(!this.isConnectionScopeCurrent(n)||n.state.sessionKey!==i||r?.sessionId!==a||r.sharingRole!==o||r.visibility!==s||!this.hasMultipleIdentities())return;let c=e?t?.trim():void 0,l=c?Array.from(c).slice(-300).join(``):void 0;this.typingRequestSentAt=e?Date.now():void 0,n.client.request(`session.typing`,{sessionKey:i,sessionId:a,typing:e,...l?{preview:l}:{},...L(n.state,i)}).catch(()=>void 0)},l=e&&this.typingRequestSentAt!==void 0?Tk-(Date.now()-this.typingRequestSentAt):0;if(l<=0){this.clearTypingRequest(),c();return}this.pendingTypingRequest=c,this.typingRequestTimer??=window.setTimeout(()=>{let e=this.pendingTypingRequest;this.typingRequestTimer=void 0,this.pendingTypingRequest=void 0,e?.()},l)}clearTypingRequest(){window.clearTimeout(this.typingRequestTimer),this.typingRequestTimer=void 0,this.typingRequestSentAt=void 0,this.pendingTypingRequest=void 0}}})))()}var Ok;function kk(){return(kk=e((()=>{t(),Br(),Rr(),Pr(),H(),bn(),on(),fa(),me(),It(),Dk(),Vw(),Ok=class extends Ek{constructor(...e){super(...e),this.taskSuggestions=[],this.taskSuggestionBusyIds=new Set,this.taskSuggestionCopiedIds=new Set,this.taskSuggestionOperations=new Map,this.taskSuggestionsRequestVersion=0,this.taskSuggestionSwapGeneration=0,this.navigateTaskSuggestion=(e,t)=>{let n=this.taskSuggestions.findIndex(t=>t.id===e);if(n<0||this.taskSuggestions.length<2)return;let r=t===`next`?1:-1,i=this.taskSuggestions[(n+r+this.taskSuggestions.length)%this.taskSuggestions.length];i&&(this.activeTaskSuggestionId=i.id,this.taskSuggestionSwapDirection=t,this.taskSuggestionSwapGeneration+=1,this.requestUpdate(),this.updateComplete.then(()=>{[...this.querySelectorAll(`.task-suggestion`)].find(e=>e.dataset.taskId===i.id)?.querySelector(`[data-task-${t===`next`?`next`:`prev`}]`)?.focus()}))},this.acceptTaskSuggestion=(e,t=`local`,n)=>this.resolveTaskSuggestion(e,`accept`,t,n),this.dismissTaskSuggestion=e=>this.resolveTaskSuggestion(e,`dismiss`),this.copyTaskSuggestionPrompt=async e=>{let t=await Jt(e.prompt);if(this.isConnected){if(!t){let e=R(`chat.taskSuggestions.copyPromptFailed`);this.state&&(this.state.lastError=e,this.state.chatError=e),this.requestUpdate();return}this.taskSuggestionCopiedIds.add(e.id),this.requestUpdate(),setTimeout(()=>{this.taskSuggestionCopiedIds.delete(e.id),this.isConnected&&this.requestUpdate()},2e3)}}}setTaskSuggestions(e){let t=e.filter(e=>this.taskSuggestionOperations.get(e.id)?.action!==`dismiss`);for(let e of this.taskSuggestionOperations.values()){if(e.action!==`accept`||!e.canDisplay())continue;let n=t.findIndex(t=>t.id===e.suggestion.id);n<0?t.push(e.suggestion):t[n]=e.suggestion}this.taskSuggestions=t,t.some(e=>e.id===this.activeTaskSuggestionId)||(this.activeTaskSuggestionId=t[0]?.id,this.taskSuggestionSwapDirection=void 0)}reconcileTaskSuggestionConnection(e){let t=new Set;for(let[n,r]of this.taskSuggestionOperations)(r.action===`dismiss`?e:!r.canDisplay())?(this.taskSuggestionOperations.delete(n),this.taskSuggestionBusyIds.delete(n),t.add(n)):r.action===`accept`&&r.outcome.phase===`starting`&&!r.isCurrent()&&(r.outcome={phase:`failed`,error:R(`chat.queue.deliveryUnconfirmed`)},this.taskSuggestionBusyIds.delete(n));this.setTaskSuggestions(e?[]:this.taskSuggestions.filter(e=>!t.has(e.id)))}async refreshTaskSuggestions(e){let t=++this.taskSuggestionsRequestVersion,n=this.captureConnectionScope();if(!n||!da(n.context.gateway.snapshot,`taskSuggestions.list`)){this.setTaskSuggestions([]),this.requestUpdate();return}let r=n.state.sessionKey;if(Wt(r)){this.setTaskSuggestions([]),this.requestUpdate();return}let i=Z(n.state),a=JSON.stringify([this.connectionGeneration,r,i]);if(e?.automatic){if(!this.secondarySessionReadsReady(this.explicitReadScope===a))return}else this.explicitReadScope=a;try{let e=await n.client.request(`taskSuggestions.list`,{agentId:i});if(t!==this.taskSuggestionsRequestVersion||!this.isConnectionScopeCurrent(n)||r!==n.state.sessionKey)return;this.setTaskSuggestions(e.suggestions.filter(e=>this.suggestionMatchesCurrentSession(e))),this.requestUpdate()}catch{}}handleTaskSuggestionEvent(e){if(e.action===`created`){if(!this.suggestionMatchesCurrentSession(e.suggestion))return;this.setTaskSuggestions([e.suggestion,...this.taskSuggestions.filter(t=>t.id!==e.suggestion.id)])}else{let t=this.taskSuggestionOperations.get(e.taskId);t&&(t.resolved=!0),this.setTaskSuggestions(this.taskSuggestions.filter(t=>t.id!==e.taskId)),t?.action!==`accept`&&this.taskSuggestionBusyIds.delete(e.taskId)}this.requestUpdate(),this.refreshTaskSuggestions({automatic:!0})}suggestionChatProps(e,t,n){let r=this.context.gateway.snapshot,i=r.hello?.auth??null,a=e&&Ur(i),o=e&&Hr(i),s=new Map(this.taskSuggestionOperations),c=e=>{let t=s.get(e.id);return t?.action!==`accept`||this.taskSuggestionOperations.get(e.id)===t&&t.canDisplay()};return{taskSuggestions:this.taskSuggestions.filter(e=>{let t=this.taskSuggestionOperations.get(e.id);return t?.action!==`accept`||t.canDisplay()}),activeTaskSuggestionId:this.activeTaskSuggestionId,taskSuggestionSwapDirection:this.taskSuggestionSwapDirection,taskSuggestionSwapGeneration:this.taskSuggestionSwapGeneration,onNavigateTaskSuggestion:this.navigateTaskSuggestion,taskSuggestionBusyIds:this.taskSuggestionBusyIds,taskSuggestionAcceptance:e=>{let t=this.taskSuggestionOperations.get(e);return t?.action===`accept`&&t.canDisplay()?t.outcome:void 0},canOpenTaskSuggestions:e&&r.phase===`connected`&&Gr(i),onOpenTaskSuggestion:this.onPaneSessionChange?e=>{let t=this.taskSuggestionOperations.get(e.id),n=this.context.gateway.snapshot;n.phase===`connected`&&Gr(n.hello?.auth??null)&&c(e)&&t?.action===`accept`&&t.canDisplay()&&t.outcome.phase===`started`&&this.onPaneSessionChange?.(this.paneId,t.outcome.sessionKey)}:void 0,sessionSuggestions:n?this.sessionSuggestions:[],sessionSuggestionRole:this.sessionSuggestionRole,sessionSuggestionBusyIds:this.sessionSuggestionBusyIds,sessionSuggestionsArchived:t,canResolveSessionSuggestions:a&&da(r,`session.suggestions.resolve`)===!0,onResolveSessionSuggestion:this.resolveCurrentSessionSuggestion.bind(this),canAcceptTaskSuggestions:o&&da(r,`taskSuggestions.accept`)===!0,canDismissTaskSuggestions:a&&da(r,`taskSuggestions.dismiss`)===!0,taskSuggestionCopiedIds:this.taskSuggestionCopiedIds,onCopyTaskSuggestionPrompt:this.copyTaskSuggestionPrompt,onChangeTaskRepository:(e,t)=>{let n=this.taskSuggestionOperations.get(e.id);c(e)&&n?.action===`accept`&&n.outcome.phase===`failed`&&n.outcome.repository&&(Object.assign(n.outcome.repository,t),this.requestUpdate())},onAcceptTaskSuggestion:(e,t,n)=>c(e)?this.acceptTaskSuggestion(e,t,n):void 0,onDismissTaskSuggestion:e=>c(e)?this.dismissTaskSuggestion(e):void 0}}async resolveTaskSuggestion(e,t,n=`local`,r){let i=this.captureConnectionScope();if(!i||!this.suggestionMatchesCurrentSession(e))return;let a=this.taskSuggestionOperations.get(e.id);if(a?.action===`dismiss`)return;if(a?.action===`accept`){if(!a.canDisplay()||a.outcome.phase===`starting`)return;if(a.outcome.phase===`started`){t===`dismiss`&&(this.taskSuggestionsRequestVersion+=1,this.taskSuggestionOperations.delete(e.id),this.setTaskSuggestions(this.taskSuggestions.filter(t=>t.id!==e.id)),this.requestUpdate());return}}let o=i.context.gateway.snapshot,s=o.hello?.auth??null;if(!da(o,`taskSuggestions.${t}`)||!(t===`accept`?Hr(s):Ur(s)))return;let c=i.state.sessionKey,l=j(i.state.currentSessionId),u=!1,d=li(i.context.gateway),f=o.hello?.auth?.recoveryScope??(i.client.recoveryScopeReady?i.client.recoveryScope:void 0),p=()=>{let e=j(i.state.currentSessionId);l??=e,u||=!!(l&&e)&&e!==l;let t=i.context.gateway.snapshot,n=t.hello?.auth?.recoveryScope??(t.client?.recoveryScopeReady?t.client.recoveryScope:void 0);return f??=n,this.isConnected&&this.context===i.context&&this.state===i.state&&i.state.sessionKey===c&&!u&&li(i.context.gateway)===d&&(!n||n===f)},m=()=>this.isConnectionScopeCurrent(i)&&p(),h=t===`accept`?{action:t,resolved:!1,suggestion:a?.suggestion??e,mode:a?.mode??n,cwd:r??a?.cwd,canDisplay:p,isCurrent:m,outcome:{phase:`starting`}}:{action:t,resolved:!1},g=this.taskSuggestions.findIndex(t=>t.id===e.id),_=()=>m()&&this.taskSuggestionOperations.get(e.id)===h;this.taskSuggestionOperations.set(e.id,h),t===`accept`&&this.taskSuggestionBusyIds.add(e.id),this.setTaskSuggestions(this.taskSuggestions),this.requestUpdate();let v=!1;try{if(h.action===`accept`){let t=await i.client.request(`taskSuggestions.accept`,{taskId:e.id,mode:h.mode,...h.cwd?{cwd:h.cwd}:{}});if(!_())return;let n=j(t.key);if(t.taskId!==e.id||!n)throw Error(R(`chat.taskSuggestions.startUnconfirmed`));h.outcome={phase:`started`,sessionKey:n,href:En({face:`chat`,sessionKey:n,fallbackAgentId:e.agentId??Z(i.state),basePath:i.context.basePath,exactKey:!0}).href}}else{if(await i.client.request(`taskSuggestions.dismiss`,{taskId:e.id}),!_())return;this.setTaskSuggestions(this.taskSuggestions.filter(t=>t.id!==e.id))}}catch(e){if(!_())return;if(h.action===`dismiss`){if(h.resolved)return;v=g>=0}else{let t=e instanceof Yn?e.details:void 0,n=h.mode===`worktree`&&t&&typeof t==`object`&&`code`in t&&t.code===D.TASK_WORKTREE_SOURCE_REQUIRED?{cwd:h.cwd??h.suggestion.cwd,open:!0,projects:[]}:void 0;h.outcome={phase:`failed`,error:P(e),...n?{repository:n}:{}},n&&i.client.request(`projects.list`,{}).then(e=>{_()&&h.outcome.phase===`failed`&&h.outcome.repository===n&&(n.projects=e.projects.filter(e=>!!e.repoRoot),this.requestUpdate())}).catch(()=>{})}i.state.lastError=P(e),i.state.chatError=i.state.lastError}finally{if(this.taskSuggestionOperations.get(e.id)===h&&(h.action===`dismiss`&&this.taskSuggestionOperations.delete(e.id),this.taskSuggestionBusyIds.delete(e.id),h.action===`accept`&&!m()&&(this.reconcileTaskSuggestionConnection(!1),this.requestUpdate()),this.isConnectionScopeCurrent(i)&&i.state.sessionKey===c)){if(v){a?.action===`accept`&&this.taskSuggestionOperations.set(e.id,a);let t=[...this.taskSuggestions];t.splice(g,0,e),this.setTaskSuggestions(t)}this.requestUpdate(),t===`dismiss`&&this.refreshTaskSuggestions()}}}}})))()}var Ak;function jk(){return(jk=e((()=>{T(),H(),on(),Ke(),fa(),Jo(),se(),Da(),me(),I(),B(),Ig(),jT(),GS(),Y(),Pw(),kk(),Xv(),Vw(),Of(),hp(),Qm(),Ak=class extends Ok{constructor(...e){super(...e),this.deferredSessionHydrationActive=!1,this.pendingDeferredSessionHydration=null,this.dismissSessionPullRequest=e=>{let t=this.state?.sessionKey;t&&(this.dismissedSessionPullRequestIds=vf(t,e),this.requestUpdate())}}secondarySessionReadsReady(e=!1){let t=this.state;return!!(t?.connected&&this.presented&&document.visibilityState!==`hidden`&&(e||!this.deferredSessionHydrationActive&&(Wt(t.sessionKey)||this.transcriptReady||iy(t))))}subscribeSessionRepositoryContext(){this.chatState.addCleanup(qa(this.context.gateway).subscribe(()=>this.requestUpdate()));let e=zo(this.context.gateway);this.chatState.addCleanup(e.subscribe(()=>{this.refreshSessionPullRequests()})),this.chatState.addCleanup(()=>e.unwatch(this))}get visibleSessionPullRequests(){return this.sessionPullRequests.filter(e=>!this.dismissedSessionPullRequestIds.has(Dd(e)))}applyPullRequestPresentation(e,t=this.dismissedSessionPullRequestIds){let n=e?.pullRequests??[],r=Pc(e),i=e?.status??`ready`,a=this.sessionPullRequests!==n&&(this.sessionPullRequests.length>0||n.length>0)||this.sessionPullRequestsBranch!==e?.branch||this.githubRepo?.owner!==r?.owner||this.githubRepo?.repo!==r?.repo||this.sessionPullRequestsStatus!==i||this.dismissedSessionPullRequestIds.size!==t.size||[...t].some(e=>!this.dismissedSessionPullRequestIds.has(e));this.sessionPullRequests=n,this.sessionPullRequestsBranch=e?.branch,this.githubRepo=r,this.sessionPullRequestsStatus=i,this.dismissedSessionPullRequestIds=t,a&&this.requestUpdate()}refreshSessionPullRequests(e={}){if(!this.presented)return zo(this.context.gateway).unwatch(this),!1;let t=this.captureConnectionScope();if(!t||!da(t.context.gateway.snapshot,`controlUi.sessionPullRequests.subscribe`))return t&&zo(t.context.gateway).unwatch(this),this.applyPullRequestPresentation(),!1;let n=t.state.sessionKey;if(!n.trim()||Wt(n))return zo(t.context.gateway).unwatch(this),this.applyPullRequestPresentation(),!1;let r=t.context.sessions.capturePullRequestEpoch(n),i=zo(t.context.gateway),a=wn(n,L(t.state,n).agentId??Z(t.state));i.watch(this,[a],{foreground:!0});let o=e.refresh===!0&&i.refresh(a,e),s=i.get(a);if(!this.isConnectionScopeCurrent(t)||n!==t.state.sessionKey)return o;if(!s)return(this.sessionPullRequests.length>0||this.sessionPullRequestsBranch!==void 0)&&t.context.sessions.setPullRequestSummary(n,void 0,r),this.applyPullRequestPresentation(void 0,new Set),o;let c=Pc(s),l=this.githubRepo!=null&&c!==null&&(this.githubRepo.owner!==c.owner||this.githubRepo.repo!==c.repo);if(this.applyPullRequestPresentation(s,Nd(n)),!s.rateLimited||s.pullRequests.length>0||l){let e=t.context.sessions.pullRequestSummary(n);t.context.sessions.setPullRequestSummary(n,Na(s.pullRequests,e),r)}let u=this.githubPublication?.result?.status===`published`?this.githubPublication?.result:void 0,d=u?s.pullRequests.find(e=>e.url===u.url):void 0;return s.branch&&u&&(s.branch.branch!==u.branch||d&&d.state!==`open`&&d.state!==`draft`)&&this.githubPublication?.reset(),o}resetSessionPullRequests(){this.state&&Uv(this.state),zo(this.context.gateway).unwatch(this),this.sessionPullRequests=[],this.sessionPullRequestsBranch=void 0,this.githubRepo=null,this.sessionPullRequestsStatus=`ready`,this.githubPublication?.detach(),this.githubPublication=null,this.dismissedSessionPullRequestIds=new Set}deferSessionHydrationUntilTranscript(e,t){let n=this.state;if(!n)return;this.deferredSessionHydrationActive=!0,this.pendingDeferredSessionHydration=null;let r=++this.deferredSessionHydrationRequestVersion,i=this.connectionGeneration,a=n.client,o=()=>{this.deferredSessionHydrationRequestVersion===r&&(this.deferredSessionHydrationActive=!1,this.pendingDeferredSessionHydration=null)},s=()=>this.deferredSessionHydrationRequestVersion===r&&this.connectionGeneration===i&&this.state===n&&n.connected&&n.client===a&&n.sessionKey===e,c=t=>{if(!s()){o();return}if(!this.presented||document.visibilityState===`hidden`){this.pendingDeferredSessionHydration=()=>c(t);return}this.pendingDeferredSessionHydration=null,Sp(n,()=>{s()&&this.presented&&document.visibilityState!==`hidden`?(this.deferredSessionHydrationActive=!1,n.requestUpdate?.(),this.refreshTaskSuggestions({automatic:!0}),t&&this.markSessionRead(Q(n)),a&&this.loadHeaderPlatform(a,i),WS(n),this.probeSessionDiscussion(e),this.hydrateSessionCompanion(e),this.refreshSessionPullRequests()):s()?this.pendingDeferredSessionHydration=()=>c(t):o()})};t.then(c,()=>c(!1))}resumeDeferredSessionHydration(){let e=this.pendingDeferredSessionHydration;return this.pendingDeferredSessionHydration=null,e?.(),this.deferredSessionHydrationActive}retireDeferredSessionHydration(){this.deferredSessionHydrationRequestVersion+=1,this.deferredSessionHydrationActive=!1,this.pendingDeferredSessionHydration=null}markSessionRead(e){let t=this.state;if(!t?.connected||!e)return;let n=e.endedAt??e.updatedAt??0,r=(e.status===`failed`||e.status===`timeout`)&&(e.lastReadAt==null||n>e.lastReadAt),i=!!(e.agentStatus&&e.agentStatus.expiresAt>Date.now());if(!(e.unread===!0||r||i)){this.unreadPatchGuard.shouldPatch(t.sessionKey,!1,e.markedUnreadAt);return}let a=jt(e.key)?.agentId??Z(t);if(!z(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:e.key,unread:!1,agentId:a}}).allowed||e.sharingRole===`viewer`||this.sessionParticipationTracker.resolve({catalog:Wt(t.sessionKey)!==null,listLoading:t.sessionsLoading,sessionKey:`${Z(t)??``}\0${t.sessionKey}`,session:e})||!this.unreadPatchGuard.shouldPatch(t.sessionKey,!0,e.markedUnreadAt))return;let o=t.sessionKey;this.context.sessions.patch(e.key,{unread:!1},{agentId:a,expectedMarkedUnreadAt:e.markedUnreadAt??null}).then(e=>{e===null&&this.unreadPatchGuard.patchFailed(o)},e=>{this.unreadPatchGuard.patchFailed(o,e)})}async restoreArchivedSession(e,t){let n=this.captureConnectionScope();if(!n||n.state.sessionKey!==e)return;let r=z(n.context.gateway.snapshot,{method:`sessions.patch`,params:{key:e,archived:!1},sessionScope:!0,session:Q(n.state)});if(!r.allowed){n.state.lastError=r.reason,n.state.chatError=r.reason,n.state.requestUpdate?.();return}let i=jt(e)?.agentId??Z(n.state),a=null;try{await n.sessions.patch(e,{archived:!1},{agentId:i,expectedSessionId:t})||(a=n.sessions.state.error)}catch(e){a=P(e)}a&&this.isConnectionScopeCurrent(n)&&n.state.sessionKey===e&&(n.state.lastError=a,n.state.chatError=a,n.state.requestUpdate?.())}setPaneSessionKey(e){let t=this.state;if(!t)return null;let n=Wt(e)?e:ht(e,this.context.gateway.snapshot.hello);return n?(t.sessionKey=n,n):null}openCatalogSession(e,t){this.catalogRequestedSessionKey=this.sessionKey,this.catalogMessages=[],this.catalogCursor=void 0,this.catalogSession=null,this.catalogHost=null,en(t.chatAttachments),t.chatAttachments=[],t.chatLoading=!0,t.requestUpdate(),this.loadCatalogSession(e,!1)}catalogItemMessage(e){let t=C(e.timestamp)??null,n=e.text?.trim()?e.text:null;if(e.type===`userMessage`)return n?{role:`user`,senderLabel:e.sender?.label??R(`sessionsView.user`),...e.sender?{__openclaw:{senderIdentity:e.sender.identity,senderId:e.sender.identity.id,senderName:e.sender.label,senderProfileAvatarUrl:e.sender.avatarUrl}}:{},content:n,...t==null?{}:{timestamp:t},messageId:e.id}:null;let r=n,i=e.truncated;if(e.type===`reasoning`)r=n?`Thinking\n\n${n}`:`Thinking`;else if(e.type===`toolCall`){let t=n??gw(e.raw,[`command`,`name`,`tool`,`title`,`query`]);r=t?`Tool call\n\n${t}`:`Tool call`}else if(e.type===`toolResult`){let t=n??gw(e.raw,[`aggregatedOutput`])??_w(e.raw),a=t?ue(t,500):null;i||=!!(t&&a!==t),r=a?`Tool result\n\n${a}`:`Tool result`}return r?(i&&(r=`${r}\n\n${R(`chat.catalogOutputTruncated`)}`),{role:`assistant`,content:[{type:`text`,text:r}],...t==null?{}:{timestamp:t},messageId:e.id}):null}prependUniqueCatalogMessages(e){let t=new Set(this.catalogMessages.map(AT).filter(Boolean));return[...e.filter(e=>{let n=AT(e);return!n||!t.has(n)?(n&&t.add(n),!0):!1}),...this.catalogMessages]}async loadCatalogSession(e,t){let n=this.captureConnectionScope();if(!n)return!1;let{state:r,client:i}=n;if(t&&!this.catalogCursor)return!1;let a=Z(r),o=t?this.catalogLoadGeneration:++this.catalogLoadGeneration,s=this.sessionKey,c=()=>this.isConnectionScopeCurrent(n)&&o===this.catalogLoadGeneration&&this.sessionKey===s&&Z(r)===a;t||(this.catalogLoading=!0,this.catalogCursor=void 0,this.olderCursorsSeen.clear(),this.historyObserverArmed=!1,this.transcriptScrollTop=null,this.historyObserver?.disconnect(),this.historyObserver=null);try{if(!t){let t=await Be({agentId:a,client:i,key:e,isCurrent:c});if(!t||!c())return!1;this.catalogHost=t.host,this.catalogSession=t.session}let n=t?this.catalogCursor:void 0;n&&this.olderCursorsSeen.add(n);let o=await i.request(`sessions.catalog.read`,{agentId:a,catalogId:e.catalogId,hostId:e.hostId,threadId:e.threadId,...this.catalogSession?.sourceHomeId?{sourceHomeId:this.catalogSession.sourceHomeId}:{},limit:50,...t&&this.catalogCursor?{cursor:this.catalogCursor}:{}});if(!c())return!1;let s=o.items.toReversed().map(e=>this.catalogItemMessage(e)).filter(e=>e!==null),l=t?this.prependUniqueCatalogMessages(s):s,u=l.length>this.catalogMessages.length,d=t&&(!o.nextCursor||o.nextCursor===n||this.olderCursorsSeen.has(o.nextCursor));return this.catalogMessages=l,this.catalogCursor=d?void 0:o.nextCursor,r.lastError=null,Np(r,!t),!t||u||!d}catch(e){return c()&&(r.lastError=P(e)),!1}finally{c()&&!t&&(this.catalogLoading=!1,r.chatLoading=!1,r.requestUpdate())}}}})))()}var Mk;function Nk(){return(Nk=e((()=>{H(),Ua(),me(),I(),B(),jk(),yx(),oo(),Mk=class extends Ak{constructor(...e){super(...e),this.activeReplyNavigation=null,this.replyNavigationSessionKey=null,this.replyNavigationId=null,this.replyMessageRevision=0,this.replyMessages=new Map,this.readReplyMessage=e=>{let t=this.state;if(!t)return;let n=this.replyMessages.get(this.replyMessageCacheKey(t.sessionKey,e));return n?.client===t.client&&n.generation===this.connectionGeneration?n.message:void 0},this.requestReplyMessage=e=>{this.loadReplyMessage(e)},this.openReplyMessage=e=>{this.navigateToReplyMessage(e)}}replyMessageCacheKey(e,t){let n=this.state;return`${e}\u0000${(n?L(n,e).agentId:void 0)??``}\u0000${t}`}async loadReplyMessage(e){let t=this.captureConnectionScope();if(!t||Wt(t.state.sessionKey))return;let n=t.state.sessionKey,r=L(t.state,n).agentId,i=this.replyMessageCacheKey(n,e),a=this.replyMessages.get(i);if(a?.client===t.client&&a.generation===t.generation)return;for(;this.replyMessages.size>=256;)this.replyMessages.delete(this.replyMessages.keys().next().value);let o={client:t.client,generation:t.generation};this.replyMessages.set(i,o);let s;try{s=await t.client.request(`chat.message.get`,{sessionKey:n,...r?{agentId:r}:{},messageId:e,maxChars:500})}catch{return}this.isConnectionScopeCurrent(t)&&this.replyMessages.get(i)===o&&s.ok&&s.message&&(this.replyMessages.set(i,{...o,message:s.message}),this.replyMessageRevision+=1,F(t.state.sessionKey,n)&&this.requestUpdate())}replyNavigationIsCurrent(e,t,n,r){return this.activeReplyNavigation===e&&this.state===t&&F(t.sessionKey,n)&&(!r||t.currentSessionId===r)}currentReplyNavigationId(e){return this.replyNavigationSessionKey&&F(this.replyNavigationSessionKey,e)?this.replyNavigationId:null}currentReplyMessageAccess(e){return{revision:this.replyMessageRevision,navigationId:this.currentReplyNavigationId(e),read:this.readReplyMessage,request:this.requestReplyMessage,open:this.openReplyMessage}}retireReplyMessages(){this.replyMessages.clear()}resetReplyNavigation(){this.activeReplyNavigation=null,this.replyNavigationSessionKey=null,this.replyNavigationId=null}async navigateToReplyMessage(e){let t=this.state;if(!t||Wt(t.sessionKey))return;let n=t.sessionKey,r=t.currentSessionId?.trim()??``,i=Symbol(`reply-navigation`);this.activeReplyNavigation=i,this.replyNavigationSessionKey=n,this.replyNavigationId=e,this.requestUpdate();try{for(;!t.chatMessages.some(t=>F_(t)===e);){if(!this.replyNavigationIsCurrent(i,t,n,r))return;if(!t.chatHistoryPagination.hasMore){t.lastError=R(`chat.messages.originalUnavailable`),t.requestUpdate?.();return}let e=await this.loadOlderMessages();if(!this.replyNavigationIsCurrent(i,t,n,r))return;if(!e){!t.chatHistoryPagination.hasMore&&!t.lastError&&(t.lastError=R(`chat.messages.originalUnavailable`),t.requestUpdate?.());return}}if(!this.replyNavigationIsCurrent(i,t,n,r))return;this.requestUpdate(),await this.updateComplete,this.replyNavigationIsCurrent(i,t,n,r)&&this.transcript.revealMessage(e)}finally{this.activeReplyNavigation===i&&(this.resetReplyNavigation(),this.requestUpdate())}}}})))()}function Pk(e){let t=q(e).allItems(e);for(let n of t)if(!(!n.sendRunId||n.sendState!==`submitting`&&n.sendState!==`sending`&&n.sendState!==`waiting-idle`)&&!(n.sendState===`waiting-idle`&&n.sendAttempts===0&&n.sendRequestStartedAtMs===void 0&&rm(e,n.id))){if(q(e).hasVolatile(e,n.id)){q(e).change(e,n.id,e=>({...e,sendState:`unconfirmed`}));continue}t_(e,n.id,e=>({...e,sendState:`waiting-reconnect`}))}}function Fk(e,t){let n=e.sessions.find(e=>F(e.key,t));return!(!n||S(n))}function Ik(e,t,n){return F(t,n)?!0:!!(t&&mn(t)&&Sn(e,n))}function Lk(e,t,n,r){let i=r&&mn(r)?Sn(e,n):void 0;return t?.sessions.find(t=>F(t.key,n)?!0:i!=null&&Sn(e,t.key)===i)}function Rk(e,t){if(!t||!S(t)||S(e))return!1;let n=typeof e.updatedAt==`number`?e.updatedAt:null;return n==null||(typeof t.updatedAt==`number`?t.updatedAt:0)>=n||(typeof t.startedAt==`number`?t.startedAt:0)>=n}function zk(e,t,n,r,i,a){Promise.allSettled([n,r]).then(n=>{let r=n[0],o=n[1],s=e.sessionsResult,c=r.status===`fulfilled`?r.value?.sessionInfo:null,l=Lk(e,s,t,c?.key),u=!(!c||!Ik(e,c.key,t)||S(c)||Rk(c,l)),d=s?Fk(s,t):!1;o.status!==`fulfilled`||e.chatQueue.length===0||!F(e.sessionKey,t)||!s&&!u||s===i&&!u||e.sessionsError&&!u||!(u||d)||a()})}function Bk(){return(Bk=e((()=>{B(),Kg(),l_(),Gm()})))()}function Vk(e){rA.get(e)?.catalogRequest?.controller.abort(),rA.get(e)?.unsubscribe(),rA.delete(e),Zk(e),e.chatModelsLoading=!1}function Hk(e){let t=typeof globalThis.requestIdleCallback==`function`?globalThis.requestIdleCallback:null;if(t){t(e,{timeout:750});return}globalThis.setTimeout(e,50)}async function Uk(e){await bE({client:e.client,agentId:Z(e),sessionKey:e.sessionKey})}function Wk(e,t){e&&kt(e,e.sessionKey)&&!jt(e.sessionKey)?.agentId&&(e.assistantAgentId??null)!==t&&(Gk(e,t),jx(e))}function Gk(e,t){(e.assistantAgentId??null)!==t&&(kx(e),e.assistantIdentityRequestVersion+=1,e.assistantAgentId=t,e.assistantName=``,e.assistantAvatar=null,e.assistantAvatarSource=null,e.assistantAvatarStatus=null,e.assistantAvatarReason=null,e.chatAvatarUrl=null,e.chatAvatarSource=null,e.chatAvatarStatus=null,e.chatAvatarReason=null,e.modelAuthStatusResult=null,e.modelAuthStatusError=null,qk(e,{automatic:!0}),Yk(e).finally(()=>e.requestUpdate?.()),e.loadAssistantIdentity(),e.requestUpdate?.())}function Kk(e){let t=rA.get(e);if(t?.isCurrent())return t;t&&Vk(e);let n=e.client;if(!n||!e.connected)return;let r={agentId:Z(e)??void 0,sessionKey:e.sessionKey},i=e.connectionEpoch,a={client:n,sessions:e.sessions,scope:r,version:0,sessionFactsInvalidated:!1,isCurrent:()=>rA.get(e)===a&&e.connected&&e.client===n&&e.sessions===a.sessions&&e.connectionEpoch===i&&e.sessionKey===r.sessionKey&&(Z(e)??void 0)===r.agentId,unsubscribe:lc(n,r,t=>{if(a.isCurrent()){if((t.type===`invalidated`||t.type===`loading`)&&(a.sessionRefreshPending=t.type===`invalidated`&&t.scope===`session`,a.version+=1,a.sessionFactsRequest&&(a.sessionFactsInvalidated=!0,a.sessionFactsRetryPending=!0)),t.type===`invalidated`){t.scope===`full`&&(a.catalogRequest?.controller.abort(),a.catalogRequest=void 0,e.chatModelsLoading=!1,Qk(e,a)),a.sessionFactsInvalidated||=t.refreshSessionFacts,qk(e,{automatic:!0});return}t.type!==`loading`&&(t.type===`result`&&(yE({client:n,agentId:r.agentId,result:t.result}),t.catalogChanged&&(a.sessionFactsInvalidated=!0,qk(e,{automatic:!0}))),a.sessionFactsRetryPending&&(a.sessionFactsRetryPending=!1,$k(e))),e.requestUpdate?.()}},()=>a.isCurrent()&&e.chatMetadataIsPresented?.()!==!1)};rA.set(e,a),e.chatModelCatalogInitialized=bt(n);let o=yc(n,r);return o&&yE({client:n,agentId:r.agentId,result:o}),a}async function qk(e,t){let n=Kk(e);if(!n){Vk(e);return}if(t?.automatic){if(e.chatMetadataIsPresented?.()===!1)return;let r=ic(n.client,n.scope,{kind:t.startup?`startup`:void 0}),i=$k(e);if(n.refreshPending?.refresh===r)return n.refreshPending.promise;n.catalogRequest=void 0,e.chatModelsLoading=!i&&e.chatModelCatalog.length===0,e.requestUpdate?.();let a=()=>n.isCurrent()&&r.isCurrent()&&n.refreshPending?.refresh===r,o=!1,s=r.catalog.then(async t=>{o=!r.isCurrent(),t&&n.isCurrent()&&n.refreshPending?.refresh===r&&(o&&Nc(n.client,n.scope,{allowStale:!0})!==t||(o=!1,Qk(e,n),a()&&(e.chatModelsLoading=!1,e.requestUpdate?.(),n.sessionFactsInvalidated&&e.chatMetadataIsPresented?.()!==!1&&await Jk(e,n))))},t=>{o=!r.isCurrent(),a()&&!$k(e)&&a()&&(e.chatModelCatalogError=P(t),e.chatModelsLoading=!1,e.requestUpdate?.())}).finally(()=>{n.isCurrent()&&n.refreshPending?.refresh===r&&(e.chatModelsLoading=!1,e.requestUpdate?.())}),c=Promise.allSettled([r.completed,s]).then(()=>{if(n.refreshPending?.refresh===r&&(n.refreshPending=void 0,o&&n.isCurrent()))return qk(e,{automatic:!0})});return n.refreshPending={refresh:r,promise:c},c}n.refreshPending=void 0,Vs(n.client,n.scope);let r=kc(n.client,n.scope).catch(()=>void 0),i=n.version,a=Xk(e,n).then(async t=>{n.sessionFactsInvalidated&&t&&n.isCurrent()&&n.version===i&&await Jk(e,n)});await Promise.all([r,a])}function Jk(e,t){t.sessionFactsRetryPending=!1;let n=t.version;if(t.sessionFactsRequest?.version===n)return t.sessionFactsRequest.promise;let r=t.scope.agentId;if(!r||!t.isCurrent())return Promise.resolve();let i=t.sessions.observeRow({key:t.scope.sessionKey,agentId:r},()=>{}),a=i.captureReconcile();t.sessionFactsInvalidated=!1;let o=t.sessions.describe({key:t.scope.sessionKey,agentId:r},{client:t.client,refresh:!0}).then(r=>{if(!t.isCurrent()||t.version!==n)return;let i=a(r.session??void 0);t.isCurrent()&&t.version===n&&(i.status===`invalidated`&&(t.sessionFactsInvalidated=!0,t.sessionFactsRequest=void 0),i.status===`current`&&e.sessionsResult&&(e.sessionsResult={...e.sessionsResult,sessions:t.sessions.projectRows(e.sessionsResult.sessions)},e.requestUpdate?.()))}).catch(()=>{t.isCurrent()&&t.version===n&&(t.sessionFactsInvalidated=!0,t.sessionFactsRequest=void 0)}).finally(()=>{i.dispose(),t.sessionFactsRequest?.promise===o&&(t.sessionFactsRequest=void 0)});return t.sessionFactsRequest={version:n,promise:o},o}async function Yk(e,t){if(!e.client||!e.connected)return;let n=e.client,r=e.connectionEpoch,i=Z(e),a=++e.modelAuthStatusRequestVersion,o=()=>e.client===n&&e.connected&&e.connectionEpoch===r&&e.modelAuthStatusRequestVersion===a&&Z(e)===i;try{let r=await ms(n,{...t,agentId:i});if(!o())return;e.modelAuthStatusResult=r,e.modelAuthStatusError=r.unavailable?.message??null}catch(t){if(!o())return;e.modelAuthStatusResult={ts:0,providers:[]},e.modelAuthStatusError=P(t)}}async function Xk(e,t){if(Qk(e,t))return!0;if(t.catalogRequest?.version===t.version)return t.catalogRequest.promise;t.catalogRequest?.controller.abort();let n=new AbortController,r=t.version,i=()=>t.isCurrent()&&t.catalogRequest?.controller===n;e.chatModelsLoading=e.chatModelCatalog.length===0,e.requestUpdate?.();let a=Ss(t.client,{...t.scope,signal:n.signal}).then(n=>{if(!t.isCurrent())return!1;let r=Nc(t.client,t.scope);if(r||i()){Qk(e,t);let a=!!r||Nc(t.client,t.scope,{allowStale:!0})===n;return!a&&i()?(t.catalogRequest=void 0,Xk(e,t)):a}return!1},t=>(i()&&(e.chatModelCatalogError=P(t)),!1)).finally(()=>{i()&&(t.catalogRequest=void 0,e.chatModelsLoading=!1,e.requestUpdate?.())});return t.catalogRequest={version:r,controller:n,promise:a},a}function Zk(e,t){e.chatModelCatalog=t?.models??[],e.chatModelCatalogInitialized=t!==void 0||bt(e.client),e.chatModelSelectionPolicy=t?.modelSelectionPolicy,e.chatModelCatalogRetired=!1,e.chatAccountSelection=t?.accountSelection??null,e.chatModelCatalogError=null,e.chatModelCatalogRefreshFailed=t?.refreshFailed,e.chatModelCatalogPendingProviders=t?.pendingProviders}function Qk(e,t){let n=Nc(t.client,t.scope),r=n??Nc(t.client,t.scope,{allowStale:!0});return!r&&t.isCurrent()&&On(t.client,t.scope)&&(Zk(e),e.chatModelCatalogRetired=!0,e.requestUpdate?.()),!r||!t.isCurrent()?!1:(n&&(t.catalogRequest?.controller.abort(),t.catalogRequest=void 0),Zk(e,r),e.chatModelsLoading=!1,e.requestUpdate?.(),!!n)}function $k(e){let t=rA.get(e),n=!!(t&&Qk(e,t));return t&&n&&!t.sessionRefreshPending&&t.sessionFactsInvalidated&&e.chatMetadataIsPresented?.()!==!1&&Jk(e,t),n}async function eA(e){let t=Kk(e);t&&Qk(e,t)||(t&&(t.refreshPending=void 0,Vs(t.client,t.scope)),t&&await Xk(e,t)&&t.isCurrent()&&await Jk(e,t))}async function tA(e,t){let n=e.client,r=e.sessions,i=e.connectionEpoch,a=e.sessionKey,o=By(e),s=()=>e.connected&&e.sessions===r&&e.client===n&&e.connectionEpoch===i&&e.sessionKey===a&&By(e)===o,c=()=>e.requestUpdate?.(),l=e.sessionsResult,u=t?.historyLoad??ZC(e,{deferBranches:t?.deferBranches===!0,startup:t?.startup===!0}),d=u.finally(()=>{t?.scheduleScroll!==!1&&Np(e),c()}),f=u.then(t=>{if(!t?.sessionInfo||!s()||t.observation.owner!==r)return;let n=t.observation.reconcile(t.sessionInfo,t.defaults,{resultAgentId:e.sessions.state.agentId??o,selectedGlobalAgentId:o,archivedFilter:t.sessionInfo.archived===!0?`all`:e.sessionsArchivedFilter});if(!n||!s())return;let i=e.sessions.state.agentId!==o&&(kt(e,a)||le(t.sessionInfo));if(e.sessionsResult=i?Ye(e.sessionsResultAgentId===o?e.sessionsResult:null,n===`defaults-only`?Q(e):t.sessionInfo,t.defaults,{resultAgentId:o,selectedGlobalAgentId:o,archivedFilter:`all`},n===`defaults-only`||e.sessionsResultAgentId===o&&e.sessionsResult!==l):e.sessions.state.result,e.sessionsResultAgentId=i?o:e.sessions.state.agentId,n===`defaults-only`)return;let c=Q(e),u=c??t.sessionInfo;c&&(e.selectedChatSessionArchived=u.archived===!0,e.selectedChatSessionIncognito=u.incognito===!0);let d=t.inFlightRun?.runId?.trim(),f=t.sessionInfo.activeRunIds;(!d||e.chatRunId!==d||!S(t.sessionInfo)||Array.isArray(f)&&!f.includes(d))&&c&&!Qp(e,c,{publishRunStatus:!0,historyRun:t.observation.run&&t.sessionInfo.hasActiveRun===!1&&!S(t.sessionInfo)&&!t.inFlightRun&&t.sessionInfo.sessionId===t.observation.run.sessionId?t.observation.run:null})&&!e.chatRunId&&e.chatStream==null&&km(e,{publishRunStatus:!0})}),p=t?.startup===!0&&t.onStartupMetadata?u.then(e=>t.onStartupMetadata?.(e?.metadata),()=>t.onStartupMetadata?.(void 0)):Promise.resolve();if(zk(e,a,d,f,l,()=>void AO(e)),Promise.allSettled([f,p]).finally(c),t?.awaitHistory===!0){await d;return}await Promise.resolve()}function nA(e,t){let n=t?.startup?Kk(e):void 0,r=n?ma(n.client,n.scope):void 0;n&&qk(e,{automatic:!0,startup:!0});let i=tA(e,{...t,onStartupMetadata:async e=>{n&&r?.isCurrent()&&(e?r.publish(e):await ic(n.client,n.scope,{kind:`metadata`,revalidateMetadata:()=>r.isCurrent()}).completed)}}),a=e.sessionKey,o=e.client,s=e.connectionEpoch;return Hk(()=>{e.connected&&e.client===o&&e.connectionEpoch===s&&e.sessionKey===a&&Promise.allSettled([Yy(e),...t?.startup?[]:[qk(e,{automatic:!0})]]).finally(()=>e.requestUpdate?.())}),i}var rA;function iA(){return(iA=e((()=>{Os(),on(),os(),Cn(),Tc(),Ce(),B(),Mn(),nb(),OE(),ew(),Bk(),jO(),Wx(),Vw(),Lp(),Qm(),rA=new WeakMap})))()}var aA;function oA(){return(oA=e((()=>{ta(),oa(),fr(),dc(),on(),me(),I(),B(),Ig(),uT(),AC(),hC(),Y(),tC(),ew(),Nk(),Pw(),tk(),iA(),Vw(),zu(),ip(),Qm(),zh(),ng(),aA=class extends Mk{constructor(...e){super(...e),this.activeCatalogContinuation=null,this.activeOlderLoad=null,this.stagedOlderPage=null,this.stagedOlderLoad=null,this.stagedOlderGeneration=0,this.refreshHistory=()=>{let e=this.state;if(!e)return;let t=Wt(e.sessionKey);if(t){this.loadCatalogSession(t,!1);return}Xh(e,{preserveStreamSegments:e.chatRunId!==null}),this.reconcileWaitingApprovalSnapshot(),Zv(e).subscriptionError&&ZS(e);let n=ry(e),r=n.phase===`failed`&&n.startup;nA(e,{historyLoad:ZC(e,{startup:r,supersedeInFlight:!0}),awaitHistory:!0,scheduleScroll:!1,startup:r})},this.handleCommandPaletteSlashCommand=e=>{let t=this.state;t&&(t.handleChatDraftChange(e.endsWith(` `)?e:`${e} `),t.requestUpdate?.())}}hydrateStoredChatSnapshot(e,t){let n=this.sessionSnapshotStore;if(!n)return;let r=ft(e,{sessionKey:t}),i=Zv(e),a=this.context.gateway.snapshot.phase!==`connected`,o,s=n.read(r,e=>{a=!0,o=e}),c={sessionKey:t,startedBeforeReady:a,readyAt:o,promise:s.then(n=>{if(i.initialSnapshotHydration!==c||i.acceptedHistory||this.state!==e||!F(e.sessionKey,t)||ft(e,{sessionKey:t})!==r)return c.complete?.();let a=e.chatMessagesBySession,o=Qh(a,e,{sessionKey:t})??n;if(!o)return c.complete?.();Pp(e,o);let s={...o,messages:e.chatMessages};gh(a,e,{sessionKey:t},s),c.complete?.(),e.requestUpdate?.()}).catch(()=>c.complete?.()).finally(()=>{i.initialSnapshotHydration===c&&!c.wait&&delete i.initialSnapshotHydration})};i.initialSnapshotHydration=c}hasOlderMessages(){let e=this.state;return e?Wt(e.sessionKey)?!(!this.catalogCursor||this.catalogLoading):e.chatHistoryPagination.hasMore&&!e.chatLoading:!1}resetOlderMessagesViewport(){this.olderLoadGeneration+=1,this.activeOlderLoad=null,this.stagedOlderGeneration+=1,this.stagedOlderPage=null,this.stagedOlderLoad=null,this.resetReplyNavigation(),this.loadingOlder=!1,this.historyObserverArmed=!1,this.historyAutoLoadBlocked=!1,this.historyIntentConsumed=!1,this.historyTouchY=null,this.historyIntentTimer!==null&&(window.clearTimeout(this.historyIntentTimer),this.historyIntentTimer=null),this.transcriptScrollTop=null,this.olderCursorsSeen.clear(),this.clearHistoryObserver()}clearHistoryObserver(){this.historyObserver?.disconnect(),this.historyObserver=null,this.historyObserverRoot=null,this.historyObserverSentinel=null,this.historyObserverBootstrap=!1}syncHistoryObserver(){if((this.state&&Wt(this.state.sessionKey)?this.catalogLoading:this.state?.chatLoading)&&(this.historyObserverArmed=!1,this.loadingOlder&&=(this.olderLoadGeneration+=1,!1)),typeof IntersectionObserver!=`function`||!this.presented||!this.state?.connected||this.loadingOlder||!this.hasOlderMessages()){this.clearHistoryObserver();return}let e=this.transcript.scrollElement,t=e?.querySelector(`.chat-history-sentinel`)??null;if(!e||!t){this.clearHistoryObserver();return}this.transcriptScrollTop??=e.scrollTop;let n=!this.historyObserverArmed;if(this.historyAutoLoadBlocked){this.clearHistoryObserver();return}this.historyObserver&&this.historyObserverRoot===e&&this.historyObserverSentinel===t&&this.historyObserverBootstrap===n||(this.clearHistoryObserver(),this.historyObserver=new IntersectionObserver((t,r)=>{this.historyObserver===r&&t.some(e=>e.isIntersecting)&&(this.clearHistoryObserver(),!(n&&e.scrollHeight>e.clientHeight)&&(this.historyObserverArmed=!1,this.loadOlderMessages()))},{root:e,rootMargin:`${ww}px 0px 0px`,threshold:0}),this.historyObserverRoot=e,this.historyObserverSentinel=t,this.historyObserverBootstrap=n,this.historyObserver.observe(t))}handleTranscriptScroll(e){let t=e.currentTarget instanceof HTMLElement?e.currentTarget:e.target instanceof HTMLElement?e.target:null,n=this.transcriptScrollTop;if(t){this.transcriptScrollTop=t.scrollTop;let e=this.transcript.renderedSessionKey,n=this.state?.sessionKey;e&&n&&F(e,n)&&Mm(this.paneId,e,tm(t))}!this.loadingOlder&&!this.transcript.isMaintenanceScroll&&t!==null&&n!==null&&t.scrollTop<n&&t.scrollTop<t.scrollHeight-t.clientHeight&&t.scrollTop<=1200&&this.consumeHistoryIntent()&&(this.historyAutoLoadBlocked||!this.historyObserverArmed)&&(this.historyAutoLoadBlocked=!1,this.historyObserverArmed=!0,this.syncHistoryObserver()),this.state?.handleChatScroll(e)}consumeHistoryIntent(){return this.historyIntentTimer!==null&&window.clearTimeout(this.historyIntentTimer),this.historyIntentTimer=window.setTimeout(()=>{this.historyIntentTimer=null,this.historyIntentConsumed=!1},200),!this.historyIntentConsumed&&(this.historyIntentConsumed=!0,!0)}handleTranscriptHistoryIntent(e){let t=e.currentTarget instanceof HTMLElement?e.currentTarget:null,n=e instanceof WheelEvent&&e.deltaY<0||e instanceof KeyboardEvent&&Tw.has(e.key)&&$O(e);if(typeof TouchEvent<`u`&&e instanceof TouchEvent){let t=e.touches[0]?.clientY??null;if(e.type===`touchstart`){this.historyTouchY=t;return}if(e.type===`touchend`||e.type===`touchcancel`){this.historyTouchY=null;return}let r=this.historyTouchY;t!==null&&r!==null&&(n=t-r>=8,(n||t<r)&&(this.historyTouchY=t))}if(!(!t||!n||t.scrollTop>1200||this.loadingOlder||!this.hasOlderMessages()||!this.consumeHistoryIntent())){if(this.historyAutoLoadBlocked=!1,typeof IntersectionObserver!=`function`){this.loadOlderMessages();return}this.historyObserverArmed=!0,this.syncHistoryObserver()}}async loadOlderMessages(){if(this.activeOlderLoad)return this.activeOlderLoad;let e=this.performOlderMessagesLoad();this.activeOlderLoad=e;try{return await e}finally{this.activeOlderLoad===e&&(this.activeOlderLoad=null)}}async performOlderMessagesLoad(){let e=this.state,t=e?Wt(e.sessionKey):null;if(!e||this.loadingOlder||!this.hasOlderMessages())return!1;let n=++this.olderLoadGeneration,r=()=>{this.loadingOlder||(this.loadingOlder=!0,e.requestUpdate())},i=!1;try{if(t)r(),i=await this.loadCatalogSession(t,!0);else{let t=e.chatHistoryPagination;if(!t.hasMore)return!1;let a=t.nextOffset,o=typeof e.currentSessionId==`string`?e.currentSessionId.trim():``,s=this.takeStagedOlderPage(e);if(!s&&this.stagedOlderLoad){if(r(),await this.stagedOlderLoad,n!==this.olderLoadGeneration)return!1;s=this.takeStagedOlderPage(e)}if(s||=(r(),await SC(e,a)??null),!s||n!==this.olderLoadGeneration)return!1;if(s.windowReset)return Pp(e,{messages:s.messages??[],pagination:lC(s),sessionId:s.sessionInfo?.sessionId??s.sessionId??null,displayedLeafEntryId:s.sessionInfo?.activeLeafEntryId??null,deltaCursor:s.deltaCursor}),pC(e),e.lastError=null,i=!0,!0;let c=typeof s.sessionInfo?.sessionId==`string`&&s.sessionInfo.sessionId.trim()?s.sessionInfo.sessionId.trim():typeof s.sessionId==`string`?s.sessionId.trim():``;if(o&&c!==o)return await ZC(e),i=!0,!0;let l=lC(s),u=!l.hasMore||l.nextOffset<=a,d=Array.isArray(s.messages)?s.messages:[],f=Xf(e),p=f.entries.flatMap(e=>e.pending&&e.identity?.role===`user`&&e.pendingRunId?[e.pendingRunId]:[]);if(p.length){let t=d.filter(e=>{let t=ea(e);return t?.role===`user`&&!t.isImported&&(t.id!==null||t.sequence!==null)}),n=Yi(f,{type:`snapshotLoaded`,messages:t,scope:f.scope}),r=new Set(n.entries.filter(e=>e.pending&&e.identity?.role===`user`).map(e=>e.pendingRunId));Qf(e,new Set(p.filter(e=>!r.has(e))))}let m=Zs(d,e.chatMessages),h=m.length>e.chatMessages.length;yp(e,m),e.chatHistoryPagination=u?{hasMore:!1,...l.totalMessages===void 0?{}:{totalMessages:l.totalMessages}}:l,e.lastError=null,pC(e),Np(e,!1),i=h||!u,u||this.stageNextOlderPage(e)}}catch(t){n===this.olderLoadGeneration&&(e.lastError=P(t),this.transcriptScrollTop=this.transcript.scrollElement?.scrollTop??null)}finally{n===this.olderLoadGeneration&&(i?this.hasOlderMessages()||(this.historyAutoLoadBlocked=!1):this.historyAutoLoadBlocked=this.hasOlderMessages(),this.loadingOlder=!1,e.requestUpdate())}return i}stageNextOlderPage(e){if(this.stagedOlderPage||this.stagedOlderLoad)return;let t=e.chatHistoryPagination;if(!t.hasMore||Wt(e.sessionKey))return;let n=this.stagedOlderGeneration;this.stagedOlderLoad=(async()=>{try{let r=await CC(e,t.nextOffset);r&&n===this.stagedOlderGeneration&&this.state===e&&(this.stagedOlderPage=r)}catch{}finally{n===this.stagedOlderGeneration&&(this.stagedOlderLoad=null)}})()}takeStagedOlderPage(e){let t=this.stagedOlderPage;return t?(this.stagedOlderPage=null,wC(e,t)?t.result:null):null}async continueCatalogSession(e){let t=this.captureConnectionScope(),n=t?.state,r=t?.client,i=n?.chatMessage.trim()??``;if(!t||!n||!r||!this.catalogSession?.canContinue)return;let a=Dg(n.chatAttachments);if(!i&&a.length===0)return;let o=n.sessionKey,s=Z(n),c=this.catalogLoadGeneration,l=Symbol(`catalog-continuation`);this.activeCatalogContinuation=l;let u=()=>this.activeCatalogContinuation===l&&this.isConnectionScopeCurrent(t)&&this.catalogLoadGeneration===c&&n.sessionKey===o&&Z(n)===s;n.chatSending=!0,n.requestUpdate();let d=()=>{this.activeCatalogContinuation===l&&(this.activeCatalogContinuation=null,n.chatSendingScopeKey==null&&n.chatSending&&(n.chatSending=!1,n.requestUpdate()))};try{let t=await r.request(`sessions.catalog.continue`,{...e,agentId:s,...this.catalogSession.sourceHomeId?{sourceHomeId:this.catalogSession.sourceHomeId}:{}});if(!u()){d();return}if(fw(this.context,this.paneId,t.sessionKey,{attachments:a,draft:i,send:!0}),this.onPaneSessionChange?.(this.paneId,t.sessionKey)===!1){mw(this.context,this.paneId,t.sessionKey),d();return}de({...e,agentId:s,sessionKey:t.sessionKey}),this.activeCatalogContinuation=null,n.chatSending=!1,n.requestUpdate()}catch(e){if(!u()){d();return}this.activeCatalogContinuation=null,n.lastError=P(e),n.chatSending=!1,n.requestUpdate()}}async rewindToMessage(e){let t=this.state;if(!t)return!1;let n=await cT(t,e,this.chatState.attachmentReads);return t.requestUpdate?.(),!!n}async forkFromMessage(e){let t=this.captureConnectionScope();if(!t)return;let n=t.state,r=n.sessionKey,i=L(n,r);try{let a=await n.sessions.forkAtMessage(r,e,i),o=a.editorText??``;if(!this.ownsHeaderOutcomeScope(t)||!V(n,r,i.agentId)||this.onPaneSessionChange?.(this.paneId,a.sessionKey)===!1)return;Hu(n,a.sessionKey,{agentId:jt(a.sessionKey)?.agentId,draft:o,mentions:[],replyTarget:null}),fw(this.context,this.paneId,a.sessionKey,{attachments:Ag([],a.editorAttachments),draft:o})}catch(e){if(!this.ownsHeaderOutcomeScope(t)||!V(n,r,i.agentId))return;n.lastError=P(e),n.chatError=n.lastError,n.requestUpdate?.()}}async switchToBranch(e){let t=this.state;t&&(await lT(t,e),t.requestUpdate?.())}announceCommandPaletteTarget(e){this.dispatchEvent(new CustomEvent(Er,{bubbles:!0,composed:!0,detail:{owner:this,onSlashCommand:e}}))}}})))()}var sA;function cA(){return(cA=e((()=>{bi(),Ei(),qi(),Pr(),Vr(),ql(),H(),ao(),vc(),nt(),on(),fa(),se(),I(),It(),B(),tt(),kT(),oA(),Vw(),Lh(),n(),sA=class extends aA{get dashboardDefaultWriteOwner(){return JSON.stringify([this.headerOutcomeOwner,this.state?.sessionKey,this.resolveBoardConversation().agentId])}canSaveDashboardDefault(e){return!!(this.state?.connected&&e.sessionId&&!this.sessionParticipationTracker.resolve({catalog:!1,listLoading:this.state.sessionsLoading,sessionKey:e.key,session:e})&&z(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:e.key,boardFace:`dashboard`,boardPresentation:`split`}}).allowed)}isDashboardDefault(e,t){return kn(e)===`dashboard`&&t===(e.boardPresentation??`split`)}dashboardDefaultMenuAction(e,t){let n=t?Up(t):void 0;if(!e?.sessionId||!this.state?.connected||!n)return;let r=R(`chat.sidePanel.defaultViewDescription`);if(this.isDashboardDefault(e,n))return{kind:`status`,label:R(`chat.sidePanel.currentViewIsDefault`),description:r};if(!this.canSaveDashboardDefault(e))return;let i=this.dashboardDefaultWrite?.owner===this.dashboardDefaultWriteOwner,a=this.resolveBoardConversation().agentId;return{label:R(i?`chat.sidePanel.savingDefault`:`chat.sidePanel.useViewAsDefault`),description:r,disabled:i,onActivate:()=>void this.saveDashboardDefault(e,a)}}async saveDashboardDefault(e,t){let n=this.captureConnectionScope(),r=this.state?Q(this.state):void 0,i=this.state?Up(this.state.sidebarLayout):void 0;if(!n||!r||r.key!==e.key||r.sessionId!==e.sessionId||this.resolveBoardConversation().agentId!==t||!i||!this.canSaveDashboardDefault(r)||this.isDashboardDefault(r,i)||this.dashboardDefaultWrite?.owner===this.dashboardDefaultWriteOwner)return;let a={owner:this.dashboardDefaultWriteOwner};this.dashboardDefaultWrite=a;let o=()=>this.ownsHeaderOutcomeScope(n)&&this.dashboardDefaultWrite===a&&this.context.sessions===n.sessions&&this.dashboardDefaultWriteOwner===a.owner&&Q(n.state)?.sessionId===e.sessionId;this.requestUpdate();try{let r=await n.sessions.patch(e.key,{boardFace:`dashboard`,boardPresentation:i},{agentId:t,expectedSessionId:e.sessionId});if(!o())return;if(!r)throw Error(R(`chat.sidePanel.defaultSaveFailed`));ct({message:R(`chat.sidePanel.defaultSaved`),anchor:this})}catch(e){o()&&(this.publishHeaderError(e,n.headerOutcomeOwner),ct({message:R(`chat.sidePanel.defaultSaveError`,{error:P(e)}),anchor:this}))}finally{this.dashboardDefaultWrite===a&&(this.dashboardDefaultWrite=void 0,this.requestUpdate())}}commitSidebarLayout(e,t){let n=this.state;if(!n)return;let r=this.initializeBrowserSidebarLayout(e),i=this.paneWidth>=680?Se(r,this.paneWidth)??r:r;n.updateSidebarLayout(i,t)}initializeBrowserSidebarLayout(e){if(!e.columns[0]?.browserWidthPending||!Je(e,`browser`))return e;let t=this.querySelector(`.agent-chat__composer-shell`);if(!t)return e;let n=Number.parseFloat(getComputedStyle(t).getPropertyValue(`--chat-composer-side-inset`));return Fe(e,this.querySelector(`.sidebar-region`)?.getBoundingClientRect().width??this.paneWidth,t.getBoundingClientRect().width+(Number.isFinite(n)?n:0))}commitSidebarPanelResize(e,t,n){let r=this.state;if(!r)return;let i=fg(e,t,n),a=this.paneWidth>=680?Se(i,this.paneWidth)??i:i,o=a.columns.find(e=>e.id===t),s=ce(a)===`bottom`?o?.height:o?.width;if(s!==void 0&&r.sidebarLayout.columns.some(e=>e.id===t)){r.updateSidebarLayout(fg(r.sidebarLayout,t,s),{geometryOnly:!0});return}this.commitSidebarLayout(a,{geometryOnly:!0})}resolveBoardConversation(){return Ft({assistantAgentId:this.state?.assistantAgentId,agentsList:this.state?.agentsList,hello:this.context?.gateway.snapshot.hello},this.state?.sessionKey||this.sessionKey)}resolveBoardProvider(){let e=this.resolveBoardConversation();if(this.boardProvider)return this.releaseBoardProviderLease(),this.boardProvider;let t=this.context?.gateway.snapshot,n=!t||da(t,`board.get`)!==!1,r=!t||Ur(t.hello?.auth??null),i=!t||ni(t.hello?.auth??null),a=r&&(!t||pa(t,Ui.BOARD_WIDGET_PUT_CANVAS_DOC)===!0),o=r&&(!t||da(t,`board.widget.appView`)===!0&&da(t,`board.widget.put`)===!0),s=t?.client;if(this.boardProviderLifecycleConnected&&s&&n){let n=Oc(e);return this.boardProviderLease?.cacheKey===n?this.boardProviderLease.update(s,t.phase===`connected`,{canPinWidgets:a,canPinMcpApps:o,canMutate:r,canGrant:i}):(this.releaseBoardProviderLease(),this.boardProviderLease={...ga(e,s,t.phase===`connected`,a,o,r,i),cacheKey:n}),this.boardProviderLease.provider}return this.releaseBoardProviderLease(),rc(e,n)}releaseBoardProviderLease(){this.boardProviderLease?.release(),this.boardProviderLease=void 0}readSavedDashboardLayout(){return this.state?Xr().sidebarSessionLayouts?.[Mt(this.state,this.state.sessionKey)]:void 0}captureNavigationFace(){let e=this.state;return e?Je(e.sidebarLayout,`dashboard`)?(this.retainDashboardPresentation(this.routeFace!==`dashboard`),`dashboard`):this.readSavedDashboardLayout()===void 0?this.routeFace:`chat`:this.routeFace}retainDashboardPresentation(e=!1){this.dashboardPresentationActivation={client:this.state?.client??null,key:Oc(this.resolveBoardConversation()),expanded:this.dashboardExpanded,pendingRoute:e}}syncRetainedBoardSession(e){let t=this.resolveBoardSessionKey(e.snapshot.sessionKey),n=this.routeFace===`dashboard`||this.dashboardExpanded,r=Oc(this.resolveBoardConversation()),i=this.dashboardPresentationActivation,a=this.state?.client??null,o=this.state?Q(this.state):void 0,s=i?.pendingRoute===!0&&i.key===r&&i.client===a;if(i&&n&&(i.pendingRoute=!1),!this.presented||!n&&!s)this.dashboardPresentationActivation=void 0;else if(e.available&&t&&(i?.key!==r||i.client!==a||i.expanded!==this.dashboardExpanded)){let e=this.readSavedDashboardLayout(),t=e!==void 0&&e.dashboardPresentationOverride!==null;if(this.dashboardExpanded||o||t){let t=e?.dashboardPresentationOverride??o?.boardPresentation??`split`,n=e&&(Up(e)??(e.columns.some(e=>e.panels.some(e=>e.slot===`dashboard`))?`split`:void 0));this.dashboardExpanded?this.showDashboard(!0):e&&(e.dashboardPresentationOverride===void 0||n===t)?(this.retainDashboardPresentation(),this.commitSidebarLayout(this.restorePaneSidebarLayout(e),{persist:!1})):this.showDashboard(t===`expanded`)}}if(t&&e.provider.hasLoadedSnapshot){let n=this.observedBoardPresence.get(t);this.observedBoardPresence.set(t,e.hasBoard),this.presented&&n===!1&&e.hasBoard&&e.face===`chat`&&!this.readSavedDashboardLayout()&&this.showDashboard((o?.boardPresentation??`split`)===`expanded`)}e.available&&this.state&&Je(this.state.sidebarLayout,`dashboard`)&&!customElements.get(`openclaw-board-view`)&&TT().then(e=>{e&&this.requestUpdate()})}resolveBoardSessionKey(e=``){let t=ht(e||this.state?.sessionKey||this.sessionKey,this.context?.gateway.snapshot.hello),n=xn(t);return n===`main`?i({agentId:`main`}):n}refreshSwarmRoster(){let e=this.context,t=!1;e.connectionBootstrap.run(this,async()=>{this.context===e&&(t=await this.hydrateSwarmRoster())},{background:!0}).then(()=>{t&&this.context===e&&this.presented&&this.isConnected&&this.refreshSwarmRoster()})}async hydrateSwarmRoster(){let e=this.state,t=this.context;if(!e||!this.presented||!this.isConnected)return!1;let n=this.resolveChatReadTarget();if(!n)return this.swarmHydrator?.dispose(),this.swarmHydrator=null,!1;let{sessionKey:r,agentId:i}=n,a=e.client;if(!a)return!1;let o=e.connectionEpoch,s=()=>this.context===t&&this.state===e&&this.presented&&this.isConnected&&e.client===a&&e.connectionEpoch===o&&r===this.resolveChatReadTarget()?.sessionKey&&i===this.resolveChatReadTarget()?.agentId,c=!1;return await M(async()=>{let{isSwarmEnabledInConfig:e,SwarmRosterHydrator:t}=await import(`./swarm-roster-udqDx5Ow.js`);return{isSwarmEnabledInConfig:e,SwarmRosterHydrator:t}},__vite__mapDeps([47,48,1,2,3,4,5,6,7,8,49,50,51,52,53,54,55,9,10,11,12,13,56,57,58,59,60,61,62]),import.meta.url).then(({isSwarmEnabledInConfig:n,SwarmRosterHydrator:l})=>{if(!s()){c=!0;return}if(!(e.connected&&n(t.runtimeConfig?.state.configSnapshot?.config,i))){this.swarmHydrator&&(this.swarmHydrator.dispose(),this.swarmHydrator=null,YO(e,`animation-frame`));return}this.swarmHydrator??=new l,this.swarmHydrator.update({sessions:t.sessions,parentKey:r,agentId:i,sourceEpoch:o,readParent:e=>t.sessions.describe({key:r,...jt(r)?{}:{agentId:i}},{client:a,refresh:e}).then(e=>e.session??null),currentRows:()=>s()?e.sessionsResult?.sessions??[]:[],onRows:()=>{s()&&YO(e,`animation-frame`)}})}),c}resolveBoardView(){let e=this.resolveBoardProvider(),t=e.snapshot$.value,n=t.tabs.length>0||t.widgets.length>0,r=this.resolveBoardSessionKey(t.sessionKey),i=this.context.theme.settings.boardSessionViews?.[r],a=(t.tabs.some(e=>e.tabId===i?.activeTabId)?i?.activeTabId:void 0)??t.tabs[0]?.tabId??t.widgets[0]?.tabId??``;return{provider:e,snapshot:t,available:!!this.boardProvider||da(this.context.gateway.snapshot,`board.get`)!==!1,hasBoard:n,face:this.routeFace??`chat`,activeTabId:a}}selectBoardTab(e){let t=this.resolveBoardView(),n=this.resolveBoardSessionKey(t.snapshot.sessionKey);if(!n)return;let r=this.context.theme.settings.boardSessionViews,i=br({boardSessionViews:Te(r,n,{activeTabId:e})});this.state&&(this.state.settings=i),this.requestUpdate()}isBoardPanelAvailable(e=this.resolveBoardView()){return e.available&&!!this.resolveBoardSessionKey(e.snapshot.sessionKey)}fullscreenBoardWidget(e,t){if(!e||!this.state||!Q(this.state)||!this.visuallyPresented||!t.provider.hasLoadedSnapshot||!customElements.get(`openclaw-board-view`)||Up(e)!==`expanded`)return;let n=t.snapshot.widgets.filter(e=>e.tabId===t.activeTabId),r=n.length===1?n[0]:void 0;return r?.sizeW===12?r:void 0}fullscreenBoardWidgetMenu(e,t=this.resolveBoardView()){let n=this.fullscreenBoardWidget(e,t);if(!n)return;let r=this.resolveBoardConversation();return r.agentId??=jt(t.snapshot.sessionKey)?.agentId,{widget:n,tabs:t.snapshot.tabs,canMutate:t.provider.canMutate,onSelect:e=>{let i=this.resolveBoardView();if(i.provider!==t.provider||this.fullscreenBoardWidget(this.state?.sidebarLayout,i)!==n)return;let a=this.querySelector(`openclaw-board-view`);a?.snapshot?.sessionKey===t.snapshot.sessionKey&&a.session.agentId===r.agentId&&a.session.sessionKey===r.sessionKey&&a.selectPageWidgetMenuItem(n.name,n.revision,e)}}}renderBoardPanel(e,t){let n=this.resolveBoardConversation(),r=this.resolveBoardSessionKey(e.snapshot.sessionKey);if(!this.isBoardPanelAvailable(e))return G;if(!e.provider.hasLoadedSnapshot){let t=e.provider.loadError$.value;return t?W`<div
            class="board-session-surface__state board-session-surface__state--error"
            role="alert"
          >
            ${R(`dashboardDocument.loadFailed`,{error:t})}
          </div>`:tu(`board`,R(`common.loading`))}n.agentId??=jt(e.snapshot.sessionKey)?.agentId;let i=Je(t,`dashboard`)&&this.visuallyPresented,a=r=>DT({active:r,session:n,snapshot:e.snapshot,activeTabId:e.activeTabId,pageWidgetName:this.fullscreenBoardWidget(t,e)?.name,canMutate:e.provider.canMutate,canGrant:e.provider.canGrant,callbacks:{appViewGeneration:e.provider.appViewGeneration,applyOps:t=>e.provider.applyOps(t),grant:(t,n)=>e.provider.grant(t,n),selectTab:e=>{this.onFaceChange?.(this.paneId,this.sessionKey,`dashboard`),this.selectBoardTab(e)},frameLoadFailed:t=>e.provider.refreshWidgetFrame(t),widgetAppView:(t,n)=>e.provider.widgetAppView(t,n),refreshWidgetAppView:(t,n)=>e.provider.refreshWidgetAppView(t,n)},widgetFrameUrl:(t,n)=>e.provider.widgetFrameUrl(t,n)});return W`${i?a(!0):Si([r,n.agentId],()=>a(!1))}`}showDashboard(e){let t=this.state;if(!t)return;let n=Th(t.sidebarLayout,e?`expanded`:`split`);this.retainDashboardPresentation(this.routeFace!==`dashboard`&&!this.dashboardExpanded),this.commitSidebarLayout(n,{persist:!1}),this.onFaceChange?.(this.paneId,this.sessionKey,`dashboard`)}handleBoardCommand(e){if(!this.presented)return;let t=this.resolveBoardView(),n=this.resolveBoardSessionKey(t.snapshot.sessionKey);if(!n||this.resolveBoardSessionKey(e.sessionKey)!==n)return;let r=e.command;if(r.kind===`focus_tab`){t.snapshot.tabs.some(e=>e.tabId===r.tabId)&&(this.selectBoardTab(r.tabId),this.showDashboard(!1));return}t.activeTabId&&this.showDashboard(r.dock===`hidden`)}}})))()}var lA,uA,dA;function fA(){return(fA=e((()=>{bi(),Rr(),er(),H(),vc(),on(),Da(),me(),Wo(),It(),B(),yT(),GS(),Y(),ew(),wT(),cA(),Pw(),Xv(),XE(),jO(),Wx(),qO(),iA(),Vw(),qu(),fd(),Ju(),Hf(),Gm(),lA=600,uA=`agent-chat__input--prefill-attention`,dA=class extends sA{constructor(...e){super(...e),this.archiveFocusOwned=!1,this.retainedQueuedEdit=!1,this.progressPresentationReady=!1}captureProgressCardRefreshAction(){let e=this.state,t=this.captureConnectionScope();if(!e||!t)return;let n=e.sessionKey,r=e.currentSessionId,i=Z(e);return{state:this.progressCard.refreshState,onRefresh:e=>{let a=this.state;a&&this.isConnectionScopeCurrent(t)&&a.sessionKey===n&&a.currentSessionId===r&&Z(a)===i&&this.progressCard.refresh(e)}}}captureArchivePresentationFocus(){this.archiveFocusOwned=!!(this.state&&this.isCurrentSessionArchived(this.state)&&this.currentSessionArchived===!1&&sd(this.presentationId,this))}retireArchivedPresentation(){let e=this.state?this.isCurrentSessionArchived(this.state):!1;e&&this.currentSessionArchived===!1&&(Gf(this.presentationId,this),this.archiveFocusOwned&&this.querySelector(`.chat-thread`)?.focus({preventScroll:!0})),this.currentSessionArchived=e}get hasQueuedMessageEdit(){return!!this.state?.chatQueuedEdit}syncQueuedEditRetention(){let e=this.hasQueuedMessageEdit;e!==this.retainedQueuedEdit&&(this.retainedQueuedEdit=e,this.dispatchEvent(new Event(bT,{bubbles:!0})))}reviewQueuedMessageEdit(e){let t=Fm(e);if(!t||this.state!==e||!this.isConnected)return;let n=e.client,r=En({context:this.context,face:`chat`,sessionKey:t.sessionKey,agentId:t.agentId,exactKey:!0});Wa(this,{agentId:t.agentId,face:`chat`,sessionKey:t.sessionKey,commit:()=>this.state!==e||e.client!==n||this.context.gateway.snapshot.client!==n||Fm(e)!==t?!1:(this.onFocusPane?.(this.paneId,`review-edit`),this.context.navigate(`chat`,r.options),!0)})}get progressCardPresentation(){let e=this.state;if(!e||e.settings.chatShowTaskProgress===!1||!this.presented||this.isCurrentSessionArchived(e)||Wt(e.sessionKey))return this.retainedProgressCard=void 0,null;let t=li(this.context.gateway),n=Dn(e),r=this.retainedProgressCard;r&&(!Zv(e).acceptedHistory||r.gatewayScope!==t||r.client!==e.client||r.sessionKey!==e.sessionKey||r.sessionId!==e.currentSessionId||r.agentId!==n)&&(this.retainedProgressCard=void 0);let i=this.progressCard.card,a=this.resolveChatReadTarget();return i&&a?this.retainedProgressCard={gatewayScope:t,client:e.client,sessionKey:e.sessionKey,sessionId:e.currentSessionId,agentId:n,card:i,lifetime:this.progressCard.lifetime,identity:JSON.stringify([a.agentId??null,a.sessionKey])}:this.progressCard.loading||(this.retainedProgressCard=void 0),this.retainedProgressCard??null}initialProgressCardTarget(){let e=this.state;if(e?.connected&&this.presented&&document.visibilityState!==`hidden`&&!this.isCurrentSessionArchived(e)&&!Wt(e.sessionKey)&&(this.transcriptReady||iy(e)))return e.settings.chatShowTaskProgress===!1?void 0:this.resolveChatReadTarget()}get progressCardInitialLoading(){let e=this.state;if(!e||e.settings.chatShowTaskProgress===!1||(this.progressPresentationSessionKey!==e.sessionKey&&(this.progressPresentationSessionKey=e.sessionKey,this.progressPresentationReady=!1),this.progressPresentationReady))return!1;let t=this.context.gateway.snapshot.phase;return!this.isCurrentSessionArchived(e)&&!Wt(e.sessionKey)&&ry(e).phase!==`failed`&&(t===`connecting`||t===`starting`||e.connected&&(!this.presented||document.visibilityState===`hidden`||!this.transcriptReady&&!iy(e)||this.initialProgressCardTarget()&&this.progressCard.loading&&!this.progressCard.error))?!0:(this.progressPresentationReady=!0,!1)}clearComposerPrefillAttention(){this.composerPrefillAttentionTimer!==null&&(window.clearTimeout(this.composerPrefillAttentionTimer),this.composerPrefillAttentionTimer=null),this.composerPrefillAttentionTarget?.classList.remove(uA),this.composerPrefillAttentionTarget=null}showComposerPrefillAttention(e){this.clearComposerPrefillAttention(),e.offsetWidth,e.classList.add(uA),this.composerPrefillAttentionTarget=e,this.composerPrefillAttentionTimer=window.setTimeout(()=>{this.composerPrefillAttentionTarget===e&&this.clearComposerPrefillAttention()},lA)}confirmConversationReset(){let e=this.resolveBoardView(),t=Oc(this.resolveBoardConversation()),n=this.resetConfirmation;if(n&&n.scopeKey!==t&&this.settleResetConfirmation(!1),!e.hasBoard)return Promise.resolve(!0);if(this.resetConfirmation)return this.resetConfirmation.promise;let r,i=new Promise(e=>{r=e});return this.resetConfirmation={scopeKey:t,promise:i,resolve:r},this.resetConfirmationOpen=!0,i}cancelResetConfirmationForSessionChange(){let e=this.resetConfirmation;e&&e.scopeKey!==Oc(this.resolveBoardConversation())&&this.settleResetConfirmation(!1)}settleResetConfirmation(e){let t=this.resetConfirmation;t&&(this.resetConfirmation=void 0,this.resetConfirmationOpen=!1,t.resolve(e))}renderResetConfirmation(){if(!this.resetConfirmationOpen)return G;let e=R(`chat.board.resetTitle`),t=R(`chat.board.resetDescription`);return W`
      <openclaw-modal-dialog
        label=${e}
        description=${t}
        @modal-cancel=${()=>this.settleResetConfirmation(!1)}
      >
        <div class="exec-approval-card board-reset-confirmation">
          <div class="exec-approval-header">
            <div>
              <div class="exec-approval-title">${e}</div>
              <div class="exec-approval-sub">${t}</div>
            </div>
          </div>
          <div class="exec-approval-actions">
            <button
              class="btn primary"
              type="button"
              @click=${()=>this.settleResetConfirmation(!0)}
            >
              ${R(`common.confirm`)}
            </button>
            <button
              class="btn"
              type="button"
              autofocus
              @click=${()=>this.settleResetConfirmation(!1)}
            >
              ${R(`common.cancel`)}
            </button>
          </div>
        </div>
      </openclaw-modal-dialog>
    `}activeChanged(e){this.isConnected&&(this.syncActiveBindings(),e&&this.activateComposerPresentation(),e&&this.presented&&this.state?.chatQueue.length&&(jx(this.state).catch(()=>void 0),kO(this.state)),this.querySelector(`.chat-transcript-announcement`)?.setAttribute(`aria-live`,e?`polite`:`off`))}presentedChanged(e){if(e||(this.dashboardPresentationActivation=void 0,this.retainedProgressCard=void 0),!this.isConnected)return;if(e){this.minutePoll.start(),this.consumeSessionHandoff(this.sessionKey),this.activateComposerPresentation(),this.syncActiveBindings();let e=this.state;e&&(this.unreadPatchGuard.beginActivation(e.sessionKey),qk(e,{automatic:!0}),this.refreshTaskSuggestions({automatic:!0}));let t=this.resumeDeferredSessionHydration();e&&!t&&(this.markSessionRead(Q(e)),e.connected&&this.resolveChatReadTarget()&&(e.chatRunId||Q(e)?.hasActiveRun)&&ZC(e,{deferBranches:!0})),e&&!t&&(!F(e.chatBranchesSessionKey,e.sessionKey)||e.chatBranchesConnectionEpoch!==e.connectionEpoch)&&WS(e),this.refreshSwarmRoster(),this.refreshSessionPullRequests();return}this.minutePoll.stop(),this.state&&(VS(this.state),Uv(this.state)),this.swarmHydrator?.dispose(),this.swarmHydrator=null,this.clearHistoryObserver(),zo(this.context.gateway).unwatch(this),this.syncActiveBindings(),this.clearComposerPrefillAttention(),this.settleResetConfirmation(!1),this.cancelHeaderRename(),Qu(this),dd(this.presentationId,this);let t=this.state;t&&(qE(t),WO(t),t.sidebarContent=null,af(t),t.requestUpdate?.()),this.querySelector(`.chat-transcript-announcement`)?.setAttribute(`aria-live`,`off`)}prepareForEviction(){let e=this.state;if(!e?.sessionKey)return;let t=this.chatState.composerPersistence.persistForRouteSwitchResult();if(t.status===`storage-failed`){let n=this.chatState.composerPersistence.scopeForRouteSwitch();n&&fT(e,n,{message:e.chatMessage,mentions:e.chatMentions,goalMode:e.chatGoalDraftMode,replyTarget:e.chatReplyTarget,attachments:e.chatAttachments,draftRetry:t})}}takeSessionHandoff(e){return pw(this.context,this.paneId,e)}consumeSessionHandoff(e){if(!this.state||!e)return;let t=this.takeSessionHandoff(e);t&&this.applySessionHandoff(e,t)}applySessionHandoff(e,t){let n=this.state;if(n&&(t.composerFallbacks&&(n.chatComposerFallbackByScope=t.composerFallbacks),n.chatAttachments=[...t.attachments],n.chatGoalDraftMode=t.goalMode??null,n.chatReplyTarget=t.replyTarget??null,n.handleChatDraftChange(t.draft,t.mentions??[]),n.requestUpdate?.(),t.send)){let r=nf(this.presentationId),i=r.editRevision;queueMicrotask(()=>{if(this.state!==n||n.sessionKey!==e)return;let a=n.client,o=n.connectionEpoch,s=n.sessions,c=n.chatAttachments,l=n.chatMentions,u=n.chatGoalDraftMode,d=n.chatReplyTarget,f=this.headerOutcomeOwner,p=()=>this.state===n&&n.sessionKey===e&&n.connected&&n.client===a&&n.connectionEpoch===o&&n.sessions===s&&this.isConnected&&this.active&&this.ownsHeaderOutcome(f)&&r.editRevision===i&&n.chatMessage===t.draft&&n.chatAttachments===c&&n.chatMentions===l&&n.chatGoalDraftMode===u&&n.chatReplyTarget===d;if(!p())return;let m=ry(n);(m.phase===`in-flight`?m.promise:m.phase===`idle`&&oy(n)?ZC(n,{startup:!0,deferBranches:!0}):Promise.resolve()).then(()=>{if(p()&&!oy(n))return n.handleSendChat()}).catch(e=>{p()&&J(n,P(e),!0)})})}}}})))()}var pA;function mA(){return(mA=e((()=>{H(),on(),se(),ye(),I(),B(),Ig(),uT(),Y(),jS(),fA(),Pw(),Vw(),mf(),pA=class extends dA{constructor(...e){super(...e),this.recoveringSession=!1,this.creatingIncognitoSession=!1,this.recoverSession=async()=>{let e=this.state;if(!e||!e.client||!e.connected||this.recoveringSession)return!1;let t=this.context,n=t.sessions,r={context:t,state:e,client:e.client,generation:this.connectionGeneration},i=()=>this.isConnectionScopeCurrent(r)&&this.context.sessions===n,a=e.sessionKey,o=L(e,a).agentId??Zt(a),s={...o?{agentId:o}:{},key:a},c=z(t.gateway.snapshot,{method:`sessions.recover`,params:s});if(!c.allowed)return J(e,c.reason,!0),!1;this.recoveringSession=!0,this.requestUpdate(),J(e,null);try{let t=await n.recover(s);if(!i()||e.sessionKey!==a)return!1;if(!t)return J(e,e.sessionsError??`New Chat could not create a new thread. Try again in a moment.`,!0),!1;if(t.continuation.status===`rejected`)return J(e,P(t.continuation.error.message),!0),!1;let r=t.key;return this.onPaneSessionChange?.(this.paneId,r)!==!1&&(fw(this.context,this.paneId,r,{attachments:[],draft:``}),!0)}finally{this.recoveringSession=!1,this.requestUpdate()}},this.createSession=async()=>{let e=this.state;if(!e||!e.client||!e.connected||this.creatingIncognitoSession)return!1;let t=this.context,n=t.sessions,r=e.client,i=e.sessionKey,a=ay(e),o=!a&&this.resolveBoardView().hasBoard,s={...a?{incognito:!0}:{currentSessionKey:i},agentId:L(e,i).agentId??Zt(i)},c={..._e(a?void 0:i,s.agentId),...a?{incognito:!0}:{}},l=()=>z(t.gateway.snapshot,{method:o?`sessions.reset`:`sessions.create`,...o?{requiredScope:`operator.admin`}:{params:c,sessionScope:!0}}),u={context:t,state:e,client:r,generation:this.connectionGeneration},d=()=>this.isConnectionScopeCurrent(u)&&this.context.sessions===n;if(!zw(e))return J(e,Mw,!0),!1;if(e.sessionsLoading)return J(e,Nw,!0),!1;let f=l();if(!f.allowed)return J(e,f.reason,!0),!1;if(!a&&!await this.confirmConversationReset()||!d()||!F(e.sessionKey,i))return!1;if(!zw(e))return J(e,Mw,!0),!1;let p=l();if(!p.allowed)return J(e,p.reason,!0),!1;if(J(e,null),o)return await sT(e)!==`failed`;this.creatingIncognitoSession=a,a&&this.requestUpdate();try{let t=await n.create(s);return d()?!t||e.sessionKey!==i||!zw(e)?(t||J(e,e.sessionsError??(e.sessionsLoading?`Session list is still refreshing. Try New Chat again in a moment.`:`New Chat could not create a new thread. Try again in a moment.`),!0),!1):this.onPaneSessionChange?.(this.paneId,t)!==!1&&(fw(this.context,this.paneId,t,{attachments:Dg(e.chatAttachments),draft:e.chatMessage,...e.chatMentions?.length?{mentions:e.chatMentions.map(e=>({...e}))}:{},...e.chatGoalDraftMode?{goalMode:e.chatGoalDraftMode}:{},...e.chatReplyTarget?{replyTarget:e.chatReplyTarget}:{}}),!0):!1}finally{this.creatingIncognitoSession=!1,a&&d()&&this.requestUpdate()}}}sessionDisabledBanner(e){if(e.selectedSession?.classification===`subagent`||St(e.sessionKey)){let t=Xe(e.selectedSession),n=Qd(e.selectedSession,this.state?.sessionsResult?.sessions??[]);return{kind:`composer-replacement`,title:R(`chat.subagentViewOnly`),text:R(`chat.subagentSessionDisabled`,{parent:n?.title??R(`chat.parentSession`)}),tone:`neutral`,actionLabel:R(`chat.openParentSession`),disabledReason:t?void 0:R(`chat.parentSessionUnavailable`),onAction:()=>t&&this.onPaneSessionChange?.(this.paneId,t)}}if(!e.catalogDisabledReason){if(this.state&&ay(this.state)){let e=z(this.context.gateway.snapshot,{method:`sessions.create`,params:{incognito:!0,agentId:L(this.state,this.state.sessionKey).agentId??Zt(this.state.sessionKey)}});return{kind:`composer-replacement`,title:R(`chat.incognitoExpiredTitle`),text:R(`chat.incognitoExpiredBody`),tone:`neutral`,actionLabel:R(`chat.newIncognitoSession`),busy:this.creatingIncognitoSession,disabledReason:e.allowed?void 0:e.reason,onAction:()=>{this.createSession()}}}return e.restartRecoveryTombstoned?this.restartRecoveryComposerBanner():e.selectedSessionArchived?{kind:`composer-replacement`,text:R(`chat.archivedSessionDisabled`),icon:`archive`,actionLabel:R(`common.unarchive`),disabledReason:e.selectedSessionId?e.unarchiveAccess.allowed?void 0:e.unarchiveAccess.reason:`Session lifecycle action requires a durable session identity.`,onAction:()=>{e.selectedSessionId&&e.unarchiveAccess.allowed&&this.restoreArchivedSession(e.sessionKey,e.selectedSessionId)}}:e.modelSetupRequired?kS(()=>this.context.navigate(`model-providers`,{search:`?connect=1`})):void 0}}restartRecoveryComposerBanner(){let e=this.state;if(!e)return;let t=L(e,e.sessionKey).agentId??Zt(e.sessionKey),n={...t?{agentId:t}:{},key:e.sessionKey},r=z(this.context.gateway.snapshot,{method:`sessions.recover`,params:n});return{kind:`composer-replacement`,title:R(`chat.restartRecoveryTitle`),text:R(`chat.restartRecoveryDisabled`),tone:`neutral`,icon:`warning`,actionLabel:R(`chat.resumeInNewSession`),actionStyle:`primary`,busy:this.recoveringSession,busyLabel:R(`chat.resumingSession`),disabledReason:r.allowed||this.recoveringSession?void 0:r.reason,onAction:()=>{r.allowed&&!this.recoveringSession&&this.recoverSession()}}}}})))()}function hA(e,t){return e.chatQueue.some(e=>e.sendRunId===t&&e.sendState===`sending`)}function gA(e){let t=m(e);return t?.role===`assistant`&&Array.isArray(t.content)?t:null}function _A(e){let t=e.errorDetail;if(!t||t.providerRuntimeFailureKind!==`auth_refresh`)return null;let n=[t.provider?`Provider: ${t.provider}`:void 0,t.httpStatus?`HTTP status: ${t.httpStatus}`:void 0,t.failoverReason?`Reason: ${t.failoverReason}`:void 0,t.providerErrorType?`Type: ${t.providerErrorType}`:void 0].filter(e=>!!e);return n.length>0?n.join(`
`):null}function vA(e,t){let n=e.errorMessage?.trim();if(n){if(e.state===`error`&&e.errorKind===`state_contention`)return n;let t=n.startsWith(`⚠️`)||n.startsWith(`Error:`)?n:`Error: ${n}`,r=_A(e);return r?`${t}\n\n${r}`:t}return(t?Ts(t)?.trim():null)||`chat error`}function yA(e,t,n,r,i){e.chatMessagesBySession&&Nm(e.chatMessagesBySession,e,{sessionKey:t,agentId:i},n,r)}function bA(e,t){if(!t)return null;let n=t.state===`aborted`&&t.stopReason===`auth-revoked`?{...t,errorMessage:R(`chat.providerAccessRemoved`)}:t,r=n.state===`final`?zm(n.message):null,i=e.chatRunId!==null,a=dy(e,n.sessionKey,n.agentId),o=e.chatRunId!==null&&typeof n.runId==`string`&&n.runId===e.chatRunId,s=!!(n.runId&&dg(e,n.runId)&&a);if(!a){if(n.state===`final`){let t=r;if(t&&!xc(t)){let r=mn(n.sessionKey)?n.agentId??vt(e):n.agentId;yA(e,n.sessionKey,t,n,r)}}return null}let c=np(e),l=(t,r,i,a)=>{let o=n;yp(e,r,{scope:c,event:{type:`messagePersisted`,message:t,envelope:{afterSequence:a,...i?{runId:i}:{},...o.messageId===void 0?{}:{messageId:o.messageId},...o.messageSeq===void 0?{}:{messageSeq:o.messageSeq}}}})},u=n.runId&&n.state!==`status`?Zi(Xf(e,c),r?{...n,message:r}:n,c):null;u&&qf(e,u.projection);let d=n.runId??e.chatRunId,f=()=>{let t=u?.currentRun?.status;if(!n.runId||n.runId!==e.chatRunId||!t||t===`streaming`)return;th(e);let r=[e.sessionKey,n.sessionKey];if(t===`yielded`){sm(e,{yielded:!0,runId:d,sessionKey:e.sessionKey,sessionKeys:r,clearLocalRun:!0,clearChatStream:!0});return}sm(e,{outcome:t===`completed`?`done`:`interrupted`,sessionStatus:t===`completed`?`done`:t===`aborted`?`killed`:t===`timeout`?`timeout`:`failed`,errorMessage:n.errorMessage?.trim()?vA(n,null):void 0,runId:d,sessionKey:e.sessionKey,sessionKeys:r,clearLocalRun:!0,clearChatStream:!0,armLocalTerminalReconcile:i&&o})},p=u?.previousRun;if(p&&p.status!==`streaming`&&u.currentRun?.status!==`streaming`){if(n.state===`delta`)return null;if(n.state===`error`||n.state===`aborted`){let t=e.chatQueue.find(e=>e.sendState===`sending`&&e.sendRunId)?.sendRunId;if((e.chatRunId??t??e.lastLocalTerminalReconcile?.runId)===n.runId&&n.errorMessage?.trim()&&u.currentRun?.errorMessage!==p.errorMessage&&Im(e,vA(n,null),n.runId,n.state===`error`&&n.errorKind===`state_contention`?`state_contention`:n.errorDetail?.providerRuntimeFailureKind===`auth_refresh`?`auth_refresh`:void 0),n.state===`error`)return f(),`error`}let t=r;if(n.state===`aborted`||n.state===`final`&&(!t||xc(t)||Hi(p,t)))return f(),n.state}if(!e.chatRunId&&(!p||p.status===`streaming`||u?.currentRun?.status===`streaming`)&&typeof n.runId==`string`&&(n.state!==`status`||hA(e,n.runId))&&(n.state===`status`?Yp(e,n.runId,Date.now()):(e.chatRunId=n.runId,tp(e,n.runId),e.chatRunError=null,e.chatStreamStartedAt??=Date.now())),e.chatRunId&&n.runId!==e.chatRunId){if(n.state===`final`){let t=r;return t&&!xc(t)?(l(t,[...e.chatMessages,t],n.runId),null):`final`}return null}let m=wm(e),h=(t={})=>IC(e.chatMessages,e,t),g=()=>{yp(e,h(),{scope:c}),Tm(e.chatMessages.findLast(e=>X_(e)===d),d,m,n.state===`aborted`?`aborted`:u?.currentRun?.status===`timeout`?`timeout`:`error`)};if(n.state===`status`){if(!n.runId||n.runId!==e.chatRunId)return null;let t=n.retry?typeof n.seq==`number`&&{phase:`retrying`,seq:n.seq,message:R(`chat.startupStatus.retrying`,{attempt:String(n.retry.attempt),maxAttempts:String(n.retry.maxAttempts)})}:n.phase&&{phase:n.phase,...n.seq===void 0?{}:{seq:n.seq}};return t&&jC(e,{state:`status`,runId:n.runId,...t}),n.state}if(n.state===`delta`){n.runId&&n.runId===e.chatRunId&&jC(e,{state:`activity`,runId:n.runId});let t=n.message==null?null:Ts(n.message)??``;typeof t==`string`&&!Rs(t)&&!ws(n.message)&&(e.chatStream=t,$m(e))}else if(n.state===`final`){let t=r;if(!s){let n=t?$p(t,e):{kind:`none`};if(n.kind===`split`){nm(e,n.replacedSegmentIndexes);let t=h({includeCurrent:!1});if(n.tailMessage&&!xc(n.tailMessage)){let e=Tm(n.tailMessage,d,n.afterBoundaryRunId);t=Zm(t,e,{preserveKeyedCommentary:n.preserveKeyedCommentary}),l(n.tailMessage,t,d,n.afterSequence)}else yp(e,t,{scope:c})}else if(t&&!xc(t)){let e=h(),n=Tm(t,d,m);l(t,Zm(e,n),d)}else yp(e,h(),{scope:c})}f()}else if(n.state===`aborted`){let t=gA(n.message);if(t&&!xc(t)){let e=h({replacementMessages:[t],includeCurrent:!1}),n=Tm(t,d,m,`aborted`);l(t,Zm(e,n),d)}else g();n.errorMessage?.trim()&&Im(e,vA(n,null),n.runId,n.errorDetail?.providerRuntimeFailureKind===`auth_refresh`?`auth_refresh`:void 0),f()}else if(n.state===`error`){let t=zm(n.message),r=t&&!xc(t)?t:null,a=!!(r&&la(r,n.errorMessage));if(i){if(r&&!a){let t=Dh(r,e,{isHiddenStreamText:gc,persistCommentary:e.settings?.chatPersistCommentary!==!1}),n=h({includeCurrent:!t}),i=Tm(r,d,m,u?.currentRun?.status===`timeout`?`timeout`:`error`);l(r,t?Zm(n,i):[...n,i],d)}else g()}f(),Im(e,vA(n,a?r:null),n.runId,n.state===`error`&&n.errorKind===`state_contention`?`state_contention`:n.errorDetail?.providerRuntimeFailureKind===`auth_refresh`?`auth_refresh`:void 0)}return n.state!==`delta`&&th(e),n.state}function xA(){return(xA=e((()=>{Ki(),Qi(),Xi(),H(),jc(),hc(),ec(),B(),Y(),qC(),FC(),ov(),ip(),Lp(),zh(),jh(),ng(),mm(),ch()})))()}function SA(e,t){return dy(e,t.key,t.agentId??void 0)}function CA(e,t){return t?f(t):vt(e)}function wA(e,t){if(!mn(t.key))return!0;let n=mn(e.sessionKey)?Tt(e):Sn(e,e.sessionKey);return!n||CA(e,t.agentId)===n}function TA(e,t,n,r,i){return(r?Qp(e,r,{publishRunStatus:!0}):km(e,{publishRunStatus:!0}))?(c_(e,n??void 0),ZC(e,{deferBranches:!i()}).finally(()=>{F(e.sessionKey,t)&&(AO(e),e.requestUpdate?.())}).catch(()=>void 0),!0):!1}function EA(e,t,n,r){let i=rt(t);if(!i||!wA(e,i))return!1;let a=SA(e,i),o=ea(m(t)?.message)?.role===`user`;a&&(HS(e),ry(e).phase===`in-flight`&&ZC(e,{deferBranches:!n(),supersedeInFlight:!0}).finally(()=>e.requestUpdate?.()),vm(e,t,i.hasActiveRun??void 0,{kind:`live`,activeRunId:e.chatRunId})),a&&i.archived!==null&&(e.selectedChatSessionArchived=i.archived);let s=e.chatRunId;if(Gp({event:i,host:e,matchesChat:a,payload:t,runIdBeforeApply:s}),r.applied&&Cm(e),s&&a){let t=i.clientRunId??i.runId??s;return e.pendingSessionMessageReloadSessionKey=i.key,i.hasActiveRun===!0?(o&&ZC(e,{deferBranches:!n(),supersedeInFlight:!0}).finally(()=>e.requestUpdate?.()),!0):TA(e,i.key,t,r.row,n)?(e.pendingSessionMessageReloadSessionKey=null,!0):(jx(e).then(()=>{e.pendingSessionMessageReloadSessionKey&&e.chatRunId===s&&TA(e,e.pendingSessionMessageReloadSessionKey,t,void 0,n)&&(e.pendingSessionMessageReloadSessionKey=null)}),!0)}return a&&(e.pendingSessionMessageReloadSessionKey=null,ZC(e,{deferBranches:!n()}).finally(()=>e.requestUpdate?.())),a}function DA(e,t,n,r=!1){let i=e.pendingSessionMessageReloadSessionKey,a=t?.sessionKey?.trim();return!i||!a||!F(i,a)||!F(a,e.sessionKey)||e.chatRunId?!1:(e.pendingSessionMessageReloadSessionKey=null,ZC(e,{deferBranches:!n(),supersedeInFlight:r}).finally(()=>e.requestUpdate?.()),!0)}function OA(e,t){let n=t.runId;return n?{sessionKey:t.sessionKey,agentId:Z(e),runId:n,client:e.client,connectionEpoch:e.connectionEpoch,runLifecycleGeneration:e.chatRunLifecycleGeneration??0,initialTerminalReplySignatures:ym(e,n).terminalReplySignatures}:null}function kA(e,t){let n=UA.get(e);n||(n=new Map,UA.set(e,n));let r=[t.connectionEpoch,t.runLifecycleGeneration,t.agentId,t.sessionKey,t.runId].join(`\0`);if(n.has(r)&&n.get(r)===t.client)return!1;for(n.delete(r),n.set(r,t.client);n.size>HA;){let e=n.keys().next().value;if(typeof e!=`string`)break;n.delete(e)}return!0}function AA(e,t){let n=ym(e,t.runId);return n.acceptedFinal||[...n.terminalReplySignatures].some(e=>!t.initialTerminalReplySignatures.has(e))}function jA(e,t){return e.connected&&e.client===t.client&&e.connectionEpoch===t.connectionEpoch&&F(e.sessionKey,t.sessionKey)&&Z(e)===t.agentId&&(e.chatRunId===null||e.chatRunId===t.runId)&&(e.chatRunLifecycleGeneration??0)===t.runLifecycleGeneration&&!AA(e,t)}async function MA(e,t,n){for(let r=0;;r+=1){if(!jA(e,t)||(await ZC(e,{deferBranches:!n(),supersedeInFlight:!0}),e.requestUpdate?.(),!jA(e,t)))return;let i=VA[r];if(i===void 0)return;await iC(i)}}function NA(e,t,n,r){let i=n(),a=e.chatRunId,o=rt(t),s=!!(o&&wA(e,o)&&SA(e,o)),c=m(t),l=c?.reason===`reset`||c?.phase===`reset`;o&&(l||c?.reason===`new`)&&e.retireSessionCompanion?.(o.key,o.agentId);let u=s&&l;if(s&&(l||c?.reason===`new`)){let t=e.chatSubmissions?.readInitial(e.sessionKey,e.client??null);t&&Qf(e,new Set([t.pendingRunId]))}let d=s&&typeof c?.reason==`string`&&zA.has(c.reason);if((u||d)&&Uv(e),u){let t=np(e,{agentId:Z(e)});ap(e,{type:`sessionReset`},{scope:t})}d&&(HS(e),e.chatBranches=[],e.chatBranchesSessionKey=null,e.chatBranchesConnectionEpoch=null,Fu(e),i&&WS(e)),o&&s&&o.archived!==null&&(e.selectedChatSessionArchived=o.archived),r.applied&&Cm(e);let f=o?.clientRunId??o?.runId;return s&&c?.phase===`model`&&f&&r.admittedRow&&(e.chatSending?e.chatQueue.some(t=>t.sendState===`sending`&&(t.queueMode===`steer`&&e.chatRunId?e.chatRunId===f:t.sendRunId===f)):!e.chatRunId||e.chatRunId===f)&&bp(e,f,r.admittedRow),u||s&&c?.reason===`compact`?(ZC(e,{deferBranches:!i}).finally(()=>e.requestUpdate?.()),!0):s&&c?.phase===`message`&&c.message===void 0&&c.messageId===void 0&&c.messageSeq===void 0?(HS(e),ZC(e,{deferBranches:!i,supersedeInFlight:!0}).finally(()=>e.requestUpdate?.()),!0):(s&&typeof c?.reason==`string`&&BA.has(c.reason)&&ZC(e,{deferBranches:!i,supersedeInFlight:!0}).finally(()=>e.requestUpdate?.()),r.applied&&o&&a&&s&&TA(e,o.key,o.clientRunId??o.runId??a,r.row,n),s)}function PA(e,t){return typeof t?.runId==`string`&&t.runId===e.chatRunId}function FA(e,t){if(t?.state!==`final`)return!1;let n=[Ts(t.message)];return PA(e,t)&&n.push(e.chatStream,...(e.chatStreamSegments??[]).map(e=>e.text)),n.some(e=>Bv(e).length>0)}function IA(e,t){if(t?.state!==`final`||!dy(e,t.sessionKey,t.agentId))return!1;let n=Ts(t.message);return typeof n==`string`&&n.trim().length>0&&!gc(n)&&!xc(t.message)?!0:PA(e,t)?[e.chatStream,...(e.chatStreamSegments??[]).map(e=>e.text)].some(e=>typeof e==`string`&&e.trim().length>0&&!gc(e)):!1}function LA(e,t){if(e.chatRunId)return t.runId===e.chatRunId;let n=Q(e);return!!(n?.hasActiveRun&&t.runId&&n.activeRunIds?.includes(t.runId))}function RA(e,t,n=()=>!0,r={applied:!1}){if(t.event===`models.snapshot`){$k(e);return}if(t.event===`session.approval`){let n=m(t.payload);if(!n||typeof n.sessionKey!=`string`)return;let r=dh(e.chatSessionApprovalQueue??[],n,e.sessionKey,Z(e));r&&(e.chatSessionApprovalQueue=r,YO(e));return}if(t.event===`chat`){let r=t.payload,i=r&&(r.state===`final`||r.state===`aborted`||r.state===`error`)?r:void 0,a=()=>{let a=!!(r&&dy(e,r.sessionKey,r.agentId)),o=r?.state===`final`&&(r.message===void 0||r.message===null)&&a&&typeof r.runId==`string`&&(!e.chatRunId||e.chatRunId===r.runId)?r.runId:null,s=o?np(e):null;r?.state===`delta`&&typeof r.runId==`string`&&a&&(!e.chatRunId||e.chatRunId===r.runId)&&e.observerDigest&&e.observerDigest.runId!==r.runId&&(e.observerDigest=null),r?.state===`delta`&&typeof r.deltaText==`string`&&a&&Wv(e,r.runId,r.deltaText);let c=IA(e,r)&&FA(e,r);bA(e,r),i&&a&&c_(e,i.runId),c&&r&&Gv(e,r.runId,r.message);let l=o&&s&&Xf(e,s).runs[o]?.status===`completed`&&r?OA(e,r):null,u=l?kA(e,l):!1;l&&u?(e.pendingSessionMessageReloadSessionKey=null,MA(e,l,n).catch(()=>void 0)):DA(e,r,n),i&&(kO(e,t),a&&(n()?Wf(e,Je(e.sidebarLayout,`workspace`)):Fu(e))),a&&YO(e,r?.state===`delta`?`animation-frame`:`immediate`)};if(!i){a();return}let o=Ft(e,i.sessionKey,mn(i.sessionKey)?CA(e,i.agentId??null):i.agentId),s=e.connectionEpoch,c=s_(e,i.runId,o)?.item,l=jp(e),u=by(e,i.runId,o,{retainUntilConsumed:!!(c&&hy(c))}),d=t=>{t!==`stale`&&e.connectionEpoch===s&&l()&&a()};if(u instanceof Promise){u.then(d);return}d(u);return}if(t.event===`session.observer`){let n=t.payload;if(!n||!dy(e,n.sessionKey,n.agentId)||!LA(e,n))return;let r=e.observerDigest;if(r?.runId===n.runId&&Is(r,n)===r)return;e.observerDigest=n,YO(e);return}if(t.event===`agent`||t.event===`session.tool`){mg(e,t.payload)&&YO(e,`animation-frame`);return}if(t.event===`session.operation`){Km(e,t.payload),YO(e,`animation-frame`);return}if(t.event===`chat.send_timing`){qD(e,t.payload);return}if(t.event===`session.message`||t.event===`sessions.changed`){let i=(t.event===`session.message`?EA:NA)(e,t.payload,n,r);kO(e,t),i&&YO(e,`animation-frame`)}}var zA,BA,VA,HA,UA;function WA(){return(WA=e((()=>{ta(),hc(),ec(),Ce(),B(),xA(),GS(),sC(),Y(),ew(),Xv(),l_(),jO(),wy(),tO(),Wx(),iA(),Vw(),Sd(),ip(),up(),Lp(),Hh(),Lm(),Lh(),ch(),Oh(),am(),Vp(),zA=new Set([`rewind`,`branch-switch`,`fork`,`reset`,`new`]),BA=new Set([`send`,`agent.run.started`,`agent.input.settled`]),VA=[100,400,1500,3e3],HA=64,UA=new WeakMap})))()}function GA(e,t,n=null){let r=Z(e);if(!t){let t=e.sessionsResult;if(!t||e.sessionsResultAgentId!==r)return!1;let i=t.sessions.filter(t=>!dy(e,t.key,t.agentId)||n!==null&&t.sessionId!==n);return i.length!==t.sessions.length&&(e.sessionsResult={...t,sessions:i,count:i.length},!0)}if(!dy(e,t.key,t.agentId??r))return!1;let i=e.sessionsResultAgentId===r?e.sessionsResult:null,a=t.sessionId?i?.sessions.find(n=>n.sessionId===t.sessionId&&dy(e,n.key,n.agentId)):void 0,o=a&&a.key!==t.key?e.sessions.inheritRow({...t,key:a.key},t):t,s=i&&a?Ae(i,i.sessions.map(e=>e===a?o:e)):Ye(i,t,void 0,{resultAgentId:r,selectedGlobalAgentId:r,archivedFilter:t.archived?`all`:e.sessionsArchivedFilter},!1,{project:(n,r)=>e.sessions.inheritRow(n,t,r)});return t.providerReview&&(QE(e,t.key,t.agentId??r),(e.realtimeTalkSession||e.realtimeTalkActive||e.realtimeTalkUseSystemDefault)&&qE(e,{preserveConversation:!0})),s===e.sessionsResult&&e.sessionsResultAgentId===r?!1:(e.sessionsResult=s,e.sessionsResultAgentId=r,!0)}var KA;function qA(){return(qA=e((()=>{me(),Ce(),B(),Y(),nT(),mA(),$E(),XE(),jO(),WA(),Vw(),ip(),Lp(),KA=class extends pA{constructor(...e){super(...e),this.activeSessionResources=new tT,this.sessionObservation=null,this.parentSessionObservation=null}observedParentSessionRow(){let e=this.parentSessionObservation;return e?.matchesPane()&&e.observation?.isCurrent()?e.observation.row:null}retireParentSessionObservation(){let e=this.parentSessionObservation;this.parentSessionObservation=null,e?.observation?.dispose()}synchronizeParentSessionObservation(){let e=this.state,t=this.resourceSessionObservation(),n=Xe(t?.row);if(!e?.connected||!t||!n||F(n,e.sessionKey)){this.retireParentSessionObservation();return}let r=this.parentSessionObservation;if(r?.matchesPane()&&r.observation?.isCurrent()){r.retryFailedRead();return}this.retireParentSessionObservation();let i=this.context.sessions,a=e.client;if(!a)return;let o=jt(n)?.agentId??Z(e),s=!1,c={retryFailedRead:()=>{s&&d()},matchesPane:()=>this.state===e&&e.connected&&e.client===a&&this.resourceSessionObservation()===t&&Xe(t.row)===n,observation:null},l=()=>this.parentSessionObservation===c&&c.matchesPane(),u=null,d=()=>{!u&&l()&&(s=!1,u=(async()=>{let e=c.observation;for(;l()&&e?.isCurrent();){let t=e.captureReconcile(),{session:r}=await i.describe({key:n,agentId:o},{client:a});if(!l()||t(r??void 0).status!==`invalidated`)return}})().catch(()=>{s=!0}).finally(()=>{u=null}))};this.parentSessionObservation=c,c.observation=i.observeRow({key:n,agentId:o},(e,t)=>{l()&&(this.requestUpdate(),!t?.eventPending&&c.observation&&!c.observation.isCurrent()&&this.synchronizeParentSessionObservation())},{onInvalidate:d,onEvent:()=>{l()&&!c.observation?.isCurrent()&&this.synchronizeParentSessionObservation()}}),l()?d():c.observation.dispose()}resourceSessionObservation(){let e=this.sessionObservation;return e?.matchesPane()&&e.observation?.isCurrent()?e.observation:null}retireSessionObservation(){this.retireParentSessionObservation();let e=this.sessionObservation;this.sessionObservation=null,e?.observation?.dispose()}synchronizeSessionObservation(e={}){let t=this.state,n=this.context.sessions;if(!t?.connected||!t.sessionKey.trim()||Wt(t.sessionKey)){this.retireSessionObservation();return}let r=n.captureConnectionScope();if(!r){this.retireSessionObservation();return}let i=t.sessionKey,a=Z(t),o=this.sessionObservation;if(o?.matchesPane()&&o.observation?.isCurrent()){this.synchronizeParentSessionObservation();return}let s=o?.matchesPane()?o.observation?.sessionId:null,c=t.chatRunId||t.chatStream!=null||Xf(t).entries.some(e=>!e.pending)?o?.observation?.sessionId:null;this.retireSessionObservation();let l={matchesPane:()=>this.state===t&&t.sessionKey===i&&Z(t)===a&&n===this.context.sessions&&n.isConnectionScopeCurrent(r),observation:null},u=()=>t.connected&&l.matchesPane(),d=()=>this.sessionObservation===l&&u();if(this.sessionObservation=l,l.observation=n.observeRow({key:i,agentId:a},(e,n)=>{if(d()&&(e!==null||l.observation?.hasObserved)){let n=t.pendingAbort;!e&&n&&Qe(t,n.sessionKey,i,a,n.agentId)&&(t.pendingAbort=null),GA(t,e,l.observation?.sessionId)&&this.requestUpdate(),this.synchronizeParentSessionObservation(),t.pendingAbort&&gm(t).finally(()=>t.requestUpdate?.())}!n?.eventPending&&d()&&l.observation&&!l.observation.isCurrent()&&this.synchronizeSessionObservation()},{onInvalidate:e=>{if(d()){if(e===`runner-availability`){this.activeSessionResources.invalidate(),this.requestUpdate();return}this.activeSessionResources.reconcileObservation({requestUpdate:()=>this.requestUpdate(),updated:()=>this.updateComplete})}},onEvent:(e,n)=>{if(!d())return;if(n.generationRejected){this.synchronizeSessionObservation(),u()&&kO(t,e);return}let r=n,i=c,a=rt(e.payload);if(l.observation&&!l.observation.isCurrent()){let n=l.observation.sessionId;i=n,this.synchronizeSessionObservation({eventSessionId:a?.sessionId});let o=this.sessionObservation;if(!u()||!o?.matchesPane()||!o.observation?.isCurrent())return;if(!a?.sessionId||a.sessionId===n||a.sessionId!==o.observation.sessionId||a.sessionId!==o.observation.row?.sessionId||!dy(t,a.key,a.agentId??void 0)){kO(t,e);return}r={applied:!1}}let o=this.sessionObservation?.observation,s=t.currentSessionId??i;if(a?.sessionId&&o?.isCurrent()&&a.sessionId===o.sessionId&&a.sessionId===o.row?.sessionId&&dy(t,a.key,a.agentId??void 0)&&s&&s!==a.sessionId&&(t.currentSessionId||t.chatRunId||t.chatStream!=null||Xf(t).entries.some(e=>!e.pending))){this.refreshHistory(),kO(t,e);return}e.event===`session.message`&&this.clearTypingActorForSessionMessage(e.payload),RA(t,e,()=>this.presented,r)}}),!d())l.observation.dispose();else{this.projectObservedSessionRow();let n=l.observation,r=t.currentSessionId??c;s&&n?.isCurrent()&&n.sessionId&&n.sessionId!==e.eventSessionId&&n.sessionId!==s&&n.row?.sessionId===n.sessionId&&r&&r!==n.sessionId&&this.refreshHistory()}}projectObservedSessionRow(){let e=this.state,t=this.sessionObservation;e&&t&&t.matchesPane()&&t.observation?.hasObserved&&t.observation?.isCurrent()&&(GA(e,t.observation.row,t.observation.sessionId),this.synchronizeParentSessionObservation())}setPaneSessionKey(e){let t=super.setPaneSessionKey(e);return this.synchronizeSessionObservation(),t}}})))()}var JA,YA;function XA(){return(XA=e((()=>{mi(),Xn(),gr(),il(),B(),Vw(),Lh(),JA=[[jr,`terminal`,`openclaw-terminal-panel`],[wr,`browser`,`openclaw-browser-panel`],[dr,`link-reader`,`openclaw-link-reader-panel`],[pr,`desktop`,`openclaw-desktop-panel`],[Or,`portal`,`openclaw-portals-page`]],YA=class{constructor(e){this.options=e}subscribe(){let e=JA.map(([e,t,n])=>{let r=e=>{this.handle(t,n,e)};return window.addEventListener(e,r),()=>window.removeEventListener(e,r)}),t=()=>{let e=this.options.current();e&&e.state.updateSidebarLayout(bh(e.state.sidebarLayout,`terminal`))};return window.addEventListener(Dr,t),()=>{e.forEach(e=>e()),window.removeEventListener(Dr,t),this.options.pending.clear()}}handle(e,t,n){let r=this.options.current();if(!r)return!1;let i=Kr(n);if(i&&!F(i,r.state.sessionKey))return!1;let a=n instanceof CustomEvent?n.detail:null;if(e===`link-reader`&&a?.open!==!1&&(!r.state.connected||!r.state.client||r.linkReaders.length===0||a?.url!==void 0&&!_r(a.url,r.linkReaders)))return nr(e,n),!1;if(nr(e,n),e===`link-reader`&&n.preventDefault(),a?.open===!1)return this.options.pending.delete(e),this.options.updateSidebarLayout(bh(r.state.sidebarLayout,e)),!0;let o=Ch(r.state.sidebarLayout,e);(a?.dock===`right`||a?.dock===`bottom`)&&(o=lh(o,a.dock));let s=o.columns.flatMap(e=>e.panels).find(t=>t.slot===e);if(s&&e===`desktop`&&i&&typeof a?.environmentId==`string`&&(s.environmentId=a.environmentId),s&&e===`portal`&&typeof a?.portalId==`string`?(s.portalId=a.portalId,delete s.environmentId):s&&e===`portal`&&typeof a?.environmentId==`string`&&(s.environmentId=a.environmentId,delete s.portalId),e===`terminal`){let e=bl(n,Z(r.state)),t=r.renderRoot.querySelector(`openclaw-terminal-panel[embedded]`),i=customElements.get(`openclaw-terminal-panel`),a=t!==null&&i!==void 0&&t instanceof i;return e&&Cl.queue(e,{deferUntilHostChange:!a}),this.options.updateSidebarLayout(o),!0}let c=this.options.pending.get(e);if(e===`link-reader`&&c?.owner===r.state&&c.sessionKey===r.state.sessionKey)return c.events.push(n),this.options.updateSidebarLayout(o),!0;let l={events:[n],owner:r.state,sessionKey:r.state.sessionKey},u=r.state.sessionKey,d=()=>this.options.pending.get(e)===l&&this.options.current()?.state===r.state&&r.state.sessionKey===u;return this.options.pending.set(e,l),this.options.updateSidebarLayout(o),Promise.all([customElements.whenDefined(`openclaw-chat-sidebar-region`),customElements.whenDefined(t)]).then(async()=>{if(this.options.requestUpdate(),await this.options.current()?.updateComplete,!d())return;let t=r.renderRoot.querySelector(`openclaw-chat-sidebar-region`);if(await t?.updateComplete,d())for(let n of l.events){if(!d())return;let r=this.options.current(),i=n instanceof CustomEvent?n.detail:null;(e!==`link-reader`||r?.state.connected&&r.state.client&&r.linkReaders.length!==0&&(i?.url===void 0||_r(i.url,r.linkReaders)))&&t?.deliverPanelEvent(e,n)}}).finally(()=>{this.options.pending.get(e)===l&&(this.options.pending.delete(e),this.options.requestUpdate())}),!0}flush(){let e=this.options.current();if(e)for(let[,t,n]of JA){let r;for(;r=Zn(t,e.state.sessionKey);)this.handle(t,n,r)}}}})))()}function ZA(e,t){return e.placementStartup.subscribe(()=>{let e=t();e&&(Yf(e,Ov(e)?.page.items),Wt(e.sessionKey)||kO(e),e.requestUpdate?.())})}function QA(e){return Et(({sessionKey:t,reason:n})=>{let r=e();n===`cache-eviction`||!r||t&&ft(r,{sessionKey:r.sessionKey})!==t||(uy(r),r.requestUpdate?.())})}function $A(){return($A=e((()=>{me(),Y(),zv(),jO(),ip(),zh(),yt()})))()}function ej(e,t){nd(e),zf(e,t)}function tj(){return(tj=e((()=>{yu(),Hf()})))()}var nj;function rj(){return(rj=e((()=>{hi(),or(),ii(),wl(),ol(),Zl(),Pt(),me(),I(),B(),nb(),nn(),Y(),tC(),uw(),Lw(),uS(),Gw(),qA(),XA(),Pw(),wS(),$A(),zv(),Wx(),WA(),qO(),iA(),tj(),My(),Kf(),fd(),zu(),fp(),ip(),Tp(),zh(),Lh(),nj=class extends KA{constructor(...e){super(...e),this.sessionPanelToggles=new YA({current:()=>{let e=this.state;return e&&this.active&&this.presented?{renderRoot:this.renderRoot,state:e,linkReaders:Sr(this.context.gateway.snapshot),updateComplete:this.updateComplete}:null},pending:this.pendingPanelToggleRequests,requestUpdate:()=>this.requestUpdate(),updateSidebarLayout:e=>this.commitSidebarLayout(e)}),this.chatRouteReadyReported=!1,this.stagedAttachmentGatewayOwner=null,this.suppressStagedAttachmentHandoffOnDisconnect=!1,this.handlePaneInput=()=>{this.sessionCompanionFocusGeneration+=1},this.handlePaneFocus=()=>{this.sessionCompanionFocusGeneration+=1,Ir(this.context).claim(this.inputRegion),this.onFocusPane?.(this.paneId)},this.handleDocumentKeydown=e=>{let t=this.state;if(!t||!this.active||!this.presented||e.defaultPrevented||document.querySelector(`.shell-nav[aria-modal='true']`)||this.handleArchiveSessionShortcut(e))return;let n=Object.values(lS).find(t=>t&&tn(t.combo,e)),r=this.sessionDiscussionStates.get(t.sessionKey.trim());if(n?.available({state:t,desktopAvailable:oi(this.context.gateway.snapshot),discussion:t.connected&&t.client?!0:null,discussionAvailable:r===`available`||r===`open`,dashboardAvailable:()=>!this.compact&&this.isBoardPanelAvailable()})){e.preventDefault();let{slot:r}=n,i=Je(t.sidebarLayout,r);i&&Uw(t,r),this.commitSidebarLayout(i?bh(t.sidebarLayout,r):Hw(t,t.sidebarLayout,r));return}Sw(this,e),!(e.defaultPrevented||e.isComposing||e.keyCode===229||e.key!==`Escape`)&&xw(this)&&e.preventDefault()},this.handleDocumentPointerdown=e=>{this.state&&xw(this,e.composedPath())&&this.state.requestUpdate()}}activateComposerPresentation(){this.selected&&this.presented&&this.composerPresentation?.claim()}discardStagedAttachments(){this.suppressStagedAttachmentHandoffOnDisconnect=!0,this.chatState.attachmentReads.abortReads(),iw(this.state)}resumeStagedAttachments(){this.suppressStagedAttachmentHandoffOnDisconnect=!1}browserAnnotationOwner(){return this.stagedAttachmentGatewayOwner??void 0}replaceStagedAttachmentGatewayOwner(e){this.stagedAttachmentGatewayOwner=aw(this.context,this.paneId,this.state,this.stagedAttachmentGatewayOwner,e)}syncActiveBindings(){if(this.nativeDraftCleanup?.(),this.nativeDraftCleanup=null,!this.state||!this.active||!this.presented){this.sessionCompanionFocusGeneration+=1,this.announceCommandPaletteTarget(null);return}this.announceCommandPaletteTarget(this.handleCommandPaletteSlashCommand),this.nativeDraftCleanup=this.context.nativeChatDrafts.subscribe(e=>{let t=this.state;t&&this.active&&this.presented&&(t.handleChatDraftChange(e,[]),t.requestUpdate?.())})}receiveBrowserAnnotation(e){Iw(this.state,this.active&&this.presented,e,this.chatState.attachmentReads.pendingBytes(Cu(this.state?.hello?.policy)))&&(this.stagedAttachmentGatewayOwner??=this.context.gateway.snapshot.client,Fw(this))}connectedCallback(){this.boardProviderLifecycleConnected=!0,this.resumeStagedAttachments(),super.connectedCallback(),this.presented||this.minutePoll.stop();let e=this.context.gateway.snapshot.client;this.stagedAttachmentGatewayOwner=e,this.requestUpdate(),typeof ResizeObserver==`function`&&(this.paneResizeObserver=new ResizeObserver(e=>{let t=e.at(-1)?.contentRect.width;typeof t==`number`&&t>0&&t!==this.paneWidth&&(this.paneWidth=t)}),this.paneResizeObserver.observe(this)),this.addEventListener(`pointerdown`,this.handlePaneFocus),this.addEventListener(`focusin`,this.handlePaneFocus),this.addEventListener(`input`,this.handlePaneInput),document.addEventListener(`keydown`,this.handleDocumentKeydown,!0),document.addEventListener(`pointerdown`,this.handleDocumentPointerdown,!0);let t=this.chatState;t.addCleanup(()=>Oy(this.context,this)),t.addCleanup(()=>{document.removeEventListener(`keydown`,this.handleDocumentKeydown,!0),document.removeEventListener(`pointerdown`,this.handleDocumentPointerdown,!0),this.removeEventListener(`pointerdown`,this.handlePaneFocus),this.removeEventListener(`focusin`,this.handlePaneFocus),this.removeEventListener(`input`,this.handlePaneInput)});let n=KO(this.context,t.createRenderLifecycle(),this,this.chatMessagesBySession);n.chatMetadataIsPresented=()=>this.presented&&document.visibilityState!==`hidden`;let r=()=>{this.requestUpdate(),n.chatMetadataIsPresented?.()&&(qk(n,{automatic:!0}),this.resumeDeferredSessionHydration(),this.refreshTaskSuggestions({automatic:!0}))};document.addEventListener(`visibilitychange`,r),t.addCleanup(()=>document.removeEventListener(`visibilitychange`,r));let i=jt(this.sessionKey)?.agentId??this.agentId;if(i&&(n.assistantAgentId=i,n.agentsSelectedId=i),n.sidebarLayout=this.restorePaneSidebarLayout(n.sidebarLayout),n.getWorkContext=()=>this.workContext,n.chatIsProgrammaticScroll=()=>this.transcript.isProgrammaticScroll,n.chatIsMaintenanceScroll=()=>this.transcript.isMaintenanceScroll,n.chatScrollElement=()=>this.transcript.scrollElement,n.chatScrollToEnd=e=>this.transcript.scrollToEnd(e),n.chatCancelScroll=()=>this.transcript.cancelScroll(),n.reviewQueuedMessageEdit=()=>this.reviewQueuedMessageEdit(n),n.createChatSession=()=>this.createSession(),n.confirmConversationReset=()=>this.confirmConversationReset(),n.exportCurrentChat=()=>_p(n.chatMessages,n.assistantName),n.refreshCurrentSessionTools=async()=>{n.requestUpdate?.()},n.refreshCurrentChat=async()=>{await nA(n),n.requestUpdate?.()},n.refreshSessionPullRequests=e=>this.refreshSessionPullRequests(e),n.openSessionCompanion=e=>this.openSessionCompanion(n,e),n.retireSessionCompanion=(e,t)=>this.sessionCompanionThreads.retire(e,t),this.state=n,this.sessionKey){let e=this.setPaneSessionKey(this.sessionKey);if(e&&!Wt(e)){n.client=this.context.gateway.snapshot.client??null;let t=Qh(n.chatMessagesBySession,n,{sessionKey:e});t?Pp(n,t):this.hydrateStoredChatSnapshot(n,e),Cp(n,e)&&(n.lastError=Wu,n.chatError=Wu),Yf(n,Ov(n)?.page.items)}}t.attach(n),t.addCleanup(()=>this.retireSessionObservation()),t.addCleanup(xp(()=>{Cp(n,n.sessionKey)&&(n.lastError=Wu,n.chatError=Wu),n.requestUpdate?.()})),t.addCleanup(this.context.agentIdentity.subscribe(()=>void n.loadAssistantIdentity())),t.composerPersistence.restore({preserveCurrent:!0});let a=this.takeSessionHandoff(n.sessionKey);nw(this.context,this.paneId,n,e),t.composerPersistence.start(),a&&this.applySessionHandoff(n.sessionKey,a),this.draft!==void 0&&this.state.handleChatDraftChange(this.draft,[]);let o=e=>this.receiveBrowserAnnotation(e);window.addEventListener(yl,o),t.addCleanup(()=>window.removeEventListener(yl,o)),t.addCleanup(this.sessionPanelToggles.subscribe());let s=e=>{let t=e.detail,n=typeof t?.text==`string`?t.text.trim():``;n&&this.state?.handleSendChat(n)};this.addEventListener(Gl,s),t.addCleanup(()=>this.removeEventListener(Gl,s)),t.addCleanup(this.context.gateway.subscribe(e=>{this.applyGatewaySnapshot(e),this.activateComposerPresentation(),this.synchronizeForegroundTranscript()})),t.addCleanup(this.context.theme.subscribe(()=>{n.settings={...this.context.theme.settings,token:this.context.gateway.connection.token},n.requestUpdate()})),t.addCleanup(this.context.agentSelection.subscribe(e=>{let t=this.state?.assistantAgentId;Wk(this.state,this.agentId??e.selectedId),this.synchronizeSessionObservation();let n=this.state?.assistantAgentId!==t;n&&(this.swarmHydrator?.dispose(),this.swarmHydrator=null),this.synchronizeForegroundTranscript(),n&&this.refreshSwarmRoster(),this.state&&ZS(this.state),this.activateComposerPresentation()})),this.subscribeSessionRepositoryContext(),t.addCleanup(this.context.gateway.subscribeEvents(e=>{let t=this.state;if(t&&e.event===`sessions.changed`&&h(e.payload).reason===`sharing`&&(t.mediaPolicyEpoch=(t.mediaPolicyEpoch??0)+1,t.requestUpdate?.()),e.event!==`sessions.changed`&&e.event!==`session.message`){if(e.event===`presence`){let t=this.hasMultipleIdentities(),n=vr(e.payload);this.presencePayload=n?{presence:n}:void 0,this.pruneTypingActors(),this.hasMultipleIdentities()?t||this.refreshSessionSuggestions():(this.resetSessionSuggestions(),this.clearTypingActors())}t&&(e.event===`config.changed`&&(t.mediaPolicyEpoch=(t.mediaPolicyEpoch??0)+1,t.requestUpdate?.(),Ky(t),Yy(t).finally(()=>t.requestUpdate?.())),al(this.questionPromptState,e)),t&&!Wt(t.sessionKey)&&(e.event===`task.suggestion`&&e.payload&&this.handleTaskSuggestionEvent(e.payload),e.event===`session.suggestion`&&e.payload&&this.handleSessionSuggestionEvent(e.payload),e.event===`session.typing`&&e.payload&&this.handleSessionTypingEvent(e.payload),RA(t,e,()=>this.presented),e.event===`node.runnerInventory.changed`&&(this.activeSessionResources.invalidate(),this.requestUpdate()))}})),this.applyApplicationConfig(this.context.config.current),t.addCleanup(this.context.config.subscribe(this.applyApplicationConfig.bind(this))),this.applySessionsState(this.context.sessions.state),t.addCleanup(this.context.sessions.subscribe(this.applySessionsState.bind(this))),t.addCleanup(ZA(this.context,()=>this.state)),t.addCleanup(QA(()=>this.state)),this.applyGatewaySnapshot(this.context.gateway.snapshot),this.synchronizeForegroundTranscript();let c=new lw(this.context,{state:()=>this.state,owner:()=>this.stagedAttachmentGatewayOwner,region:()=>this.inputRegion,presented:()=>this.selected&&this.presented,pause:()=>this.chatState.composerPersistence.stop(),takeAttachmentReads:()=>this.chatState.takeAttachmentReads(),adoptAttachmentReads:e=>this.chatState.adoptAttachmentReads(e,n),resume:e=>{e&&this.chatState.composerPersistence.restore(),this.chatState.composerPersistence.start()}});this.composerPresentation=c,n.captureComposerRecoveryOwner=()=>c.captureOwner(),this.activateComposerPresentation()}willUpdate(e){if(this.captureArchivePresentationFocus(),this.state&&(e.has(`selected`)&&!this.selected||e.has(`presented`)&&!this.presented)&&Ox(this.state),e.has(`sessionKey`)&&this.state){let e=Wt(this.sessionKey),t=e?this.sessionKey:ht(this.sessionKey,this.context.gateway.snapshot.hello);if(t&&this.sessionDiscussionStates.delete(t),e&&this.catalogRequestedSessionKey!==this.sessionKey)this.catalogLoadGeneration+=1,this.openCatalogSession(e,this.state);else if(t){this.state.sessionKey=t;let e=jt(t)?.agentId;e&&Gk(this.state,e),this.synchronizeSessionObservation();let n=Cp(this.state,t),r=Yf(this.state,Ov(this.state)?.page.items);n&&(this.state.lastError=Wu,this.state.chatError=Wu),(n||r)&&this.requestUpdate()}if(t){let e=this.takeSessionHandoff(t);e&&this.applySessionHandoff(t,e)}}(e.has(`sessionKey`)||e.has(`inputRegion`))&&(this.syncActiveBindings(),this.activateComposerPresentation()),e.has(`draft`)&&this.draft!==void 0&&this.state&&this.draft!==this.state.chatMessage&&this.state.handleChatDraftChange(this.draft,[])}updated(e=new Map){if(this.syncQueuedEditRetention(),Jy(this.state),!this.chatRouteReadyReported&&this.querySelector(`.agent-chat__composer-combobox > textarea`)&&(this.chatRouteReadyReported=!0,this.dispatchEvent(new Event(cn,{bubbles:!0,composed:!0}))),e.has(`focusComposer`)&&this.focusComposer){let e=this.querySelector(Ow),t=e?.closest(`.agent-chat__input`);e?.focus({preventScroll:!0}),t&&this.draft&&this.showComposerPrefillAttention(t)}this.retireArchivedPresentation(),this.cancelResetConfirmationForSessionChange(),this.syncHistoryObserver();let t=this.resolveBoardView();if(this.syncRetainedBoardSession(t),this.sessionPanelToggles.flush(),this.activeSessionResources.syncPane({state:()=>this.state,observation:()=>this.resourceSessionObservation(),gateway:this.context.gateway.snapshot,isConnected:()=>this.isConnected,isPresented:()=>this.presented&&this.visuallyPresented,commit:(e,t)=>this.commitSidebarLayout(e,{persist:!1,automaticResource:t}),requestUpdate:()=>this.requestUpdate()}),this.state){let e=this.initializeBrowserSidebarLayout(this.state.sidebarLayout);e!==this.state.sidebarLayout&&this.state.updateSidebarLayout(e,{geometryOnly:!0})}this.setConversationVisible(!!(this.state&&Je(yS({board:t,layout:this.state.sidebarLayout,paneWidth:this.paneWidth}),`conversation`)))}disconnectedCallback(){this.activeSessionResources.sync(null),this.syncSessionCompanionPresentation(!1),this.composerPresentation?.dispose(),this.composerPresentation=void 0,this.state&&(Ox(this.state),Qv(this.state),Ky(this.state),Vk(this.state),this.suppressStagedAttachmentHandoffOnDisconnect?iw(this.state):rw(this.context,this.paneId,this.state,this.stagedAttachmentGatewayOwner,this.chatState.composerPersistence.draftRevision)),this.stagedAttachmentGatewayOwner=null,this.clearComposerPrefillAttention(),this.boardProviderLifecycleConnected=!1,this.releaseBoardProviderLease(),this.settleResetConfirmation(!1),this.paneResizeObserver?.disconnect(),this.paneResizeObserver=null,this.connectionGeneration+=1,this.retireReplyMessages(),this.retireHeaderSessionMutations(),this.retireDeferredSessionHydration(),this.sessionDiscussionPanels.clear(),this.taskSuggestionsRequestVersion+=1,this.setTaskSuggestions([]),this.taskSuggestionBusyIds.clear(),this.taskSuggestionOperations.clear(),this.resetSessionSuggestions(),this.clearTypingActors(),this.resetSessionPullRequests(),this.resetOlderMessagesViewport(),this.nativeDraftCleanup?.(),this.nativeDraftCleanup=null,this.headerCopiedTimer!==null&&(window.clearTimeout(this.headerCopiedTimer),this.headerCopiedTimer=null),this.swarmHydrator?.dispose(),this.swarmHydrator=null,this.headerWorktreePaths.clear(),this.headerBranches.clear(),this.presencePayload=void 0,this.announceCommandPaletteTarget(null),Qu(this),ej(this.presentationId),this.state=void 0,this.connectedClient=null,eu(this.questionPromptState),super.disconnectedCallback()}}})))()}function ij(e,t,n,r){let i=e.sessionsResult,a=i?.sessions??[],o=new Set([...e.chatSessionApprovalQueue??[],...r??[]].map(e=>e.sourceSessionKey).filter(e=>typeof e==`string`));return JSON.stringify([e.sessionKey,Z(e),e.connectionEpoch,e.sessionsResultAgentId,e.sessionsLoading,e.sessionsError,n,Qd(n,a),i?.defaults,i?.owners,t.modelOverrides[e.sessionKey],Object.hasOwn(t.modelOverrides,e.sessionKey),e.sessions.think(e.sessionKey,L(e,e.sessionKey).agentId),e.sessions.archiveVisibility(n?.key??e.sessionKey),$s(t.groups,t.result?.sessions??[]),t.groupSettings,[...o].map(e=>a.find(t=>F(t.key,e))),e.chatMessages.length===0?a:void 0])}function aj(){return(aj=e((()=>{ls(),je(),B(),Vw(),mf()})))()}var oj;function sj(){return(sj=e((()=>{kr(),Pr(),ii(),wl(),Vr(),fa(),dn(),me(),I(),B(),Ot(),nb(),Y(),tC(),ew(),rj(),Qw(),aj(),WE(),Bk(),XE(),jO(),Wx(),iA(),Vw(),Ku(),Sd(),Lp(),Qm(),zh(),cg(),Lh(),ng(),am(),n(),oj=class extends nj{constructor(){super(),this.outboxRecoveryReady=!1,this.questionProjection={prompts:[],revisions:[]},new pn(this).effect(()=>this.context?.gateway,e=>e.subscribeEvents(e=>{let t=this.state;t&&wt(e)&&(t.modelAuthStatusResult=null,t.modelAuthStatusError=null,this.requestUpdate(),Yk(t).finally(()=>this.requestUpdate()))}))}placementComposerPresentation(e,t){return qw({gatewaySnapshot:this.context.gateway.snapshot,movingKey:this.headerPlacementMovingKey,reclaimingKey:this.headerPlacementReclaimingKey,restartingKey:this.headerPlacementRestartingKey,row:e,startupPending:t,workspaceResultReconciling:(e?.placement?.state===`active`||e?.placement?.state===`draining`)&&e.placement.workspaceResultReconciling===!0,onRecover:()=>e&&void this.changeHeaderPlacement(e,`recover`),onReclaim:()=>e&&void this.reclaimHeaderPlacement(e)})}disconnectedCallback(){this.sessionPresentationKey=void 0,this.continueInTerminalDialog=null,this.gatewayConnectionLifecycle?.dispose(),this.gatewayConnectionLifecycle=void 0,this.outboxRecoveryReady=!1,super.disconnectedCallback()}async changeHeaderPlacement(e,t){let n=this.captureConnectionScope();if(!n)return;let r=t===`move`?`headerPlacementMovingKey`:`headerPlacementRestartingKey`,i={client:n.client,connectionGeneration:n.generation,gatewaySnapshot:n.context.gateway.snapshot,mode:t,pendingKey:this[r],row:e,isCurrent:()=>this.ownsHeaderOutcomeScope(n),currentRow:()=>this.state?Q(this.state):void 0,onPendingChange:n=>{t===`recover`&&n!==null&&this.state&&(RE(this.state),this.state.chatRunError=null),(n!==null||this[r]===e.key)&&(this[r]=n)},publishError:e=>this.publishHeaderError(e,n.headerOutcomeOwner),reconcileMutation:e=>n.sessions.reconcileMutation(e),requestUpdate:()=>this.requestUpdate()},{changeChatPanePlacement:a}=await M(async()=>{let{changeChatPanePlacement:e}=await import(`./chat-pane-placement.runtime-D8SiBRyF.js`);return{changeChatPanePlacement:e}},__vite__mapDeps([63,1,2,3,4,5,6,7,8,64,49,50,52,65,66,9,10,11,12,13,56,57,59,67,68]),import.meta.url);await a(i)}async reclaimHeaderPlacement(e){let t=this.captureConnectionScope();if(!t)return;let n={client:t.client,connectionGeneration:t.generation,gatewaySnapshot:t.context.gateway.snapshot,reclaimingKey:this.headerPlacementReclaimingKey,placementStartup:t.context.placementStartup,row:e,isCurrent:()=>this.ownsHeaderOutcomeScope(t),onReclaimingChange:t=>{(t!==null||this.headerPlacementReclaimingKey===e.key)&&(this.headerPlacementReclaimingKey=t)},publishError:e=>this.publishHeaderError(e,t.headerOutcomeOwner),reconcileMutation:e=>t.sessions.reconcileMutation(e),requestUpdate:()=>this.requestUpdate()},{reclaimChatPanePlacement:r}=await M(async()=>{let{reclaimChatPanePlacement:e}=await import(`./chat-pane-placement.runtime-D8SiBRyF.js`);return{reclaimChatPanePlacement:e}},__vite__mapDeps([63,1,2,3,4,5,6,7,8,64,49,50,52,65,66,9,10,11,12,13,56,57,59,67,68]),import.meta.url);await r(n)}applySessionsState(e){let t=this.state;if(!t)return;let n=this.context.sessions.canonicalListRevision,r=this.canonicalSessionList,a=r?.sessions===this.context.sessions&&n>r.revision,o=this.context.sessions.deletionState(t.sessionKey,Z(t));for(let{key:n,agentId:r}of e.deletedSessions)tg(t.chatMessagesBySession,t,{sessionKey:n,agentId:r});(!kt(t,t.sessionKey)||e.agentId===Z(t))&&(t.sessionsResult=e.result,t.sessionsResultAgentId=e.agentId),this.projectObservedSessionRow(),t.sessionsLoading=e.loading,t.sessionsError=e.error,t.connected&&t.pendingAbort&&gm(t).finally(()=>t.requestUpdate?.()),this.refreshSwarmRoster();let s=Q(t),c=s?JSON.stringify([t.sessionKey,Z(t),s.sessionId,s.status,S(s),s.lastRunId,s.activeLeafEntryId]):void 0;if(this.canonicalSessionList={sessions:this.context.sessions,revision:n,outboxState:a?c:r?.sessions===this.context.sessions?r.outboxState:void 0},IE(t,s)&&this.presented&&this.markSessionRead(s),this.syncSessionSuggestionTarget(e.agentId??Z(t)??`main`,s),o){let e=Z(t);this.onSessionDeleted?.(this.paneId,t.sessionKey,i({agentId:e,mainKey:Lt({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello})}),o===`pending`);return}let l=Cm(t);if(this.reconcileWaitingApprovalSnapshot(),l){kO(t);return}let u=ij(t,e,s,this.context.overlays?.snapshot?.approvalQueue),d=u!==this.sessionPresentationKey;this.sessionPresentationKey=u,this.presented&&d&&YO(t,`animation-frame`),a&&r?.outboxState!==c&&s&&!S(s)&&t.chatQueue.length>0&&AO(t)}reconcileWaitingApprovalSnapshot(e){let t=this.state,n=e??this.context?.overlays?.snapshot.approvalQueue;return!t||!n?!1:Wm(t,n)}projectConversationAttention(e,t,n){let r=n=>Qe(e,e.sessionKey,n.sessionKey,n.agentId,t),i=n?this.questionPrompts.filter(r):[];return(i.length!==this.questionProjection.prompts.length||i.some((e,t)=>e!==this.questionProjection.prompts[t]||e.revision!==this.questionProjection.revisions[t]))&&(this.questionProjection={prompts:i,revisions:i.map(e=>e.revision)}),{gatewayQuestionPrompts:this.questionProjection.prompts,inlineApproval:n?e.chatSessionApprovalQueue?.[0]??this.context.overlays?.snapshot?.approvalQueue?.find(e=>r(e.request))??null:null}}applyApplicationConfig(e){let t=this.state;if(!t)return;t.requestUpdate?.();let n=t.terminalAvailable;t.terminalAvailable=e.terminalEnabled&&t.connected&&Hr(t.hello?.auth??null)&&da(this.context.gateway.snapshot,`terminal.open`)===!0,(t.terminalAvailable!==n||t.embedSandboxMode!==e.embedSandboxMode||t.allowExternalEmbedUrls!==e.allowExternalEmbedUrls||t.automaticallyFetchFavicons!==e.automaticallyFetchFavicons)&&(t.embedSandboxMode=e.embedSandboxMode,t.allowExternalEmbedUrls=e.allowExternalEmbedUrls,t.automaticallyFetchFavicons=e.automaticallyFetchFavicons,t.requestUpdate?.())}applyGatewaySnapshot(e){let t=this.state;if(!t)return;let n=yr(t),r=t.connected,i=t.assistantAgentId,a=jt(t.sessionKey)?.agentId??this.agentId??this.context.agentSelection.state.selectedId??e.assistantAgentId,o=Mt(t,t.sessionKey),s=(this.gatewayConnectionLifecycle??=an({client:t.client,phase:t.connected?`connected`:`stopped`})).transition(e),c=this.connectedClient!==e.client,l=this.sidebarLayoutSource?e.client!==null&&this.sidebarLayoutSource.client!==e.client:t.client!==e.client,u=!this.sidebarLayoutSource||l||e.phase===`connected`&&!this.sidebarLayoutSource.ready;if(c&&this.replaceStagedAttachmentGatewayOwner(e.client),e.phase!==`connected`)this.presencePayload=void 0;else if(c||!r){let t=vr(e.hello?.snapshot);this.presencePayload=t?{presence:t}:void 0}s&&(this.continueInTerminalDialog=null,this.cancelHeaderRename(),Jm(t),td(t.requestUpdate),r&&(e.phase===`connected`&&Pk(t),t.chatSending=!1,t.chatSendingScopeKey=null),this.connectionGeneration+=1,this.retireReplyMessages(),this.retireHeaderSessionMutations(),Ky(t),t.assistantIdentityRequestVersion+=1,Vk(t),this.taskSuggestionsRequestVersion+=1,this.resetSessionSuggestions(),this.clearTypingActors(),this.sessionDiscussionStates.clear(),this.sessionDiscussionOpenUrls.clear(),this.sessionDiscussionPanels.clear(),this.sessionParticipationTracker.reset(),t.client!==e.client&&(this.sessionCompanionThreads.retire(),sm(t,{clearLocalRun:!0,clearChatStream:!0,clearToolStream:!0,clearRunStatus:!0,requestUpdate:!1}),t.pendingAbort=null),this.sessionSharingStates=new Map,this.sessionSharingHydrationTargets.clear(),t.guardianNotices=[],t.providerPolicyNotice=null,this.resetSessionPullRequests(),this.resetOlderMessagesViewport(),t.chatLoading=!1),(s||i!==a&&kt(t,t.sessionKey))&&(kx(t),this.swarmHydrator?.dispose(),this.swarmHydrator=null),t.client=e.client,t.connected=e.phase===`connected`,$v(t);let d=t.connected&&!!t.client?.recoveryScopeReady,f=d&&(c||!this.outboxRecoveryReady);this.outboxRecoveryReady=d,t.connectionEpoch=this.connectionGeneration,t.hello=e.hello,t.selfUser=e.selfUser??null,t.assistantAgentId=a;let p=this.sessionKey.trim(),m=Wt(p);t.connected&&!m&&(s||this.connectedClient!==e.client)&&ZS(t,{force:!0}),this.reconcileTaskSuggestionConnection(s),this.synchronizeSessionObservation(),r&&!t.connected&&(t.chatLoading=ry(t).phase===`pending-connection`);let h=!r&&t.connected?QC(t):void 0;s&&Fu(t),!s&&n!==yr(t)&&td(t.requestUpdate),t.canvasPluginSurfaceUrl=e.canvasPluginSurfaceUrl,t.terminalAvailable=this.context.config.current.terminalEnabled&&e.phase===`connected`&&Hr(e.hello?.auth??null)&&da(e,`terminal.open`)===!0,t.browserPanelAvailable=Qr(e);let g=oi(e),_=Mt(t,t.sessionKey),v=_!==o;if(_&&(u||v)){this.sidebarLayoutSource={client:e.client,ready:t.connected},this.dashboardPresentationActivation=void 0;let n=Rm({settings:Xr(),sessionKey:_,browserAvailable:t.browserPanelAvailable,desktopAvailable:g}),r=n.sidebarSessionLayouts?.[_];r===void 0?l?t.sidebarLayout={columns:[]}:v&&t.sidebarLayout.columns.length>0&&t.updateSidebarLayout(t.sidebarLayout):t.sidebarLayout=this.restorePaneSidebarLayout(Ht(r)),t.sidebarFocusPanelId=n.sidebarSessionActivePanels?.[_]??``,t.sidebarFocusVersion+=1}t.connected&&t.pendingAbort&&gm(t).finally(()=>t.requestUpdate?.());let y=p&&!m?ht(p,e.hello):null;if(!(p&&y&&y!==p&&this.presented&&(this.onPaneSessionChange?.(this.paneId,y,{replace:!0}),t.requestUpdate?.(),t.sessionKey!==y))){if(s&&(t.assistantName=this.context.config.current.assistantIdentity.name),e.phase!==`connected`){if(r){let e=typeof t.currentSessionId==`string`?t.currentSessionId.trim():``;e&&(t.reconnectResumeSessionId=e),Pk(t)}this.connectedClient=null,fl(this.questionPromptState,null),qE(t),Xh(t,{preserveStreamSegments:t.chatRunId!==null}),t.requestUpdate?.();return}if(this.refreshSwarmRoster(),(this.connectedClient!==e.client||s&&m)&&e.client){let n=e.client,r=this.connectionGeneration,i=t.sessionKey,a=()=>this.connectionGeneration===r&&this.connectedClient===n&&t.client===n&&t.connected,o=async()=>{if(!a())return;let e=await this.context.agents.ensureList();a()&&(e&&$C(t,e,n),t.requestUpdate?.())};if(this.connectedClient=n,fl(this.questionPromptState,n),El(this.questionPromptState,n,a),this.headerWorktreePaths.clear(),this.headerBranches.clear(),this.headerPlatform=null,m){this.loadHeaderPlatform(n,r),this.loadCatalogSession(m,!1),t.requestUpdate?.();return}let s=nA(t,{startup:!0,awaitHistory:!0,deferBranches:!0,historyLoad:h});this.deferSessionHydrationUntilTranscript(i,s.then(()=>ry(t).phase===`committed`)),s.finally(()=>{o()}),Yk(t).finally(()=>t.requestUpdate?.()),t.loadAssistantIdentity(),this.refreshSessionSuggestions()}f&&!m&&kO(t),this.reconcileWaitingApprovalSnapshot(),t.requestUpdate?.()}}}})))()}var cj;function lj(){return(lj=e((()=>{ui(),Ol(),Sl(),ul(),H(),bn(),cc(),on(),fa(),Pt(),Kt(),se(),Qa(),ls(),B(),Bs(),tt(),sj(),Pw(),Vw(),rf(),n(),cj=class extends oj{constructor(...e){super(...e),this.handleArchiveSessionShortcut=e=>{if(!tn(gt.archiveSession,e))return!1;let t=this.state;if(e.repeat||e.defaultPrevented||!t?.connected||!this.active||!this.presented||this.onboarding||document.openClawModalLayers?.size||document.querySelector(`.shell-nav[aria-modal='true']`))return!0;let n=Q(t);return!n||!this.canArchiveHeaderSession(n)||(e.preventDefault(),this.handleHeaderSessionAction({kind:`toggle-archived`},n),!0)},this.headerSessionOperationsLoad=null}resolveHeaderSessionTitle(e){return this.presentationTitle??ze(e?.key??this.state?.sessionKey??this.sessionKey,e)}canArchiveHeaderSession(e){return!e.archived&&!this.context.sessions.archiveVisibility(e.key)&&Ue(e,Lt({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello}))&&!Dl({snapshot:this.context.gateway.snapshot,session:e})[`toggle-archived`]}headerSessionMenuData(e,t){let n=Ft({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello},`main`,jt(e.key)?.agentId??e.agentId).sessionKey;return{label:this.resolveHeaderSessionTitle(e),sessionId:e.sessionId??null,isChild:!!ou(e,new Set([n])),pinned:e.pinned===!0,pinnable:t,unread:e.unread===!0,hiddenFromInvolvingMe:e.hiddenFromInvolvingMe,archived:e.archived===!0,archiving:this.context.sessions.archiveVisibility(e.key)===`pending`,category:j(e.category)??null,icon:j(e.icon)??null,color:j(e.color)??null,categoryClearReturnsToGroups:!1}}async loadHeaderPlatform(e,t){if(!da(this.context.gateway.snapshot,`system.info`))return;let n=Ew.get(e);n||(n=e.request(`system.info`,{}).then(e=>e.platform).catch(()=>null),Ew.set(e,n));let r=await n;this.connectedClient===e&&this.connectionGeneration===t&&(this.headerPlatform=r)}async handleHeaderSessionAction(e,t){if(e.kind===`toggle-archived`&&!t.archived&&!this.canArchiveHeaderSession(t))return;if(e.kind===`open-in`){wc(e.editor,e.path);return}if(e.kind===`rename`){this.beginHeaderRename(t);return}if(e.kind===`copy-session-id`||e.kind===`copy-session-link`||e.kind===`copy-session-preview-link`||e.kind===`copy-markdown`||e.kind===`open-new-tab`||e.kind===`open-new-window`||e.kind===`split-right`||e.kind===`split-below`){let n=this.headerOutcomeOwner;await ps(e.kind,{context:this.context,session:t,agentId:this.state?Z(this.state):t.agentId,sourceSessionKey:t.key,isCurrent:()=>this.ownsHeaderOutcome(n)});return}if(e.kind===`continue-in-terminal`){this.openContinueInTerminalDialog(t);return}let n=this.captureHeaderSessionActionScope();if(!n){this.publishHeaderError(R(`sessionsView.actionRequiresConnection`));return}let r=this.headerOutcomeOwner,i=e=>({key:e.key,sessionId:e.sessionId,sharingRole:e.sharingRole,label:this.resolveHeaderSessionTitle(e),pinned:e.pinned===!0,unread:e.unread===!0,archived:e.archived===!0,category:e.category,active:!0,hasActiveRun:e.hasActiveRun??e.status===`running`,gatewayHasActiveRun:e.hasActiveRun}),a=i(t),o=(e=!1)=>{let r=n.sessions.state.result?.sessions.find(e=>F(e.key,t.key)&&(!a.sessionId||e.sessionId===a.sessionId))??(a.sessionId?t:null);return!r&&e&&ct({message:R(`common.refresh`)}),r?i(r):null};try{let i=await(this.headerSessionOperationsLoad??=M(()=>import(`./session-organizer-operations.runtime-iW_lN0Ec.js`),__vite__mapDeps([69,1,2,3,4,5,6,7,8,70,71,66,9,10,11,12,13]),import.meta.url)),s={sessionData:{isSessionMutationScopeCurrent:e=>this.isHeaderSessionActionCurrent(e,r),publishSessionMutationError:(e,t)=>{this.isHeaderSessionActionCurrent(e,r)&&this.publishHeaderError(t,r)},refreshSidebarSessions:async e=>{let t=await n.sessions.reconcileMutation(e);t.status===`failed`&&this.isHeaderSessionActionCurrent(n,r)&&this.publishHeaderError(t.error,r)}},pruneSidebarSessionEntry:e=>{let t=ir({type:`session`,key:e}),r=n.context.navigation.snapshot.sidebarEntries.filter(e=>e!==t);n.context.navigation.update({sidebarEntries:r})},selectSession:e=>this.onPaneSessionChange?.(this.paneId,e),sidebarSessionStatusFilter:()=>`active`,knownSessionGroups:()=>$s(n.sessions.state.groups,n.sessions.state.result?.sessions??[])};switch(e.kind){case`toggle-involving-me`:await i.setSessionInvolvement(s,a,!t.hiddenFromInvolvingMe,n);break;case`toggle-pin`:case`toggle-unread`:case`set-icon`:case`set-color`:case`reset-appearance`:{let t=o(!0);if(t){let r=e.kind===`toggle-pin`?{pinned:!t.pinned}:e.kind===`toggle-unread`?{unread:!t.unread}:e.kind===`set-icon`?{icon:e.icon}:e.kind===`set-color`?{color:e.color}:{icon:null,color:null};await i.patchSession(s,t,r,n,e.kind===`toggle-pin`?{sessionScope:!0}:void 0)}break}case`assign-owner`:await i.assignSessionOwner(s,a,e.owner,n);break;case`fork`:await i.forkSession(s,a,n);break;case`move-to-group`:await i.assignSessionCategory(s,a,e.category,n,{},{resolveSession:o});break;case`new-group`:{let{showInputDialog:e}=await M(async()=>{let{showInputDialog:e}=await import(`./input-dialog-CHRxMdbT.js`);return{showInputDialog:e}},__vite__mapDeps([72,71,9]),import.meta.url),t=await e({title:R(`sessionsView.newGroupTitle`),label:R(`sessionsView.newGroupPrompt`),submitLabel:R(`sessionsView.newGroupCreate`),requireValue:!0});t&&this.isHeaderSessionActionCurrent(n,r)&&await i.assignSessionCategory(s,a,t,n,{},{resolveSession:o});break}case`toggle-archived`:a.archived?await i.patchSession(s,a,{archived:!1},n,{sessionScope:!0}):await i.archiveSessionWithUndo(s,a,n);break;case`delete`:await i.deleteSession(s,a,n)}}catch(e){this.isHeaderSessionActionCurrent(n,r)&&this.publishHeaderError(e,r)}}resolveContinueInTerminalCommand(e,t){return Xu({gatewayUrl:t.gatewayUrl,sessionKey:e.key,rowAgentId:e.agentId,selectedAgentId:this.context.agentSelection.state.selectedId??void 0})}continueInTerminalDisabledReason(e){let t=this.context.gateway,n=t.snapshot.client;if(t.snapshot.phase!==`connected`||!n)return R(`chat.sessionHeader.continueInTerminal.disconnected`);let r=this.resolveContinueInTerminalCommand(e,n);if(!r.ok)return R(r.reason===`query-routed`?`chat.sessionHeader.continueInTerminal.queryRouted`:`chat.sessionHeader.continueInTerminal.unavailable`)}openContinueInTerminalDialog(e){let t=this.captureConnectionScope();if(!t)return;let n=this.resolveContinueInTerminalCommand(e,t.client);n.ok&&(this.continueInTerminalDialog={qualifiedSessionKey:n.qualifiedSessionKey,selectedGatewayUrl:this.context.gateway.connection.gatewayUrl,clientGatewayUrl:t.client.gatewayUrl,scope:t},this.requestUpdate())}closeContinueInTerminalDialog(){this.continueInTerminalDialog&&(this.continueInTerminalDialog=null,this.requestUpdate())}currentContinueInTerminalCommand(e){let t=this.continueInTerminalDialog,n=this.context.gateway,r=n.snapshot.client;if(!t)return null;let i=e&&r?this.resolveContinueInTerminalCommand(e,r):null;return!this.isConnectionScopeCurrent(t.scope)||!i?.ok||i.qualifiedSessionKey!==t.qualifiedSessionKey||n.connection.gatewayUrl!==t.selectedGatewayUrl||r?.gatewayUrl!==t.clientGatewayUrl?(this.continueInTerminalDialog=null,null):i.command}captureHeaderSessionActionScope(){let e=this.context.gateway,t=e.snapshot.client;return e.snapshot.phase!==`connected`||!t?null:{epoch:this.connectionGeneration,context:this.context,gateway:e,sessions:this.context.sessions,client:t,selectedAgentId:this.context.agentSelection.state.selectedId??`main`,signal:this.headerSessionMutationAbortController.signal}}isHeaderSessionActionCurrent(e,t){return this.ownsHeaderOutcome(t)&&this.isConnected&&this.context===e.context&&this.context.gateway===e.gateway&&this.context.sessions===e.sessions&&e.gateway.snapshot.phase===`connected`&&e.gateway.snapshot.client===e.client}beginHeaderRename(e){let t=z(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:e.key,label:null},sessionScope:!0,session:e});if(!t.allowed){this.publishHeaderError(t.reason);return}this.headerRenameSession={key:e.key,sessionId:e.sessionId,label:e.label},this.headerRenameInitialValue=Mo(e),this.headerRenameValue=this.headerRenameInitialValue,this.headerEditing=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.chat-pane__session-title-input`);e?.focus(),e?.select()})}cancelHeaderRename(){this.headerEditing=!1,this.headerRenameSession=null}commitHeaderRename(){if(!this.headerEditing)return;let e=this.headerRenameSession,t=uo(this.headerRenameValue,this.headerRenameInitialValue,e?.label);this.headerEditing=!1,this.headerRenameSession=null;let n=this.state;if(!e||!n||!t)return;let r=z(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:e.key,...t},sessionScope:!0,session:n.sessionsResult?.sessions.find(t=>F(t.key,e.key)&&t.sessionId===e.sessionId)});if(!r.allowed){this.publishHeaderError(r.reason);return}let i=this.headerOutcomeOwner;this.context.sessions.patch(e.key,t,{agentId:Z(n),expectedSessionId:e.sessionId}).catch(e=>this.publishHeaderError(e,i))}async loadHeaderMenuData(e,t,n){let r=this.connectedClient;if(!r)return;let i=[],a=(e.execNode?e.execCwd?.trim():void 0)||e.spawnedWorkspaceDir?.trim()||e.spawnedCwd?.trim()||null,o=e.worktree?.id;if(o&&!a){let e=this.headerWorktreePaths.get(o)??{};this.headerWorktreePaths.set(o,e),!e.loaded&&!e.loading&&(e.loading=!0,i.push(r.request(`worktrees.list`,{}).then(t=>{e.path=t.worktrees.find(e=>e.id===o&&e.removedAt===void 0)?.path??null,e.loaded=!0}).catch(()=>{e.path=null,e.loaded=!1}).finally(()=>{e.loading=!1})))}let s=e.worktree?void 0:t?.trim(),c=a||(o?this.headerWorktreePaths.get(o)?.path:void 0)||s,l=!!e.execNode||sa(e.placement?.state),u=c===s?n:!!c;if(!e.worktree&&!l&&c&&u){let e=this.headerBranches.get(c)??{};this.headerBranches.set(c,e),e.loading||(e.loading=!0,i.push(r.request(`worktrees.branches`,{repoRoot:c}).then(t=>{e.value=t.headBranch??null}).catch(()=>{e.value=null}).finally(()=>{e.loading=!1})))}await Promise.all(i),this.requestUpdate()}showHeaderCopied(e){this.headerCopiedAction=e,this.headerCopiedTimer!==null&&window.clearTimeout(this.headerCopiedTimer),this.headerCopiedTimer=window.setTimeout(()=>{this.headerCopiedAction=null,this.headerCopiedTimer=null},1500)}handleHeaderMenuAction(e,t,n,r,i=Jt){let a=e===`copy-path`?n:e===`copy-branch`?r:null;if(a){let t=this.headerOutcomeOwner;i(a).then(n=>{this.ownsHeaderOutcome(t)&&(n?this.showHeaderCopied(e):this.publishHeaderError(R(`common.copyFailed`),t))});return}e===`reveal`&&n&&this.revealHeaderWorkspace(t)}publishHeaderError(e,t=this.headerOutcomeOwner){this.state&&this.ownsHeaderOutcome(t)&&(this.state.chatError=this.state.lastError=P(e),this.state.requestUpdate?.())}async revealHeaderWorkspace(e){let t=this.connectedClient;if(!t)return;let n=this.headerOutcomeOwner,r=jt(e.key)?.agentId;try{let i=await t.request(`sessions.files.reveal`,{key:e.key,...r?{agentId:r}:{}});if(!i.ok){let e=i.error??`Failed to reveal session workspace.`;this.publishHeaderError(e,n)}}catch(e){this.publishHeaderError(e,n)}}}})))()}var uj;function dj(){return(dj=e((()=>{Pr(),H(),fa(),lj(),Vw(),Lh(),uj=class extends cj{async probeSessionDiscussion(e){let t=this.state;if(!t?.connected||!t.client||this.sessionDiscussionStates.has(e)||this.sessionDiscussionProbes.has(e)||da(this.context.gateway.snapshot,`session.discussion.info`)!==!0)return;let n=this.connectionGeneration;this.sessionDiscussionProbes.add(e);try{let r=await t.client.request(`session.discussion.info`,{sessionKey:e,agentId:Z(t)});if(n!==this.connectionGeneration)return;this.sessionDiscussionStates.set(e,r.state),this.requestUpdate()}catch{}finally{this.sessionDiscussionProbes.delete(e),n!==this.connectionGeneration&&this.state?.sessionKey===e&&!this.sessionDiscussionStates.has(e)&&this.probeSessionDiscussion(e)}}buildSessionDiscussionPanel(e,t){if(!e.connected||!e.client)return null;let n=Ur(this.context.gateway.snapshot.hello?.auth??null)&&da(this.context.gateway.snapshot,`session.discussion.open`)===!0,r=this.connectionGeneration,i=this.sessionDiscussionPanels.get(t);if(i?.generation===r&&i.canOpen===n)return i.config.openUrl=this.sessionDiscussionOpenUrls.get(t)??null,i.config;let a=async(t,n)=>{if(!e.connected||!e.client)throw Error(R(`chat.sessionDiscussion.disconnected`));return e.client.request(t,{sessionKey:n,agentId:Z(e)})},o={sessionKey:t,canOpen:n,openUrl:this.sessionDiscussionOpenUrls.get(t)??null,loadInfo:e=>a(`session.discussion.info`,e),openDiscussion:e=>a(`session.discussion.open`,e),onStateChange:(t,n,i)=>{if(r!==this.connectionGeneration)return;this.sessionDiscussionStates.set(t,n);let a=e.sessionKey.trim()===t;if(a&&this.sessionDiscussionOpenUrls.set(t,i),n===`none`&&this.sessionDiscussionOpenUrls.delete(t),n===`none`&&a){e.updateSidebarLayout(bh(e.sidebarLayout,`discussion`));return}e.requestUpdate()}};return this.sessionDiscussionPanels.set(t,{generation:r,canOpen:n,config:o}),o}openSessionDiscussionSlot(){let e=this.state;if(!e)return!1;let t=Ch(e.sidebarLayout,`discussion`),n=t.columns.flatMap(e=>e.panels).find(e=>e.slot===`discussion`);n&&(t=ph(t,n.id));let r=this.paneWidth>=680?Se(t,this.paneWidth)??t:t;return this.commitSidebarLayout(r),n&&e.updateSidebarActivePanel(n.id),!0}resolveSessionDiscussionAction(){let e=this.state,t=e?.sessionKey.trim()??``,n=t?this.sessionDiscussionStates.get(t):void 0;if(!e?.connected||!e.client||!t||n===void 0||n===`none`||da(this.context.gateway.snapshot,`session.discussion.info`)!==!0||!this.buildSessionDiscussionPanel(e,t))return null;let r=e.sidebarLayout.columns.some(e=>e.panels.some(e=>e.slot===`discussion`));return{active:r,label:R(r?`chat.sessionDiscussion.hide`:`chat.sessionDiscussion.show`),onToggle:()=>r?this.commitSidebarLayout(bh(e.sidebarLayout,`discussion`)):this.openSessionDiscussionSlot()}}}})))()}var fj;function pj(){return(pj=e((()=>{bi(),Bn(),d(),kr(),Xl(),Pr(),ii(),fr(),Ar(),jl(),Sl(),ul(),H(),fa(),eo(),se(),ls(),B(),Bs(),GS(),dj(),hS(),Qw(),Zx(),yu(),Ou(),mf(),cd(),Id(),Tu(),Lp(),Lh(),fj=class extends uj{resolveWorkspaceIcon(e){if(!e)return null;let t=this.context.gateway,n=Mr({hello:t.snapshot.hello,settings:{token:t.connection.token},password:t.connection.password});return{routeUrl:qn(`workspaceIcon`,this.context.resourceBasePath,e),authTokens:n,authReady:!!(t.snapshot.hello||n.length)}}renderPanelLayoutActions(e,t){if(!e)return G;let n=jn(e),r=ot(e)?.slot??`conversation`,i=t.find(e=>e.slot===r),a=t.find(e=>e.slot===n?.slot),o=e.open===!0&&!e.expanded,s=R(e.expanded?`chat.sidePanel.restore`:`chat.sidePanel.expand`),c=i&&a?R(`chat.sidePanel.swap`,{main:i.label,side:a.label}):``;return W`${i?.headerAction?W`<span class="side-panel__action-group side-panel__action-group--content"
            >${i.headerAction}</span
          >`:G}
    ${o||e.expanded?W`<openclaw-tooltip .content=${s}>
            <button
              class="btn btn--ghost btn--icon chat-icon-btn chat-panel-focus"
              type="button"
              aria-pressed=${String(e.expanded===!0)}
              aria-label=${s}
              @click=${()=>this.state?.updateSidebarLayout(ug(Gh(e),e.expanded!==!0),{dashboardPresentation:`personal`})}
            >
              ${e.expanded?U.minimize:U.maximize}
            </button>
          </openclaw-tooltip>`:G}
    ${o&&n&&c?W`<openclaw-tooltip .content=${c}>
            <button
              class="btn btn--ghost btn--icon chat-icon-btn chat-panel-swap"
              type="button"
              aria-label=${c}
              @click=${()=>this.state?.updateSidebarLayout(rh(e,n.id))}
            >
              ${U.arrowLeftRight}
            </button>
          </openclaw-tooltip>`:G}
    ${this.narrow||!o?G:W`<wa-dropdown
            class="chat-panel-layout-menu"
            placement="bottom-end"
            @wa-select=${t=>{let n=t.detail.item.value;(n===`left`||n===`right`||n===`bottom`)&&this.state?.updateSidebarLayout(lh(e,n),{geometryOnly:!0})}}
          >
            <button
              slot="trigger"
              class="btn btn--ghost btn--icon chat-icon-btn"
              type="button"
              aria-label=${R(`chat.sidePanel.layout`)}
              title=${R(`chat.sidePanel.layout`)}
            >
              ${U.columns2}
            </button>
            ${[[`left`,`dockLeft`,U.panelLeftOpen],[`right`,`dockRight`,U.panelRightOpen],[`bottom`,`dockBottom`,U.panelBottomOpen]].map(([t,n,r])=>W`<wa-dropdown-item
                value=${t}
                type="checkbox"
                ?checked=${ce(e)===t}
                ><span slot="icon">${r}</span>${R(`chat.sidePanel.${n}`)}</wa-dropdown-item
              >`)}
          </wa-dropdown>`}`}renderPaneHeader(e,t,n,r,i,a,o,s=fS()){this.syncSelectedSessionSharing(t);let c=Fs({session:t,agentWorkspace:t?.worktree?void 0:r,worktreePath:t?.worktree?this.headerWorktreePaths.get(t.worktree.id)?.path:void 0}),l=!!t?.execNode||sa(t?.placement?.state),u=t?.repository?.branch||t?.worktree?.branch||(l||!c.root?null:this.headerBranches.get(c.root)?.value)||null,d=jf({session:t,workspaceRoot:c.root,methodAdvertised:da(this.context.gateway.snapshot,`sessions.files.reveal`)===!0,hasAdminAccess:Hr(this.context.gateway.snapshot.hello?.auth??null)}),f=this.state?this.state.chatSending||Yu({runActive:Mh(this.state),queue:this.state.chatQueue,runStatus:this.state.chatRunStatus,sessionKey:this.state.sessionKey}):!1,p=Xx(this.context.gateway.snapshot,!!this.state?.chatRunId).branchSwitch,m=this.state&&this.isCurrentSessionArchived(this.state)?R(`chat.archivedSessionDisabled`):p.allowed?f?R(`chat.sessionHeader.branchSwitchUnavailable`):null:p.reason,h=this.context.gateway.snapshot,g=da(h,`session.visibility.set`)===!0,_=z(h,{method:`session.members.listEvidence`,requiredScope:`operator.read`}),v=z(h,{method:`session.visibility.set`,requiredScope:`operator.write`}),y=z(h,{method:`session.publicShare.set`,requiredScope:`operator.write`}),b=z(h,{method:`session.members.add`,requiredScope:`operator.write`}),x=z(h,{method:`session.members.remove`,requiredScope:`operator.write`}),S=_.allowed||v.allowed?void 0:_.reason,C=t?z(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:t.key,label:null},sessionScope:!0,session:t}):null,w=this.state?.connected!==!0||!C?R(`sessionsView.actionRequiresConnection`):C.allowed?void 0:C.reason,T=Lt({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello}),D=!!(t&&this.canArchiveHeaderSession(t)),O=!!(t&&ie([t],T)),k=t!=null&&Bt(t),A=t?Dl({snapshot:this.context.gateway.snapshot,session:{...t,pinnable:k}}):{},j=t?z(this.context.gateway.snapshot,{method:`sessions.assignOwner`,params:{key:t.key,owner:{type:`human`,id:h.selfUser?.id??`profile`}},requiredScope:`operator.write`}):null,ee=t?this.continueInTerminalDisabledReason(t):void 0,te={...A,...j&&!j.allowed?{"assign-owner":j.reason}:{},...ee?{"continue-in-terminal":ee}:{}},ne=Xw(t)!==null&&oi(this.context.gateway.snapshot),M=e.onToggleDesktop??(()=>void 0),re=this.resolveSessionDiscussionAction(),ae=o??this.state?.sidebarLayout,oe=ae?.open===!0&&!ae.expanded,se=W`<openclaw-tooltip
      .content=${R(oe?`chat.sidePanel.minimize`:`chat.sidePanel.label`)}
    >
      <button
        class="btn btn--ghost btn--icon chat-icon-btn chat-side-panel-toggle"
        type="button"
        aria-label=${R(oe?`chat.sidePanel.minimize`:`chat.sidePanel.label`)}
        aria-expanded=${String(oe)}
        @click=${()=>this.setChatSidePanelOpen(!oe,o)}
      >
        ${oe?U.panelRightClose:U.panelRightOpen}
      </button>
    </openclaw-tooltip>`,ce=e.onToggleBrowser?W`<openclaw-tooltip .content=${R(`browser.toggle`)}>
          <button
            class="btn btn--ghost btn--icon chat-icon-btn chat-browser-panel-toggle"
            type="button"
            aria-label=${R(`browser.toggle`)}
            @click=${e.onToggleBrowser}
          >
            ${U.globe}
          </button>
        </openclaw-tooltip>`:G,le=this.selectedSessionRailMode(this.state?.sessionKey??``),N=()=>this.requestSessionRail(`toggle`),ue=[];e.onToggleTerminal&&ue.push({id:`terminal`,label:R(`terminal.toggle`),icon:U.terminal,onActivate:e.onToggleTerminal}),e.onToggleBrowser&&ue.push({id:`browser`,label:R(`browser.toggle`),icon:U.globe,onActivate:e.onToggleBrowser}),ne&&e.onToggleDesktop&&ue.push({id:`desktop`,label:R(`desktop.toggle`),icon:U.monitor,onActivate:M}),re&&ue.push({id:`discussion`,label:re.label,icon:U.messageSquare,active:re.active,onActivate:re.onToggle}),e.onOpenDiff&&ue.push({id:`changes`,label:R(`chat.sessionDiff.show`),icon:U.diff,onActivate:e.onOpenDiff}),ue.push({id:`session-files`,label:R(e.collapsed?`chat.workspaceFiles.showFiles`:`chat.workspaceFiles.collapse`),icon:U.fileText,active:!e.collapsed,badge:e.list?.files.filter(e=>e.kind===`modified`).length??0,onActivate:e.onToggleCollapsed}),ue.push({id:`session-companion`,label:R(le===`expanded`?`chat.rail.collapse`:`chat.rail.show`),icon:U.spark,active:le===`expanded`,onActivate:N});let de=[],fe=!n&&this.dashboardDefaultMenuAction(t,ae);fe&&de.push({id:`dashboard-default`,icon:U.check,...fe}),this.onOpenSplitView&&de.push({id:`open-split-view`,label:R(`chat.splitView.open`),icon:U.columns2,onActivate:this.onOpenSplitView}),!this.narrow&&this.onSplitDown&&de.push({id:`split-down`,label:R(`chat.splitView.splitDown`),icon:U.panelBottomOpen,onActivate:()=>this.onSplitDown?.(this.paneId)}),!this.narrow&&this.onSplitRight&&de.push({id:`split-right`,label:R(`chat.splitView.splitRight`),icon:U.panelRightOpen,onActivate:()=>this.onSplitRight?.(this.paneId)});let pe=Zw({gatewaySnapshot:this.context.gateway.snapshot,movingKey:this.headerPlacementMovingKey,reclaimingKey:this.headerPlacementReclaimingKey,restartingKey:this.headerPlacementRestartingKey,row:t}),me=this.state?.sessionKey??``,he=this.state?.sessionsResult,ge=$s(this.context.sessions?.state?.groups??[],this.context.sessions?.state?.result?.sessions??[]),_e=(he?.owners?.length??0)>=2||(t?.participantCount??0)>0,ve=nu(this.context),ye=_e?t?.owner?.actor.identity:void 0,be=n?void 0:Ga(this.presencePayload,h.selfUser,h.client?.instanceId,me,[...ye?[ye]:[],..._e?(t?.participants??[]).map(({identity:e})=>e):[]]),xe=Qo(this.presencePayload).users.some(e=>Po(e,ye)&&e.watchedSessions.includes(me)),Se=g&&t?{session:t,state:this.sessionSharingStates.get(this.sessionSharingCacheKey(t.key)),allowedVisibilities:h.hello?.policy?.allowedSessionVisibilities,membersAvailable:_.allowed,openDisabledReason:S,visibilityDisabledReason:v.allowed?void 0:v.reason,memberAddDisabledReason:b.allowed?void 0:b.reason,memberRemoveDisabledReason:x.allowed?void 0:x.reason,publicShareDisabledReason:!t.sessionId||E(t.key)?R(`chat.sessionSharing.publicUnavailable`):y.allowed?void 0:y.reason,onPublicShareChange:e=>void this.setSessionPublicShare(t,e),onCopyPublicLink:()=>void this.copySessionPublicLink(t),ownerViewing:xe,personActivity:ve,showOwner:_e,onOpen:()=>void this.loadSessionSharing(t),onVisibilityChange:e=>void this.setSessionVisibility(t,e),onMemberChange:(e,n)=>void this.setSessionMember(t,e,n)}:null,Ce=this.observedParentSessionRow(),we=Tf({paneId:this.paneId,narrow:this.narrow,mergedChrome:this.mergedChrome,navDrawerOpen:this.navDrawerOpen,title:(n?this.catalogSession?.name?.trim():void 0)||this.resolveHeaderSessionTitle(t),session:t,showOwnerChip:_e,ownerViewing:xe,personActivity:ve,catalog:n,catalogColor:this.catalogSession?.color,editing:this.headerEditing&&this.headerRenameSession?.key===t?.key,renameValue:this.headerRenameValue,workspaceRoot:c.root,workspaceLabel:c.label,workspaceIcon:this.resolveWorkspaceIcon(c.root?t?.key:void 0),parentSession:Qd(t,Ce?[Ce]:[]),branch:u,branches:this.state?US(this.state):[],branchSwitchDisabledReason:m,platform:this.headerPlatform,canReveal:d,copiedAction:this.headerCopiedAction,renameDisabledReason:w,actionsDisabled:this.state?.connected!==!0,panelActions:ce,panelLayoutActions:W`${this.renderPanelLayoutActions(ae,s)}${se}`,discussionAction:G,diffAction:G,sessionRailAction:G,workspaceAction:G,presence:be?.length?W`<openclaw-viewer-facepile
            class="chat-pane__presence"
            .staticUsers=${be}
            .maxVisible=${4}
            .personActivity=${ve}
            variant="session"
          ></openclaw-viewer-facepile>`:G,faceControl:G,sharingControl:Se&&(!Nf(Se.session)||!Se.openDisabledReason)&&(!this.narrow||!Nf(Se.session))?bf(Se):G,publicAccessIndicator:this.narrow&&Se?Bd(Se):G,placementControl:ju({session:t,placementStartupStatus:a,placementMoving:pe.moving,placementRestarting:pe.restarting,placementMoveDisabledReason:pe.moveDisabledReason,placementReclaimDisabledReason:pe.reclaimDisabledReason,placementRecoveryDisabledReason:pe.recoveryDisabledReason,onPlacementMove:()=>t&&void this.changeHeaderPlacement(t,`move`),onPlacementReclaim:()=>t&&void this.reclaimHeaderPlacement(t),onPlacementRecover:()=>t&&void this.changeHeaderPlacement(t,`recover`)}),sessionMenuAction:t&&this.state?W`<openclaw-chat-header-session-menu
              .session=${this.headerSessionMenuData(t,k)}
              .worktreePath=${t.execNode||!ru()?null:c.root}
              .onboarding=${this.onboarding}
              .preferencesBrowserOnly=${this.context.runtimeConfig?.state.connected&&this.context.runtimeConfig.canPatch===!1}
              .compact=${this.narrow}
              .navigationAllowed=${!0}
              .copyMarkdownAllowed=${nc(this.context.gateway.snapshot)}
              .splitAllowed=${_c()}
              .settings=${this.state.settings}
              .panelActions=${ue}
              .layoutActions=${de}
              .boardWidgetMenu=${this.fullscreenBoardWidgetMenu(ae)}
              .sharing=${Se}
              .groups=${ge}
              .currentOwner=${t.owner?.actor??null}
              .actionDisabledReasons=${te}
              .forkDisabled=${this.state.sessionsLoading||t.modelSelectionLocked===!0}
              .forkFromLastCompleted=${t.hasActiveRun===!0}
              .archiveAllowed=${D}
              .archiveShortcut=${this.active&&this.presented&&!this.onboarding}
              .deleteAllowed=${O}
              .onOpen=${()=>{this.loadHeaderMenuData(t,r,i)}}
              .onOpenCommandPalette=${()=>window.dispatchEvent(new Event(Cr))}
              .onSettingsChange=${this.state.applySettings}
              .onAction=${e=>this.handleHeaderSessionAction(e,t)}
            ></openclaw-chat-header-session-menu>`:G,onboarding:this.onboarding,onBeginRename:()=>t&&this.beginHeaderRename(t),onRenameInput:e=>{this.headerRenameValue=e},onCommitRename:()=>this.commitHeaderRename(),onCancelRename:()=>this.cancelHeaderRename(),onMenuOpenChange:e=>{e&&t&&this.loadHeaderMenuData(t,r,i)},onMenuAction:e=>{t&&this.handleHeaderMenuAction(e,t,c.root,u)},onOpenParentSession:e=>{this.onPaneSessionChange?.(this.paneId,e)},onBranchSelect:e=>{let t=Xx(this.context.gateway.snapshot,!!this.state?.chatRunId).branchSwitch;if(!t.allowed){this.publishHeaderError(t.reason);return}this.switchToBranch(e)},onOpenSplitView:this.onOpenSplitView,onSplitDown:this.onSplitDown,onSplitRight:this.onSplitRight,onClosePane:this.onClosePane}),P=this.currentContinueInTerminalCommand(t);return W`${we}${P?Lf({command:P,onClose:()=>this.closeContinueInTerminalDialog()}):G}`}}})))()}var mj;function hj(){return(hj=e((()=>{H(),BS(),pj(),Pw(),mj=class extends fj{constructor(...e){super(...e),this.removeBrowserAnnotation=e=>{let t=this.state;if(!t)return;let n=t.sessionKey;zS({getOwner:()=>this.browserAnnotationOwner(),getSessionKey:()=>this.state?.sessionKey??``,getAttachments:()=>this.state?.chatAttachments??[],setAttachments:e=>{this.state&&(this.state.chatAttachments=e)},requestUpdate:()=>this.state?.requestUpdate?.(),focusComposer:()=>{this.updateComplete.then(()=>{this.state===t&&this.state.sessionKey===n&&this.querySelector(Ow)?.focus({preventScroll:!0})})},focusRestoredAnnotation:e=>{this.updateComplete.then(()=>{this.state===t&&this.state.sessionKey===n&&[...this.querySelectorAll(`[data-attachment-id]`)].find(t=>t.dataset.attachmentId===e)?.querySelector(`button`)?.focus({preventScroll:!0})})}},e,{removed:R(`chat.composer.browserAnnotationRemoved`),undo:R(`common.undo`),undoUnavailable:R(`chat.composer.browserAnnotationUndoUnavailable`)})}}}})))()}var gj;function _j(){return(_j=e((()=>{Eh(),eg(),gj=class{constructor(e,t,n){this.host=e,this.getContext=t,this.getSession=n,this.icons={get:e=>this.getIcon(e)},this.owner=null,this.toolIcons=new Map,this.activityIcons=new Map,this.requested=new Set,this.pending=new Set,this.urls={},e.addController(this),this.loader=new Uh({getFetchContext:()=>{let{gateway:e,resourceBasePath:n}=t();return{resourceBasePath:n,gatewayUrl:e.connection.gatewayUrl,auth:{hello:e.snapshot.hello,settings:{token:e.connection.token},password:e.connection.password}}},isConnected:()=>this.isCurrent(),fetchIcon:(e,t,n)=>{let r=this.activityIcons.get(e);return r?mh({...t,...r,signal:n}):Promise.resolve(null)},onUrlsChange:e=>this.publish(e)})}publish(e=this.urls){this.urls=e,this.icons={get:e=>this.getIcon(e)},this.host.requestUpdate()}getIcon(e){let t=this.owner;if(!t||!this.isCurrent())return;if(this.requested.add(e),!this.toolIcons.has(e)){let t=this.pending.size>0;this.pending.add(e),t||queueMicrotask(()=>this.refresh())}let n=this.toolIcons.get(e);if(!n)return;this.loader.load(n);let r=this.urls[n];return r?{url:r,onError:()=>{this.owner===t&&this.isCurrent()&&this.urls[n]===r&&this.loader.handleError(n)}}:void 0}isCurrent(){let{snapshot:e,connectionRevision:t}=this.getContext().gateway,n=this.getSession();return!!(this.owner&&e.phase===`connected`&&e.client===this.owner.client&&t===this.owner.revision&&n?.sessionKey===this.owner.session.sessionKey&&n?.agentId===this.owner.session.agentId)}hostUpdate(){if(this.isCurrent())return;let{snapshot:e,connectionRevision:t}=this.getContext().gateway,{client:n,phase:r}=e,i=this.getSession();this.hostDisconnected(),r===`connected`&&n&&i&&(this.owner={client:n,session:i,revision:t,controller:new AbortController},this.publish())}refresh(){let e=this.owner;if(!e||!this.isCurrent()||e.loading||this.pending.size===0)return;for(let e of this.pending)this.toolIcons.set(e,void 0);this.pending.clear(),e.loading=!0;let t={signal:e.controller.signal};Promise.all([e.client.request(`tools.effective`,e.session,t),e.plugins??=e.client.request(`plugins.list`,{},t).catch(t=>{throw e.plugins=void 0,t})]).then(([t,n])=>{if(this.owner!==e||!this.isCurrent())return;let r=new Map(n.plugins.map(e=>[e.id,{default:e.hasActivityIcon,tools:new Set(e.activityIconTools)}]));this.activityIcons.clear();for(let e of t.groups)for(let t of e.tools){let e=t.pluginId,n=e?r.get(e):void 0,i=n?.tools.has(t.id)?t.id:void 0,a=e&&(i||n?.default)?JSON.stringify([e,i??null]):void 0;a&&e&&this.activityIcons.set(a,{pluginId:e,tool:i}),this.toolIcons.set(t.id,a),this.pending.delete(t.id)}this.loader.reconcileKeys(new Set(this.activityIcons.keys()));for(let e of this.requested){let t=this.toolIcons.get(e);t&&this.loader.load(t)}this.publish()}).catch(()=>{}).finally(()=>{this.owner===e&&(e.loading=!1,this.refresh())})}hostDisconnected(){this.owner&&(this.owner.controller.abort(),this.owner=null,this.toolIcons.clear(),this.activityIcons.clear(),this.requested.clear(),this.pending.clear(),this.loader.reset())}}})))()}function vj(e){if(!e||e.status===`ok`)return G;let t=e.totalBytes>0?Math.round((e.totalBytes-e.availableBytes)/e.totalBytes*100):0,n=e.status===`critical`;return W`
    <div
      class="chat-composer-neighbor-card chat-composer-neighbor-card--${n?`danger`:`warn`} chat-cloud-disk-space-notice"
      role=${n?`alert`:`status`}
    >
      <span class="chat-composer-neighbor-card__icon" aria-hidden="true"
        >${U.alertTriangle}</span
      >
      <div class="chat-composer-neighbor-card__copy">
        <strong
          >${R(n?`chat.diskSpace.criticalTitle`:`chat.diskSpace.warningTitle`)}</strong
        >
        <span>
          ${R(n?`chat.diskSpace.criticalBody`:`chat.diskSpace.warningBody`,{percent:String(t),free:Re(e.availableBytes)})}
        </span>
      </div>
    </div>
  `}function yj(e){if(!e)return G;let t={transferred:Re(e.transferredBytes),total:Re(e.totalBytes),percent:String(Math.round(e.transferredBytes/e.totalBytes*100))},n=e.phase===`installing`,r=n?R(`chat.workerRuntimeInstall.installingBody`):R(`chat.workerRuntimeInstall.transferringBody`,t);return W`
    <div
      class="chat-composer-neighbor-card chat-composer-neighbor-card--info chat-worker-runtime-install-notice"
      role="status"
      title=${r}
    >
      <span class="chat-composer-neighbor-card__icon" aria-hidden="true">${U.info}</span>
      <div class="chat-composer-neighbor-card__copy">
        <strong
          >${n?R(`chat.workerRuntimeInstall.installingTitle`):R(`chat.workerRuntimeInstall.transferringTitle`,t)}</strong
        >
        <span>${r}</span>
      </div>
    </div>
  `}function bj(e,t=G,n=cl(e),r=`danger`){let i=n.trim().split(/\r?\n/u).map(e=>e.replace(/\s+/gu,` `).trim()),[a=``]=i,o=ue(a),s=i.some(e=>e!==``&&e!==o);return W`
    <div
      class="chat-composer-neighbor-card chat-composer-neighbor-card--${r} chat-error"
      role=${r===`warn`?`status`:`alert`}
    >
      <span class="chat-composer-neighbor-card__icon" aria-hidden="true"
        >${U.alertTriangle}</span
      >
      ${s?W`<details class="chat-error__content">
              <summary class="chat-error__summary">
                <strong>${o}</strong>
                <span>${R(`chat.details`)}</span>
                <span class="chat-error__chevron" aria-hidden="true">${U.chevronDown}</span>
                ${vl(e,R(`chat.copyError`))}
              </summary>
              <pre class="chat-error__diagnostic" tabindex="0" aria-label=${R(`chat.errorDetails`)}>
${n}</pre>
            </details>`:W`<span class="chat-error__content"
              ><strong>${o}</strong>${vl(e,R(`chat.copyError`))}</span
            >`}
      ${t}
    </div>
  `}function xj(e){let t=e.onDismissError?W`
        <openclaw-tooltip .content=${R(`chat.actions.dismissError`)}>
          <button
            class="chat-error__dismiss"
            type="button"
            @click=${e.onDismissError}
            aria-label=${R(`chat.actions.dismissError`)}
          >
            ${U.x}
          </button>
        </openclaw-tooltip>
      `:G;return W`
    <div class="chat-topbar-notices">
      ${vj(e.diskSpace)}
      ${yj(e.workerRuntimeInstall)}
      ${e.error?bj(e.error,t):G}
      ${e.focusMode&&e.onToggleFocusMode?W`
              <openclaw-tooltip .content=${R(`chat.actions.exitFocusMode`)}>
                <button
                  class="chat-focus-exit"
                  type="button"
                  @click=${e.onToggleFocusMode}
                  aria-label=${R(`chat.actions.exitFocusMode`)}
                >
                  ${U.x}
                </button>
              </openclaw-tooltip>
            `:G}
    </div>
  `}function Sj(e){let t=e.runError?.kind===`state_contention`,n=e.onRefresh?W`<button
        class="btn btn--sm chat-error__refresh"
        type="button"
        ?disabled=${!e.connected}
        @click=${e.onRefresh}
      >
        ${R(t?`chat.checkStatus`:`common.refresh`)}
      </button>`:G;return W`
    ${e.providerReviewNotice??G}
    ${Cj(e.providerPolicyNotice)}
    ${e.runError?bj(e.runError.summary,n,void 0,t?`warn`:`danger`):G}
    ${Zd({conflict:e.workspaceConflict??void 0,onDismiss:e.onDismissWorkspaceConflict})}
    ${wj(e.placementStartup,e.messages,e.onRetrySessionPlacementStartup)}
  `}function Cj(e){if(!e)return G;let t=e.state===`blocked`||e.state===`unavailable`,n=e.fallbackModel??e.model,r=e.state!==`buffering`&&e.state!==`blocked`&&!n?R(`chat.providerPolicy.fallbackUnknownBody`):R(`chat.providerPolicy.${e.state}Body`,{model:n??``});return W`
    <div
      class="chat-composer-neighbor-card chat-composer-neighbor-card--${t?`danger`:`warn`} chat-provider-policy-notice"
      role=${t?`alert`:`status`}
    >
      <span class="chat-composer-neighbor-card__icon" aria-hidden="true"
        >${U.alertTriangle}</span
      >
      <div class="chat-composer-neighbor-card__copy">
        <strong>${R(`chat.providerPolicy.${e.state}Title`)}</strong>
        <span>${r}</span>
      </div>
    </div>
  `}function wj(e,t,n){if(e?.phase!==`failed`)return G;let r=e.action===`check-delivery`,i=e.error??R(`newSession.createFailed`),a=r?[R(`chat.queue.checkDeliveryHelp`),e.error].filter(Boolean).join(`

`):R(`newSession.placementStartFailed`,{error:i}),o=cl(i),s=r?[R(`chat.queue.checkDeliveryHelp`),e.error?o:void 0].filter(Boolean).join(`

`):R(`newSession.placementStartFailed`,{error:o}),c=e.initialTurn&&!ks(t,e.initialTurn.sendRunId,!0);return bj(a,e.discardAndReload?W`<button
        class="btn btn--sm danger chat-error__discard"
        type="button"
        @click=${e.discardAndReload}
      >
        ${R(`newSession.discardUnsavedAndReload`)}
      </button>`:e.retryable&&n&&!c?W`<button class="btn btn--sm" type="button" @click=${n}>
          ${R(r?`chat.queue.checkDelivery`:`common.retry`)}
        </button>`:G,s)}function Tj(){return(Tj=e((()=>{bi(),tl(),pl(),Ar(),H(),_a(),He(),dc(),Ke(),wf(),Hs()})))()}function Ej(e){let t=e.inlineApproval?.sourceSessionKey,n=t?e.sessions?.sessions.find(e=>F(e.key,t)):void 0,r=e.historyState?Ov(e.historyState):void 0,i=r?[...r.page.items.filter(e=>!e.queued),...r.queuedInputs]:void 0,a=e.onRequestUpdate??(()=>{}),o=()=>e.transcript.scrollElement?.closest(`.chat`)?.querySelector(`.agent-chat__composer-combobox > textarea`)?.focus({preventScroll:!0}),s=(t,n,r,i,a=!1)=>{$u({paneId:e.paneId,anchorRect:n,sourceRange:e.transcript.scrollElement?od(e.transcript.scrollElement,t)?.range:void 0,comment:``,readSignal:e.readSignal,onCancel:i,onSave:n=>{if(e.readSignal?.aborted)return!0;if(!a&&!yn(e.uploadConfig))return ct({message:qt()}),!1;let i=ff({...t,comment:n,sessionKey:e.sessionKey},{attachmentLimits:e.attachmentLimits,selectionContextOnly:a},cf(e));return i?r(i)?!0:(en([i]),!1):!1}})},c=e.canSend,l=jd(e.paneId),u=Ad(l,{...e,onReopen:(t,n)=>{let r=nf(e.paneId);r.activeQuestionKey=JSON.stringify([n,t]),r.questionCollapsed=!1}}),d=e.onOpenImage?(t,n)=>n===void 0?e.onOpenImage?.(t):e.onOpenImage?.(t,n):void 0,f=e.onOpenImage?t=>d?.(t,e.onRequestOpenImage?.()):void 0,p=Xd({...e,canCompose:c}),m=e.placementStartup?.phase===`failed`?null:e.placementStartup,h=e.placementStartup?.initialTurn,g=e.queue;if(h){let t=Dj.get(e.queue);t?.initialTurn!==h&&(t={initialTurn:h,queue:[...e.queue,h]},Dj.set(e.queue,t)),g=t.queue}let _=!!m||Yu(e),v=Rt(`transcript`,{sessionKey:e.sessionKey,agentId:e.currentAgentId,messages:e.messages,stream:e.stream,loading:e.loading},Md({...e,asyncQuestions:u,loading:e.loading&&!m,streamStartedAt:m?.startedAt??e.streamStartedAt,queue:g,initialTurnId:e.placementStartup?.initialTurn?.id,pendingInputs:i,runActive:e.runActive===!0,runWorking:_,startupLabel:MC(e.startupStatus,m),questionPrompts:e.gatewayQuestionPrompts,agents:e.agentsList?.agents,onOpenImage:d,onRequestUpdate:a,queuedMessageAction:e.placementStartup?.initialTurn?{id:e.placementStartup.initialTurn.id,label:e.placementStartup.action===`check-delivery`?R(`chat.queue.checkDelivery`):void 0,onAction:e.connected?e.onRetrySessionPlacementStartup:void 0}:void 0,onRetryQueuedMessage:e.connected&&c?e.onQueueRetry:void 0,onDiscardQueuedMessage:e.onQueueRemove,onCompanionSelection:e.canSend&&!e.suggestionComposer&&e.onCompanionStageAttachment?(t,n)=>s(t,n,t=>e.onCompanionStageAttachment?.(t,e.sessionKey)??!1,void 0,!0):void 0,commentAttachments:e.suggestionComposer?void 0:e.attachments,commentsDisabled:!c||!!e.readSignal?.aborted,onAddToChat:e.canSend&&!e.suggestionComposer&&yn(e.uploadConfig)?(t,n)=>s(t,n,t=>e.onAttachmentsChange?(e.onAttachmentsChange([...e.getAttachments?.()??e.attachments??[],t]),a(),o(),!0):!1,o):void 0,onOpenSession:e.onSessionSelect,onFocusComposer:()=>e.transcript.scrollElement?.closest(`.chat`)?.querySelector(`openclaw-plugin-view[data-plugin-composer], .agent-chat__composer-combobox > textarea`)?.focus({preventScroll:!0})},e.transcript),e.presented??!0),y=W`${r&&(r.error||r.page.nextBefore!==void 0||r.before!==void 0)?W`<div class="chat-pending-inputs" role="status">
            ${r.error?W`<span>${r.error}</span>`:G}
            ${r.page.nextBefore===void 0?G:W`<button
                    class="btn btn--sm"
                    type="button"
                    ?disabled=${r.loading}
                    @click=${()=>e.historyState&&Lv(e.historyState,r.page.nextBefore)}
                  >
                    ${R(`chat.pendingInputs.earlier`)}
                  </button>`}
            ${r.before===void 0?G:W`<button
                    class="btn btn--sm"
                    type="button"
                    ?disabled=${r.loading}
                    @click=${()=>e.historyState&&Lv(e.historyState)}
                  >
                    ${R(`chat.pendingInputs.latest`)}
                  </button>`}
          </div>`:G}
    ${e.inlineApproval&&e.onApprovalDecision?W`<div class="chat-inline-approval">
            ${Xc({approval:e.inlineApproval,sourceSession:n,busy:e.approvalBusy===!0,canGrant:e.approvalCanGrant,error:e.approvalErrors?.get(e.inlineApproval.id)??null,variant:`inline`,onDecision:e.onApprovalDecision})}
          </div>`:G}
    ${lf({pullRequests:e.pullRequests??[],gateway:e.pullRequestsGateway,sessionKey:wn(e.sessionKey,e.currentAgentId??void 0),presented:e.presented??!0,branch:e.pullRequestsBranch,status:e.pullRequestsStatus??`ready`,onDismiss:t=>e.onDismissPullRequest?.(t),onOpenSessionDiff:e.onOpenSessionDiff,publication:e.githubPublication})}
    ${Uf({suggestions:e.sessionSuggestions??[],role:e.sessionSuggestionRole,busyIds:e.sessionSuggestionBusyIds??new Set,archived:e.sessionSuggestionsArchived===!0,canResolve:e.canResolveSessionSuggestions===!0,onResolve:(t,n)=>e.onResolveSessionSuggestion?.(t,n)})}
    ${e.swarm?xd(e.swarm):G}
    <openclaw-plugin-contributions
      .kind=${`composer`}
      .sessionKey=${e.sessionKey}
      .agentId=${e.currentAgentId}
      .presented=${e.presented??!0}
    ></openclaw-plugin-contributions>`,b=Sj(e);l.transcriptRenderContext.onAsyncQuestionSubmit=e.onAsyncQuestionSubmit,l.transcriptRenderContext.onAsyncQuestionDiscard=u.discard;let x=ep(e.messages,e.queue,i??[]),S=$d({...e,asyncQuestions:u,displayQueue:[...Ev(x.queuedInputs),...x.queue],footerContent:y,notices:b,onRequestUpdate:a,onToggleRealtimeTalk:e.suggestionComposer?void 0:e.onToggleRealtimeTalk,onOpenImage:f}),C=Rt(`composer`,{sessionKey:e.sessionKey,agentId:e.currentAgentId,draft:e.draft,canSend:e.canSend&&!e.submitDisabledReason,sending:e.sending,disabledReason:e.submitDisabledReason??e.disabledReason,setDraft:e.onDraftChange,send:async()=>e.onSend(),abort:e.onAbort},S,e.presented??!0,W`<div class="chat-footer__context">
      ${y}
      <div class="agent-chat__composer-notices">${b}</div>
      ${md(Lu({...e,asyncQuestions:u},nf(e.paneId),a))}
      ${e.suggestionComposer?G:Fd({...e,disabled:!c})}
    </div>`),w=Gd(e),T=w===G?G:W`<div class="chat-gutter-stack">${w}</div>`,E=e.onScrollToBottom?W`
        <div class="chat-scroll-to-bottom-wrap">
          <button
            class="chat-scroll-to-bottom"
            data-visible=${!!e.showNewMessages}
            type="button"
            ?inert=${!e.showNewMessages}
            aria-hidden=${!e.showNewMessages}
            @click=${()=>e.onScrollToBottom?.({smooth:!0})}
            aria-label=${R(`chat.actions.scrollToLatest`)}
          >
            ${U.arrowDown}
          </button>
        </div>
      `:G,D=e.historyState,O=D?ry(D):void 0,k=D!==void 0&&O?.phase===`failed`&&O.sessionKey===e.sessionKey,A=!_&&e.messages.length===0&&x.pendingInputs.length===0&&x.queuedInputs.length===0&&e.toolMessages.length===0&&e.streamSegments.length===0&&!e.stream&&g.length===0,j=t=>W`<div
      class="chat-history-error${t?` chat-history-error--inline`:``}"
      role=${t?`status`:`alert`}
    >
      <span>${O?.phase===`failed`?O.message:``}</span>
      <button
        class="btn btn--sm"
        type="button"
        @click=${()=>{D&&ry(D).phase===`failed`&&(e.onRefresh(),D.requestUpdate?.())}}
      >
        ${R(`common.retry`)}
      </button>
    </div>`,ee=k&&A?j(!1):G,te=k&&!A?j(!0):G;return W`
    <section
      class="chat"
      style=${Ci(e.chatMessageMaxWidth?{"--chat-thread-max-width":e.chatMessageMaxWidth,"--chat-message-max-width":`100%`}:{})}
      @drop=${p.onDrop}
      @dragenter=${p.onDragenter}
      @dragleave=${p.onDragleave}
      @click=${e=>ku(e,f)}
      @dragover=${p.onDragover}
      @keydown=${t=>{if(!Mu(t)&&(t.key!==`Enter`&&t.key!==` `||!ku(t,f))){if(t.key===`Escape`&&e.replyTarget&&!t.defaultPrevented&&!t.isComposing&&t.keyCode!==229&&!nf(e.paneId).composerComposing){t.preventDefault(),e.onClearReply?.();return}tn(gt.transcriptSearch,t)&&(t.preventDefault(),Pu(e.paneId,a,t))}}}
    >
      ${e.suggestionComposer?G:W`<openclaw-chat-comment-controller
              .paneId=${e.paneId}
              .props=${{...e,disabled:!c}}
              .sessionKey=${e.sessionKey}
              .presented=${e.presented??!0}
            ></openclaw-chat-comment-controller>`}
      <div class="chat-workbench" ${ai({workbench:!0})}>
        <div class="chat-workbench__main">
          <div class="chat-split-container">
            <div class="chat-main">
              <div class="chat-main__conversation-column">
                ${e.header??G} ${xj(e)}
                <openclaw-plugin-contributions
                  .kind=${`header`}
                  .sessionKey=${e.sessionKey}
                  .agentId=${e.currentAgentId}
                  .presented=${e.presented??!0}
                ></openclaw-plugin-contributions>
                ${Du(e.paneId,a)}
                <div class="chat-main__conversation-frame">
                  <!-- Chromium can crash when DevTools inspects a blocking Lit object listener. -->
                  <div
                    class="chat-main__conversation"
                    .onwheel=${t=>QO(t,e.transcript.scrollElement)}
                  >
                    ${te} ${ee===G?v:ee}
                    ${E} ${T}
                    <div class="chat-footer">${C}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  `}var Dj;function Oj(){return(Oj=e((()=>{bi(),wi(),Zr(),Zc(),Ar(),H(),Pt(),B(),tt(),Dt(),Qt(),Ig(),Y(),zv(),FC(),tk(),Tj(),Od(),Vf(),_f(),Su(),qu(),yu(),ld(),Of(),Mf(),Wd(),Au(),Pf(),Vd(),uf(),Hf(),Ef(),ip(),ei(),Dj=new WeakMap})))()}var kj;function Aj(){return(Aj=e((()=>{w(),bi(),PS(),or(),ii(),dl(),Rc(),Cs(),I(),B(),hj(),hS(),Qw(),wS(),_j(),Oj(),My(),Td(),ld(),Sd(),sf(),vp(),Lh(),kj=class extends mj{constructor(...e){super(...e),this.toolIcons=new gj(this,()=>this.context,()=>this.state&&!this.catalogHost?this.resolveChatReadTarget():void 0),this.desktopFocus=null}renderChatPaneLayout(e){let{state:t,selectedSession:n,currentAgentId:r,board:i,sidebarLayout:a,sessionWorkspace:o,chatProps:s,observerDigest:c,observerRunId:l,catalog:u,agentWorkspace:d,workspaceGit:f,openPanelSlot:p,closePanelSlot:m}=e;if(this.inputRegion===`page`){let e=t.sessionWorkspaceState?.previews.find(e=>e.id===t.sessionWorkspaceState?.activePreviewId)?.content,i=e?.kind===`file`&&Je(a,`workspace`)?e:void 0,o=Fs({session:n,agentWorkspace:d,worktreePath:n?.worktree?this.headerWorktreePaths.get(n.worktree.id)?.path:void 0});Oy(this.context,this,this.presented&&this.selected?{sessionKey:t.sessionKey,sessionId:t.currentSessionId??void 0,agentId:r,workspace:i?.root??o.root??void 0,file:i?.path}:void 0)}let h=W`<openclaw-chat-outbox-recovery
      .host=${t}
      .identity=${JSON.stringify([t.settings.gatewayUrl,t.connected&&t.client?.recoveryScopeReady?t.client.recoveryScope:null,N(Ft(t,t.sessionKey))])}
      @outbox-restored=${()=>{this.chatState.composerPersistence.restore(),t.requestUpdate?.()}}
    ></openclaw-chat-outbox-recovery>`,g=gs(s.messages,s.toolMessages),_=Ej({...s,pluginToolIcons:this.toolIcons.icons,presented:this.active&&this.presented,transcriptVisible:this.presented&&this.visuallyPresented&&Je(a,`conversation`),latestBrowserTabs:this.active&&this.presented?g:void 0,historyState:u?void 0:t,header:G}),v=W`<div class="chat-pane-primary-column">${_}</div>`,y=this.buildSessionDiscussionPanel(t,t.sessionKey.trim()),b=this.sessionDiscussionStates.get(t.sessionKey.trim()),x=b===`available`||b===`open`,S=oi(this.context.gateway.snapshot),C=t.sessionKey,w=this.sessionCompanionThreads.view(C,r),T=this.presented&&this.visuallyPresented&&Je(a,`companion`);this.syncSessionCompanionPresentation(T);let E=this.active&&this.presented&&Je(a,`browser`),D=ot(a)?.slot!==`browser`,O=ot(a)?.slot!==`terminal`,k=this.presented&&this.visuallyPresented&&Je(a,`desktop`),A=!this.pendingPanelToggleRequests.has(`desktop`),j=this.activeSessionResources.desktopSource(t.client,t.sessionKey,L(t,t.sessionKey).agentId,t.connectionEpoch,this.resourceSessionObservation()?.row??void 0),ee=a.columns.flatMap(e=>e.panels).find(e=>e.slot===`desktop`)?.environmentId??(j===void 0?Xw(n):j),ne=JSON.stringify([t.sessionKey,this.connectionGeneration,S,k,t.basePath]);(this.desktopFocus?.key!==ne||this.desktopFocus.client!==t.client)&&(this.desktopFocus={key:ne,client:t.client,href:te({kind:`desktop`,session:t.sessionKey},t.basePath)});let M=this.desktopFocus,re=fS({state:t,themeMode:this.context.theme.resolvedMode,agentId:r,browserPresented:E,browserTabsInHeader:D,linkReaders:Sr(this.context.gateway.snapshot),linkReaderPresented:this.presented&&this.visuallyPresented&&Je(a,`link-reader`),linkReaderTabsInHeader:ot(a)?.slot!==`link-reader`,onCloseLinkReader:()=>m(`link-reader`),terminalTabsInHeader:O,browserRefreshOnPresentation:!this.pendingPanelToggleRequests.has(`browser`),preferredBrowserTab:[...g.values()].at(-1),sessionBrowserTabs:[...g.values()].map(e=>e.tab),desktopPresented:k,desktopRefreshOnPresentation:A,desktopAvailable:S,desktopSource:ee,portalPresented:this.presented&&this.visuallyPresented&&Je(a,`portal`),desktopFocusHref:M.href,onDesktopFocusTargetChange:e=>{let n=te(e,t.basePath);this.desktopFocus===M&&M.href!==n&&(M.href=n,this.requestUpdate())},dashboard:this.compact?G:this.renderBoardPanel(i,a),workspace:Eu(o,{embedded:!0}),renderDetail:e=>hf({chat:s,content:e,host:t}),digest:c,activeRunId:l,startedAt:n?.startedAt??t.chatStreamStartedAt??void 0,lastReadAt:n?.lastReadAt,pullRequests:this.sessionPullRequests,companion:w,companionFocusRequest:this.sessionCompanionFocusRequest,companionPresented:T,onCompanionSubmit:e=>void this.submitSessionCompanionQuestion(e),onCompanionDraftChange:e=>this.sessionCompanionThreads.setDraft(t.sessionKey,e,r),onCompanionAttachmentsChange:e=>this.sessionCompanionThreads.setAttachments(C,e,r),onCompanionVisibilityChange:this.setSessionObserverVisibility,connected:t.connected,onClearCompanion:()=>void this.clearSessionCompanion(),discussion:y,discussionAvailable:x,discussionOpenUrl:y?.openUrl??null,discussionSourceGeneration:this.connectionGeneration,pluginPanels:this.context.plugins.registrations(`panels`),isPluginPanelPresented:e=>this.active&&this.presented&&Je(a,e)}),ie=pS(re),ae=mS(re),oe=mS(re,`headerAction`),se=this.compact?G:W`${this.renderPaneHeader(o,n,u,d,f,s.placementStartup,a,re)}<openclaw-plugin-contributions
            .kind=${`session-header`}
            .sessionKey=${t.sessionKey}
            .agentId=${r}
            .presented=${this.visuallyPresented}
          ></openclaw-plugin-contributions>`,ce=vS({presentationId:this.presentationId,conversationTab:{label:s.assistantName,icon:Il(Pd(s))},availableWidth:this.paneWidth,fetchFavicon:pp(t),availableSlots:ie,callbacks:_S({state:t,layout:a,closePanelSlot:m,openPanelSlot:p,forgetDiscussionUrl:()=>this.sessionDiscussionOpenUrls.delete(t.sessionKey.trim()),resizePanel:(e,t)=>this.commitSidebarPanelResize(a,e,t),setPanelOpen:e=>this.setChatSidePanelOpen(e,a)}),layout:a,panelDefinitions:re,panelActions:oe,narrow:this.paneWidth<680,panelTemplates:ae,header:W`${se}${h}`,primary:v,requestUpdate:t.requestUpdate});return W`${ce}
    ${Zu(t.imageLightbox,t.handleCloseImage)}${this.renderResetConfirmation()}`}}})))()}function jj(e,t){let n=Fm(e);return{editingId:n?.id??null,editingText:n?.draftText,editingMentions:n?.mentions,source:n?.source,onEdit:t?void 0:e.editQueuedChatMessage,onEditChange:t?void 0:e.updateQueuedChatMessageEdit,onEditSubmit:t?void 0:e.submitQueuedChatMessageEdit,onCancel:e.cancelQueuedChatMessageEdit}}function Mj(e,t,n){let r=e.hello?.auth??null,i=Ur(r)||!n&&Le(r,{method:`chat.send`,requiredScope:`operator.write`,sessionScope:!0,session:t}).allowed;return{canCompose:Gr(r)||i,canSend:i}}function Nj(e,t,n){return{model:z(e,{method:`sessions.patch`,params:{key:t,model:null},sessionScope:!0,session:n}),effort:z(e,{method:`sessions.patch`,params:{key:t,thinkingLevel:null},sessionScope:!0,session:n}),contextWindow:z(e,{method:`sessions.patch`,params:{key:t,contextWindow:null}}),permission:z(e,{method:`sessions.patch`,params:{key:t,permissionMode:`guarded`},sessionScope:!0,session:n}),unarchive:z(e,{method:`sessions.patch`,params:{key:t,archived:!1},sessionScope:!0,session:n})}}function Pj(e){let{state:t,selectedSession:n,agentDefaultModel:r,agentDefaultPermissionMode:i,modelAccess:a,effortAccess:o,contextWindowAccess:s,permissionAccess:c,canSelectFull:l,onModelSetup:u,onProviderSettings:d,onModelAccounts:f}=e,p=t.sessionKey,m=t.client,h=t.chatAccountSelection,g=t.connectionEpoch,_=L(t,p),v=ae(t,p).agentId,y=n?.sessionId?.trim(),b=JSON.stringify([p,_.agentId]),x=Ij.get(t)??new Map;Ij.set(t,x);let S=()=>t.connected&&t.sessionKey===p&&t.client===m&&t.connectionEpoch===g&&L(t,p).agentId===_.agentId,C=()=>{let e=Q(t);return S()&&!!e==!!n&&e?.sessionId===y},w=(e,n=p)=>F(n,p)&&C()&&z({client:t.client,hello:t.hello,phase:t.connected?`connected`:`offline`},{method:`sessions.patch`,params:{key:p,...e},sessionScope:!0,session:Q(t)}).allowed,T=x.get(b);T&&T.expectedSessionId!==y&&(x.delete(b),T=void 0),T?.retainWhileCurrent&&!T.retainWhileCurrent()&&(x.delete(b),T=void 0);let E=T?.ownsSelection()?T:void 0,D=!!(E?.pending||n?.permissionModePending),O=js({models:t.chatModelCatalog,refreshFailed:t.chatModelCatalogRefreshFailed,pendingProviders:t.chatModelCatalogPendingProviders,modelSelectionPolicy:t.chatModelSelectionPolicy},{connected:t.connected,loading:t.chatModelsLoading,error:t.chatModelCatalogError,retired:t.chatModelCatalogRetired,initialized:t.chatModelCatalogInitialized}),k=t.sessions.think(p,_.agentId),A=t.sessions.settingsPreview(p,_.agentId),j=k||A?{...n,...k?{thinkingLevel:k}:{},...A}:n;return{composerControls:W`
      <div class="chat-composer-model-control">
        ${pf({modelAuthStatusResult:t.modelAuthStatusResult,accountSelection:h,renderAccountSection:e=>Jd({owner:t,client:m,selection:h,modelAuthStatusResult:t.modelAuthStatusResult,model:e,disabled:!a.allowed||!t.connected||!e||n?.modelSelectionLocked===!0||t.chatLoading||t.chatSending||!!t.chatRunId||t.chatStream!==null||!!t.chatModelSwitchPromises[p],ownsSelection:()=>C()&&t.chatAccountSelection===h,onSelect:n=>a.allowed&&w({model:`${e}@${n.authProfileId}`})?Bx(t,`${e}@${n.authProfileId}`,p):Promise.resolve(!1),onManage:f,onRequestUpdate:()=>t.requestUpdate?.()}),activeRunId:t.chatRunId,activeRunSessionKey:Zf(t),modelObservedRunId:Op(t,n),agentDefaultModel:r,connected:t.connected,gatewayAvailable:!!t.client,loading:t.chatLoading,modelCatalog:t.chatModelCatalog,modelCatalogState:O,modelOverrides:t.sessions.state.modelOverrides,thinkingSession:j,fastModeTarget:j,contextWindowTarget:A?{...n??t.sessionsResult?.defaults,...A}:void 0,modelSelectionLocked:n?.modelSelectionLocked===!0,modelSelectionTarget:t.sessionsResult?.defaults.modelSelectionTarget,modelPickerOpen:t.chatModelPickerOpenSessionKey===t.sessionKey,modelSwitching:!!t.chatModelSwitchPromises[t.sessionKey],modelsLoading:t.chatModelsLoading,modelMutationDisabledReason:a.allowed?void 0:a.reason,effortMutationDisabledReason:o.allowed?void 0:o.reason,contextWindowMutationDisabledReason:s.allowed?void 0:s.reason,sending:t.chatSending&&t.chatSendingScopeKey===N({sessionKey:p,..._.agentId?{agentId:_.agentId}:{}}),sessionKey:t.sessionKey,selectedSession:n,sessionsResult:t.sessionsResult,stream:t.chatStream,onRequestUpdate:()=>t.requestUpdate?.(),onModelSetup:u,onProviderSettings:d,onFastModeSelect:(e,n)=>o.allowed&&w({fastMode:null},n)?Ix(t,e,n):Promise.resolve(!1),onContextWindowSelect:(e,n)=>s.allowed&&w({contextWindow:e},n)?Hx(t,e,n):Promise.resolve(!1),onModelPickerOpen:()=>eA(t),onModelPickerOpenChange:e=>{t.chatModelPickerOpenSessionKey=e?t.sessionKey:null,t.requestUpdate?.()},onModelSelect:(e,n,r)=>a.allowed&&w({model:e,agentRuntime:r},n)?Bx(t,e,n,r):Promise.resolve(!1),onThinkingSelect:(e,n)=>o.allowed&&w({thinkingLevel:e},n)?Vx(t,e,n):Promise.resolve(!1)})}
      </div>
    `,permissionPicker:{canSelectFull:l,defaultMode:i,disabled:!c.allowed,disabledReason:c.allowed?void 0:c.reason,mode:E?E.nextMode:n?.permissionMode,pending:D,onSelect:async e=>{let r=x.get(b);if(!c.allowed||!w({permissionMode:e})||n?.permissionModePending||r?.pending&&r.ownsSelection())return;let i={expectedSessionId:y,nextMode:e??void 0,ownsSelection:C,pending:!0},a=Symbol(b),o=Lj.get(t)??new Map;Lj.set(t,o),o.set(b,a);let s=()=>o.get(b)===a;x.set(b,i),t.requestUpdate?.();try{t.chatError=t.lastError=null;let n=await Cx(t,p,{permissionMode:e},{..._,expectedSessionId:y,canDispatch:()=>w({permissionMode:e})});if(!C())return;if(!n)throw Error(`Session capability is unavailable`);n.listRefreshError&&s()&&(t.chatError=t.lastError=R(`chat.permissionControls.refreshFailed`,{error:n.listRefreshError}))}catch(e){if(!S()||!s())return;let n=t.sessions.capturePermissionObservation(p,v),r=await t.sessions.reconcileMutation(v);if(!C()||!s())return;r.status!==`refreshed`&&(i.pending=!1,i.retainWhileCurrent=n),t.chatError=t.lastError=R(`chat.permissionControls.updateFailed`,{error:String(e)})}finally{s()&&o.delete(b),x.get(b)===i&&i.retainWhileCurrent===void 0&&x.delete(b),S()&&t.requestUpdate?.()}}}}}function Fj(e){let{state:t}=e,n=t.client,r=e.getSnapshot().hello?.auth?.recoveryScope??n?.recoveryScope,i=t.sessionKey,a=Q(t),o=a?.sessionId,s=L(t,i).agentId,c=t.chatRunId??null,l=c?void 0:a?.activeRunIds?.slice(),u=t.chatRunSessionAbortable===!0,d=()=>{let a=Q(t),d=e.getSnapshot(),f=d.hello?.auth?.recoveryScope??(d.phase!==`connected`||n?.recoveryScopeReady?n?.recoveryScope:void 0);return t.client===n&&d.client===n&&r===f&&t.sessionKey===i&&L(t,i).agentId===s&&(t.chatRunId??null)===c&&t.chatRunSessionAbortable===!0===u&&(!o||!a?.sessionId||a.sessionId===o)&&(!l||a?.activeRunIds?.length===l.length&&l.every(e=>a?.activeRunIds?.includes(e)))},f=()=>{let n=e.getSnapshot(),i=!!t.chatRunId,a=Xx(n,i,{session:Q(t),sessionAbortable:t.chatRunSessionAbortable===!0});return n.client&&i&&r&&!a.abort.allowed&&a.abort.cause===`disconnected`&&(a.abort={allowed:!0,requiredScope:`operator.write`}),a},p=f(),m=t=>{let n=f()[t];return n.allowed?!0:(e.onDenied(n.reason),!1)};return{onAbort:e.sessionParticipationBlocked||!p.abort.allowed?void 0:()=>{d()&&m(`abort`)&&e.onAbort()},onRewindMessage:p.rewind.allowed?t=>m(`rewind`)?e.onRewind(t):!1:void 0,onForkMessage:p.fork.allowed?t=>m(`fork`)?e.onFork(t):void 0:void 0}}var Ij,Lj;function Rj(){return(Rj=e((()=>{bi(),Pr(),H(),To(),Cs(),Tc(),se(),I(),B(),Zx(),Wx(),Dx(),iA(),Vw(),Sf(),kf(),ip(),Gm(),Ra(),Ij=new WeakMap,Lj=new WeakMap})))()}var zj;function Bj(){return(Bj=e((()=>{bi(),Ar(),H(),on(),B(),o(),$E(),yg(),n(),zj=class{constructor(e,t){this.host=e,this.readState=t,this.canWrite=!1,this.binding=null,e.addController(this)}hostDisconnected(){this.binding=null}isCurrent(e){let t=this.readState(),n=t&&ZE(t),r=n?.providerReview;return this.binding===e&&t===e.state&&t.connected&&t.client===e.client&&t.connectionEpoch===e.connectionEpoch&&t.client?.connectionGeneration===e.connectionGeneration&&t.sessionKey===e.sessionKey&&Dn(t)===e.agentId&&n?.sessionId===e.sessionId&&(!t.currentSessionId||t.currentSessionId===e.sessionId)&&r?.id===e.review.id&&r.runId===e.review.runId&&r.explanation===e.review.explanation&&r.continuationMessage===e.review.continuationMessage&&r.canContinue===e.review.canContinue}sync(e){if(this.canWrite=e,this.binding&&this.isCurrent(this.binding)){this.reconcileTerminalAttempt(this.binding);return}this.binding=null;let t=this.readState(),n=t&&ZE(t);t?.connected&&n?.sessionId&&n.providerReview&&(this.binding={state:t,sessionKey:t.sessionKey,sessionId:n.sessionId,agentId:Dn(t),client:t.client,connectionEpoch:t.connectionEpoch,connectionGeneration:t.client?.connectionGeneration,review:n.providerReview,open:!1,loading:!1,pending:!1,submitted:!1,refreshing:!1,error:null,idempotencyKey:p(),attemptedRunId:null})}reconcileTerminalAttempt(e){if(e.pending||e.refreshing||!e.attemptedRunId)return;let t=ZE(e.state);!t||t.lastRunId!==e.attemptedRunId||t.hasActiveRun!==!1||t.activeRunIds?.length||t.status!==`failed`&&t.status!==`timeout`&&t.status!==`killed`||this.recordFailedAttempt(e,t.lastRunError)}recordFailedAttempt(e,t){e.submitted=!1,e.attemptedRunId=null,e.idempotencyKey=p(),e.error=[R(`chat.providerReview.continuationFailed`),t?P(t):null].filter(Boolean).join(` `)}async open(e){if(this.isCurrent(e)&&!e.loading){e.loading=!0,this.host.requestUpdate();try{await M(()=>import(`./modal-dialog-BgQB7Fm_.js`),__vite__mapDeps([73,9]),import.meta.url),this.isCurrent(e)&&(e.open=!0)}catch(t){this.isCurrent(e)&&(e.error=P(t))}finally{this.isCurrent(e)&&(e.loading=!1,this.host.requestUpdate())}}}async acknowledge(e){if(this.isCurrent(e)&&e.open&&this.canWrite&&!e.pending&&!e.submitted&&e.review.canContinue&&e.review.explanation?.trim()&&e.review.continuationMessage?.trim()){if(!QE(e.state,e.sessionKey,e.agentId)){e.error=R(`chat.providerReview.queueHoldFailed`),this.host.requestUpdate();return}e.pending=!0,e.attemptedRunId=e.idempotencyKey,e.error=null,this.host.requestUpdate();try{let t=await e.client.request(`sessions.providerReview.continue`,{sessionKey:e.sessionKey,...e.agentId?{agentId:e.agentId}:{},sessionId:e.sessionId,reviewId:e.review.id,idempotencyKey:e.idempotencyKey});if(!this.isCurrent(e))return;let n=_g(t,e.idempotencyKey);if(vg(n)){this.recordFailedAttempt(e);return}e.attemptedRunId=n.runId,e.submitted=!0,await this.refresh(e)}catch(t){this.isCurrent(e)&&(e.error=P(t))}finally{this.isCurrent(e)&&(e.pending=!1,this.host.requestUpdate())}}}async refresh(e){if(this.isCurrent(e)&&e.submitted&&!e.refreshing){e.refreshing=!0,e.error=null,this.host.requestUpdate();try{let t=await e.state.sessions.reconcileMutation(e.agentId);this.isCurrent(e)&&t.status===`failed`&&(e.error=R(`chat.providerReview.refreshFailed`))}catch{this.isCurrent(e)&&(e.error=R(`chat.providerReview.refreshFailed`))}finally{this.isCurrent(e)&&(e.refreshing=!1,this.host.requestUpdate())}}}notice(){let e=this.readState(),t=e&&ZE(e)?.providerReview;if(!t)return G;let n=this.binding,r=!!t.explanation?.trim();return W`
      <div
        class="chat-composer-neighbor-card chat-composer-neighbor-card--warn chat-provider-review"
        role="alert"
      >
        <span class="chat-composer-neighbor-card__icon" aria-hidden="true"
          >${U.alertTriangle}</span
        >
        <div class="chat-composer-neighbor-card__copy">
          <strong
            >${R(t.canContinue?`chat.providerReview.pausedTitle`:`chat.providerReview.stoppedTitle`)}</strong
          >
          <span
            >${R(r?t.canContinue?`chat.providerReview.pausedBody`:`chat.providerReview.stoppedWithFindingsBody`:`chat.providerReview.stoppedBody`)}</span
          >
          ${n?.error&&!n.open?W`<span>${n.error}</span>`:G}
        </div>
        ${r?W`<button class="btn btn--sm" type="button" ?disabled=${!n||n.loading} @click=${()=>n&&void this.open(n)}>${R(`chat.providerReview.review`)}</button>`:G}
      </div>
    `}dialog(){let e=this.binding;if(!e?.open||!this.isCurrent(e))return G;let{review:t}=e,n=t.canContinue&&!!(t.explanation?.trim()&&t.continuationMessage?.trim()),r=()=>{this.isCurrent(e)&&(e.open=!1,this.host.requestUpdate())};return W`
      <openclaw-modal-dialog label=${R(`chat.providerReview.review`)} @modal-cancel=${r}>
        <section class="exec-approval-card chat-provider-review-dialog">
          <h2 class="exec-approval-title">
            ${R(n?`chat.providerReview.pausedTitle`:`chat.providerReview.stoppedTitle`)}
          </h2>
          <div class="chat-provider-review-dialog__content">
            ${n?W`
                    <h3>${R(`chat.providerReview.continuationTitle`)}</h3>
                    <p>${R(`chat.providerReview.continuationBody`)}</p>
                    <blockquote
                      class="chat-provider-review-dialog__text"
                      .textContent=${t.continuationMessage}
                    ></blockquote>
                  `:W`<p>${R(`chat.providerReview.noContinuation`)}</p>`}
            <h3>${R(`chat.providerReview.findings`)}</h3>
            <div class="chat-provider-review-dialog__text">${t.explanation}</div>
            <p>
              ${R(n?`chat.providerReview.queueHelp`:`chat.providerReview.queueStopped`)}
            </p>
            ${e.error?W`<p class="callout danger" role="alert">${e.error}</p>`:G}
            ${e.submitted&&!e.error?W`<p role="status">${R(e.refreshing?`chat.providerReview.checkingStatus`:`chat.providerReview.waiting`)}</p>`:G}
          </div>
          <div class="exec-approval-actions">
            <button type="button" class="btn" autofocus @click=${r}>
              ${R(`common.close`)}
            </button>
            ${e.submitted?W`<button type="button" class="btn" ?disabled=${e.refreshing} @click=${()=>void this.refresh(e)}>${R(e.refreshing?`chat.providerReview.checkingStatus`:`chat.providerReview.checkStatus`)}</button>`:G}
            ${n?W`<button type="button" class="btn primary" ?disabled=${!this.canWrite||e.pending||e.submitted} @click=${()=>void this.acknowledge(e)}>${R(e.pending&&!e.submitted?`chat.providerReview.continuing`:`chat.providerReview.acknowledge`)}</button>`:G}
          </div>
        </section>
      </openclaw-modal-dialog>
    `}}})))()}function Vj({state:e,questionState:t,canSend:n,isCurrent:r}){let i=e.sessionKey,a=e.connectionEpoch,o=()=>e.sessionKey===i&&e.connectionEpoch===a&&r();return{onGatewayQuestionChange:t.onChange,onGatewayQuestionSubmit:(e,n)=>qc(t,e,n),onGatewayQuestionSkip:e=>el(t,e),onAsyncQuestionSubmit:n?async(t,n,r)=>{if(!o())return!1;if(n&&e.chatQueue.some(e=>e.asyncQuestionItemId===n))return!0;let i=!1,a;try{a=await e.handleSendChat(t,{followUpMode:`steer`,asyncQuestionItemId:n,replyTargetOverride:r?{messageId:r,sourceMessageId:r,text:``}:null,onOutboxAdmitted:()=>{i=!0}})}catch(e){if(!i)throw e}if(!o())return!1;if(!i&&!a&&e.lastError)throw Error(e.lastError);return i||a===!0}:void 0}}function Hj(){return(Hj=e((()=>{wl()})))()}var Uj;function Wj(){return(Wj=e((()=>{bi(),kr(),Rr(),Pr(),Vr(),Ql(),jl(),ul(),H(),fs(),fa(),eo(),Jo(),Vc(),B(),tt(),sS(),Y(),ES(),jS(),Aj(),Gw(),Rj(),wS(),WE(),Bj(),Hj(),XE(),FC(),wy(),iA(),Vw(),qu(),Sd(),vp(),Lp(),Qm(),am(),Wp(),Uj=class extends kj{constructor(...e){super(...e),this.providerReview=new zj(this,()=>this.state??void 0),this.presentationUserId=null,this.emptyTranscriptItems=[],this.retrySessionPlacementStartup=()=>{let e=this.state?.sessionKey;e&&this.context.placementStartup.retry(e)}}render(){let e=this.state;if(!e)return W`<main class="app-shell app-shell--booting" aria-busy="true"></main>`;let t=this.connectionGeneration,n=Q(e),r=!!n?.providerReview,i=this.resolveChatReadTarget(),a=this.progressCardPresentation,o=this.isCurrentSessionArchived(e),s=Nj(this.context.gateway.snapshot,e.sessionKey,n),c=Is(e.observerDigest,Ns(n?.key??e.sessionKey,n?.observerDigest)),l=cs({localRunId:e.chatRunId,session:n,digest:c}),u=Dm(n?.placement),d=n?.placement,f=u&&this.dismissedWorkspaceConflictRefs.get(n?.key??e.sessionKey)!==u.stagedResultRef?u:void 0,p=this.resolveBoardView(),m=yS({board:p,layout:e.sidebarLayout,paneWidth:this.paneWidth});e.chatFollowUpMode=BE(e,n,this.context.runtimeConfig.state);let h=Z(e),{catalogKey:g,chatProps:_}=TS(e),v=g!==null,y=this.context?.overlays,b=this.context.agents.state.agentsList?.agents.find(e=>e.id===h),x=b?.model?.primary,{modelSetupRequired:S,modelUnavailableBanner:C,requiredReason:w}=DS({activeSession:n,chatModelCatalog:e.chatModelCatalog,modelOverrides:e.sessions.state.modelOverrides,sessionKey:e.sessionKey,sessionsResult:e.sessionsResult,catalog:v,connected:e.connected,agentsLoaded:this.context.agents.state.agentsList!==null,selectedAgentFound:b!==void 0,agentModel:x,modelSelectionPolicy:e.chatModelSelectionPolicy,catalogRetired:e.chatModelCatalogRetired,catalogInitialized:e.chatModelCatalogInitialized,catalogError:e.chatModelCatalogError,onSetup:()=>this.context.navigate(`model-setup`)}),T=this.context.placementStartup.get(e.sessionKey),E=_y(e,e.sessionKey,T!==null),D=Mh(e),O=this.sessionParticipationTracker.resolve({catalog:v,listLoading:e.sessionsLoading,sessionKey:`${h??``}\0${e.sessionKey}`,session:n}),k=this.context.gateway.snapshot,A=Mj(k,n,v),j=Ur(k.hello?.auth??null),ee=this.placementComposerPresentation(n,T!==null),te=e.connected&&!O&&j;this.providerReview.sync(te&&!o);let ne=n?.restartRecoveryStatus===`tombstoned`,M=this.hasMultipleIdentities(),re=M&&!o&&j&&n?.visibility===`suggest`&&n.sharingRole===`viewer`&&da(k,`session.suggestions.add`)===!0&&da(k,`session.suggestions.list`)===!0,ie=O&&!re?R(`chat.sessionSharing.readOnlyNotice`):null,ae=g||re?void 0:w,oe=M&&j&&!g&&da(k,`session.typing`)===!0&&za(this.presencePayload,k.selfUser,k.client?.instanceId,e.sessionKey),se=g&&!this.catalogLoading&&this.catalogSession?.canContinue!==!0?this.catalogHost?.kind===`node`?R(`chat.catalog.remoteViewOnly`):R(`chat.catalog.unsupportedViewOnly`):null,{closePanelSlot:ce,openPanelSlot:le,sessionWorkspace:N}=Ww({state:e,sidebarLayout:m,presentationId:this.presentationId,sessionTitle:this.resolveHeaderSessionTitle(n),paneLabel:this.paneLabel,presented:this.presented,gatewaySnapshot:k,setObserverVisibility:this.setSessionObserverVisibility,updateSidebarLayout:e=>this.commitSidebarLayout(e)}),ue=Jr({snapshotUser:k.selfUser,presenceEntries:vr(this.presencePayload),presenceInstanceId:k.client?.instanceId});ue?.identity?.type===`profile`&&(this.presentationUserId=ue.identity.id);let de=Ym({localRunId:e.chatRunId,activeRunIds:n?.activeRunIds,queue:e.chatQueue}),fe=g?!!this.catalogCursor:e.chatHistoryPagination.hasMore,pe=pp(e),me=Fj({getSnapshot:()=>this.context.gateway.snapshot,state:e,sessionParticipationBlocked:O,onDenied:e=>this.publishHeaderError(e),onAbort:()=>void e.handleAbortChat({preserveDraft:!0}),onRewind:e=>this.rewindToMessage(e),onFork:e=>this.forkFromMessage(e)}),he=t=>{e.chatReplyTarget=t,e.handleChatDraftChange(e.chatMessage),e.requestUpdate?.()},ge=this.currentReplyMessageAccess(e.sessionKey),_e=g?void 0:Pj({state:e,selectedSession:n,agentDefaultModel:x,agentDefaultPermissionMode:b?.defaultPermissionMode,modelAccess:s.model,effortAccess:s.effort,contextWindowAccess:s.contextWindow,permissionAccess:s.permission,canSelectFull:Hr(k.hello?.auth??null),onModelSetup:()=>this.context.navigate(`model-setup`),onProviderSettings:e=>im(this.context,h,e),onModelAccounts:()=>this.context.navigate(`profile`)}),ve=nf(this.presentationId),ye=qa(this.context.gateway).snapshot,be=this.captureConnectionScope(),xe=()=>{let t=Q(e);return t&&{...t,agentId:t.agentId??Z(e)??void 0,archived:this.isCurrentSessionArchived(e)}},Se=xe();if(!be||!Se||!da(k,`sessions.github.publish`))this.githubPublication?.detach(),this.githubPublication=null;else{this.githubPublication?.matches(Se)||(this.githubPublication?.detach(),this.githubPublication=this.context.sessions.githubPublication.attach(Se,()=>this.requestUpdate(),No));let t=this.githubPublication;t?.sync({canWrite:!o&&!O&&j,personalReady:!Em(e)&&(!sa(d?.state)||!!Se.repositoryWorkspaceId&&d?.state===`active`)&&!u,isPresented:()=>this.presented,isCurrent:()=>{let e=xe();return this.isConnectionScopeCurrent(be)&&e!==void 0&&t?.matches(e)}})}let Ce=this.sessionDisabledBanner({catalogDisabledReason:se,modelSetupRequired:S,restartRecoveryTombstoned:ne,selectedSessionArchived:o,selectedSessionId:n?.sessionId?.trim()||void 0,selectedSession:n,sessionKey:e.sessionKey,unarchiveAccess:s.unarchive}),we=!g&&oy(e),P=!r&&Ce?.kind!==`composer-replacement`&&(g?this.catalogSession?.canContinue===!0:!ie&&!(o||ne||ee.blocksSend)&&(!E||we)),Te={canCompose:A.canCompose&&P,canSend:A.canSend&&P,...zE(e,we),modelRequiredReason:ae,disabledReason:se??(A.canSend?null:R(`chat.sessionSharing.scopeReadOnlyNotice`))??ie??ee.busyMessage??(ee.state.kind===`failed`&&!ee.state.recoveryAction?ee.failedUnavailableMessage:null)??(e.connected&&(T||we)?null:E),disabledReasonTone:!A.canSend||ee.busyMessage||O&&!re?`info`:`danger`,disabledReasonBusy:ee.busyMessage!==null,disabledBanner:Ce??ee.disabledBanner??C},Ee=te&&Te.canSend&&!g&&!re&&a?this.captureProgressCardRefreshAction():void 0,De=ue?.identity?.type===`profile`?ue.identity.id:null,Oe=!!(g||re||n?.incognito||!De),{gatewayQuestionPrompts:ke,inlineApproval:Ae}=this.projectConversationAttention(e,h,!g&&!O),je={transcript:this.transcript,paneId:this.presentationId,sessionKey:e.sessionKey,announceTranscript:this.active&&this.presented,autoExpandToolCalls:e.chatVerboseLevel===`full`,showThinking:e.settings.chatShowThinking,showToolCalls:e.settings.chatShowToolCalls,persistCommentary:e.settings.chatPersistCommentary!==!1,loading:g?this.catalogLoading:e.chatLoading||!D&&E!==null&&T===null,routeLoadingSkeleton:this.routeLoadingSkeleton&&we,sending:T!==null&&T.phase!==`failed`||e.chatSending||this.recoveringSession||this.sessionSuggestionAddOperation!==void 0,placementStartup:T??ee.startup,onRetrySessionPlacementStartup:T?.retryable?this.retrySessionPlacementStartup:void 0,canAbort:!O&&Em(e),runActive:D,runStatus:e.chatRunStatus,startupStatus:NC(e.chatRunStartup),waitingApproval:e.waitingApprovalStatuses.size>0,compactionStatus:e.compactionStatus,fallbackStatus:e.fallbackStatus,providerPolicyNotice:g?null:e.providerPolicyNotice,providerReviewNotice:this.providerReview.notice(),progressCard:a?.card??null,progressCardIdentity:a?.identity,progressCardLifetime:a?.lifetime,gatewayScope:li(this.context.gateway),progressCardInitialLoading:this.progressCardInitialLoading,progressCardRefresh:Ee,collapseTaskProgress:e.settings.chatCollapseTaskProgress===!0,readingHistory:e.chatReadingHistory,onProgressManipulate:()=>{Xm(e),this.transcript.cancelScroll()},onDismissProgressCard:te?e=>void this.progressCard.dismiss(e).catch(()=>ct({message:R(`sessionProgressCard.dismissFailed`)})):void 0,gatewayQuestionPrompts:ke,asyncQuestionStorage:!g&&!re?this.chatState.composerPersistence.durableScope:null,...Vj({state:e,questionState:this.questionPromptState,canSend:Te.canSend&&!g&&!re&&e.connected,isCurrent:()=>this.state===e}),messages:g?this.catalogMessages:e.chatMessages,historyPagination:fe||this.loadingOlder?{hasMore:fe,loading:this.loadingOlder||(g?this.catalogLoading:e.chatLoading),onShowEarlier:()=>void this.loadOlderMessages()}:void 0,toolMessages:g?this.emptyTranscriptItems:e.chatToolMessages,guardianNotices:g?this.emptyTranscriptItems:e.guardianNotices,streamSegments:g?this.emptyTranscriptItems:e.chatStreamSegments,stream:g?null:e.chatStream,streamStartedAt:g?null:e.chatStreamStartedAt,runId:g?null:de,runUsageById:g?void 0:e.chatRunUsageById,assistantAvatarUrl:Bw(e),sendShortcut:e.settings.chatSendShortcut,followUpMode:e.chatFollowUpMode,draft:e.chatMessage,mentions:e.chatMentions,getMentions:()=>e.chatMentions??[],mentionsUnsupported:Oe,mentionDirectory:e.connected&&e.client&&!Oe&&!O?{client:e.client,ownerKey:JSON.stringify([e.connectionEpoch,De]),params:{sessionKey:e.sessionKey,agentId:h}}:void 0,modelCatalog:e.chatModelCatalog,modelSwitching:!!e.chatModelSwitchPromises[e.sessionKey],queue:e.chatQueue,queuedOutboxCount:e.chatQueue.filter(e=>!e.pendingRunId).length,realtimeTalkActive:e.realtimeTalkActive,realtimeTalkStatus:e.realtimeTalkStatus,realtimeTalkDetail:e.realtimeTalkDetail,realtimeTalkInputNotice:e.realtimeTalkInputNotice,realtimeTalkInputLevel:e.realtimeTalkInputLevel,realtimeTalkConversation:e.realtimeTalkConversation,realtimeTalkVideoStream:e.realtimeTalkVideoStream,realtimeTalkCameraDevices:e.realtimeTalkCameraDevices,realtimeTalkVideoCapable:e.realtimeTalkVideoCapable,realtimeTalkVideoPending:e.realtimeTalkVideoPending,realtimeTalkCameraError:e.realtimeTalkCameraError,connected:e.connected,offline:k.offlineStable,gatewayClient:e.client,composerHoldToRecord:e.settings.composerHoldToRecord,realtimeTalkInputDeviceId:e.settings.realtimeTalkInputDeviceId,onComposerHoldToRecordChange:t=>{e.settings=br({composerHoldToRecord:t})},onOpenTalkSettings:()=>this.context.navigate(`talk`),onOpenDictationSettings:()=>this.context.navigate(`model-setup`),suggestionComposer:re,typingActors:M?this.typingActorViews():[],typingOverflow:M?this.typingOverflow:void 0,onTypingChange:oe?(e,t)=>this.sendTypingState(e,t):void 0,...Te,modelSetupRequired:S&&!o&&!ne,onModelSetup:()=>this.context.navigate(`model-setup`),error:r?null:e.lastError,diskSpace:ee.diskSpace,workerRuntimeInstall:ee.workerRuntimeInstall,runError:g||r?null:e.chatRunError??ee.runError,inlineApproval:Ae,approvalBusy:y?.snapshot?.approvalBusy,approvalCanGrant:y?.snapshot?.approvalCanGrant??!1,approvalErrors:y?.snapshot?.approvalErrors,onApprovalDecision:y&&!O?(e,t)=>y.decideApproval(t,e,Ae??void 0):void 0,workspaceConflict:f,onDismissWorkspaceConflict:f&&n?()=>{this.dismissedWorkspaceConflictRefs.set(n.key,f.stagedResultRef),this.requestUpdate()}:void 0,sessions:e.sessionsResult,selectedSession:g?void 0:n,toolOverrides:n?.toolOverrides,capabilityMenu:g?void 0:this.composerCapabilities.props(this.context,e,n,h,ve.capabilityMenuView.startsWith(`tools:`),ve.capabilityMenuOpen&&(ve.capabilityMenuView===`skills`||ve.capabilityMenuView.startsWith(`library:`))),swarm:i?{...i,sessions:this.swarmHydrator?.rows??[]}:void 0,sessionHost:{assistantAgentId:e.assistantAgentId,agentsList:e.agentsList,hello:e.hello},providerUsage:{basePath:e.basePath,modelAuthStatusResult:e.modelAuthStatusResult},composerControls:_e?.composerControls??G,permissionPicker:_e?.permissionPicker,...this.suggestionChatProps(e.connected,o,M),pullRequests:this.visibleSessionPullRequests,githubRepo:ye.result?this.githubRepo:null,githubRepositories:ye.repositories,pullRequestsGateway:this.context.gateway,pullRequestsBranch:this.sessionPullRequestsBranch,pullRequestsStatus:this.sessionPullRequestsStatus,onOpenSessionDiff:N.onOpenDiff,onDismissPullRequest:this.dismissSessionPullRequest,githubPublication:this.githubPublication?.view(),onOpenWorkspaceFile:t=>Ff(e,t),onOpenSessionLink:e=>kl(this.context,e),onRevealWorkspaceFile:t=>Bf(e,t),onRefresh:this.refreshHistory,onChatScroll:e=>this.handleTranscriptScroll(e),onHistoryIntent:e=>this.handleTranscriptHistoryIntent(e),onAssistantAttachmentLoaded:()=>Np(e),getDraft:()=>e.chatMessage,onDraftChange:e.handleChatDraftChange,onRequestUpdate:e.requestUpdate,onHistoryKeydown:e.handleChatInputHistoryKey,onSlashIntent:()=>Uk(e),onSlashCommand:re||g?void 0:t=>void e.handleSendChat(t),showNewMessages:e.chatNewMessagesBelow,onScrollToBottom:e.scrollToBottom,...this.chatState.attachmentInputProps(e),cameraActive:this.conversationPresented,onRemoveAttachment:this.removeBrowserAnnotation,onSend:(t,n)=>!Te.canSend||ae&&(e.chatAttachments.length>0||!Sc(e.chatMessage))?void 0:g?this.continueCatalogSession(g):re?this.addCurrentSessionSuggestion():e.handleSendChat(void 0,t?{followUpMode:t}:void 0,n),onUseSystemDefaultMicrophone:e.realtimeTalkUseSystemDefault??void 0,onToggleRealtimeTalk:()=>{r||e.toggleRealtimeTalk()},onToggleRealtimeCamera:()=>void e.toggleRealtimeTalkCamera(),onSwitchRealtimeCamera:()=>void e.switchRealtimeTalkCamera(),onDismissError:()=>{RE(e),e.requestUpdate?.()},onDismissRealtimeTalkError:()=>{JE(e),e.requestUpdate?.()},onDismissRealtimeTalkInputNotice:()=>{e.realtimeTalkInputNotice=null,e.requestUpdate?.()},onAbort:me.onAbort,onQueueRemove:e.removeQueuedMessage,onQueueRetry:r?void 0:t=>void e.retryQueuedChatMessage(t),onQueueSteer:O||r?void 0:t=>void e.steerQueuedChatMessage(t),onQueueMove:O?void 0:e.moveQueuedChatMessage,queuedEdit:jj(e,O),goalRecovery:eS(e),onGoalAction:(t,n)=>void nS(e,{goalId:t,action:n}),goalDraftMode:e.chatGoalDraftMode??null,currentSessionId:e.currentSessionId,onGoalDraftModeChange:t=>{e.chatGoalDraftMode=t,e.handleChatDraftChange(e.chatMessage)},onGoalSubmit:re||g?void 0:(t,n)=>tS(e,t,n),onCompanionStageAttachment:(n,r)=>this.state===e&&this.connectionGeneration===t&&Z(e)===h&&this.stageSessionCompanionAttachment(n,r),replyTarget:e.chatReplyTarget??null,onClearReply:()=>he(null),onSetReply:Ce?void 0:he,replyMessageAccess:g||o?void 0:ge,onRewindMessage:o?void 0:me.onRewindMessage,onForkMessage:me.onForkMessage,agentsList:e.agentsList,currentAgentId:h,..._,onSessionSelect:e=>this.onPaneSessionChange?.(this.paneId,e),canvasPluginSurfaceUrl:e.canvasPluginSurfaceUrl,boardProvider:p.provider,onOpenSidebar:e.handleOpenSidebar,onRequestOpenImage:e.beginImageOpen,onOpenImage:e.handleOpenImage,assistantName:e.assistantName,assistantAvatar:e.assistantAvatar,senderAgentAvatars:e.senderAgentAvatars,mainKey:Lt({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello}),userId:this.presentationUserId,userName:ue?.name??e.userName,userAvatar:ue?.avatarUrl??e.userAvatar,personActivity:nu(this.context),mediaPolicyEpoch:e.mediaPolicyEpoch,connectionEpoch:e.connectionEpoch,embedSandboxMode:e.embedSandboxMode,allowExternalEmbedUrls:e.allowExternalEmbedUrls,fetchLinkFavicon:pe,chatMessageMaxWidth:e.settings.chatMessageMaxWidth,branding:this.context?.theme.branding,assistantAttachmentAuthToken:yr(e),resolveArtifactDownload:(t,n)=>LE(e,t,n),basePath:e.basePath,sessionPublicOrigin:zl(this.context),resourceBasePath:e.resourceBasePath};return W`${this.renderChatPaneLayout({state:e,selectedSession:n,currentAgentId:h,board:p,sidebarLayout:m,sessionWorkspace:N,chatProps:je,observerDigest:c,observerRunId:l,catalog:v,agentWorkspace:b?.workspace,workspaceGit:b?.workspaceGit===!0,openPanelSlot:le,closePanelSlot:ce})}${this.providerReview.dialog()}`}}})))()}function Gj(){return(Gj=e((()=>{Wj(),customElements.get(`openclaw-chat-pane`)||customElements.define(`openclaw-chat-pane`,Uj)})))()}export{Gx as $,X_ as $t,Pw as A,Dg as An,Py as At,jC as B,vg as Bn,hy as Bt,Jw as C,e_ as Cn,bb as Ct,Vw as D,q as Dn,Ry as Dt,Rw as E,t_ as En,Iy as Et,ZC as F,Cg as Fn,Ey as Ft,OS as G,Fv as Gt,AC as H,xy as Ht,JC as I,Ig as In,X as It,Zx as J,hv as Jt,hS as K,zv as Kt,Z as L,xg as Ln,Cy as Lt,uw as M,Tg as Mn,My as Mt,ow as N,Sg as Nn,ky as Nt,Q as O,Kg as On,Ny as Ot,ew as P,Eg as Pn,Ty as Pt,Yx as Q,Z_ as Qt,MC as R,Og as Rn,vy as Rt,Qw as S,$g as Sn,pb as St,Yw as T,Jg as Tn,nb as Tt,bC as U,Y as Ut,gC as V,_g as Vn,by as Vt,jS as W,J as Wt,qx as X,bv as Xt,Xx as Y,uv as Yt,Jx as Z,ov as Zt,OE as _,c_ as _n,Ib as _t,jO as a,N_ as an,px as at,CT as b,qg as bn,_b as bt,DO as c,v_ as cn,ux as ct,_O as d,m_ as dn,mx as dt,R_ as en,Dx as et,sO as f,p_ as fn,qb as ft,nD as g,Yg as gn,Fb as gt,lD as h,d_ as hn,Xb as ht,AO as i,H_ as in,fx as it,sw as j,kg as jn,Ay as jt,Sw as k,zg as kn,Fy as kt,TO as l,g_ as ln,Zb as lt,zD as m,f_ as mn,Yb as mt,tk as n,j_ as nn,ox as nt,EO as o,M_ as on,sx as ot,RD as p,u_ as pn,Wb as pt,fS as q,wv as qt,$O as r,F_ as rn,ax as rt,kO as s,P_ as sn,yx as st,Gj as t,Y_ as tn,Cx as tt,aO as u,y_ as un,cx as ut,vE as v,n_ as vn,Ab as vt,Xw as w,o_ as wn,Cb as wt,wT as x,Xg as xn,Sb as xt,bE as y,l_ as yn,Nb as yt,FC as z,yg as zn,wy as zt};