@rizom/brain 0.2.0-alpha.853 → 0.2.0-alpha.854
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brain.js +5 -5
- package/dist/chunks/{app-z9aj70dk.js → app-gs1my9sk.js} +2 -2
- package/dist/chunks/{index-6zrp0qqf.js → index-r24najdd.js} +2 -2
- package/dist/chunks/{index-5tn1r5ge.js → index-rwndt26q.js} +3 -3
- package/dist/chunks/{index-5tn1r5ge.js.map → index-rwndt26q.js.map} +1 -1
- package/dist/chunks/{package-502aw82e.js → package-cw1f875h.js} +3 -3
- package/dist/chunks/{package-502aw82e.js.map → package-cw1f875h.js.map} +1 -1
- package/dist/model.js +5 -5
- package/dist/model.js.map +3 -3
- package/dist/testing.js +1 -1
- package/dist/ui/{studio-app-f87685d9f5a3c8208ba58c13b00290661cc6d37f46aac1c8e30f8c8fc928eb50.css → studio-app-713f1653001bb6b165dcc0b1103a4a411524782217e79eddb0d251d16f4269d3.css} +7 -0
- package/dist/ui/{studio-app-5cpk1p7j.js → studio-app-h23yy6b7.js} +70 -70
- package/dist/ui/{studio-app-5cpk1p7j.js.map → studio-app-h23yy6b7.js.map} +3 -3
- package/dist/ui/studio-asset-manifest.json +39 -39
- package/dist/ui/studio-chunks/{account-view-8rtm4q64.js → account-view-1ypavank.js} +2 -2
- package/dist/ui/studio-chunks/{account-view-8rtm4q64.js.map → account-view-1ypavank.js.map} +1 -1
- package/dist/ui/studio-chunks/{chat-tmjeqy83.js → chat-074f46ar.js} +2 -2
- package/dist/ui/studio-chunks/{chat-tmjeqy83.js.map → chat-074f46ar.js.map} +1 -1
- package/dist/ui/studio-chunks/{highlighted-body-OFNGDK62-ehbpd06t.js → highlighted-body-OFNGDK62-h4be8w1a.js} +2 -2
- package/dist/ui/studio-chunks/{highlighted-body-OFNGDK62-ehbpd06t.js.map → highlighted-body-OFNGDK62-h4be8w1a.js.map} +1 -1
- package/dist/ui/studio-chunks/{main-aggt26f0.js → main-2p0znfdr.js} +3 -3
- package/dist/ui/studio-chunks/{main-aggt26f0.js.map → main-2p0znfdr.js.map} +1 -1
- package/dist/ui/studio-chunks/{main-nwgh1q48.js → main-6eh2h8nw.js} +3 -3
- package/dist/ui/studio-chunks/{main-nwgh1q48.js.map → main-6eh2h8nw.js.map} +1 -1
- package/dist/ui/studio-chunks/main-8q14xfsq.js +5 -0
- package/dist/ui/studio-chunks/{main-agdkrbww.js.map → main-8q14xfsq.js.map} +5 -5
- package/dist/ui/studio-chunks/{main-1mt3cyaa.js → main-9n0h1xh2.js} +5 -5
- package/dist/ui/studio-chunks/{main-1mt3cyaa.js.map → main-9n0h1xh2.js.map} +1 -1
- package/dist/ui/studio-chunks/{main-vzkqtry9.js → main-9vf4g1p7.js} +3 -3
- package/dist/ui/studio-chunks/{main-vzkqtry9.js.map → main-9vf4g1p7.js.map} +1 -1
- package/dist/ui/studio-chunks/{main-s08weg8b.js → main-cw0bfz5n.js} +3 -3
- package/dist/ui/studio-chunks/{main-s08weg8b.js.map → main-cw0bfz5n.js.map} +3 -3
- package/dist/ui/studio-chunks/{main-srtqh1ey.js → main-e9me2114.js} +2 -2
- package/dist/ui/studio-chunks/{main-srtqh1ey.js.map → main-e9me2114.js.map} +1 -1
- package/dist/ui/studio-chunks/{main-g8vsytt4.js → main-jrwrjge5.js} +3 -3
- package/dist/ui/studio-chunks/{main-g8vsytt4.js.map → main-jrwrjge5.js.map} +1 -1
- package/dist/ui/studio-chunks/{main-tynww570.js → main-sjvbdz9v.js} +2 -2
- package/dist/ui/studio-chunks/{main-tynww570.js.map → main-sjvbdz9v.js.map} +1 -1
- package/dist/ui/studio-chunks/{main-myms7tpb.js → main-tq0n1rdw.js} +3 -3
- package/dist/ui/studio-chunks/{main-myms7tpb.js.map → main-tq0n1rdw.js.map} +1 -1
- package/dist/ui/studio-chunks/{main-m9twkcja.js → main-xyyhtpga.js} +3 -3
- package/dist/ui/studio-chunks/{main-m9twkcja.js.map → main-xyyhtpga.js.map} +1 -1
- package/dist/ui/studio-chunks/mermaid-GHXKKRXX-bad6jrkg.js +3 -0
- package/dist/ui/studio-chunks/mermaid-GHXKKRXX-bad6jrkg.js.map +9 -0
- package/dist/ui/studio-chunks/{studio-ask-panel-p08h9ga3.js → studio-ask-panel-gydb5tgh.js} +2 -2
- package/dist/ui/studio-chunks/{studio-ask-panel-p08h9ga3.js.map → studio-ask-panel-gydb5tgh.js.map} +1 -1
- package/dist/ui/studio-chunks/{studio-chat-workspace-z58fbq5h.js → studio-chat-workspace-mxr1a4b2.js} +2 -2
- package/dist/ui/studio-chunks/{studio-chat-workspace-z58fbq5h.js.map → studio-chat-workspace-mxr1a4b2.js.map} +1 -1
- package/package.json +1 -1
- package/dist/ui/studio-chunks/main-agdkrbww.js +0 -5
- package/dist/ui/studio-chunks/mermaid-GHXKKRXX-2w11scmw.js +0 -3
- package/dist/ui/studio-chunks/mermaid-GHXKKRXX-2w11scmw.js.map +0 -9
- /package/dist/chunks/{app-z9aj70dk.js.map → app-gs1my9sk.js.map} +0 -0
- /package/dist/chunks/{index-6zrp0qqf.js.map → index-r24najdd.js.map} +0 -0
package/dist/model.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunks/index-6zrp0qqf.js";import{$ as wo,$a as j8r,$b as vkr,$c as Vkr,Aa as Ax,Ab as uU,Ad as b5r,Ba as fhi,Bb as lkr,Bd as M6,C as Cy,Ca as xhi,Cb as ukr,Cc as cgi,Cd as E5r,D as FSr,Da as b8r,Db as Gv,Dd as v5r,E as rhi,Ea as E8r,Eb as bhi,Ed as A5r,F as mhi,Fa as Yre,Fb as sU,Fd as Iy,G as GSr,Ga as v8r,Gb as dkr,Gd as lU,H as WSr,Hb as pkr,Hd as w5r,I as ZSr,Ia as aTe,Ib as mkr,Id as S5r,J as VSr,Ja as A8r,Jb as hkr,Jd as k5r,K as KSr,Ka as w8r,Kd as B5r,La as S8r,Lb as Ehi,Ld as C5r,M as Xre,Ma as k8r,Mb as vhi,Md as D5r,Na as B8r,Nb as Ahi,Nd as I5r,Oa as C8r,Ob as whi,Od as _5r,P as N6,Pa as D8r,Pb as Shi,Pd as T5r,Q as Ymi,Qa as ghi,Qb as khi,Qd as toe,R as O6,Ra as I8r,Rb as Bhi,Rc as Phi,Rd as xTe,S as By,Sa as _8r,Sb as Chi,Sc as zkr,Sd as P5r,Ta as T8r,Tb as Dhi,Tc as Ukr,Td as cTe,U as hTe,Ua as P8r,Ub as Ihi,Uc as qkr,Ud as R5r,V as YSr,Va as R8r,Vb as fkr,Vc as $kr,Vd as mh,W as Vt,Wa as F8r,Wb as xkr,Wc as F6,Wd as Ire,Xa as M8r,Xb as gkr,Xc as Hkr,Xd as F5r,Y as hhi,Ya as O8r,Yb as ykr,Yc as Gkr,Z as JSr,Za as N8r,Zb as bkr,Zc as Wkr,_ as QS,_a as L8r,_b as Ekr,_c as Zkr,aa as t8,ab as z8r,ac as Akr,ad as Kkr,ba as ll,bb as U8r,bc as wkr,bd as Ykr,ca as QSr,cb as q8r,cc as Skr,cd as Jkr,da as XSr,db as XS,dc as kkr,dd as Qkr,ea as e8r,eb as $8r,ec as Bkr,ed as Xkr,fa as t8r,fb as nTe,fc as Ckr,fd as e5r,ga as i8r,gb as H8r,gc as Dkr,gd as t5r,ha as n8r,hb as G8r,hc as Ikr,hd as i5r,ia as r8r,ib as W8r,ic as _kr,id as n5r,ja as o8r,jb as Z8r,jc as rTe,jd as r5r,ka as s8r,kb as V8r,kc as cU,kd as o5r,la as a8r,lb as K8r,lc as Tkr,ld as s5r,ma as c8r,mb as Y8r,mc as Pkr,md as a5r,na as l8r,nb as J8r,nc as Rkr,nd as c5r,oa as u8r,ob as Q8r,oc as Fkr,od as l5r,pa as d8r,pb as X8r,pc as Mkr,qa as p8r,qb as ekr,qc as Okr,qd as u5r,ra as m8r,rb as tkr,rc as Nkr,rd as d5r,sa as h8r,sb as ikr,sc as _hi,sd as p5r,ta as p_e,tb as nkr,tc as Thi,td as ehi,ua as f8r,ub as rkr,uc as Kmi,ud as m5r,va as x8r,vb as okr,vc as Lkr,vd as h5r,wa as g8r,wb as yhi,wc as jkr,wd as f5r,xa as y8r,xb as skr,xc as fTe,xd as x5r,ya as iTe,yb as akr,yd as g5r,za as hU,zb as ckr,zd as y5r}from"./chunks/index-fhmc36f3.js";import{$d as u8i,Yd as PT,Zd as q8i,be as UMe}from"./chunks/index-a7826mse.js";import{de as TV}from"./chunks/index-27h92m2e.js";import"./chunks/index-e84v85w3.js";import"./chunks/index-e0qz6mam.js";import"./chunks/index-624fhq2j.js";import"./chunks/index-z0k97qgd.js";import"./chunks/index-x8e40qwv.js";import{ie as xk}from"./chunks/index-5tn1r5ge.js";import{$e as Ytt,Ce as GYe,De as HNi,Ee as NUi,Fe as Xg,Ge as bX,He as u$,Ie as KSi,Je as Vy,Ke as hOi,Le as DT,Me as iji,Ne as ZSi,Oe as YSi,Pe as vOi,Qe as dOi,Re as DEt,Se as v$i,Te as ZWe,Ue as VWe,Ve as KWe,We as fSi,Xe as bT,Ye as pOi,Ze as Zf,_e as IT,af as IEt,if as eZ,ke as Hfe,le as oR,ne as Io,oe as m5,pe as PEe,qe as OEe,re as IE,se as xK,te as gK,ue as yK,ve as Prt,we as bK,xe as S4,ye as wst,ze as bs}from"./chunks/index-4mqgq4bb.js";import{lf as K0e,mf as QVi}from"./chunks/index-7f3ccxrq.js";import"./chunks/index-kz9a2wvt.js";import{$f as Ust,$g as CR,$h as Ys,$l as yg,$n as _vt,Af as Qw,Ag as km,Ah as Ur,Ai as J_,Aj as ZVi,Ak as P0e,Al as $xe,Am as LZi,Ao as Ew,Bf as xt,Bg as A0,Bh as WX,Bi as Q_,Bj as EZi,Bk as bw,Bl as Yn,Bo as W0e,Cf as XK,Cg as ji,Ch as fAt,Ci as z8e,Cj as vZi,Ck as Yb,Cl as Hxe,Cn as H0e,Co as fYe,Df as zl,Dg as Ds,Dh as w2,Di as h8i,Dj as AZi,Dk as Pk,Dl as Gxe,Do as Z0e,Ef as $at,Eg as ho,Eh as ND,Ei as Ea,Ej as wZi,Ek as gR,El as Bm,Eo as gw,Ff as yM,Fg as gu,Fh as GX,Fi as $ot,Fj as SZi,Fk as R0e,Fl as Ut,Fn as Ogi,Fo as $h,Gf as bM,Gg as Zb,Gh as iAt,Gi as Oxe,Gj as VVi,Gk as EZ,Gl as tE,Gn as Ngi,Go as V0e,Hf as gi,Hg as y0e,Hh as k2,Hi as qT,Hj as qZi,Hk as F0e,Hl as oo,Hn as NX,Ho as vR,If as O4,Ig as b0e,Ih as Yl,Ii as kB,Ij as $Zi,Ik as M0e,Il as Fo,Im as SA,In as Pvt,Io as hNi,Jf as eY,Jh as X1,Ji as zae,Jj as ZZi,Jk as O0e,Jl as Vw,Jm as f8,Jn as Rvt,Kf as tM,Kh as aL,Ki as Uae,Kj as tVi,Kk as MC,Kl as bR,Km as u2i,Kn as cVi,Lg as _xe,Lh as Q1,Li as aR,Lj as iVi,Lk as N0e,Ll as Dr,Lm as e2i,Ln as lVi,Mf as Jw,Mg as pr,Mh as lx,Mi as qWe,Mj as nVi,Ml as dt,Mm as Q5i,Mn as Fvt,Nf as zEe,Ng as Nr,Nh as o5e,Ni as uk,Nj as Ghe,Nk as L0e,Nm as $Ni,Nn as Mvt,No as vw,Of as tY,Og as REt,Oh as pAt,Oi as GFe,Oj as JVi,Ol as eNi,Om as zyi,On as Dke,Oo as RE,Pf as ys,Pg as Txe,Ph as dAt,Pj as YZi,Pk as Cr,Pm as Fyi,Pn as vvt,Po as Gh,Qf as ri,Qh as ire,Qi as Zw,Qj as cZi,Ql as Rn,Qm as Uyi,Qn as Bvt,Qo as xg,Rf as Qe,Rg as wR,Rh as yAt,Ri as jKe,Rl as sLi,Rm as XU,Rn as nL,Ro as rbi,Sf as Lo,Sg as Lk,Sh as Wvt,Si as iht,Sk as Jb,Sl as sG,Sm as dle,Sn as Ovt,So as na,Tf as ea,Tg as RC,Th as Zvt,Ti as nht,Tk as j0e,Tl as rLi,Tm as TT,Tn as rL,Uf as of,Ug as SR,Uj as ow,Ul as U0e,Um as bce,Un as pZi,Vf as LEe,Vg as kR,Vh as HX,Vj as Tk,Vl as Vi,Vm as I$,Vn as xPe,Wg as Pxe,Wh as bAt,Wj as E0e,Wm as wce,Wn as Cvt,Xf as jst,Xg as Xb,Xh as u5e,Xj as gg,Xm as r2i,Xn as Dvt,Yf as zst,Yg as BR,Yk as yR,Ym as a2i,Yn as p8,Zg as jk,Zh as DNi,Zk as z0e,Zl as Qb,Zm as d2i,Zn as Ivt,_g as zk,_l as ft,_n as UX,ag as qst,ah as DR,aj as Kb,ak as FC,am as Is,ao as IZi,bh as Rxe,bk as v0e,bl as lZi,bm as Gmt,bo as Nvt,cg as $st,ch as NC,ci as Vb,ck as A0e,cm as Dl,co as Hvt,dh as ww,di as Fxe,dk as w0e,dm as ER,do as _Zi,eh as Vh,ek as S0e,em as q0e,en as lme,eo as DZi,fh as eE,fi as Uk,fk as xR,fl as kEi,fm as $0e,fn as bf,fo as Avt,gh as Bw,gj as V$i,gk as k0e,gl as Zse,gm as zt,go as Loe,hh as R1,hk as B0e,hl as Ugi,hm as fg,ho as GU,ih as tOi,ii as yc,ik as C0e,il as tZ,im as qoe,io as Agi,jh as lct,ji as Mxe,jk as D0e,jm as $oe,jo as Cm,kh as Mve,kk as I0e,km as HYe,ko as Zk,lk as _0e,ll as Am,lm as Do,ln as uZi,lo as iE,mg as J$i,mi as hR,mk as T0e,mm as Or,mn as dZi,mo as nE,nh as Hoe,ni as yw,nj as rw,nl as _l,nm as mNi,nn as qX,no as rE,og as Q$i,oh as Goe,oi as Cw,oj as NZi,ol as Nxe,om as xs,on as Lvt,oo as Il,pf as Dxe,pg as Z8i,ph as ZU,pi as Z_,pj as mVi,pl as Lxe,pn as jvt,po as G0e,qf as Ixe,qh as VU,qi as HWe,qj as oKe,ql as jxe,qn as zvt,qo as Fk,rf as x0e,rh as O7e,ri as LKe,rj as HVi,rk as k0,rl as zxe,rn as OD,ro as vZ,sf as Uc,sh as jgi,si as nHi,sj as GVi,sk as qk,sl as Uxe,sn as oL,tf as _k,th as M7e,ti as kX,tj as Yq,tk as $k,tl as qxe,tm as eL,uf as g0e,uh as tB,ui as Xse,uj as d0,uk as _Z,ul as Gk,um as Evt,un as REe,uo as Mk,vf as PC,vi as qme,vj as X9,vl as IR,vm as OX,vo as Ok,wf as et,wh as yo,wi as eae,wj as XZi,wk as Hk,wl as Wk,wm as efe,wn as Hh,xf as Bi,xg as yu,xh as gAt,xi as Dpe,xj as eVi,xl as ya,xm as tfe,yg as mR,yh as Ie,yi as wX,yj as Whe,yl as Xo,zf as xe,zg as cn,zh as cx,zi as lk,zj as WVi,zl as _R}from"./chunks/index-x7qrfd1q.js";import{$o as xn,$p as kVi,$q as Ude,$r as cG,$s as S9,$t as wm,Ap as Lhe,Aq as OYe,As as YVi,At as uc,Bp as zWi,Bq as rZ,Bs as Ese,Bt as G_,Cp as Kki,Cq as fZ,Cr as ANi,Cs as She,Ct as nt,Dp as UWi,Dq as xZ,Dr as Yw,Ds as Ope,Dt as Lu,Ep as ROe,Eq as NF,Er as aq,Es as V7,Et as eKe,Fp as FOe,Fs as vHe,Ft as gd,Gp as k$,Gq as xme,Gs as wHe,Gt as bu,Hp as MOe,Hq as lwi,Hs as PLi,Ht as We,Ip as Yki,Iq as ds,Is as cLi,Jp as OOe,Jq as DUi,Js as RLi,Kp as Jki,Kq as S1i,Kr as rle,Ks as lLi,Kt as fR,Lp as Qki,Lq as d8,Lr as ZT,Ls as mLi,Lt as y0,Mp as ele,Mq as Iyi,Mr as Koe,Ms as vse,Mt as Wfe,Np as tle,Nq as F_,Nr as xse,Ns as aD,Op as Xki,Oq as Bae,Or as In,Os as yse,Ot as Kfe,Pp as ile,Pq as Bzi,Pr as Y$i,Ps as XJ,Qp as vi,Qq as Czi,Qr as yHi,Qs as eQ,Rp as h5,Rq as QJ,Rr as DK,Rs as Qoe,Sp as Ht,Sr as IEi,Ss as Hmt,To as n5i,Tp as Ix,Tq as Uat,Tr as gse,Uo as rhe,Up as AK,Uq as qat,Ur as a0,Us as jwi,Vp as tm,Vq as Qst,Vs as M8e,Wo as Br,Wp as jy,Wq as Xst,Wr as z7,Xo as $f,Xp as Zr,Xq as $mt,Xr as cle,Xs as XEi,Yo as Bse,Yp as qhe,Yq as Ar,Yr as SG,Ys as wA,Zq as Ad,Zr as gme,Zs as BOi,_o as ki,_p as SVi,_q as Z8,_r as _Ge,_s as lpe,_t as gp,ap as U_,ar as aFi,as as lG,at as aB,au as xd,bp as G9,br as qde,bs as VG,bt as S5i,cp as nhe,cq as kP,cr as UEe,cs as OGi,ct as fle,dp as N9,dr as VK,ds as KG,dt as Gfe,ep as WH,es as _se,et as Uoe,fp as RX,fr as K1,fs as Lbi,ft as I_,fu as Rk,gp as ka,gq as pR,gr as he,gs as zbi,gt as ygi,hp as EA,hq as Azi,hs as Tse,ht as $m,ip as L9,ir as eo,is as qpe,it as M1,jp as k$e,js as $Li,jt as ga,kq as $Vi,ks as Xpe,kt as iSi,lp as nle,ls as eme,lt as om,mp as bA,mq as Tzi,mr as bi,ms as Wbi,mt as Mt,np as Yce,nq as ust,nr as D4,ns as Ubi,nt as Y_,op as Jce,or as RVi,os as qbi,ot as LC,pp as LWi,pq as m0e,pr as TC,ps as Y1,pt as yd,qp as Xae,qq as dZ,qr as fse,qs as pyi,qt as gc,rp as UB,rq as pZ,rr as AX,rt as V1,sp as Obe,sq as mZ,sr as CD,ss as Npe,st as fo,tp as Xce,tq as hZ,ts as XNi,tt as Of,up as qB,uq as yZ,us as eLi,ut as Uwi,vp as Qce,vq as bZ,vr as Fae,vs as F1,vt as zgi,wp as _8,wq as Ik,wr as uAi,ws as whe,wt as fT,xp as Hki,xq as HKe,xr as Igi,xs as ase,xt as Rx,yp as Gki,yq as MYe,yr as zoe,ys as cse,yt as dvt,zp as jWi,zq as hg,zr as joe,zs as lKe,zt as Dw}from"./chunks/index-w2hsw2bk.js";import{hu as $$e,ju as nZ}from"./chunks/index-srfy20t3.js";import{Cy as xc,Mz as $X,QB as tt,Ry as Ks,XB as Gvt,_v as rke,cC as qh,dC as W4,fC as zc,hC as rm,iC as Evi,jC as Qn,kC as KVi,oy as xu,qy as Z4}from"./chunks/index-k9a6e379.js";import{CD as u}from"./chunks/index-tf89v3fj.js";import"./chunks/index-jhg1vjf7.js";import{GD as ao,HD as crn,ID as E,JD as Kh,KD as gs,LD as ce}from"./chunks/index-fvb55vgy.js";function FQe(e){return e===0||e>=55296&&e<=57343||e>1114111}function MQe(e){if(FQe(e))return 65533;if(e>=128&&e<=159)return qXi[e-128]||e;return e}function OQe(e){return FQe(e)?65533:e}var qXi;var NQe=gs(()=>{qXi=[8364,0,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,0,381,0,0,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,0,382,376]});function LQe(e,t,i,n,r,o){let a=e.length,c=o*90,l=0,d=()=>{let L=C0[e.charCodeAt(l++)];return L<o?L:L*91-c+C0[e.charCodeAt(l++)]},p=i-n,m=i+r,h=new Int32Array(m);h.fill(-1,n,o),h.fill(-1,o+p,m);let f=new Int32Array(m),g=new Int32Array(m);function y(L,G){let V=0,ee=G,q=G+L;while(ee<q){let S=C0[e.charCodeAt(l++)];if(S<89)V+=S,h[ee++]=V;else if(S===89){let P=C0[e.charCodeAt(l++)]+2;while(P--)h[ee++]=++V}else{let P=C0[e.charCodeAt(l++)];V+=89+(P<90?P*91+C0[e.charCodeAt(l++)]:C0[e.charCodeAt(l++)]*8281+C0[e.charCodeAt(l++)]*91+C0[e.charCodeAt(l++)]),h[ee++]=V}}}y(n,0),y(p,o);let b=new Int32Array(r*2),v=0,w=0;function B(L,G){for(let V=0;V<L;V++){let ee=G+V,q=d(),S=d();b[w*2]=q,b[w*2+1]=S,w+=1,f[ee]=v;let P=(h[q]<0?g[q]:1)+(h[S]<0?g[S]:1);g[ee]=P,v+=P}}B(r-o+n,o+p),B(o-n,n);let T=new Uint16Array(v),F=0;for(let L=0;L<w;L++)for(let G=0;G<2;G++){let V=b[L*2+G],ee=h[V];if(ee<0){let q=f[V],S=q+g[V];while(q<S)T[F++]=T[q++]}else T[F++]=ee}let k=new Uint16Array(t),N=0;while(l<a){let L=C0[e.charCodeAt(l++)];if(L>=o)L=L*91-c+C0[e.charCodeAt(l++)];let G=h[L];if(G<0){let V=f[L],ee=V+g[L];while(V<ee)k[N++]=T[V++]}else k[N++]=G}return k}var C0;var jQe=gs(()=>{C0=(()=>{let e=new Uint8Array(127),t=0;for(let i=33;i<=126;i++)if(i!==34&&i!==36&&i!==92)e[i]=t++;return e})()});var wge;var zQe=gs(()=>{jQe();wge=LQe("!}.&u%}'&}*'~!6*)%&,~!J~!J~%L~y<~!R,~~%Lu~~#GD~~#|)1#%}^%}2%+#.##%##%}&%##%'#%##&%#%#'%#&#%#&#'#%%#&#%##%#)%''%&%#%#'%#%%#%%}%%%#%#&(23#%%#&-%0%('1#(##%#'##+%'*.:1}#%#6-+(%'%%#%%%}#L'2351&('%}&/N'(0(/*-%(%%}#'+&T%7.2}#&%&#%#36/5##%&%%#&#%%#))2%%##%&&'0~!#*+&'%1~!%).'3q?&%'1~!.##%6(~!+%%%(Gw'rT~!E#<nA%#jZ~!H%(~!42##~!*31&~!G%U~#)5~#`3~!J~!Z~%]~%Y~%C~!q~!u~#kz~%#~!6'~!D~!U~!?~#T~!c%~!G#'~%7|~!G~!J~!G&~#pb~(Df}#%}*&}#%##%##%##&#-}&'#'&%#.++}%mI,#,@&(}*%}*'%&##&#%##%}&0}#.},U},%}+%}&%}#%##&}B%(}(%}+%)})%##%#&}&%##%&}<%}>%#%&}*%}(%}9%}/%})%}*%}*%}?&}&%}3%}&*#%})%#%#)}#&#-#+*%E%%'%'#%}#*V##&##I}#&&##%&%#&&Qf%%))w/0+&%#(#.%-''''++++7}>%4'',##1,#%#&%##&#'##&#*#9)%&%}#*}%,#+P(%A&%#'&##wSD',9E00#y#@}(+}&%&>~!#~!X}#*}(&&}(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Eg>unwfh;9:4E|YjQsBt|vjx'hYq3!(?C2F|J:2<BaY?C2F|GOu!5x,g|p{ah!-(?C2F|c9:4E|OjXuvvNr}:Rh&i[w*t|cd+U#jJvsu)vsSn~Mkfrmu9p}u7vwv]So!McW#Xa!ax5@A5aY:5;5<H|>kJv~vYrquJu3x4ib#T)2@SmZM?C2F|Bj:rmu9@xPhI(a*a#U#`a3-5Abb|L~@:RhK9:4E|0@52B5G|#C::aY?C2F|-:2<BaY?C2F|.5Jvk!a)javYrquJu3x4ia#T)2@SmYM?C2F|HAxPhH(!a#U#`a*-5Abb|4~@:RhJ9:4E|R@52B5G|F:2<BaY?C2F|Sc^#Xa2j=Qq5CJvB!-g<v{z;hhM?C2F|Zi[vrv{z;hiM?C2F|XKsA>!a)-g<v{z;h[eb?C2F|]i[vrv{z;h]eb?C2F|^iZu.vix,hZq3ah!.(?C2F|QOu!5ShXM:2<BaY?C2F|P",13494,2713,49,25,61)});var HR;var Sge=gs(()=>{HR=new Uint16Array([512,26465,29036,7,0,2,4,116,24638,116,24636,8693,29807,24610,621,1,0,0,3,112,24614,111,115,24615])});var Hc;var UQe=gs(()=>{(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.FLAG13=8192]="FLAG13",e[e.BRANCH_LENGTH=8064]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE",e[e.VALUE_MASK=8191]="VALUE_MASK"})(Hc||(Hc={}))});function qQe(e){return e-vu.ZERO>>>0<=9}function $Xi(e){return(e|qZ)-vu.LOWER_A>>>0<=5}function HXi(e){return(e|qZ)-vu.LOWER_A>>>0<=25}function GXi(e){return e===vu.EQUALS||HXi(e)||qQe(e)}class kge{decodeTree;emitCodePoint;errors;state=Eu.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=D0.Strict;runConsumed=0;constructor(e,t,i){this.decodeTree=e,this.emitCodePoint=t,this.errors=i}startEntity(e){this.decodeMode=e,this.state=Eu.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case Eu.EntityStart:{if(e.charCodeAt(t)===vu.NUM)return this.state=Eu.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=Eu.NamedEntity,this.stateNamedEntity(e,t)}case Eu.NumericStart:return this.stateNumericStart(e,t);case Eu.NumericDecimal:return this.stateNumericDecimal(e,t);case Eu.NumericHex:return this.stateNumericHex(e,t);default:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){if(t>=e.length)return-1;if((e.charCodeAt(t)|qZ)===vu.LOWER_X)return this.state=Eu.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=Eu.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){let i=e.length,{result:n}=this,{consumed:r}=this;while(t<i){let o=e.charCodeAt(t);if(qQe(o)||$Xi(o)){let s=o<=vu.NINE?o-vu.ZERO:(o|qZ)-vu.LOWER_A+10;n=n*16+s,r+=1,t+=1}else return this.result=n,this.consumed=r,this.emitNumericEntity(o,3)}return this.result=n,this.consumed=r,-1}stateNumericDecimal(e,t){let i=e.length,{result:n}=this,{consumed:r}=this;while(t<i){let o=e.charCodeAt(t)-vu.ZERO;if(o>>>0>9)return this.result=n,this.consumed=r,this.emitNumericEntity(o+vu.ZERO,2);n=n*10+o,r+=1,t+=1}return this.result=n,this.consumed=r,-1}emitNumericEntity(e,t){if(this.consumed<=t)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===vu.SEMI)this.consumed+=1;else if(this.decodeMode===D0.Strict)return 0;if(this.emitCodePoint((this.decodeTree===HR?OQe:MQe)(this.result),this.consumed),this.errors){if(e!==vu.SEMI)this.errors.missingSemicolonAfterCharacterReference();this.errors.validateNumericCharacterReference(this.result)}return this.consumed}flushAndEmitLegacyOrReject(e,t,i,n){return this.consumed=e,this.excess=t,this.result===0||this.decodeMode===D0.Attribute&&(n===0||t>1||GXi(i))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:i}=this,n=e.length,r=this.decodeMode===D0.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=i[o];while(t<n){while((c&(Hc.VALUE_LENGTH|Hc.FLAG13))===0&&(c&Hc.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&Hc.JUMP_TABLE,f=(c&Hc.BRANCH_LENGTH)>>7;if(f===0){if(m!==h)return this.flushAndEmitLegacyOrReject(a,s,m,0);o+=1}else{let g=m-h;if(g>>>0>=f)return this.flushAndEmitLegacyOrReject(a,s,m,0);let y=i[o+1+g];if(y===0)return this.flushAndEmitLegacyOrReject(a,s,m,0);o=o+f+y&65535}if(c=i[o],t+=1,s+=1,t>=n)break}if(t>=n)break;if((c&(Hc.VALUE_LENGTH|Hc.FLAG13))===Hc.FLAG13){let m=(c&Hc.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&Hc.JUMP_TABLE))return this.flushAndEmitLegacyOrReject(a,s,f,0);t+=1,s+=1,h=1}while(h<m){if(t>=n)return this.treeIndex=o,this.excess=s,this.consumed=a,this.runConsumed=h,-1;let f=h-1,y=i[o+1+(f>>1)]>>((f&1)<<3)&255,b=e.charCodeAt(t);if(b!==y)return this.runConsumed=0,this.flushAndEmitLegacyOrReject(a,s,b,0);t+=1,s+=1,h+=1}this.runConsumed=0,o+=1+(m>>1),c=i[o];continue}let l=c>>>14,d=e.charCodeAt(t);if(l!==0){if(!r&&(c&Hc.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===vu.SEMI)return this.emitNamedEntityData(o,l,a+s);if(l===1)return this.flushAndEmitLegacyOrReject(a,s,d,l)}let p=WXi(i,c,o+(l||1),d);if(p<0)return this.flushAndEmitLegacyOrReject(a,s,d,l);o=p,c=i[o],t+=1,s+=1}if(!r&&c>>>14!==0&&(c&Hc.FLAG13)===0)this.result=o,a+=s-1,s=1;return this.treeIndex=o,this.excess=s,this.consumed=a,-1}emitNotTerminatedNamedEntity(){let{result:e,decodeTree:t}=this,i=t[e]>>>14;return this.emitNamedEntityData(e,i,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,i){let{decodeTree:n}=this;if(this.emitCodePoint(t===1?n[e]&Hc.VALUE_MASK:n[e+1],i),t===3)this.emitCodePoint(n[e+2],i);return i}end(){switch(this.state){case Eu.NamedEntity:return this.result!==0&&(this.decodeMode!==D0.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Eu.NumericDecimal:return this.emitNumericEntity(0,2);case Eu.NumericHex:return this.emitNumericEntity(0,3);case Eu.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function WXi(e,t,i,n){let r=(t&Hc.BRANCH_LENGTH)>>7,o=t&Hc.JUMP_TABLE;if(o){if(r===0)return n===o?i:-1;let c=n-o;if(c>>>0>=r)return-1;let l=e[i+c];return l===0?-1:i+r+l-1&65535}if(r===0)return-1;let s=r+1>>1,a=i+s+r;for(let c=0;c<r;c++){let d=e[i+(c>>1)]>>((c&1)<<3)&255;if(d===n){let p=i+s+c;return a+e[p]&65535}if(d>n)return-1}return-1}var vu,qZ=32,Eu,D0;var $Qe=gs(()=>{NQe();Sge();UQe();zQe();Sge();(function(e){e[e.AMP=38]="AMP",e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_X=120]="LOWER_X"})(vu||(vu={}));(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(Eu||(Eu={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(D0||(D0={}))});function Yk(e){return e===Ei.Space||e===Ei.NewLine||e===Ei.Tab||e===Ei.FormFeed||e===Ei.CarriageReturn}function WC(e){return e===Ei.Slash||e===Ei.Gt||Yk(e)}function ZXi(e){return e>=Ei.LowerA&&e<=Ei.LowerZ||e>=Ei.UpperA&&e<=Ei.UpperZ}class ZC{cbs;state=Ze.Text;buffer="";sectionStart=0;index=0;entityStart=0;baseState=Ze.Text;isSpecial=!1;running=!0;offset=0;xmlMode;decodeEntities;recognizeSelfClosing;entityDecoder;constructor({xmlMode:e=!1,decodeEntities:t=!0,recognizeSelfClosing:i=e},n){this.cbs=n,this.xmlMode=e,this.decodeEntities=t,this.recognizeSelfClosing=i,this.entityDecoder=new kge(e?HR:wge,(r,o)=>this.emitCodePoint(r,o))}reset(){this.state=Ze.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=Ze.Text,this.isSpecial=!1,this.currentSequence=ln.Empty,this.sequenceIndex=0,this.running=!0,this.offset=0}write(e){this.offset+=this.buffer.length,this.buffer=e,this.parse()}end(){if(this.running)this.finish()}pause(){this.running=!1}resume(){if(this.running=!0,this.index<this.buffer.length+this.offset)this.parse()}stateText(e){if(e===Ei.Lt||!this.decodeEntities&&this.fastForwardTo(Ei.Lt)){if(this.index>this.sectionStart)this.cbs.ontext(this.sectionStart,this.index);this.state=Ze.BeforeTagName,this.sectionStart=this.index}else if(this.decodeEntities&&e===Ei.Amp)this.startEntity()}currentSequence=ln.Empty;sequenceIndex=0;enterTagBody(){if(this.currentSequence===ln.Plaintext)this.currentSequence=ln.Empty,this.state=Ze.InPlainText;else if(this.isSpecial)this.state=Ze.InSpecialTag,this.sequenceIndex=0;else this.state=Ze.Text}stateSpecialStartSequence(e){let t=e|32;if(this.sequenceIndex<this.currentSequence.length){if(t===this.currentSequence[this.sequenceIndex]){this.sequenceIndex++;return}if(this.sequenceIndex===3){if(this.currentSequence===ln.ScriptEnd&&t===ln.StyleEnd[3]){this.currentSequence=ln.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===ln.TitleEnd&&t===ln.TextareaEnd[3]){this.currentSequence=ln.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===ln.NoembedEnd&&t===ln.NoframesEnd[4]){this.currentSequence=ln.NoframesEnd,this.sequenceIndex=5;return}}else if(WC(e)){this.sequenceIndex=0,this.state=Ze.InTagName,this.stateInTagName(e);return}this.isSpecial=!1,this.currentSequence=ln.Empty,this.sequenceIndex=0,this.state=Ze.InTagName,this.stateInTagName(e)}stateCDATASequence(e){if(e===ln.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===ln.Cdata.length)this.state=Ze.InCommentLike,this.currentSequence=ln.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1}else if(this.sequenceIndex=0,this.xmlMode)this.state=Ze.InDeclaration,this.stateInDeclaration(e);else this.state=Ze.InSpecialComment,this.stateInSpecialComment(e)}fastForwardTo(e){while(++this.index<this.buffer.length+this.offset)if(this.buffer.charCodeAt(this.index-this.offset)===e)return!0;return this.index=this.buffer.length+this.offset-1,!1}emitComment(e){this.cbs.oncomment(this.sectionStart,this.index,e),this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=Ze.Text}stateInCommentLike(e){if(!this.xmlMode&&this.currentSequence===ln.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&e===Ei.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===ln.CommentEnd&&this.sequenceIndex===2&&e===Ei.Gt)this.emitComment(2);else if(this.currentSequence===ln.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&e!==Ei.Gt)this.sequenceIndex=Number(e===Ei.Dash);else if(e===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===ln.CdataEnd)this.cbs.oncdata(this.sectionStart,this.index,2);else this.cbs.oncomment(this.sectionStart,this.index,3);this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=Ze.Text}}else if(this.sequenceIndex===0){if(this.fastForwardTo(this.currentSequence[0]))this.sequenceIndex=1}else if(e!==this.currentSequence[this.sequenceIndex-1])this.sequenceIndex=0}isTagStartChar(e){return this.xmlMode?!WC(e):ZXi(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(WC(e)){let t=this.index-this.currentSequence.length;if(this.sectionStart<t){let i=this.index;this.index=t,this.cbs.ontext(this.sectionStart,t),this.index=i}this.isSpecial=!1,this.sectionStart=t+2,this.stateInClosingTagName(e);return}this.sequenceIndex=0}if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(this.sequenceIndex===0){if(this.currentSequence===ln.TitleEnd||this.currentSequence===ln.TextareaEnd){if(this.decodeEntities&&e===Ei.Amp)this.startEntity()}else if(this.fastForwardTo(Ei.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(e===Ei.Lt)}stateBeforeTagName(e){if(e===Ei.ExclamationMark)this.state=Ze.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===Ei.Questionmark)if(this.xmlMode)this.state=Ze.InProcessingInstruction,this.sequenceIndex=0,this.sectionStart=this.index+1;else this.state=Ze.InSpecialComment,this.sectionStart=this.index;else if(this.isTagStartChar(e)){this.sectionStart=this.index;let t=this.xmlMode||this.cbs.isInForeignContext?.()?void 0:VXi.get(e|32);if(t===void 0)this.state=Ze.InTagName;else this.isSpecial=!0,this.currentSequence=t,this.sequenceIndex=3,this.state=Ze.SpecialStartSequence}else if(e===Ei.Slash)this.state=Ze.BeforeClosingTagName;else this.state=Ze.Text,this.stateText(e)}stateInTagName(e){if(WC(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(Yk(e))if(this.xmlMode);else this.state=Ze.InSpecialComment,this.sectionStart=this.index;else if(e===Ei.Gt){if(this.state=Ze.Text,!this.xmlMode)this.sectionStart=this.index+1}else this.state=this.isTagStartChar(e)?Ze.InClosingTagName:Ze.InSpecialComment,this.sectionStart=this.index}stateInClosingTagName(e){if(WC(e))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=Ze.AfterClosingTagName,this.stateAfterClosingTagName(e)}stateAfterClosingTagName(e){if(e===Ei.Gt||this.fastForwardTo(Ei.Gt))this.state=Ze.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(e){if(e===Ei.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(e===Ei.Slash)this.state=Ze.InSelfClosingTag;else if(!Yk(e))this.state=Ze.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(e){if(e===Ei.Gt){if(this.cbs.onselfclosingtag(this.index),this.sectionStart=this.index+1,!this.recognizeSelfClosing){this.enterTagBody();return}this.state=Ze.Text,this.isSpecial=!1,this.currentSequence=ln.Empty}else if(!Yk(e))this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===Ei.Eq||WC(e))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=Ze.AfterAttributeName,this.stateAfterAttributeName(e)}stateAfterAttributeName(e){if(e===Ei.Eq)this.state=Ze.BeforeAttributeValue;else if(e===Ei.Slash||e===Ei.Gt)this.cbs.onattribend(Im.NoValue,this.sectionStart),this.sectionStart=-1,this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!Yk(e))this.cbs.onattribend(Im.NoValue,this.sectionStart),this.state=Ze.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(e){if(e===Ei.DoubleQuote)this.state=Ze.InAttributeValueDq,this.sectionStart=this.index+1;else if(e===Ei.SingleQuote)this.state=Ze.InAttributeValueSq,this.sectionStart=this.index+1;else if(!Yk(e))this.sectionStart=this.index,this.state=Ze.InAttributeValueNq,this.stateInAttributeValueNoQuotes(e)}handleInAttributeValue(e,t){if(e===t||!this.decodeEntities&&this.fastForwardTo(t))this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(t===Ei.DoubleQuote?Im.Double:Im.Single,this.index+1),this.state=Ze.BeforeAttributeName;else if(this.decodeEntities&&e===Ei.Amp)this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,Ei.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,Ei.SingleQuote)}stateInAttributeValueNoQuotes(e){if(Yk(e)||e===Ei.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(Im.Unquoted,this.index),this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(this.decodeEntities&&e===Ei.Amp)this.startEntity()}stateBeforeDeclaration(e){if(e===Ei.OpeningSquareBracket)this.state=Ze.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=e===Ei.Dash?Ze.BeforeComment:Ze.InDeclaration;else if((e|32)===ln.Doctype[0])this.state=Ze.DeclarationSequence,this.currentSequence=ln.Doctype,this.sequenceIndex=1;else if(e===Ei.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else if(e===Ei.Dash)this.state=Ze.BeforeComment;else this.state=Ze.InSpecialComment}stateDeclarationSequence(e){if(this.sequenceIndex===this.currentSequence.length)this.state=Ze.InDeclaration,this.stateInDeclaration(e);else if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(e===Ei.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else this.state=Ze.InSpecialComment}stateInDeclaration(e){if(e===Ei.Gt||this.fastForwardTo(Ei.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=Ze.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(e){if(e===Ei.Questionmark)this.sequenceIndex=1;else if(e===Ei.Gt&&this.sequenceIndex===1)this.cbs.onprocessinginstruction(this.sectionStart,this.index-1),this.sequenceIndex=0,this.state=Ze.Text,this.sectionStart=this.index+1;else this.sequenceIndex=Number(this.fastForwardTo(Ei.Questionmark))}stateBeforeComment(e){if(e===Ei.Dash)this.state=Ze.InCommentLike,this.currentSequence=ln.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=Ze.InDeclaration;else if(e===Ei.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else this.state=Ze.InSpecialComment}stateInSpecialComment(e){if(e===Ei.Gt||this.fastForwardTo(Ei.Gt))this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1}startEntity(){this.baseState=this.state,this.state=Ze.InEntity,this.entityStart=this.index,this.entityDecoder.startEntity(this.xmlMode?D0.Strict:this.baseState===Ze.Text||this.baseState===Ze.InSpecialTag?D0.Legacy:D0.Attribute)}stateInEntity(){let e=this.index-this.offset,t=this.entityDecoder.write(this.buffer,e);if(t>=0){if(this.state=this.baseState,t===0)this.index-=1}else{if(e<this.buffer.length&&this.buffer.charCodeAt(e)===Ei.Amp){this.state=this.baseState,this.index-=1;return}this.index=this.offset+this.buffer.length-1}}cleanup(){if(this.running&&this.sectionStart!==this.index){if(this.state===Ze.Text||this.state===Ze.InPlainText||this.state===Ze.InSpecialTag&&this.sequenceIndex===0)this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index;else if(this.state===Ze.InAttributeValueDq||this.state===Ze.InAttributeValueSq||this.state===Ze.InAttributeValueNq)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=this.index}}shouldContinue(){return this.index<this.buffer.length+this.offset&&this.running}parse(){while(this.shouldContinue()){let e=this.buffer.charCodeAt(this.index-this.offset);switch(this.state){case Ze.Text:{this.stateText(e);break}case Ze.InPlainText:{this.index=this.buffer.length+this.offset-1;break}case Ze.SpecialStartSequence:{this.stateSpecialStartSequence(e);break}case Ze.InSpecialTag:{this.stateInSpecialTag(e);break}case Ze.CDATASequence:{this.stateCDATASequence(e);break}case Ze.DeclarationSequence:{this.stateDeclarationSequence(e);break}case Ze.InAttributeValueDq:{this.stateInAttributeValueDoubleQuotes(e);break}case Ze.InAttributeName:{this.stateInAttributeName(e);break}case Ze.InCommentLike:{this.stateInCommentLike(e);break}case Ze.InSpecialComment:{this.stateInSpecialComment(e);break}case Ze.BeforeAttributeName:{this.stateBeforeAttributeName(e);break}case Ze.InTagName:{this.stateInTagName(e);break}case Ze.InClosingTagName:{this.stateInClosingTagName(e);break}case Ze.BeforeTagName:{this.stateBeforeTagName(e);break}case Ze.AfterAttributeName:{this.stateAfterAttributeName(e);break}case Ze.InAttributeValueSq:{this.stateInAttributeValueSingleQuotes(e);break}case Ze.BeforeAttributeValue:{this.stateBeforeAttributeValue(e);break}case Ze.BeforeClosingTagName:{this.stateBeforeClosingTagName(e);break}case Ze.AfterClosingTagName:{this.stateAfterClosingTagName(e);break}case Ze.InAttributeValueNq:{this.stateInAttributeValueNoQuotes(e);break}case Ze.InSelfClosingTag:{this.stateInSelfClosingTag(e);break}case Ze.InDeclaration:{this.stateInDeclaration(e);break}case Ze.BeforeDeclaration:{this.stateBeforeDeclaration(e);break}case Ze.BeforeComment:{this.stateBeforeComment(e);break}case Ze.InProcessingInstruction:{this.stateInProcessingInstruction(e);break}case Ze.InEntity:{this.stateInEntity();break}}this.index++}this.cleanup()}finish(){if(this.state===Ze.InEntity)this.entityDecoder.end(),this.state=this.baseState;this.handleTrailingData(),this.cbs.onend()}handleTrailingCommentLikeData(e){if(this.state!==Ze.InCommentLike)return!1;if(this.currentSequence===ln.CdataEnd)if(this.xmlMode){if(this.sectionStart<e)this.cbs.oncdata(this.sectionStart,e,0)}else{let t=this.sectionStart-ln.Cdata.length-1;this.cbs.oncomment(t,e,0)}else{let t=this.xmlMode?0:Math.min(this.sequenceIndex,ln.CommentEnd.length-1);this.cbs.oncomment(this.sectionStart,e,t)}return!0}handleTrailingMarkupDeclaration(e){if(this.xmlMode)switch(this.state){case Ze.InSpecialComment:case Ze.BeforeComment:case Ze.CDATASequence:case Ze.DeclarationSequence:case Ze.InDeclaration:return this.cbs.ontext(this.sectionStart,e),!0;default:return!1}switch(this.state){case Ze.BeforeDeclaration:case Ze.InSpecialComment:case Ze.BeforeComment:case Ze.CDATASequence:return this.cbs.oncomment(this.sectionStart,e,0),!0;case Ze.DeclarationSequence:{if(this.sequenceIndex!==ln.Doctype.length)this.cbs.oncomment(this.sectionStart,e,0);return!0}case Ze.InDeclaration:return!0;default:return!1}}handleTrailingData(){let e=this.buffer.length+this.offset;if(this.handleTrailingCommentLikeData(e)||this.handleTrailingMarkupDeclaration(e))return;if(this.sectionStart>=e)return;switch(this.state){case Ze.InTagName:case Ze.BeforeAttributeName:case Ze.BeforeAttributeValue:case Ze.AfterAttributeName:case Ze.InAttributeName:case Ze.InAttributeValueSq:case Ze.InAttributeValueDq:case Ze.InAttributeValueNq:case Ze.InClosingTagName:break;default:this.cbs.ontext(this.sectionStart,e)}}emitCodePoint(e,t){if(this.baseState!==Ze.Text&&this.baseState!==Ze.InSpecialTag){if(this.sectionStart<this.entityStart)this.cbs.onattribdata(this.sectionStart,this.entityStart);this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.onattribentity(e)}else{if(this.sectionStart<this.entityStart)this.cbs.ontext(this.sectionStart,this.entityStart);this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.ontextentity(e,this.sectionStart)}}}var Ei,Ze,Im,ln,VXi;var Bge=gs(()=>{$Qe();(function(e){e[e.Tab=9]="Tab",e[e.NewLine=10]="NewLine",e[e.FormFeed=12]="FormFeed",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.ExclamationMark=33]="ExclamationMark",e[e.Number=35]="Number",e[e.Amp=38]="Amp",e[e.SingleQuote=39]="SingleQuote",e[e.DoubleQuote=34]="DoubleQuote",e[e.Dash=45]="Dash",e[e.Slash=47]="Slash",e[e.Zero=48]="Zero",e[e.Nine=57]="Nine",e[e.Semi=59]="Semi",e[e.Lt=60]="Lt",e[e.Eq=61]="Eq",e[e.Gt=62]="Gt",e[e.Questionmark=63]="Questionmark",e[e.UpperA=65]="UpperA",e[e.LowerA=97]="LowerA",e[e.UpperF=70]="UpperF",e[e.LowerF=102]="LowerF",e[e.UpperZ=90]="UpperZ",e[e.LowerZ=122]="LowerZ",e[e.LowerX=120]="LowerX",e[e.OpeningSquareBracket=91]="OpeningSquareBracket"})(Ei||(Ei={}));(function(e){e[e.Text=1]="Text",e[e.BeforeTagName=2]="BeforeTagName",e[e.InTagName=3]="InTagName",e[e.InSelfClosingTag=4]="InSelfClosingTag",e[e.BeforeClosingTagName=5]="BeforeClosingTagName",e[e.InClosingTagName=6]="InClosingTagName",e[e.AfterClosingTagName=7]="AfterClosingTagName",e[e.BeforeAttributeName=8]="BeforeAttributeName",e[e.InAttributeName=9]="InAttributeName",e[e.AfterAttributeName=10]="AfterAttributeName",e[e.BeforeAttributeValue=11]="BeforeAttributeValue",e[e.InAttributeValueDq=12]="InAttributeValueDq",e[e.InAttributeValueSq=13]="InAttributeValueSq",e[e.InAttributeValueNq=14]="InAttributeValueNq",e[e.BeforeDeclaration=15]="BeforeDeclaration",e[e.InDeclaration=16]="InDeclaration",e[e.InProcessingInstruction=17]="InProcessingInstruction",e[e.BeforeComment=18]="BeforeComment",e[e.CDATASequence=19]="CDATASequence",e[e.DeclarationSequence=20]="DeclarationSequence",e[e.InSpecialComment=21]="InSpecialComment",e[e.InCommentLike=22]="InCommentLike",e[e.SpecialStartSequence=23]="SpecialStartSequence",e[e.InSpecialTag=24]="InSpecialTag",e[e.InPlainText=25]="InPlainText",e[e.InEntity=26]="InEntity"})(Ze||(Ze={}));(function(e){e[e.NoValue=0]="NoValue",e[e.Unquoted=1]="Unquoted",e[e.Single=2]="Single",e[e.Double=3]="Double"})(Im||(Im={}));ln={Empty:new Uint8Array(0),Cdata:new Uint8Array([67,68,65,84,65,91]),CdataEnd:new Uint8Array([93,93,62]),CommentEnd:new Uint8Array([45,45,33,62]),Doctype:new Uint8Array([100,111,99,116,121,112,101]),IframeEnd:new Uint8Array([60,47,105,102,114,97,109,101]),NoembedEnd:new Uint8Array([60,47,110,111,101,109,98,101,100]),NoframesEnd:new Uint8Array([60,47,110,111,102,114,97,109,101,115]),Plaintext:new Uint8Array([60,47,112,108,97,105,110,116,101,120,116]),ScriptEnd:new Uint8Array([60,47,115,99,114,105,112,116]),StyleEnd:new Uint8Array([60,47,115,116,121,108,101]),TitleEnd:new Uint8Array([60,47,116,105,116,108,101]),TextareaEnd:new Uint8Array([60,47,116,101,120,116,97,114,101,97]),XmpEnd:new Uint8Array([60,47,120,109,112])},VXi=new Map([[ln.IframeEnd[2],ln.IframeEnd],[ln.NoembedEnd[2],ln.NoembedEnd],[ln.Plaintext[2],ln.Plaintext],[ln.ScriptEnd[2],ln.ScriptEnd],[ln.TitleEnd[2],ln.TitleEnd],[ln.XmpEnd[2],ln.XmpEnd]])});class YC{options;startIndex=0;endIndex=0;openTagStart=0;tagname="";attribname="";attribvalue="";attribs=null;stack=[];foreignContext;cbs;lowerCaseTagNames;lowerCaseAttributeNames;recognizeSelfClosing;htmlMode;tokenizer;buffers=[];bufferOffset=0;writeIndex=0;ended=!1;constructor(e,t={}){this.options=t,this.cbs=e??{},this.htmlMode=!this.options.xmlMode,this.lowerCaseTagNames=t.lowerCaseTags??this.htmlMode,this.lowerCaseAttributeNames=t.lowerCaseAttributeNames??this.htmlMode,this.recognizeSelfClosing=t.recognizeSelfClosing??!this.htmlMode,this.tokenizer=new(t.Tokenizer??ZC)(this.options,this),this.foreignContext=[cE.None],this.cbs.onparserinit?.(this)}ontext(e,t){let i=this.getSlice(e,t);this.endIndex=t-1,this.cbs.ontext?.(i),this.startIndex=t}ontextentity(e,t){this.endIndex=t-1,this.cbs.ontext?.(HQe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==cE.None}isVoidElement(e){return this.htmlMode&&YXi.has(e)}readTagName(e,t){let i=this.lowerCaseTagNames?this.getSlice(e,t).toLowerCase():this.getSlice(e,t);if(!(this.lowerCaseTagNames&&this.htmlMode))return i;if(this.foreignContext[0]===cE.Svg)return YQe.get(i)??i;if(this.foreignContext.length>1){let n=YQe.get(i);if(n!==void 0&&this.stack.includes(n))return n}if(!this.isInForeignContext())return i==="image"?"img":i;return i}onopentagname(e,t){this.endIndex=t,this.emitOpenTag(this.readTagName(e,t))}emitOpenTag(e){if(this.openTagStart=this.startIndex,this.tagname=e,this.htmlMode&&e==="form"&&this.stack.includes("form")){this.tagname="";return}let t=this.htmlMode&&KXi.get(e);if(t)while(this.stack.length>0&&t.has(this.stack[0]))this.popElement(!0);if(!this.isVoidElement(e)){if(this.stack.unshift(e),this.htmlMode){if(e==="svg")this.foreignContext.unshift(cE.Svg);else if(e==="math")this.foreignContext.unshift(cE.MathML);else if(KQe.has(e))this.foreignContext.unshift(cE.None)}}if(this.cbs.onopentagname?.(e),this.cbs.onopentag)this.attribs={}}endOpenTag(e){if(this.startIndex=this.openTagStart,this.attribs)this.cbs.onopentag?.(this.tagname,this.attribs,e),this.attribs=null;if(this.cbs.onclosetag&&this.isVoidElement(this.tagname))this.cbs.onclosetag(this.tagname,!0);this.tagname=""}onopentagend(e){this.endIndex=e,this.endOpenTag(!1),this.startIndex=e+1}onclosetag(e,t){this.endIndex=t;let i=this.readTagName(e,t);if(!this.isVoidElement(i)){let n=this.stack.indexOf(i);if(n!==-1){for(let r=0;r<n;r++)this.popElement(!0);this.popElement(!1)}else if(this.htmlMode&&i==="p")this.emitOpenTag("p"),this.closeCurrentTag(!0)}else if(this.htmlMode&&i==="br")this.cbs.onopentagname?.("br"),this.cbs.onopentag?.("br",{},!0),this.cbs.onclosetag?.("br",!1);this.startIndex=t+1}onselfclosingtag(e){if(this.endIndex=e,this.recognizeSelfClosing||this.isInForeignContext())this.closeCurrentTag(!1),this.startIndex=e+1;else this.onopentagend(e)}popElement(e){let t=this.stack.shift();if(this.htmlMode&&(JXi.has(t)||KQe.has(t)))this.foreignContext.shift();this.cbs.onclosetag?.(t,e)}closeCurrentTag(e){let t=this.tagname;if(this.endOpenTag(e),this.stack[0]===t)this.popElement(!e)}onattribname(e,t){this.startIndex=e;let i=this.getSlice(e,t);this.attribname=this.lowerCaseAttributeNames?i.toLowerCase():i}onattribdata(e,t){this.attribvalue+=this.getSlice(e,t)}onattribentity(e){this.attribvalue+=HQe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===Im.Double?'"':e===Im.Single?"'":e===Im.NoValue?void 0:null),this.attribs&&!Object.hasOwn(this.attribs,this.attribname))this.attribs[this.attribname]=this.attribvalue;this.attribvalue=""}getInstructionName(e){let t=e.search(QXi),i=t<0?e:e.substr(0,t);if(this.lowerCaseTagNames)i=i.toLowerCase();return i}ondeclaration(e,t){this.endIndex=t;let i=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let n=this.htmlMode?this.lowerCaseTagNames?VQe:i.slice(0,VQe.length):this.getInstructionName(i);this.cbs.onprocessinginstruction(`!${n}`,`!${i}`)}this.startIndex=t+1}onprocessinginstruction(e,t){this.endIndex=t;let i=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let n=this.getInstructionName(i);this.cbs.onprocessinginstruction(`?${n}`,`?${i}`)}this.startIndex=t+1}oncomment(e,t,i){this.endIndex=t,this.cbs.oncomment?.(this.getSlice(e,t-i)),this.cbs.oncommentend?.(),this.startIndex=t+1}oncdata(e,t,i){this.endIndex=t;let n=this.getSlice(e,t-i);if(!this.htmlMode||this.options.recognizeCDATA)this.cbs.oncdatastart?.(),this.cbs.ontext?.(n),this.cbs.oncdataend?.();else if(this.isInForeignContext())this.cbs.ontext?.(n);else this.cbs.oncomment?.(`[CDATA[${n}]]`),this.cbs.oncommentend?.();this.startIndex=t+1}onend(){if(this.cbs.onclosetag){this.endIndex=this.startIndex;for(let e=0;e<this.stack.length;e++)this.cbs.onclosetag(this.stack[e],!0)}this.cbs.onend?.()}reset(){this.cbs.onreset?.(),this.tokenizer.reset(),this.tagname="",this.attribname="",this.attribvalue="",this.attribs=null,this.stack.length=0,this.startIndex=0,this.endIndex=0,this.cbs.onparserinit?.(this),this.buffers.length=0,this.foreignContext.length=0,this.foreignContext.unshift(cE.None),this.bufferOffset=0,this.writeIndex=0,this.ended=!1}parseComplete(e){this.reset(),this.end(e)}getSlice(e,t){if(e===t)return"";while(e-this.bufferOffset>=this.buffers[0].length)this.shiftBuffer();let i=this.buffers[0].slice(e-this.bufferOffset,t-this.bufferOffset);while(t-this.bufferOffset>this.buffers[0].length)this.shiftBuffer(),i+=this.buffers[0].slice(0,t-this.bufferOffset);return i}shiftBuffer(){this.bufferOffset+=this.buffers[0].length,this.writeIndex--,this.buffers.shift()}write(e){if(this.ended){this.cbs.onerror?.(Error(".write() after done!"));return}if(this.buffers.push(e),this.tokenizer.running)this.tokenizer.write(e),this.writeIndex++}end(e){if(this.ended){this.cbs.onerror?.(Error(".end() after done!"));return}if(e)this.write(e);this.ended=!0,this.tokenizer.end()}pause(){this.tokenizer.pause()}resume(){this.tokenizer.resume();while(this.tokenizer.running&&this.writeIndex<this.buffers.length)this.tokenizer.write(this.buffers[this.writeIndex++]);if(this.ended)this.tokenizer.end()}}var HQe,VC,Qs,KC,GQe,WQe,ZQe,KXi,VQe="doctype",YXi,JXi,KQe,YQe,cE,QXi;var Cge=gs(()=>{Bge();({fromCodePoint:HQe}=String),VC=new Set(["input","option","optgroup","select","button","datalist","textarea"]),Qs=new Set(["p"]),KC=new Set(["h1","h2","h3","h4","h5","h6","p"]),GQe=new Set(["thead","tbody"]),WQe=new Set(["dd","dt"]),ZQe=new Set(["rt","rp"]),KXi=new Map([["tr",new Set(["tr","th","td"])],["th",new Set(["th"])],["td",new Set(["thead","th","td"])],["body",new Set(["head","link","script"])],["a",new Set(["a"])],["li",new Set(["li"])],["p",Qs],["h1",KC],["h2",KC],["h3",KC],["h4",KC],["h5",KC],["h6",KC],["select",VC],["input",VC],["output",VC],["button",VC],["datalist",VC],["textarea",VC],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",WQe],["dt",WQe],["address",Qs],["article",Qs],["aside",Qs],["blockquote",Qs],["details",Qs],["div",Qs],["dl",Qs],["fieldset",Qs],["figcaption",Qs],["figure",Qs],["footer",Qs],["form",Qs],["header",Qs],["hr",Qs],["main",Qs],["nav",Qs],["ol",Qs],["pre",Qs],["section",Qs],["table",Qs],["ul",Qs],["rt",ZQe],["rp",ZQe],["tbody",GQe],["tfoot",GQe]]),YXi=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),JXi=new Set(["math","svg"]),KQe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),YQe=new Map([["altglyph","altGlyph"],["altglyphdef","altGlyphDef"],["altglyphitem","altGlyphItem"],["animatecolor","animateColor"],["animatemotion","animateMotion"],["animatetransform","animateTransform"],["clippath","clipPath"],["feblend","feBlend"],["fecolormatrix","feColorMatrix"],["fecomponenttransfer","feComponentTransfer"],["fecomposite","feComposite"],["feconvolvematrix","feConvolveMatrix"],["fediffuselighting","feDiffuseLighting"],["fedisplacementmap","feDisplacementMap"],["fedistantlight","feDistantLight"],["fedropshadow","feDropShadow"],["feflood","feFlood"],["fefunca","feFuncA"],["fefuncb","feFuncB"],["fefuncg","feFuncG"],["fefuncr","feFuncR"],["fegaussianblur","feGaussianBlur"],["feimage","feImage"],["femerge","feMerge"],["femergenode","feMergeNode"],["femorphology","feMorphology"],["feoffset","feOffset"],["fepointlight","fePointLight"],["fespecularlighting","feSpecularLighting"],["fespotlight","feSpotLight"],["fetile","feTile"],["feturbulence","feTurbulence"],["foreignobject","foreignObject"],["glyphref","glyphRef"],["lineargradient","linearGradient"],["radialgradient","radialGradient"],["textpath","textPath"]]);(function(e){e[e.None=0]="None",e[e.Svg=1]="Svg",e[e.MathML=2]="MathML"})(cE||(cE={}));QXi=/\s|\//});var $Z={};Kh($Z,{CDATA:()=>Oge,Comment:()=>Pge,Directive:()=>Tge,Doctype:()=>XXi,ElementType:()=>mr,Root:()=>Ige,Script:()=>Rge,Style:()=>Fge,Tag:()=>Mge,Text:()=>_ge,isTag:()=>Dge});function Dge(e){return e.type===mr.Tag||e.type===mr.Script||e.type===mr.Style}var mr,Ige,_ge,Tge,Pge,Rge,Fge,Mge,Oge,XXi;var JC=gs(()=>{(function(e){e.Root="root",e.Text="text",e.Directive="directive",e.Comment="comment",e.Script="script",e.Style="style",e.Tag="tag",e.CDATA="cdata",e.Doctype="doctype"})(mr||(mr={}));Ige=mr.Root,_ge=mr.Text,Tge=mr.Directive,Pge=mr.Comment,Rge=mr.Script,Fge=mr.Style,Mge=mr.Tag,Oge=mr.CDATA,XXi=mr.Doctype});class Lge{parent=null;prev=null;next=null;startIndex=null;endIndex=null;get parentNode(){return this.parent}set parentNode(e){this.parent=e}get previousSibling(){return this.prev}set previousSibling(e){this.prev=e}get nextSibling(){return this.next}set nextSibling(e){this.next=e}cloneNode(e=!1){return JQe(this,e)}}function Au(e){return Dge(e)}function YZ(e){return e.type===mr.CDATA}function Pw(e){return e.type===mr.Text}function jge(e){return e.type===mr.Comment}function een(e){return e.type===mr.Directive}function ten(e){return e.type===mr.Root}function yp(e){return Object.hasOwn(e,"children")}function JQe(e,t=!1){let i;if(Pw(e))i=new GR(e.data);else if(jge(e))i=new GZ(e.data);else if(Au(e)){let n=t?Nge(e.children):[],r=new KZ(e.name,{...e.attribs},n);for(let o of n)o.parent=r;if(e.namespace!=null)r.namespace=e.namespace;if(e["x-attribsNamespace"])r["x-attribsNamespace"]={...e["x-attribsNamespace"]};if(e["x-attribsPrefix"])r["x-attribsPrefix"]={...e["x-attribsPrefix"]};i=r}else if(YZ(e)){let n=t?Nge(e.children):[],r=new VZ(n);for(let o of n)o.parent=r;i=r}else if(ten(e)){let n=t?Nge(e.children):[],r=new WR(n);for(let o of n)o.parent=r;if(e["x-mode"])r["x-mode"]=e["x-mode"];i=r}else if(een(e)){let n=new WZ(e.name,e.data);if(e["x-name"]!=null)n["x-name"]=e["x-name"],n["x-publicId"]=e["x-publicId"],n["x-systemId"]=e["x-systemId"];i=n}else throw Error(`Not implemented yet: ${e.type}`);if(i.startIndex=e.startIndex,i.endIndex=e.endIndex,e.sourceCodeLocation!=null)i.sourceCodeLocation=e.sourceCodeLocation;return i}function Nge(e){let t=e.map((i)=>JQe(i,!0));for(let i=1;i<t.length;i++)t[i].prev=t[i-1],t[i-1].next=t[i];return t}var HZ,GR,GZ,WZ,ZZ,VZ,WR,KZ;var zge=gs(()=>{JC();HZ=class HZ extends Lge{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};GR=class GR extends HZ{type=mr.Text;get nodeType(){return 3}};GZ=class GZ extends HZ{type=mr.Comment;get nodeType(){return 8}};WZ=class WZ extends HZ{type=mr.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};ZZ=class ZZ extends Lge{children;constructor(e){super();this.children=e}get firstChild(){return this.children[0]??null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(e){this.children=e}};VZ=class VZ extends ZZ{type=mr.CDATA;get nodeType(){return 4}};WR=class WR extends ZZ{type=mr.Root;get nodeType(){return 9}};KZ=class KZ extends ZZ{name;attribs;type;constructor(e,t,i=[],n=e==="script"?mr.Script:e==="style"?mr.Style:mr.Tag){super(i);this.name=e,this.attribs=t,this.type=n}get nodeType(){return 1}get tagName(){return this.name}set tagName(e){this.name=e}get attributes(){return Object.keys(this.attribs).map((e)=>({name:e,value:this.attribs[e],namespace:this["x-attribsNamespace"]?.[e],prefix:this["x-attribsPrefix"]?.[e]}))}namespace;"x-attribsNamespace";"x-attribsPrefix"}});class Jk{dom=[];root=new WR(this.dom);callback;options;elementCB;done=!1;tagStack=[this.root];lastNode=null;parser=null;constructor(e,t,i){if(typeof t==="function")i=t,t=QQe;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??QQe,this.elementCB=i??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new WR(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){if(this.done)return;this.done=!0,this.parser=null,this.handleCallback(null)}onerror(e){this.handleCallback(e)}onclosetag(){this.lastNode=null;let e=this.tagStack.pop();if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(this.elementCB)this.elementCB(e)}onopentag(e,t){let i=this.options.xmlMode?mr.Tag:void 0,n=new KZ(e,t,void 0,i);this.addNode(n),this.tagStack.push(n)}ontext(e){let{lastNode:t}=this;if(t&&t.type===mr.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let i=new GR(e);this.addNode(i),this.lastNode=i}}oncomment(e){if(this.lastNode&&this.lastNode.type===mr.Comment){this.lastNode.data+=e;return}let t=new GZ(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new GR(""),t=new VZ([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let i=new WZ(e,t);this.addNode(i)}handleCallback(e){if(typeof this.callback==="function")this.callback(e,this.dom);else if(e)throw e}addNode(e){let t=this.tagStack[this.tagStack.length-1],i=t.children[t.children.length-1];if(this.options.withStartIndices&&this.parser)e.startIndex=this.parser.startIndex;if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(t.children.push(e),i)e.prev=i,i.next=e;e.parent=t,this.lastNode=null}}var QQe;var Rw=gs(()=>{JC();zge();zge();QQe={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function QC(e,t,i=!0,n=Number.POSITIVE_INFINITY){return XQe(e,Array.isArray(t)?t:[t],i,n)}function XQe(e,t,i,n){let r=[],o=[Array.isArray(t)?t:[t]],s=[0];for(;;){if(s[0]>=o[0].length){if(s.length===1)return r;o.shift(),s.shift();continue}let a=o[0][s[0]++];if(e(a)){if(r.push(a),--n<=0)return r}if(i&&yp(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function JZ(e,t,i=!0){let n=Array.isArray(t)?t:[t];for(let r of n){if(Au(r)&&e(r))return r;if(i&&yp(r)&&r.children.length>0){let o=JZ(e,r.children,!0);if(o)return o}}return null}function eXe(e,t){return(Array.isArray(t)?t:[t]).some((i)=>Au(i)&&e(i)||yp(i)&&eXe(e,i.children))}function ien(e,t){let i=[],n=[Array.isArray(t)?t:[t]],r=[0];for(;;){if(r[0]>=n[0].length){if(n.length===1)return i;n.shift(),r.shift();continue}let o=n[0][r[0]++];if(Au(o)&&e(o))i.push(o);if(yp(o)&&o.children.length>0)r.unshift(0),n.unshift(o.children)}}var Uge=gs(()=>{Rw()});function qge(e,t){if(typeof t==="function")return(i)=>Au(i)&&t(i.attribs[e]);return(i)=>Au(i)&&i.attribs[e]===t}function nen(e,t){return(i)=>e(i)||t(i)}function tXe(e){let t=Object.keys(e).map((i)=>{let n=e[i];return Object.hasOwn(QZ,i)?QZ[i](n):qge(i,n)});return t.length===0?null:t.reduce(nen)}function ren(e,t){let i=tXe(e);return i?i(t):!0}function oen(e,t,i,n=Number.POSITIVE_INFINITY){let r=tXe(e);return r?QC(r,t,i,n):[]}function sen(e,t,i=!0){if(!Array.isArray(t))t=[t];return JZ(qge("id",e),t,i)}function Qk(e,t,i=!0,n=Number.POSITIVE_INFINITY){return QC(QZ.tag_name(e),t,i,n)}function aen(e,t,i=!0,n=Number.POSITIVE_INFINITY){return QC(qge("class",e),t,i,n)}function cen(e,t,i=!0,n=Number.POSITIVE_INFINITY){return QC(QZ.tag_type(e),t,i,n)}var QZ;var $ge=gs(()=>{Rw();Uge();QZ={tag_name(e){if(typeof e==="function")return(t)=>Au(t)&&e(t.name);if(e==="*")return Au;return(t)=>Au(t)&&t.name===e},tag_type(e){if(typeof e==="function")return(t)=>e(t.type);return(t)=>t.type===e},tag_contains(e){if(typeof e==="function")return(t)=>Pw(t)&&e(t.data);return(t)=>Pw(t)&&t.data===e}}});function nXe(e){return e===34?""":e===38?"&":e===39?"'":e===60?"<":e===62?">":" "}function iXe(e){return e>=128||e>=32&&e<64&&(len>>>e&1)===1}function XZ(e){let{length:t}=e,i,n=0,r=0;while(r<t){let o=e.charCodeAt(r);if(!iXe(o)){let a=Math.min(r+32,t),c=r+1;while(c<a&&!iXe(e.charCodeAt(c)))c++;if(c<a){r=c;continue}if(c>=t)break;if(Hge.lastIndex=c,!Hge.test(e))break;r=Hge.lastIndex-1;continue}if(i===void 0)i=e.substring(0,r);else if(n!==r)i+=e.substring(n,r);if(o<64){i+=nXe(o),n=r+=1;continue}let s=e.codePointAt(r);if(i+=`&#x${s.toString(16)};`,s!==o)r++;n=r+=1}if(i===void 0)return e;if(n<t)i+=e.substr(n);return i}function rXe(e,t){if(e.lastIndex=0,!e.test(t))return t;let i="",n=0;do{let r=e.lastIndex-1;if(n!==r)i+=t.substring(n,r);let o=t.charCodeAt(r);i+=nXe(o),n=r+1}while(e.test(t));return i+t.substring(n)}function Gge(e){return rXe(uen,e)}function Wge(e){return rXe(den,e)}var len=1342177476,Hge,uen,den;var oXe=gs(()=>{Hge=/["&'<>\u0080-\uFFFF]/g;uen=/["&\u{A0}]/gu;den=/[&<>\u{A0}]/gu});var sXe,aXe;var cXe=gs(()=>{oXe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(sXe||(sXe={}));(function(e){e[e.UTF8=0]="UTF8",e[e.ASCII=1]="ASCII",e[e.Extensive=2]="Extensive",e[e.Attribute=3]="Attribute",e[e.Text=4]="Text"})(aXe||(aXe={}))});var lXe,uXe;var dXe=gs(()=>{lXe=new Map("altGlyph altGlyphDef altGlyphItem animateColor animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject glyphRef linearGradient radialGradient textPath".split(" ").map((e)=>[e.toLowerCase(),e])),uXe=new Map("definitionURL attributeName attributeType baseFrequency baseProfile calcMode clipPathUnits diffuseConstant edgeMode filterUnits glyphRef gradientTransform gradientUnits kernelMatrix kernelUnitLength keyPoints keySplines keyTimes lengthAdjust limitingConeAngle markerHeight markerUnits markerWidth maskContentUnits maskUnits numOctaves pathLength patternContentUnits patternTransform patternUnits pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits refX refY repeatCount repeatDur requiredExtensions requiredFeatures specularConstant specularExponent spreadMethod startOffset stdDeviation stitchTiles surfaceScale systemLanguage tableValues targetX targetY textLength viewBox viewTarget xChannelSelector yChannelSelector zoomAndPan".split(" ").map((e)=>[e.toLowerCase(),e]))});function xen(e,t={}){let i="length"in e?e:[e],n=t.xmlMode??!1,r="";for(let o=0;o<i.length;o++)r+=mXe(i[o],t,n);return r}function pXe(e,t,i){let n="";for(let r=0;r<e.length;r++)n+=mXe(e[r],t,i);return n}function mXe(e,t,i){switch(e.type){case Ige:return pXe(e.children,t,i);case Tge:return`<${e.data}>`;case Pge:return`<!--${e.data}-->`;case Oge:return`<![CDATA[${e.children[0].data}]]>`;case Rge:case Fge:case Mge:return gen(e,t,i);case _ge:{let n=e,r=n.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!i&&n.parent&&pen.has(n.parent.name)))return i||t.encodeEntities!=="utf8"?XZ(r):Wge(r);return r}}}function gen(e,t,i){if(i==="foreign"){if(e.name=lXe.get(e.name)??e.name,e.parent&&fen.has(e.parent.name))i=!1}if(!i&&hen.has(e.name))i="foreign";let{name:n,children:r}=e,o=!i&&men.has(n),s=`<${n}${ben(e.attribs,t,i)}`;if(r.length===0&&(i?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=i?"/>":" />";else{if(s+=">",r.length>0)s+=pXe(r,t,i);if(!o)s+=`</${n}>`}return s}function yen(e){return e.replaceAll('"',""")}function ben(e,t,i){if(!e)return"";let n=(t.encodeEntities??t.decodeEntities)===!1?yen:i||t.encodeEntities!=="utf8"?XZ:Gge,r=i==="foreign",o=!!(t.emptyAttrs??i),s="";for(let a in e){if(!Object.hasOwn(e,a))continue;let c=e[a],l=r?uXe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${l}`:` ${l}="${n(c==null?"":String(c))}"`}return s}var pen,men,hen,fen,hXe;var fXe=gs(()=>{JC();cXe();dXe();pen=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),men=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),hen=new Set(["svg","math"]),fen=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));hXe=xen});function xXe(e,t){return hXe(e,t)}function Een(e,t){return yp(e)?e.children.map((i)=>xXe(i,t)).join(""):""}function eV(e){if(Array.isArray(e))return e.map(eV).join("");if(Au(e))return e.name==="br"?`
|
|
2
|
+
import"./chunks/index-r24najdd.js";import{$ as wo,$a as j8r,$b as vkr,$c as Vkr,Aa as Ax,Ab as uU,Ad as b5r,Ba as fhi,Bb as lkr,Bd as M6,C as Cy,Ca as xhi,Cb as ukr,Cc as cgi,Cd as E5r,D as FSr,Da as b8r,Db as Gv,Dd as v5r,E as rhi,Ea as E8r,Eb as bhi,Ed as A5r,F as mhi,Fa as Yre,Fb as sU,Fd as Iy,G as GSr,Ga as v8r,Gb as dkr,Gd as lU,H as WSr,Hb as pkr,Hd as w5r,I as ZSr,Ia as aTe,Ib as mkr,Id as S5r,J as VSr,Ja as A8r,Jb as hkr,Jd as k5r,K as KSr,Ka as w8r,Kd as B5r,La as S8r,Lb as Ehi,Ld as C5r,M as Xre,Ma as k8r,Mb as vhi,Md as D5r,Na as B8r,Nb as Ahi,Nd as I5r,Oa as C8r,Ob as whi,Od as _5r,P as N6,Pa as D8r,Pb as Shi,Pd as T5r,Q as Ymi,Qa as ghi,Qb as khi,Qd as toe,R as O6,Ra as I8r,Rb as Bhi,Rc as Phi,Rd as xTe,S as By,Sa as _8r,Sb as Chi,Sc as zkr,Sd as P5r,Ta as T8r,Tb as Dhi,Tc as Ukr,Td as cTe,U as hTe,Ua as P8r,Ub as Ihi,Uc as qkr,Ud as R5r,V as YSr,Va as R8r,Vb as fkr,Vc as $kr,Vd as mh,W as Vt,Wa as F8r,Wb as xkr,Wc as F6,Wd as Ire,Xa as M8r,Xb as gkr,Xc as Hkr,Xd as F5r,Y as hhi,Ya as O8r,Yb as ykr,Yc as Gkr,Z as JSr,Za as N8r,Zb as bkr,Zc as Wkr,_ as QS,_a as L8r,_b as Ekr,_c as Zkr,aa as t8,ab as z8r,ac as Akr,ad as Kkr,ba as ll,bb as U8r,bc as wkr,bd as Ykr,ca as QSr,cb as q8r,cc as Skr,cd as Jkr,da as XSr,db as XS,dc as kkr,dd as Qkr,ea as e8r,eb as $8r,ec as Bkr,ed as Xkr,fa as t8r,fb as nTe,fc as Ckr,fd as e5r,ga as i8r,gb as H8r,gc as Dkr,gd as t5r,ha as n8r,hb as G8r,hc as Ikr,hd as i5r,ia as r8r,ib as W8r,ic as _kr,id as n5r,ja as o8r,jb as Z8r,jc as rTe,jd as r5r,ka as s8r,kb as V8r,kc as cU,kd as o5r,la as a8r,lb as K8r,lc as Tkr,ld as s5r,ma as c8r,mb as Y8r,mc as Pkr,md as a5r,na as l8r,nb as J8r,nc as Rkr,nd as c5r,oa as u8r,ob as Q8r,oc as Fkr,od as l5r,pa as d8r,pb as X8r,pc as Mkr,qa as p8r,qb as ekr,qc as Okr,qd as u5r,ra as m8r,rb as tkr,rc as Nkr,rd as d5r,sa as h8r,sb as ikr,sc as _hi,sd as p5r,ta as p_e,tb as nkr,tc as Thi,td as ehi,ua as f8r,ub as rkr,uc as Kmi,ud as m5r,va as x8r,vb as okr,vc as Lkr,vd as h5r,wa as g8r,wb as yhi,wc as jkr,wd as f5r,xa as y8r,xb as skr,xc as fTe,xd as x5r,ya as iTe,yb as akr,yd as g5r,za as hU,zb as ckr,zd as y5r}from"./chunks/index-fhmc36f3.js";import{$d as u8i,Yd as PT,Zd as q8i,be as UMe}from"./chunks/index-a7826mse.js";import{de as TV}from"./chunks/index-27h92m2e.js";import"./chunks/index-e84v85w3.js";import"./chunks/index-e0qz6mam.js";import"./chunks/index-624fhq2j.js";import"./chunks/index-z0k97qgd.js";import"./chunks/index-x8e40qwv.js";import{ie as xk}from"./chunks/index-rwndt26q.js";import{$e as Ytt,Ce as GYe,De as HNi,Ee as NUi,Fe as Xg,Ge as bX,He as u$,Ie as KSi,Je as Vy,Ke as hOi,Le as DT,Me as iji,Ne as ZSi,Oe as YSi,Pe as vOi,Qe as dOi,Re as DEt,Se as v$i,Te as ZWe,Ue as VWe,Ve as KWe,We as fSi,Xe as bT,Ye as pOi,Ze as Zf,_e as IT,af as IEt,if as eZ,ke as Hfe,le as oR,ne as Io,oe as m5,pe as PEe,qe as OEe,re as IE,se as xK,te as gK,ue as yK,ve as Prt,we as bK,xe as S4,ye as wst,ze as bs}from"./chunks/index-4mqgq4bb.js";import{lf as K0e,mf as QVi}from"./chunks/index-7f3ccxrq.js";import"./chunks/index-kz9a2wvt.js";import{$f as Ust,$g as CR,$h as Ys,$l as yg,$n as _vt,Af as Qw,Ag as km,Ah as Ur,Ai as J_,Aj as ZVi,Ak as P0e,Al as $xe,Am as LZi,Ao as Ew,Bf as xt,Bg as A0,Bh as WX,Bi as Q_,Bj as EZi,Bk as bw,Bl as Yn,Bo as W0e,Cf as XK,Cg as ji,Ch as fAt,Ci as z8e,Cj as vZi,Ck as Yb,Cl as Hxe,Cn as H0e,Co as fYe,Df as zl,Dg as Ds,Dh as w2,Di as h8i,Dj as AZi,Dk as Pk,Dl as Gxe,Do as Z0e,Ef as $at,Eg as ho,Eh as ND,Ei as Ea,Ej as wZi,Ek as gR,El as Bm,Eo as gw,Ff as yM,Fg as gu,Fh as GX,Fi as $ot,Fj as SZi,Fk as R0e,Fl as Ut,Fn as Ogi,Fo as $h,Gf as bM,Gg as Zb,Gh as iAt,Gi as Oxe,Gj as VVi,Gk as EZ,Gl as tE,Gn as Ngi,Go as V0e,Hf as gi,Hg as y0e,Hh as k2,Hi as qT,Hj as qZi,Hk as F0e,Hl as oo,Hn as NX,Ho as vR,If as O4,Ig as b0e,Ih as Yl,Ii as kB,Ij as $Zi,Ik as M0e,Il as Fo,Im as SA,In as Pvt,Io as hNi,Jf as eY,Jh as X1,Ji as zae,Jj as ZZi,Jk as O0e,Jl as Vw,Jm as f8,Jn as Rvt,Kf as tM,Kh as aL,Ki as Uae,Kj as tVi,Kk as MC,Kl as bR,Km as u2i,Kn as cVi,Lg as _xe,Lh as Q1,Li as aR,Lj as iVi,Lk as N0e,Ll as Dr,Lm as e2i,Ln as lVi,Mf as Jw,Mg as pr,Mh as lx,Mi as qWe,Mj as nVi,Ml as dt,Mm as Q5i,Mn as Fvt,Nf as zEe,Ng as Nr,Nh as o5e,Ni as uk,Nj as Ghe,Nk as L0e,Nm as $Ni,Nn as Mvt,No as vw,Of as tY,Og as REt,Oh as pAt,Oi as GFe,Oj as JVi,Ol as eNi,Om as zyi,On as Dke,Oo as RE,Pf as ys,Pg as Txe,Ph as dAt,Pj as YZi,Pk as Cr,Pm as Fyi,Pn as vvt,Po as Gh,Qf as ri,Qh as ire,Qi as Zw,Qj as cZi,Ql as Rn,Qm as Uyi,Qn as Bvt,Qo as xg,Rf as Qe,Rg as wR,Rh as yAt,Ri as jKe,Rl as sLi,Rm as XU,Rn as nL,Ro as rbi,Sf as Lo,Sg as Lk,Sh as Wvt,Si as iht,Sk as Jb,Sl as sG,Sm as dle,Sn as Ovt,So as na,Tf as ea,Tg as RC,Th as Zvt,Ti as nht,Tk as j0e,Tl as rLi,Tm as TT,Tn as rL,Uf as of,Ug as SR,Uj as ow,Ul as U0e,Um as bce,Un as pZi,Vf as LEe,Vg as kR,Vh as HX,Vj as Tk,Vl as Vi,Vm as I$,Vn as xPe,Wg as Pxe,Wh as bAt,Wj as E0e,Wm as wce,Wn as Cvt,Xf as jst,Xg as Xb,Xh as u5e,Xj as gg,Xm as r2i,Xn as Dvt,Yf as zst,Yg as BR,Yk as yR,Ym as a2i,Yn as p8,Zg as jk,Zh as DNi,Zk as z0e,Zl as Qb,Zm as d2i,Zn as Ivt,_g as zk,_l as ft,_n as UX,ag as qst,ah as DR,aj as Kb,ak as FC,am as Is,ao as IZi,bh as Rxe,bk as v0e,bl as lZi,bm as Gmt,bo as Nvt,cg as $st,ch as NC,ci as Vb,ck as A0e,cm as Dl,co as Hvt,dh as ww,di as Fxe,dk as w0e,dm as ER,do as _Zi,eh as Vh,ek as S0e,em as q0e,en as lme,eo as DZi,fh as eE,fi as Uk,fk as xR,fl as kEi,fm as $0e,fn as bf,fo as Avt,gh as Bw,gj as V$i,gk as k0e,gl as Zse,gm as zt,go as Loe,hh as R1,hk as B0e,hl as Ugi,hm as fg,ho as GU,ih as tOi,ii as yc,ik as C0e,il as tZ,im as qoe,io as Agi,jh as lct,ji as Mxe,jk as D0e,jm as $oe,jo as Cm,kh as Mve,kk as I0e,km as HYe,ko as Zk,lk as _0e,ll as Am,lm as Do,ln as uZi,lo as iE,mg as J$i,mi as hR,mk as T0e,mm as Or,mn as dZi,mo as nE,nh as Hoe,ni as yw,nj as rw,nl as _l,nm as mNi,nn as qX,no as rE,og as Q$i,oh as Goe,oi as Cw,oj as NZi,ol as Nxe,om as xs,on as Lvt,oo as Il,pf as Dxe,pg as Z8i,ph as ZU,pi as Z_,pj as mVi,pl as Lxe,pn as jvt,po as G0e,qf as Ixe,qh as VU,qi as HWe,qj as oKe,ql as jxe,qn as zvt,qo as Fk,rf as x0e,rh as O7e,ri as LKe,rj as HVi,rk as k0,rl as zxe,rn as OD,ro as vZ,sf as Uc,sh as jgi,si as nHi,sj as GVi,sk as qk,sl as Uxe,sn as oL,tf as _k,th as M7e,ti as kX,tj as Yq,tk as $k,tl as qxe,tm as eL,uf as g0e,uh as tB,ui as Xse,uj as d0,uk as _Z,ul as Gk,um as Evt,un as REe,uo as Mk,vf as PC,vi as qme,vj as X9,vl as IR,vm as OX,vo as Ok,wf as et,wh as yo,wi as eae,wj as XZi,wk as Hk,wl as Wk,wm as efe,wn as Hh,xf as Bi,xg as yu,xh as gAt,xi as Dpe,xj as eVi,xl as ya,xm as tfe,yg as mR,yh as Ie,yi as wX,yj as Whe,yl as Xo,zf as xe,zg as cn,zh as cx,zi as lk,zj as WVi,zl as _R}from"./chunks/index-x7qrfd1q.js";import{$o as xn,$p as kVi,$q as Ude,$r as cG,$s as S9,$t as wm,Ap as Lhe,Aq as OYe,As as YVi,At as uc,Bp as zWi,Bq as rZ,Bs as Ese,Bt as G_,Cp as Kki,Cq as fZ,Cr as ANi,Cs as She,Ct as nt,Dp as UWi,Dq as xZ,Dr as Yw,Ds as Ope,Dt as Lu,Ep as ROe,Eq as NF,Er as aq,Es as V7,Et as eKe,Fp as FOe,Fs as vHe,Ft as gd,Gp as k$,Gq as xme,Gs as wHe,Gt as bu,Hp as MOe,Hq as lwi,Hs as PLi,Ht as We,Ip as Yki,Iq as ds,Is as cLi,Jp as OOe,Jq as DUi,Js as RLi,Kp as Jki,Kq as S1i,Kr as rle,Ks as lLi,Kt as fR,Lp as Qki,Lq as d8,Lr as ZT,Ls as mLi,Lt as y0,Mp as ele,Mq as Iyi,Mr as Koe,Ms as vse,Mt as Wfe,Np as tle,Nq as F_,Nr as xse,Ns as aD,Op as Xki,Oq as Bae,Or as In,Os as yse,Ot as Kfe,Pp as ile,Pq as Bzi,Pr as Y$i,Ps as XJ,Qp as vi,Qq as Czi,Qr as yHi,Qs as eQ,Rp as h5,Rq as QJ,Rr as DK,Rs as Qoe,Sp as Ht,Sr as IEi,Ss as Hmt,To as n5i,Tp as Ix,Tq as Uat,Tr as gse,Uo as rhe,Up as AK,Uq as qat,Ur as a0,Us as jwi,Vp as tm,Vq as Qst,Vs as M8e,Wo as Br,Wp as jy,Wq as Xst,Wr as z7,Xo as $f,Xp as Zr,Xq as $mt,Xr as cle,Xs as XEi,Yo as Bse,Yp as qhe,Yq as Ar,Yr as SG,Ys as wA,Zq as Ad,Zr as gme,Zs as BOi,_o as ki,_p as SVi,_q as Z8,_r as _Ge,_s as lpe,_t as gp,ap as U_,ar as aFi,as as lG,at as aB,au as xd,bp as G9,br as qde,bs as VG,bt as S5i,cp as nhe,cq as kP,cr as UEe,cs as OGi,ct as fle,dp as N9,dr as VK,ds as KG,dt as Gfe,ep as WH,es as _se,et as Uoe,fp as RX,fr as K1,fs as Lbi,ft as I_,fu as Rk,gp as ka,gq as pR,gr as he,gs as zbi,gt as ygi,hp as EA,hq as Azi,hs as Tse,ht as $m,ip as L9,ir as eo,is as qpe,it as M1,jp as k$e,js as $Li,jt as ga,kq as $Vi,ks as Xpe,kt as iSi,lp as nle,ls as eme,lt as om,mp as bA,mq as Tzi,mr as bi,ms as Wbi,mt as Mt,np as Yce,nq as ust,nr as D4,ns as Ubi,nt as Y_,op as Jce,or as RVi,os as qbi,ot as LC,pp as LWi,pq as m0e,pr as TC,ps as Y1,pt as yd,qp as Xae,qq as dZ,qr as fse,qs as pyi,qt as gc,rp as UB,rq as pZ,rr as AX,rt as V1,sp as Obe,sq as mZ,sr as CD,ss as Npe,st as fo,tp as Xce,tq as hZ,ts as XNi,tt as Of,up as qB,uq as yZ,us as eLi,ut as Uwi,vp as Qce,vq as bZ,vr as Fae,vs as F1,vt as zgi,wp as _8,wq as Ik,wr as uAi,ws as whe,wt as fT,xp as Hki,xq as HKe,xr as Igi,xs as ase,xt as Rx,yp as Gki,yq as MYe,yr as zoe,ys as cse,yt as dvt,zp as jWi,zq as hg,zr as joe,zs as lKe,zt as Dw}from"./chunks/index-w2hsw2bk.js";import{hu as $$e,ju as nZ}from"./chunks/index-srfy20t3.js";import{Cy as xc,Mz as $X,QB as tt,Ry as Ks,XB as Gvt,_v as rke,cC as qh,dC as W4,fC as zc,hC as rm,iC as Evi,jC as Qn,kC as KVi,oy as xu,qy as Z4}from"./chunks/index-k9a6e379.js";import{CD as u}from"./chunks/index-tf89v3fj.js";import"./chunks/index-jhg1vjf7.js";import{GD as ao,HD as crn,ID as E,JD as Kh,KD as gs,LD as ce}from"./chunks/index-fvb55vgy.js";function FQe(e){return e===0||e>=55296&&e<=57343||e>1114111}function MQe(e){if(FQe(e))return 65533;if(e>=128&&e<=159)return qXi[e-128]||e;return e}function OQe(e){return FQe(e)?65533:e}var qXi;var NQe=gs(()=>{qXi=[8364,0,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,0,381,0,0,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,0,382,376]});function LQe(e,t,i,n,r,o){let a=e.length,c=o*90,l=0,d=()=>{let L=C0[e.charCodeAt(l++)];return L<o?L:L*91-c+C0[e.charCodeAt(l++)]},p=i-n,m=i+r,h=new Int32Array(m);h.fill(-1,n,o),h.fill(-1,o+p,m);let f=new Int32Array(m),g=new Int32Array(m);function y(L,G){let V=0,ee=G,q=G+L;while(ee<q){let S=C0[e.charCodeAt(l++)];if(S<89)V+=S,h[ee++]=V;else if(S===89){let P=C0[e.charCodeAt(l++)]+2;while(P--)h[ee++]=++V}else{let P=C0[e.charCodeAt(l++)];V+=89+(P<90?P*91+C0[e.charCodeAt(l++)]:C0[e.charCodeAt(l++)]*8281+C0[e.charCodeAt(l++)]*91+C0[e.charCodeAt(l++)]),h[ee++]=V}}}y(n,0),y(p,o);let b=new Int32Array(r*2),v=0,w=0;function B(L,G){for(let V=0;V<L;V++){let ee=G+V,q=d(),S=d();b[w*2]=q,b[w*2+1]=S,w+=1,f[ee]=v;let P=(h[q]<0?g[q]:1)+(h[S]<0?g[S]:1);g[ee]=P,v+=P}}B(r-o+n,o+p),B(o-n,n);let T=new Uint16Array(v),F=0;for(let L=0;L<w;L++)for(let G=0;G<2;G++){let V=b[L*2+G],ee=h[V];if(ee<0){let q=f[V],S=q+g[V];while(q<S)T[F++]=T[q++]}else T[F++]=ee}let k=new Uint16Array(t),N=0;while(l<a){let L=C0[e.charCodeAt(l++)];if(L>=o)L=L*91-c+C0[e.charCodeAt(l++)];let G=h[L];if(G<0){let V=f[L],ee=V+g[L];while(V<ee)k[N++]=T[V++]}else k[N++]=G}return k}var C0;var jQe=gs(()=>{C0=(()=>{let e=new Uint8Array(127),t=0;for(let i=33;i<=126;i++)if(i!==34&&i!==36&&i!==92)e[i]=t++;return e})()});var wge;var zQe=gs(()=>{jQe();wge=LQe("!}.&u%}'&}*'~!6*)%&,~!J~!J~%L~y<~!R,~~%Lu~~#GD~~#|)1#%}^%}2%+#.##%##%}&%##%'#%##&%#%#'%#&#%#&#'#%%#&#%##%#)%''%&%#%#'%#%%#%%}%%%#%#&(23#%%#&-%0%('1#(##%#'##+%'*.:1}#%#6-+(%'%%#%%%}#L'2351&('%}&/N'(0(/*-%(%%}#'+&T%7.2}#&%&#%#36/5##%&%%#&#%%#))2%%##%&&'0~!#*+&'%1~!%).'3q?&%'1~!.##%6(~!+%%%(Gw'rT~!E#<nA%#jZ~!H%(~!42##~!*31&~!G%U~#)5~#`3~!J~!Z~%]~%Y~%C~!q~!u~#kz~%#~!6'~!D~!U~!?~#T~!c%~!G#'~%7|~!G~!J~!G&~#pb~(Df}#%}*&}#%##%##%##&#-}&'#'&%#.++}%mI,#,@&(}*%}*'%&##&#%##%}&0}#.},U},%}+%}&%}#%##&}B%(}(%}+%)})%##%#&}&%##%&}<%}>%#%&}*%}(%}9%}/%})%}*%}*%}?&}&%}3%}&*#%})%#%#)}#&#-#+*%E%%'%'#%}#*V##&##I}#&&##%&%#&&Qf%%))w/0+&%#(#.%-''''++++7}>%4'',##1,#%#&%##&#'##&#*#9)%&%}#*}%,#+P(%A&%#'&##wSD',9E00#y#@}(+}&%&>~!#~!X}#*}(&&}(&}(,%}%&#+&}#&}I%#%}%)#(},'%#*}4%%#%}(''}#/##(##),%-##%%)#&}(.}&%#&}%%}*&#%},&&}&%}#%*'#%})%}D&}&%}-&}6&#&}-,%}#%})-(~+`~,=?~I9'9%~!,#%})%})%}@%}?%}(~!?~#<~#pP~#BG~#=1#%K+~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u3x4ib#T)2@SmZM?C2F|Bj:rmu9@xPhI(a*a#U#`a3-5Abb|L~@:RhK9:4E|0@52B5G|#C::aY?C2F|-:2<BaY?C2F|.5Jvk!a)javYrquJu3x4ia#T)2@SmYM?C2F|HAxPhH(!a#U#`a*-5Abb|4~@:RhJ9:4E|R@52B5G|F:2<BaY?C2F|Sc^#Xa2j=Qq5CJvB!-g<v{z;hhM?C2F|Zi[vrv{z;hiM?C2F|XKsA>!a)-g<v{z;h[eb?C2F|]i[vrv{z;h]eb?C2F|^iZu.vix,hZq3ah!.(?C2F|QOu!5ShXM:2<BaY?C2F|P",13494,2713,49,25,61)});var HR;var Sge=gs(()=>{HR=new Uint16Array([512,26465,29036,7,0,2,4,116,24638,116,24636,8693,29807,24610,621,1,0,0,3,112,24614,111,115,24615])});var Hc;var UQe=gs(()=>{(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.FLAG13=8192]="FLAG13",e[e.BRANCH_LENGTH=8064]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE",e[e.VALUE_MASK=8191]="VALUE_MASK"})(Hc||(Hc={}))});function qQe(e){return e-vu.ZERO>>>0<=9}function $Xi(e){return(e|qZ)-vu.LOWER_A>>>0<=5}function HXi(e){return(e|qZ)-vu.LOWER_A>>>0<=25}function GXi(e){return e===vu.EQUALS||HXi(e)||qQe(e)}class kge{decodeTree;emitCodePoint;errors;state=Eu.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=D0.Strict;runConsumed=0;constructor(e,t,i){this.decodeTree=e,this.emitCodePoint=t,this.errors=i}startEntity(e){this.decodeMode=e,this.state=Eu.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case Eu.EntityStart:{if(e.charCodeAt(t)===vu.NUM)return this.state=Eu.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=Eu.NamedEntity,this.stateNamedEntity(e,t)}case Eu.NumericStart:return this.stateNumericStart(e,t);case Eu.NumericDecimal:return this.stateNumericDecimal(e,t);case Eu.NumericHex:return this.stateNumericHex(e,t);default:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){if(t>=e.length)return-1;if((e.charCodeAt(t)|qZ)===vu.LOWER_X)return this.state=Eu.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=Eu.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){let i=e.length,{result:n}=this,{consumed:r}=this;while(t<i){let o=e.charCodeAt(t);if(qQe(o)||$Xi(o)){let s=o<=vu.NINE?o-vu.ZERO:(o|qZ)-vu.LOWER_A+10;n=n*16+s,r+=1,t+=1}else return this.result=n,this.consumed=r,this.emitNumericEntity(o,3)}return this.result=n,this.consumed=r,-1}stateNumericDecimal(e,t){let i=e.length,{result:n}=this,{consumed:r}=this;while(t<i){let o=e.charCodeAt(t)-vu.ZERO;if(o>>>0>9)return this.result=n,this.consumed=r,this.emitNumericEntity(o+vu.ZERO,2);n=n*10+o,r+=1,t+=1}return this.result=n,this.consumed=r,-1}emitNumericEntity(e,t){if(this.consumed<=t)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===vu.SEMI)this.consumed+=1;else if(this.decodeMode===D0.Strict)return 0;if(this.emitCodePoint((this.decodeTree===HR?OQe:MQe)(this.result),this.consumed),this.errors){if(e!==vu.SEMI)this.errors.missingSemicolonAfterCharacterReference();this.errors.validateNumericCharacterReference(this.result)}return this.consumed}flushAndEmitLegacyOrReject(e,t,i,n){return this.consumed=e,this.excess=t,this.result===0||this.decodeMode===D0.Attribute&&(n===0||t>1||GXi(i))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:i}=this,n=e.length,r=this.decodeMode===D0.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=i[o];while(t<n){while((c&(Hc.VALUE_LENGTH|Hc.FLAG13))===0&&(c&Hc.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&Hc.JUMP_TABLE,f=(c&Hc.BRANCH_LENGTH)>>7;if(f===0){if(m!==h)return this.flushAndEmitLegacyOrReject(a,s,m,0);o+=1}else{let g=m-h;if(g>>>0>=f)return this.flushAndEmitLegacyOrReject(a,s,m,0);let y=i[o+1+g];if(y===0)return this.flushAndEmitLegacyOrReject(a,s,m,0);o=o+f+y&65535}if(c=i[o],t+=1,s+=1,t>=n)break}if(t>=n)break;if((c&(Hc.VALUE_LENGTH|Hc.FLAG13))===Hc.FLAG13){let m=(c&Hc.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&Hc.JUMP_TABLE))return this.flushAndEmitLegacyOrReject(a,s,f,0);t+=1,s+=1,h=1}while(h<m){if(t>=n)return this.treeIndex=o,this.excess=s,this.consumed=a,this.runConsumed=h,-1;let f=h-1,y=i[o+1+(f>>1)]>>((f&1)<<3)&255,b=e.charCodeAt(t);if(b!==y)return this.runConsumed=0,this.flushAndEmitLegacyOrReject(a,s,b,0);t+=1,s+=1,h+=1}this.runConsumed=0,o+=1+(m>>1),c=i[o];continue}let l=c>>>14,d=e.charCodeAt(t);if(l!==0){if(!r&&(c&Hc.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===vu.SEMI)return this.emitNamedEntityData(o,l,a+s);if(l===1)return this.flushAndEmitLegacyOrReject(a,s,d,l)}let p=WXi(i,c,o+(l||1),d);if(p<0)return this.flushAndEmitLegacyOrReject(a,s,d,l);o=p,c=i[o],t+=1,s+=1}if(!r&&c>>>14!==0&&(c&Hc.FLAG13)===0)this.result=o,a+=s-1,s=1;return this.treeIndex=o,this.excess=s,this.consumed=a,-1}emitNotTerminatedNamedEntity(){let{result:e,decodeTree:t}=this,i=t[e]>>>14;return this.emitNamedEntityData(e,i,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,i){let{decodeTree:n}=this;if(this.emitCodePoint(t===1?n[e]&Hc.VALUE_MASK:n[e+1],i),t===3)this.emitCodePoint(n[e+2],i);return i}end(){switch(this.state){case Eu.NamedEntity:return this.result!==0&&(this.decodeMode!==D0.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Eu.NumericDecimal:return this.emitNumericEntity(0,2);case Eu.NumericHex:return this.emitNumericEntity(0,3);case Eu.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function WXi(e,t,i,n){let r=(t&Hc.BRANCH_LENGTH)>>7,o=t&Hc.JUMP_TABLE;if(o){if(r===0)return n===o?i:-1;let c=n-o;if(c>>>0>=r)return-1;let l=e[i+c];return l===0?-1:i+r+l-1&65535}if(r===0)return-1;let s=r+1>>1,a=i+s+r;for(let c=0;c<r;c++){let d=e[i+(c>>1)]>>((c&1)<<3)&255;if(d===n){let p=i+s+c;return a+e[p]&65535}if(d>n)return-1}return-1}var vu,qZ=32,Eu,D0;var $Qe=gs(()=>{NQe();Sge();UQe();zQe();Sge();(function(e){e[e.AMP=38]="AMP",e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_X=120]="LOWER_X"})(vu||(vu={}));(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(Eu||(Eu={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(D0||(D0={}))});function Yk(e){return e===Ei.Space||e===Ei.NewLine||e===Ei.Tab||e===Ei.FormFeed||e===Ei.CarriageReturn}function WC(e){return e===Ei.Slash||e===Ei.Gt||Yk(e)}function ZXi(e){return e>=Ei.LowerA&&e<=Ei.LowerZ||e>=Ei.UpperA&&e<=Ei.UpperZ}class ZC{cbs;state=Ze.Text;buffer="";sectionStart=0;index=0;entityStart=0;baseState=Ze.Text;isSpecial=!1;running=!0;offset=0;xmlMode;decodeEntities;recognizeSelfClosing;entityDecoder;constructor({xmlMode:e=!1,decodeEntities:t=!0,recognizeSelfClosing:i=e},n){this.cbs=n,this.xmlMode=e,this.decodeEntities=t,this.recognizeSelfClosing=i,this.entityDecoder=new kge(e?HR:wge,(r,o)=>this.emitCodePoint(r,o))}reset(){this.state=Ze.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=Ze.Text,this.isSpecial=!1,this.currentSequence=ln.Empty,this.sequenceIndex=0,this.running=!0,this.offset=0}write(e){this.offset+=this.buffer.length,this.buffer=e,this.parse()}end(){if(this.running)this.finish()}pause(){this.running=!1}resume(){if(this.running=!0,this.index<this.buffer.length+this.offset)this.parse()}stateText(e){if(e===Ei.Lt||!this.decodeEntities&&this.fastForwardTo(Ei.Lt)){if(this.index>this.sectionStart)this.cbs.ontext(this.sectionStart,this.index);this.state=Ze.BeforeTagName,this.sectionStart=this.index}else if(this.decodeEntities&&e===Ei.Amp)this.startEntity()}currentSequence=ln.Empty;sequenceIndex=0;enterTagBody(){if(this.currentSequence===ln.Plaintext)this.currentSequence=ln.Empty,this.state=Ze.InPlainText;else if(this.isSpecial)this.state=Ze.InSpecialTag,this.sequenceIndex=0;else this.state=Ze.Text}stateSpecialStartSequence(e){let t=e|32;if(this.sequenceIndex<this.currentSequence.length){if(t===this.currentSequence[this.sequenceIndex]){this.sequenceIndex++;return}if(this.sequenceIndex===3){if(this.currentSequence===ln.ScriptEnd&&t===ln.StyleEnd[3]){this.currentSequence=ln.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===ln.TitleEnd&&t===ln.TextareaEnd[3]){this.currentSequence=ln.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===ln.NoembedEnd&&t===ln.NoframesEnd[4]){this.currentSequence=ln.NoframesEnd,this.sequenceIndex=5;return}}else if(WC(e)){this.sequenceIndex=0,this.state=Ze.InTagName,this.stateInTagName(e);return}this.isSpecial=!1,this.currentSequence=ln.Empty,this.sequenceIndex=0,this.state=Ze.InTagName,this.stateInTagName(e)}stateCDATASequence(e){if(e===ln.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===ln.Cdata.length)this.state=Ze.InCommentLike,this.currentSequence=ln.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1}else if(this.sequenceIndex=0,this.xmlMode)this.state=Ze.InDeclaration,this.stateInDeclaration(e);else this.state=Ze.InSpecialComment,this.stateInSpecialComment(e)}fastForwardTo(e){while(++this.index<this.buffer.length+this.offset)if(this.buffer.charCodeAt(this.index-this.offset)===e)return!0;return this.index=this.buffer.length+this.offset-1,!1}emitComment(e){this.cbs.oncomment(this.sectionStart,this.index,e),this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=Ze.Text}stateInCommentLike(e){if(!this.xmlMode&&this.currentSequence===ln.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&e===Ei.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===ln.CommentEnd&&this.sequenceIndex===2&&e===Ei.Gt)this.emitComment(2);else if(this.currentSequence===ln.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&e!==Ei.Gt)this.sequenceIndex=Number(e===Ei.Dash);else if(e===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===ln.CdataEnd)this.cbs.oncdata(this.sectionStart,this.index,2);else this.cbs.oncomment(this.sectionStart,this.index,3);this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=Ze.Text}}else if(this.sequenceIndex===0){if(this.fastForwardTo(this.currentSequence[0]))this.sequenceIndex=1}else if(e!==this.currentSequence[this.sequenceIndex-1])this.sequenceIndex=0}isTagStartChar(e){return this.xmlMode?!WC(e):ZXi(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(WC(e)){let t=this.index-this.currentSequence.length;if(this.sectionStart<t){let i=this.index;this.index=t,this.cbs.ontext(this.sectionStart,t),this.index=i}this.isSpecial=!1,this.sectionStart=t+2,this.stateInClosingTagName(e);return}this.sequenceIndex=0}if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(this.sequenceIndex===0){if(this.currentSequence===ln.TitleEnd||this.currentSequence===ln.TextareaEnd){if(this.decodeEntities&&e===Ei.Amp)this.startEntity()}else if(this.fastForwardTo(Ei.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(e===Ei.Lt)}stateBeforeTagName(e){if(e===Ei.ExclamationMark)this.state=Ze.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===Ei.Questionmark)if(this.xmlMode)this.state=Ze.InProcessingInstruction,this.sequenceIndex=0,this.sectionStart=this.index+1;else this.state=Ze.InSpecialComment,this.sectionStart=this.index;else if(this.isTagStartChar(e)){this.sectionStart=this.index;let t=this.xmlMode||this.cbs.isInForeignContext?.()?void 0:VXi.get(e|32);if(t===void 0)this.state=Ze.InTagName;else this.isSpecial=!0,this.currentSequence=t,this.sequenceIndex=3,this.state=Ze.SpecialStartSequence}else if(e===Ei.Slash)this.state=Ze.BeforeClosingTagName;else this.state=Ze.Text,this.stateText(e)}stateInTagName(e){if(WC(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(Yk(e))if(this.xmlMode);else this.state=Ze.InSpecialComment,this.sectionStart=this.index;else if(e===Ei.Gt){if(this.state=Ze.Text,!this.xmlMode)this.sectionStart=this.index+1}else this.state=this.isTagStartChar(e)?Ze.InClosingTagName:Ze.InSpecialComment,this.sectionStart=this.index}stateInClosingTagName(e){if(WC(e))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=Ze.AfterClosingTagName,this.stateAfterClosingTagName(e)}stateAfterClosingTagName(e){if(e===Ei.Gt||this.fastForwardTo(Ei.Gt))this.state=Ze.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(e){if(e===Ei.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(e===Ei.Slash)this.state=Ze.InSelfClosingTag;else if(!Yk(e))this.state=Ze.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(e){if(e===Ei.Gt){if(this.cbs.onselfclosingtag(this.index),this.sectionStart=this.index+1,!this.recognizeSelfClosing){this.enterTagBody();return}this.state=Ze.Text,this.isSpecial=!1,this.currentSequence=ln.Empty}else if(!Yk(e))this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===Ei.Eq||WC(e))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=Ze.AfterAttributeName,this.stateAfterAttributeName(e)}stateAfterAttributeName(e){if(e===Ei.Eq)this.state=Ze.BeforeAttributeValue;else if(e===Ei.Slash||e===Ei.Gt)this.cbs.onattribend(Im.NoValue,this.sectionStart),this.sectionStart=-1,this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!Yk(e))this.cbs.onattribend(Im.NoValue,this.sectionStart),this.state=Ze.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(e){if(e===Ei.DoubleQuote)this.state=Ze.InAttributeValueDq,this.sectionStart=this.index+1;else if(e===Ei.SingleQuote)this.state=Ze.InAttributeValueSq,this.sectionStart=this.index+1;else if(!Yk(e))this.sectionStart=this.index,this.state=Ze.InAttributeValueNq,this.stateInAttributeValueNoQuotes(e)}handleInAttributeValue(e,t){if(e===t||!this.decodeEntities&&this.fastForwardTo(t))this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(t===Ei.DoubleQuote?Im.Double:Im.Single,this.index+1),this.state=Ze.BeforeAttributeName;else if(this.decodeEntities&&e===Ei.Amp)this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,Ei.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,Ei.SingleQuote)}stateInAttributeValueNoQuotes(e){if(Yk(e)||e===Ei.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(Im.Unquoted,this.index),this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(this.decodeEntities&&e===Ei.Amp)this.startEntity()}stateBeforeDeclaration(e){if(e===Ei.OpeningSquareBracket)this.state=Ze.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=e===Ei.Dash?Ze.BeforeComment:Ze.InDeclaration;else if((e|32)===ln.Doctype[0])this.state=Ze.DeclarationSequence,this.currentSequence=ln.Doctype,this.sequenceIndex=1;else if(e===Ei.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else if(e===Ei.Dash)this.state=Ze.BeforeComment;else this.state=Ze.InSpecialComment}stateDeclarationSequence(e){if(this.sequenceIndex===this.currentSequence.length)this.state=Ze.InDeclaration,this.stateInDeclaration(e);else if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(e===Ei.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else this.state=Ze.InSpecialComment}stateInDeclaration(e){if(e===Ei.Gt||this.fastForwardTo(Ei.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=Ze.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(e){if(e===Ei.Questionmark)this.sequenceIndex=1;else if(e===Ei.Gt&&this.sequenceIndex===1)this.cbs.onprocessinginstruction(this.sectionStart,this.index-1),this.sequenceIndex=0,this.state=Ze.Text,this.sectionStart=this.index+1;else this.sequenceIndex=Number(this.fastForwardTo(Ei.Questionmark))}stateBeforeComment(e){if(e===Ei.Dash)this.state=Ze.InCommentLike,this.currentSequence=ln.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=Ze.InDeclaration;else if(e===Ei.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else this.state=Ze.InSpecialComment}stateInSpecialComment(e){if(e===Ei.Gt||this.fastForwardTo(Ei.Gt))this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1}startEntity(){this.baseState=this.state,this.state=Ze.InEntity,this.entityStart=this.index,this.entityDecoder.startEntity(this.xmlMode?D0.Strict:this.baseState===Ze.Text||this.baseState===Ze.InSpecialTag?D0.Legacy:D0.Attribute)}stateInEntity(){let e=this.index-this.offset,t=this.entityDecoder.write(this.buffer,e);if(t>=0){if(this.state=this.baseState,t===0)this.index-=1}else{if(e<this.buffer.length&&this.buffer.charCodeAt(e)===Ei.Amp){this.state=this.baseState,this.index-=1;return}this.index=this.offset+this.buffer.length-1}}cleanup(){if(this.running&&this.sectionStart!==this.index){if(this.state===Ze.Text||this.state===Ze.InPlainText||this.state===Ze.InSpecialTag&&this.sequenceIndex===0)this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index;else if(this.state===Ze.InAttributeValueDq||this.state===Ze.InAttributeValueSq||this.state===Ze.InAttributeValueNq)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=this.index}}shouldContinue(){return this.index<this.buffer.length+this.offset&&this.running}parse(){while(this.shouldContinue()){let e=this.buffer.charCodeAt(this.index-this.offset);switch(this.state){case Ze.Text:{this.stateText(e);break}case Ze.InPlainText:{this.index=this.buffer.length+this.offset-1;break}case Ze.SpecialStartSequence:{this.stateSpecialStartSequence(e);break}case Ze.InSpecialTag:{this.stateInSpecialTag(e);break}case Ze.CDATASequence:{this.stateCDATASequence(e);break}case Ze.DeclarationSequence:{this.stateDeclarationSequence(e);break}case Ze.InAttributeValueDq:{this.stateInAttributeValueDoubleQuotes(e);break}case Ze.InAttributeName:{this.stateInAttributeName(e);break}case Ze.InCommentLike:{this.stateInCommentLike(e);break}case Ze.InSpecialComment:{this.stateInSpecialComment(e);break}case Ze.BeforeAttributeName:{this.stateBeforeAttributeName(e);break}case Ze.InTagName:{this.stateInTagName(e);break}case Ze.InClosingTagName:{this.stateInClosingTagName(e);break}case Ze.BeforeTagName:{this.stateBeforeTagName(e);break}case Ze.AfterAttributeName:{this.stateAfterAttributeName(e);break}case Ze.InAttributeValueSq:{this.stateInAttributeValueSingleQuotes(e);break}case Ze.BeforeAttributeValue:{this.stateBeforeAttributeValue(e);break}case Ze.BeforeClosingTagName:{this.stateBeforeClosingTagName(e);break}case Ze.AfterClosingTagName:{this.stateAfterClosingTagName(e);break}case Ze.InAttributeValueNq:{this.stateInAttributeValueNoQuotes(e);break}case Ze.InSelfClosingTag:{this.stateInSelfClosingTag(e);break}case Ze.InDeclaration:{this.stateInDeclaration(e);break}case Ze.BeforeDeclaration:{this.stateBeforeDeclaration(e);break}case Ze.BeforeComment:{this.stateBeforeComment(e);break}case Ze.InProcessingInstruction:{this.stateInProcessingInstruction(e);break}case Ze.InEntity:{this.stateInEntity();break}}this.index++}this.cleanup()}finish(){if(this.state===Ze.InEntity)this.entityDecoder.end(),this.state=this.baseState;this.handleTrailingData(),this.cbs.onend()}handleTrailingCommentLikeData(e){if(this.state!==Ze.InCommentLike)return!1;if(this.currentSequence===ln.CdataEnd)if(this.xmlMode){if(this.sectionStart<e)this.cbs.oncdata(this.sectionStart,e,0)}else{let t=this.sectionStart-ln.Cdata.length-1;this.cbs.oncomment(t,e,0)}else{let t=this.xmlMode?0:Math.min(this.sequenceIndex,ln.CommentEnd.length-1);this.cbs.oncomment(this.sectionStart,e,t)}return!0}handleTrailingMarkupDeclaration(e){if(this.xmlMode)switch(this.state){case Ze.InSpecialComment:case Ze.BeforeComment:case Ze.CDATASequence:case Ze.DeclarationSequence:case Ze.InDeclaration:return this.cbs.ontext(this.sectionStart,e),!0;default:return!1}switch(this.state){case Ze.BeforeDeclaration:case Ze.InSpecialComment:case Ze.BeforeComment:case Ze.CDATASequence:return this.cbs.oncomment(this.sectionStart,e,0),!0;case Ze.DeclarationSequence:{if(this.sequenceIndex!==ln.Doctype.length)this.cbs.oncomment(this.sectionStart,e,0);return!0}case Ze.InDeclaration:return!0;default:return!1}}handleTrailingData(){let e=this.buffer.length+this.offset;if(this.handleTrailingCommentLikeData(e)||this.handleTrailingMarkupDeclaration(e))return;if(this.sectionStart>=e)return;switch(this.state){case Ze.InTagName:case Ze.BeforeAttributeName:case Ze.BeforeAttributeValue:case Ze.AfterAttributeName:case Ze.InAttributeName:case Ze.InAttributeValueSq:case Ze.InAttributeValueDq:case Ze.InAttributeValueNq:case Ze.InClosingTagName:break;default:this.cbs.ontext(this.sectionStart,e)}}emitCodePoint(e,t){if(this.baseState!==Ze.Text&&this.baseState!==Ze.InSpecialTag){if(this.sectionStart<this.entityStart)this.cbs.onattribdata(this.sectionStart,this.entityStart);this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.onattribentity(e)}else{if(this.sectionStart<this.entityStart)this.cbs.ontext(this.sectionStart,this.entityStart);this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.ontextentity(e,this.sectionStart)}}}var Ei,Ze,Im,ln,VXi;var Bge=gs(()=>{$Qe();(function(e){e[e.Tab=9]="Tab",e[e.NewLine=10]="NewLine",e[e.FormFeed=12]="FormFeed",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.ExclamationMark=33]="ExclamationMark",e[e.Number=35]="Number",e[e.Amp=38]="Amp",e[e.SingleQuote=39]="SingleQuote",e[e.DoubleQuote=34]="DoubleQuote",e[e.Dash=45]="Dash",e[e.Slash=47]="Slash",e[e.Zero=48]="Zero",e[e.Nine=57]="Nine",e[e.Semi=59]="Semi",e[e.Lt=60]="Lt",e[e.Eq=61]="Eq",e[e.Gt=62]="Gt",e[e.Questionmark=63]="Questionmark",e[e.UpperA=65]="UpperA",e[e.LowerA=97]="LowerA",e[e.UpperF=70]="UpperF",e[e.LowerF=102]="LowerF",e[e.UpperZ=90]="UpperZ",e[e.LowerZ=122]="LowerZ",e[e.LowerX=120]="LowerX",e[e.OpeningSquareBracket=91]="OpeningSquareBracket"})(Ei||(Ei={}));(function(e){e[e.Text=1]="Text",e[e.BeforeTagName=2]="BeforeTagName",e[e.InTagName=3]="InTagName",e[e.InSelfClosingTag=4]="InSelfClosingTag",e[e.BeforeClosingTagName=5]="BeforeClosingTagName",e[e.InClosingTagName=6]="InClosingTagName",e[e.AfterClosingTagName=7]="AfterClosingTagName",e[e.BeforeAttributeName=8]="BeforeAttributeName",e[e.InAttributeName=9]="InAttributeName",e[e.AfterAttributeName=10]="AfterAttributeName",e[e.BeforeAttributeValue=11]="BeforeAttributeValue",e[e.InAttributeValueDq=12]="InAttributeValueDq",e[e.InAttributeValueSq=13]="InAttributeValueSq",e[e.InAttributeValueNq=14]="InAttributeValueNq",e[e.BeforeDeclaration=15]="BeforeDeclaration",e[e.InDeclaration=16]="InDeclaration",e[e.InProcessingInstruction=17]="InProcessingInstruction",e[e.BeforeComment=18]="BeforeComment",e[e.CDATASequence=19]="CDATASequence",e[e.DeclarationSequence=20]="DeclarationSequence",e[e.InSpecialComment=21]="InSpecialComment",e[e.InCommentLike=22]="InCommentLike",e[e.SpecialStartSequence=23]="SpecialStartSequence",e[e.InSpecialTag=24]="InSpecialTag",e[e.InPlainText=25]="InPlainText",e[e.InEntity=26]="InEntity"})(Ze||(Ze={}));(function(e){e[e.NoValue=0]="NoValue",e[e.Unquoted=1]="Unquoted",e[e.Single=2]="Single",e[e.Double=3]="Double"})(Im||(Im={}));ln={Empty:new Uint8Array(0),Cdata:new Uint8Array([67,68,65,84,65,91]),CdataEnd:new Uint8Array([93,93,62]),CommentEnd:new Uint8Array([45,45,33,62]),Doctype:new Uint8Array([100,111,99,116,121,112,101]),IframeEnd:new Uint8Array([60,47,105,102,114,97,109,101]),NoembedEnd:new Uint8Array([60,47,110,111,101,109,98,101,100]),NoframesEnd:new Uint8Array([60,47,110,111,102,114,97,109,101,115]),Plaintext:new Uint8Array([60,47,112,108,97,105,110,116,101,120,116]),ScriptEnd:new Uint8Array([60,47,115,99,114,105,112,116]),StyleEnd:new Uint8Array([60,47,115,116,121,108,101]),TitleEnd:new Uint8Array([60,47,116,105,116,108,101]),TextareaEnd:new Uint8Array([60,47,116,101,120,116,97,114,101,97]),XmpEnd:new Uint8Array([60,47,120,109,112])},VXi=new Map([[ln.IframeEnd[2],ln.IframeEnd],[ln.NoembedEnd[2],ln.NoembedEnd],[ln.Plaintext[2],ln.Plaintext],[ln.ScriptEnd[2],ln.ScriptEnd],[ln.TitleEnd[2],ln.TitleEnd],[ln.XmpEnd[2],ln.XmpEnd]])});class YC{options;startIndex=0;endIndex=0;openTagStart=0;tagname="";attribname="";attribvalue="";attribs=null;stack=[];foreignContext;cbs;lowerCaseTagNames;lowerCaseAttributeNames;recognizeSelfClosing;htmlMode;tokenizer;buffers=[];bufferOffset=0;writeIndex=0;ended=!1;constructor(e,t={}){this.options=t,this.cbs=e??{},this.htmlMode=!this.options.xmlMode,this.lowerCaseTagNames=t.lowerCaseTags??this.htmlMode,this.lowerCaseAttributeNames=t.lowerCaseAttributeNames??this.htmlMode,this.recognizeSelfClosing=t.recognizeSelfClosing??!this.htmlMode,this.tokenizer=new(t.Tokenizer??ZC)(this.options,this),this.foreignContext=[cE.None],this.cbs.onparserinit?.(this)}ontext(e,t){let i=this.getSlice(e,t);this.endIndex=t-1,this.cbs.ontext?.(i),this.startIndex=t}ontextentity(e,t){this.endIndex=t-1,this.cbs.ontext?.(HQe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==cE.None}isVoidElement(e){return this.htmlMode&&YXi.has(e)}readTagName(e,t){let i=this.lowerCaseTagNames?this.getSlice(e,t).toLowerCase():this.getSlice(e,t);if(!(this.lowerCaseTagNames&&this.htmlMode))return i;if(this.foreignContext[0]===cE.Svg)return YQe.get(i)??i;if(this.foreignContext.length>1){let n=YQe.get(i);if(n!==void 0&&this.stack.includes(n))return n}if(!this.isInForeignContext())return i==="image"?"img":i;return i}onopentagname(e,t){this.endIndex=t,this.emitOpenTag(this.readTagName(e,t))}emitOpenTag(e){if(this.openTagStart=this.startIndex,this.tagname=e,this.htmlMode&&e==="form"&&this.stack.includes("form")){this.tagname="";return}let t=this.htmlMode&&KXi.get(e);if(t)while(this.stack.length>0&&t.has(this.stack[0]))this.popElement(!0);if(!this.isVoidElement(e)){if(this.stack.unshift(e),this.htmlMode){if(e==="svg")this.foreignContext.unshift(cE.Svg);else if(e==="math")this.foreignContext.unshift(cE.MathML);else if(KQe.has(e))this.foreignContext.unshift(cE.None)}}if(this.cbs.onopentagname?.(e),this.cbs.onopentag)this.attribs={}}endOpenTag(e){if(this.startIndex=this.openTagStart,this.attribs)this.cbs.onopentag?.(this.tagname,this.attribs,e),this.attribs=null;if(this.cbs.onclosetag&&this.isVoidElement(this.tagname))this.cbs.onclosetag(this.tagname,!0);this.tagname=""}onopentagend(e){this.endIndex=e,this.endOpenTag(!1),this.startIndex=e+1}onclosetag(e,t){this.endIndex=t;let i=this.readTagName(e,t);if(!this.isVoidElement(i)){let n=this.stack.indexOf(i);if(n!==-1){for(let r=0;r<n;r++)this.popElement(!0);this.popElement(!1)}else if(this.htmlMode&&i==="p")this.emitOpenTag("p"),this.closeCurrentTag(!0)}else if(this.htmlMode&&i==="br")this.cbs.onopentagname?.("br"),this.cbs.onopentag?.("br",{},!0),this.cbs.onclosetag?.("br",!1);this.startIndex=t+1}onselfclosingtag(e){if(this.endIndex=e,this.recognizeSelfClosing||this.isInForeignContext())this.closeCurrentTag(!1),this.startIndex=e+1;else this.onopentagend(e)}popElement(e){let t=this.stack.shift();if(this.htmlMode&&(JXi.has(t)||KQe.has(t)))this.foreignContext.shift();this.cbs.onclosetag?.(t,e)}closeCurrentTag(e){let t=this.tagname;if(this.endOpenTag(e),this.stack[0]===t)this.popElement(!e)}onattribname(e,t){this.startIndex=e;let i=this.getSlice(e,t);this.attribname=this.lowerCaseAttributeNames?i.toLowerCase():i}onattribdata(e,t){this.attribvalue+=this.getSlice(e,t)}onattribentity(e){this.attribvalue+=HQe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===Im.Double?'"':e===Im.Single?"'":e===Im.NoValue?void 0:null),this.attribs&&!Object.hasOwn(this.attribs,this.attribname))this.attribs[this.attribname]=this.attribvalue;this.attribvalue=""}getInstructionName(e){let t=e.search(QXi),i=t<0?e:e.substr(0,t);if(this.lowerCaseTagNames)i=i.toLowerCase();return i}ondeclaration(e,t){this.endIndex=t;let i=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let n=this.htmlMode?this.lowerCaseTagNames?VQe:i.slice(0,VQe.length):this.getInstructionName(i);this.cbs.onprocessinginstruction(`!${n}`,`!${i}`)}this.startIndex=t+1}onprocessinginstruction(e,t){this.endIndex=t;let i=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let n=this.getInstructionName(i);this.cbs.onprocessinginstruction(`?${n}`,`?${i}`)}this.startIndex=t+1}oncomment(e,t,i){this.endIndex=t,this.cbs.oncomment?.(this.getSlice(e,t-i)),this.cbs.oncommentend?.(),this.startIndex=t+1}oncdata(e,t,i){this.endIndex=t;let n=this.getSlice(e,t-i);if(!this.htmlMode||this.options.recognizeCDATA)this.cbs.oncdatastart?.(),this.cbs.ontext?.(n),this.cbs.oncdataend?.();else if(this.isInForeignContext())this.cbs.ontext?.(n);else this.cbs.oncomment?.(`[CDATA[${n}]]`),this.cbs.oncommentend?.();this.startIndex=t+1}onend(){if(this.cbs.onclosetag){this.endIndex=this.startIndex;for(let e=0;e<this.stack.length;e++)this.cbs.onclosetag(this.stack[e],!0)}this.cbs.onend?.()}reset(){this.cbs.onreset?.(),this.tokenizer.reset(),this.tagname="",this.attribname="",this.attribvalue="",this.attribs=null,this.stack.length=0,this.startIndex=0,this.endIndex=0,this.cbs.onparserinit?.(this),this.buffers.length=0,this.foreignContext.length=0,this.foreignContext.unshift(cE.None),this.bufferOffset=0,this.writeIndex=0,this.ended=!1}parseComplete(e){this.reset(),this.end(e)}getSlice(e,t){if(e===t)return"";while(e-this.bufferOffset>=this.buffers[0].length)this.shiftBuffer();let i=this.buffers[0].slice(e-this.bufferOffset,t-this.bufferOffset);while(t-this.bufferOffset>this.buffers[0].length)this.shiftBuffer(),i+=this.buffers[0].slice(0,t-this.bufferOffset);return i}shiftBuffer(){this.bufferOffset+=this.buffers[0].length,this.writeIndex--,this.buffers.shift()}write(e){if(this.ended){this.cbs.onerror?.(Error(".write() after done!"));return}if(this.buffers.push(e),this.tokenizer.running)this.tokenizer.write(e),this.writeIndex++}end(e){if(this.ended){this.cbs.onerror?.(Error(".end() after done!"));return}if(e)this.write(e);this.ended=!0,this.tokenizer.end()}pause(){this.tokenizer.pause()}resume(){this.tokenizer.resume();while(this.tokenizer.running&&this.writeIndex<this.buffers.length)this.tokenizer.write(this.buffers[this.writeIndex++]);if(this.ended)this.tokenizer.end()}}var HQe,VC,Qs,KC,GQe,WQe,ZQe,KXi,VQe="doctype",YXi,JXi,KQe,YQe,cE,QXi;var Cge=gs(()=>{Bge();({fromCodePoint:HQe}=String),VC=new Set(["input","option","optgroup","select","button","datalist","textarea"]),Qs=new Set(["p"]),KC=new Set(["h1","h2","h3","h4","h5","h6","p"]),GQe=new Set(["thead","tbody"]),WQe=new Set(["dd","dt"]),ZQe=new Set(["rt","rp"]),KXi=new Map([["tr",new Set(["tr","th","td"])],["th",new Set(["th"])],["td",new Set(["thead","th","td"])],["body",new Set(["head","link","script"])],["a",new Set(["a"])],["li",new Set(["li"])],["p",Qs],["h1",KC],["h2",KC],["h3",KC],["h4",KC],["h5",KC],["h6",KC],["select",VC],["input",VC],["output",VC],["button",VC],["datalist",VC],["textarea",VC],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",WQe],["dt",WQe],["address",Qs],["article",Qs],["aside",Qs],["blockquote",Qs],["details",Qs],["div",Qs],["dl",Qs],["fieldset",Qs],["figcaption",Qs],["figure",Qs],["footer",Qs],["form",Qs],["header",Qs],["hr",Qs],["main",Qs],["nav",Qs],["ol",Qs],["pre",Qs],["section",Qs],["table",Qs],["ul",Qs],["rt",ZQe],["rp",ZQe],["tbody",GQe],["tfoot",GQe]]),YXi=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),JXi=new Set(["math","svg"]),KQe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),YQe=new Map([["altglyph","altGlyph"],["altglyphdef","altGlyphDef"],["altglyphitem","altGlyphItem"],["animatecolor","animateColor"],["animatemotion","animateMotion"],["animatetransform","animateTransform"],["clippath","clipPath"],["feblend","feBlend"],["fecolormatrix","feColorMatrix"],["fecomponenttransfer","feComponentTransfer"],["fecomposite","feComposite"],["feconvolvematrix","feConvolveMatrix"],["fediffuselighting","feDiffuseLighting"],["fedisplacementmap","feDisplacementMap"],["fedistantlight","feDistantLight"],["fedropshadow","feDropShadow"],["feflood","feFlood"],["fefunca","feFuncA"],["fefuncb","feFuncB"],["fefuncg","feFuncG"],["fefuncr","feFuncR"],["fegaussianblur","feGaussianBlur"],["feimage","feImage"],["femerge","feMerge"],["femergenode","feMergeNode"],["femorphology","feMorphology"],["feoffset","feOffset"],["fepointlight","fePointLight"],["fespecularlighting","feSpecularLighting"],["fespotlight","feSpotLight"],["fetile","feTile"],["feturbulence","feTurbulence"],["foreignobject","foreignObject"],["glyphref","glyphRef"],["lineargradient","linearGradient"],["radialgradient","radialGradient"],["textpath","textPath"]]);(function(e){e[e.None=0]="None",e[e.Svg=1]="Svg",e[e.MathML=2]="MathML"})(cE||(cE={}));QXi=/\s|\//});var $Z={};Kh($Z,{CDATA:()=>Oge,Comment:()=>Pge,Directive:()=>Tge,Doctype:()=>XXi,ElementType:()=>mr,Root:()=>Ige,Script:()=>Rge,Style:()=>Fge,Tag:()=>Mge,Text:()=>_ge,isTag:()=>Dge});function Dge(e){return e.type===mr.Tag||e.type===mr.Script||e.type===mr.Style}var mr,Ige,_ge,Tge,Pge,Rge,Fge,Mge,Oge,XXi;var JC=gs(()=>{(function(e){e.Root="root",e.Text="text",e.Directive="directive",e.Comment="comment",e.Script="script",e.Style="style",e.Tag="tag",e.CDATA="cdata",e.Doctype="doctype"})(mr||(mr={}));Ige=mr.Root,_ge=mr.Text,Tge=mr.Directive,Pge=mr.Comment,Rge=mr.Script,Fge=mr.Style,Mge=mr.Tag,Oge=mr.CDATA,XXi=mr.Doctype});class Lge{parent=null;prev=null;next=null;startIndex=null;endIndex=null;get parentNode(){return this.parent}set parentNode(e){this.parent=e}get previousSibling(){return this.prev}set previousSibling(e){this.prev=e}get nextSibling(){return this.next}set nextSibling(e){this.next=e}cloneNode(e=!1){return JQe(this,e)}}function Au(e){return Dge(e)}function YZ(e){return e.type===mr.CDATA}function Pw(e){return e.type===mr.Text}function jge(e){return e.type===mr.Comment}function een(e){return e.type===mr.Directive}function ten(e){return e.type===mr.Root}function yp(e){return Object.hasOwn(e,"children")}function JQe(e,t=!1){let i;if(Pw(e))i=new GR(e.data);else if(jge(e))i=new GZ(e.data);else if(Au(e)){let n=t?Nge(e.children):[],r=new KZ(e.name,{...e.attribs},n);for(let o of n)o.parent=r;if(e.namespace!=null)r.namespace=e.namespace;if(e["x-attribsNamespace"])r["x-attribsNamespace"]={...e["x-attribsNamespace"]};if(e["x-attribsPrefix"])r["x-attribsPrefix"]={...e["x-attribsPrefix"]};i=r}else if(YZ(e)){let n=t?Nge(e.children):[],r=new VZ(n);for(let o of n)o.parent=r;i=r}else if(ten(e)){let n=t?Nge(e.children):[],r=new WR(n);for(let o of n)o.parent=r;if(e["x-mode"])r["x-mode"]=e["x-mode"];i=r}else if(een(e)){let n=new WZ(e.name,e.data);if(e["x-name"]!=null)n["x-name"]=e["x-name"],n["x-publicId"]=e["x-publicId"],n["x-systemId"]=e["x-systemId"];i=n}else throw Error(`Not implemented yet: ${e.type}`);if(i.startIndex=e.startIndex,i.endIndex=e.endIndex,e.sourceCodeLocation!=null)i.sourceCodeLocation=e.sourceCodeLocation;return i}function Nge(e){let t=e.map((i)=>JQe(i,!0));for(let i=1;i<t.length;i++)t[i].prev=t[i-1],t[i-1].next=t[i];return t}var HZ,GR,GZ,WZ,ZZ,VZ,WR,KZ;var zge=gs(()=>{JC();HZ=class HZ extends Lge{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};GR=class GR extends HZ{type=mr.Text;get nodeType(){return 3}};GZ=class GZ extends HZ{type=mr.Comment;get nodeType(){return 8}};WZ=class WZ extends HZ{type=mr.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};ZZ=class ZZ extends Lge{children;constructor(e){super();this.children=e}get firstChild(){return this.children[0]??null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(e){this.children=e}};VZ=class VZ extends ZZ{type=mr.CDATA;get nodeType(){return 4}};WR=class WR extends ZZ{type=mr.Root;get nodeType(){return 9}};KZ=class KZ extends ZZ{name;attribs;type;constructor(e,t,i=[],n=e==="script"?mr.Script:e==="style"?mr.Style:mr.Tag){super(i);this.name=e,this.attribs=t,this.type=n}get nodeType(){return 1}get tagName(){return this.name}set tagName(e){this.name=e}get attributes(){return Object.keys(this.attribs).map((e)=>({name:e,value:this.attribs[e],namespace:this["x-attribsNamespace"]?.[e],prefix:this["x-attribsPrefix"]?.[e]}))}namespace;"x-attribsNamespace";"x-attribsPrefix"}});class Jk{dom=[];root=new WR(this.dom);callback;options;elementCB;done=!1;tagStack=[this.root];lastNode=null;parser=null;constructor(e,t,i){if(typeof t==="function")i=t,t=QQe;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??QQe,this.elementCB=i??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new WR(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){if(this.done)return;this.done=!0,this.parser=null,this.handleCallback(null)}onerror(e){this.handleCallback(e)}onclosetag(){this.lastNode=null;let e=this.tagStack.pop();if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(this.elementCB)this.elementCB(e)}onopentag(e,t){let i=this.options.xmlMode?mr.Tag:void 0,n=new KZ(e,t,void 0,i);this.addNode(n),this.tagStack.push(n)}ontext(e){let{lastNode:t}=this;if(t&&t.type===mr.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let i=new GR(e);this.addNode(i),this.lastNode=i}}oncomment(e){if(this.lastNode&&this.lastNode.type===mr.Comment){this.lastNode.data+=e;return}let t=new GZ(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new GR(""),t=new VZ([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let i=new WZ(e,t);this.addNode(i)}handleCallback(e){if(typeof this.callback==="function")this.callback(e,this.dom);else if(e)throw e}addNode(e){let t=this.tagStack[this.tagStack.length-1],i=t.children[t.children.length-1];if(this.options.withStartIndices&&this.parser)e.startIndex=this.parser.startIndex;if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(t.children.push(e),i)e.prev=i,i.next=e;e.parent=t,this.lastNode=null}}var QQe;var Rw=gs(()=>{JC();zge();zge();QQe={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function QC(e,t,i=!0,n=Number.POSITIVE_INFINITY){return XQe(e,Array.isArray(t)?t:[t],i,n)}function XQe(e,t,i,n){let r=[],o=[Array.isArray(t)?t:[t]],s=[0];for(;;){if(s[0]>=o[0].length){if(s.length===1)return r;o.shift(),s.shift();continue}let a=o[0][s[0]++];if(e(a)){if(r.push(a),--n<=0)return r}if(i&&yp(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function JZ(e,t,i=!0){let n=Array.isArray(t)?t:[t];for(let r of n){if(Au(r)&&e(r))return r;if(i&&yp(r)&&r.children.length>0){let o=JZ(e,r.children,!0);if(o)return o}}return null}function eXe(e,t){return(Array.isArray(t)?t:[t]).some((i)=>Au(i)&&e(i)||yp(i)&&eXe(e,i.children))}function ien(e,t){let i=[],n=[Array.isArray(t)?t:[t]],r=[0];for(;;){if(r[0]>=n[0].length){if(n.length===1)return i;n.shift(),r.shift();continue}let o=n[0][r[0]++];if(Au(o)&&e(o))i.push(o);if(yp(o)&&o.children.length>0)r.unshift(0),n.unshift(o.children)}}var Uge=gs(()=>{Rw()});function qge(e,t){if(typeof t==="function")return(i)=>Au(i)&&t(i.attribs[e]);return(i)=>Au(i)&&i.attribs[e]===t}function nen(e,t){return(i)=>e(i)||t(i)}function tXe(e){let t=Object.keys(e).map((i)=>{let n=e[i];return Object.hasOwn(QZ,i)?QZ[i](n):qge(i,n)});return t.length===0?null:t.reduce(nen)}function ren(e,t){let i=tXe(e);return i?i(t):!0}function oen(e,t,i,n=Number.POSITIVE_INFINITY){let r=tXe(e);return r?QC(r,t,i,n):[]}function sen(e,t,i=!0){if(!Array.isArray(t))t=[t];return JZ(qge("id",e),t,i)}function Qk(e,t,i=!0,n=Number.POSITIVE_INFINITY){return QC(QZ.tag_name(e),t,i,n)}function aen(e,t,i=!0,n=Number.POSITIVE_INFINITY){return QC(qge("class",e),t,i,n)}function cen(e,t,i=!0,n=Number.POSITIVE_INFINITY){return QC(QZ.tag_type(e),t,i,n)}var QZ;var $ge=gs(()=>{Rw();Uge();QZ={tag_name(e){if(typeof e==="function")return(t)=>Au(t)&&e(t.name);if(e==="*")return Au;return(t)=>Au(t)&&t.name===e},tag_type(e){if(typeof e==="function")return(t)=>e(t.type);return(t)=>t.type===e},tag_contains(e){if(typeof e==="function")return(t)=>Pw(t)&&e(t.data);return(t)=>Pw(t)&&t.data===e}}});function nXe(e){return e===34?""":e===38?"&":e===39?"'":e===60?"<":e===62?">":" "}function iXe(e){return e>=128||e>=32&&e<64&&(len>>>e&1)===1}function XZ(e){let{length:t}=e,i,n=0,r=0;while(r<t){let o=e.charCodeAt(r);if(!iXe(o)){let a=Math.min(r+32,t),c=r+1;while(c<a&&!iXe(e.charCodeAt(c)))c++;if(c<a){r=c;continue}if(c>=t)break;if(Hge.lastIndex=c,!Hge.test(e))break;r=Hge.lastIndex-1;continue}if(i===void 0)i=e.substring(0,r);else if(n!==r)i+=e.substring(n,r);if(o<64){i+=nXe(o),n=r+=1;continue}let s=e.codePointAt(r);if(i+=`&#x${s.toString(16)};`,s!==o)r++;n=r+=1}if(i===void 0)return e;if(n<t)i+=e.substr(n);return i}function rXe(e,t){if(e.lastIndex=0,!e.test(t))return t;let i="",n=0;do{let r=e.lastIndex-1;if(n!==r)i+=t.substring(n,r);let o=t.charCodeAt(r);i+=nXe(o),n=r+1}while(e.test(t));return i+t.substring(n)}function Gge(e){return rXe(uen,e)}function Wge(e){return rXe(den,e)}var len=1342177476,Hge,uen,den;var oXe=gs(()=>{Hge=/["&'<>\u0080-\uFFFF]/g;uen=/["&\u{A0}]/gu;den=/[&<>\u{A0}]/gu});var sXe,aXe;var cXe=gs(()=>{oXe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(sXe||(sXe={}));(function(e){e[e.UTF8=0]="UTF8",e[e.ASCII=1]="ASCII",e[e.Extensive=2]="Extensive",e[e.Attribute=3]="Attribute",e[e.Text=4]="Text"})(aXe||(aXe={}))});var lXe,uXe;var dXe=gs(()=>{lXe=new Map("altGlyph altGlyphDef altGlyphItem animateColor animateMotion animateTransform clipPath feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence foreignObject glyphRef linearGradient radialGradient textPath".split(" ").map((e)=>[e.toLowerCase(),e])),uXe=new Map("definitionURL attributeName attributeType baseFrequency baseProfile calcMode clipPathUnits diffuseConstant edgeMode filterUnits glyphRef gradientTransform gradientUnits kernelMatrix kernelUnitLength keyPoints keySplines keyTimes lengthAdjust limitingConeAngle markerHeight markerUnits markerWidth maskContentUnits maskUnits numOctaves pathLength patternContentUnits patternTransform patternUnits pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits refX refY repeatCount repeatDur requiredExtensions requiredFeatures specularConstant specularExponent spreadMethod startOffset stdDeviation stitchTiles surfaceScale systemLanguage tableValues targetX targetY textLength viewBox viewTarget xChannelSelector yChannelSelector zoomAndPan".split(" ").map((e)=>[e.toLowerCase(),e]))});function xen(e,t={}){let i="length"in e?e:[e],n=t.xmlMode??!1,r="";for(let o=0;o<i.length;o++)r+=mXe(i[o],t,n);return r}function pXe(e,t,i){let n="";for(let r=0;r<e.length;r++)n+=mXe(e[r],t,i);return n}function mXe(e,t,i){switch(e.type){case Ige:return pXe(e.children,t,i);case Tge:return`<${e.data}>`;case Pge:return`<!--${e.data}-->`;case Oge:return`<![CDATA[${e.children[0].data}]]>`;case Rge:case Fge:case Mge:return gen(e,t,i);case _ge:{let n=e,r=n.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!i&&n.parent&&pen.has(n.parent.name)))return i||t.encodeEntities!=="utf8"?XZ(r):Wge(r);return r}}}function gen(e,t,i){if(i==="foreign"){if(e.name=lXe.get(e.name)??e.name,e.parent&&fen.has(e.parent.name))i=!1}if(!i&&hen.has(e.name))i="foreign";let{name:n,children:r}=e,o=!i&&men.has(n),s=`<${n}${ben(e.attribs,t,i)}`;if(r.length===0&&(i?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=i?"/>":" />";else{if(s+=">",r.length>0)s+=pXe(r,t,i);if(!o)s+=`</${n}>`}return s}function yen(e){return e.replaceAll('"',""")}function ben(e,t,i){if(!e)return"";let n=(t.encodeEntities??t.decodeEntities)===!1?yen:i||t.encodeEntities!=="utf8"?XZ:Gge,r=i==="foreign",o=!!(t.emptyAttrs??i),s="";for(let a in e){if(!Object.hasOwn(e,a))continue;let c=e[a],l=r?uXe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${l}`:` ${l}="${n(c==null?"":String(c))}"`}return s}var pen,men,hen,fen,hXe;var fXe=gs(()=>{JC();cXe();dXe();pen=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),men=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),hen=new Set(["svg","math"]),fen=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));hXe=xen});function xXe(e,t){return hXe(e,t)}function Een(e,t){return yp(e)?e.children.map((i)=>xXe(i,t)).join(""):""}function eV(e){if(Array.isArray(e))return e.map(eV).join("");if(Au(e))return e.name==="br"?`
|
|
3
3
|
`:eV(e.children);if(YZ(e))return eV(e.children);if(Pw(e))return e.data;return""}function ZR(e){if(Array.isArray(e))return e.map(ZR).join("");if(yp(e)&&!jge(e))return ZR(e.children);if(Pw(e))return e.data;return""}function Zge(e){if(Array.isArray(e))return e.map(Zge).join("");if(yp(e)&&(e.type===mr.Tag||YZ(e)))return Zge(e.children);if(Pw(e))return e.data;return""}var Vge=gs(()=>{fXe();JC();Rw()});function VR(e){let t=tV(ken,e);return t?t.name==="feed"?ven(t):Aen(t):null}function ven(e){let t=e.children,i={type:"atom",items:Qk("entry",t).map((o)=>{let{children:s}=o,a={media:gXe(s)};bp(a,"id","id",s),bp(a,"title","title",s);let c=tV("link",s)?.attribs.href;if(c)a.link=c;let l=Fw("summary",s)||Fw("content",s);if(l)a.description=l;let d=Fw("updated",s);if(d)a.pubDate=new Date(d);return a})};bp(i,"id","id",t),bp(i,"title","title",t);let n=tV("link",t)?.attribs.href;if(n)i.link=n;bp(i,"description","subtitle",t);let r=Fw("updated",t);if(r)i.updated=new Date(r);return bp(i,"author","email",t,!0),i}function Aen(e){let t=tV("channel",e.children)?.children??[],i={type:e.name.substr(0,3),id:"",items:Qk("item",e.children).map((r)=>{let{children:o}=r,s={media:gXe(o)};bp(s,"id","guid",o),bp(s,"title","title",o),bp(s,"link","link",o),bp(s,"description","description",o);let a=Fw("pubDate",o)||Fw("dc:date",o);if(a)s.pubDate=new Date(a);return s})};bp(i,"title","title",t),bp(i,"link","link",t),bp(i,"description","description",t);let n=Fw("lastBuildDate",t);if(n)i.updated=new Date(n);return bp(i,"author","managingEditor",t,!0),i}function gXe(e){return Qk("media:content",e).map((t)=>{let{attribs:i}=t,n={medium:i.medium,isDefault:!!i.isDefault};for(let r of wen)if(i[r])n[r]=i[r];for(let r of Sen)if(i[r])n[r]=Number.parseInt(i[r],10);if(i.expression)n.expression=i.expression;return n})}function tV(e,t){return Qk(e,t,!0,1)[0]}function Fw(e,t,i=!1){return ZR(Qk(e,t,i,1)).trim()}function bp(e,t,i,n,r=!1){let o=Fw(i,n,r);if(o)e[t]=o}function ken(e){return e==="rss"||e==="feed"||e==="rdf:RDF"}var wen,Sen;var yXe=gs(()=>{$ge();Vge();wen=["url","type","lang"],Sen=["fileSize","bitrate","framerate","samplingrate","channels","duration","height","width"]});function Ben(e){let t=e.length;while(--t>=0){let i=e[t];if(t>0&&e.lastIndexOf(i,t-1)>=0){e.splice(t,1);continue}for(let n=i.parent;n;n=n.parent)if(e.includes(n)){e.splice(t,1);break}}return e}function bXe(e,t){let i=[],n=[];if(e===t)return 0;let r=yp(e)?e:e.parent;while(r)i.unshift(r),r=r.parent;r=yp(t)?t:t.parent;while(r)n.unshift(r),r=r.parent;let o=Math.min(i.length,n.length),s=0;while(s<o&&i[s]===n[s])s++;if(s===0)return Yh.DISCONNECTED;let a=i[s-1],c=a.children,l=i[s],d=n[s];if(c.indexOf(l)>c.indexOf(d)){if(a===t)return Yh.FOLLOWING|Yh.CONTAINED_BY;return Yh.FOLLOWING}if(a===e)return Yh.PRECEDING|Yh.CONTAINS;return Yh.PRECEDING}function Cen(e){return e=e.filter((t,i,n)=>!n.includes(t,i+1)),e.sort((t,i)=>{let n=bXe(t,i);if(n&Yh.PRECEDING)return-1;if(n&Yh.FOLLOWING)return 1;return 0}),e}var Yh;var EXe=gs(()=>{Rw();(function(e){e[e.DISCONNECTED=1]="DISCONNECTED",e[e.PRECEDING=2]="PRECEDING",e[e.FOLLOWING=4]="FOLLOWING",e[e.CONTAINS=8]="CONTAINS",e[e.CONTAINED_BY=16]="CONTAINED_BY"})(Yh||(Yh={}))});function KR(e){if(e.prev)e.prev.next=e.next;if(e.next)e.next.prev=e.prev;if(e.parent){let t=e.parent.children,i=t.lastIndexOf(e);if(i!==-1)t.splice(i,1)}e.next=null,e.prev=null,e.parent=null}function Den(e,t){if(t.prev=e.prev,t.prev)t.prev.next=t;if(t.next=e.next,t.next)t.next.prev=t;if(t.parent=e.parent,t.parent){let{children:i}=t.parent,n=i.lastIndexOf(e);if(n===-1)return;i[n]=t,e.parent=null}}function Ien(e,t){if(KR(t),t.next=null,t.parent=e,e.children.push(t)>1){let i=e.children[e.children.length-2];i.next=t,t.prev=i}else t.prev=null}function _en(e,t){KR(t);let{parent:i}=e,n=e.next;if(t.next=n,t.prev=e,e.next=t,t.parent=i,n){if(n.prev=t,i){let r=i.children;r.splice(r.lastIndexOf(n),0,t)}}else if(i)i.children.push(t)}function Ten(e,t){if(KR(t),t.parent=e,t.prev=null,e.children.unshift(t)===1)t.next=null;else{let i=e.children[1];i.prev=t,t.next=i}}function Pen(e,t){KR(t);let{parent:i}=e;if(i){let n=i.children;n.splice(n.indexOf(e),0,t)}if(e.prev)e.prev.next=t;t.parent=i,t.prev=e.prev,t.next=e,e.prev=t}var vXe=()=>{};function AXe(e){return yp(e)?e.children:[]}function wXe(e){return e.parent||null}function Ren(e){let t=wXe(e);if(t!=null)return AXe(t);let i=[e],{prev:n,next:r}=e;while(n!=null)i.unshift(n),{prev:n}=n;while(r!=null)i.push(r),{next:r}=r;return i}function Fen(e,t){let{attribs:i}=e;return i?.[t]}function Men(e,t){let{attribs:i}=e;return i!=null&&Object.hasOwn(i,t)&&i[t]!=null}function Oen(e){return e.name}function Nen(e){let{next:t}=e;while(t!==null&&!Au(t))({next:t}=t);return t}function Len(e){let{prev:t}=e;while(t!==null&&!Au(t))({prev:t}=t);return t}var SXe=gs(()=>{Rw()});var Kge={};Kh(Kge,{DocumentPosition:()=>Yh,append:()=>_en,appendChild:()=>Ien,compareDocumentPosition:()=>bXe,existsOne:()=>eXe,filter:()=>QC,find:()=>XQe,findAll:()=>ien,findOne:()=>JZ,getAttributeValue:()=>Fen,getChildren:()=>AXe,getElementById:()=>sen,getElements:()=>oen,getElementsByClassName:()=>aen,getElementsByTagName:()=>Qk,getElementsByTagType:()=>cen,getFeed:()=>VR,getInnerHTML:()=>Een,getName:()=>Oen,getOuterHTML:()=>xXe,getParent:()=>wXe,getSiblings:()=>Ren,getText:()=>eV,hasAttrib:()=>Men,innerText:()=>Zge,nextElementSibling:()=>Nen,prepend:()=>Pen,prependChild:()=>Ten,prevElementSibling:()=>Len,removeElement:()=>KR,removeSubsets:()=>Ben,replaceElement:()=>Den,testElement:()=>ren,textContent:()=>ZR,uniqueSort:()=>Cen});var iV=gs(()=>{yXe();EXe();$ge();vXe();Uge();Vge();SXe()});var BXe={};Kh(BXe,{DefaultHandler:()=>Jk,DomHandler:()=>Jk,DomUtils:()=>Kge,ElementType:()=>$Z,Parser:()=>YC,QuoteType:()=>Im,Tokenizer:()=>ZC,createDocumentStream:()=>jen,getFeed:()=>VR,parseDocument:()=>kXe,parseFeed:()=>Uen});function kXe(e,t){let i=new Jk(void 0,t);return new YC(i,t).end(e),i.root}function jen(e,t,i){let n=new Jk((r)=>e(r,n.root),t,i);return new YC(n,t)}function Uen(e,t=zen){return VR(kXe(e,t).children)}var zen;var CXe=gs(()=>{Cge();Cge();Rw();Rw();JC();Bge();iV();iV();iV();zen={xmlMode:!0}});var IXe=E(function(xMo,DXe){DXe.exports=(e)=>{if(typeof e!=="string")throw TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}});var TXe=E(function($en){/*!
|
|
4
4
|
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
|
|
5
5
|
*
|
|
@@ -1035,7 +1035,7 @@ ${zA(e.cont)}`}}function gdo(e,t){return t.map((i,n,{length:r})=>ydo(e,i,n===r-1
|
|
|
1035
1035
|
`).find((b)=>b.startsWith("data: "));if(!d)continue;let p;try{let b=NYi.safeParse(JSON.parse(d.slice(6)));if(!b.success)continue;p=b.data}catch{return await u0e(n),{success:!1,error:"Malformed SSE event from remote agent"}}let m=p.result;if(m?.kind==="artifact-update"&&m.artifact)a.push(m.artifact);if(!m?.final)continue;await u0e(n);let h=m.status,f=h?.state??"unknown",y=(h?.message?.parts??[]).filter((b)=>b.kind==="text"&&typeof b.text==="string").map((b)=>b.text).join(`
|
|
1036
1036
|
`)||"No response text";return{success:!0,data:{state:f,response:y,sources:MYi(a)}}}s=await PYe(n,t,i)}return{success:!1,error:"Stream ended without a terminal event"}}class p0e extends Error{timeoutMs;constructor(e){super(`request timed out after ${e}ms`);this.timeoutMs=e,this.name="A2ARequestTimeoutError"}}class dR extends Error{timeoutMs;constructor(e){super(`A2A stream stalled waiting for final event after ${e}ms`);this.timeoutMs=e,this.name="A2AStreamIdleTimeoutError"}}async function GYi(e,t,i,n,r){return c0e((o)=>e(t,{...i,signal:o}),{timeoutMs:n,onTimeout:()=>new p0e(n),signal:r})}async function PYe(e,t,i){try{return await c0e(()=>e.read(),{timeoutMs:t,onTimeout:()=>new dR(t),signal:i})}catch(n){if(n instanceof dR||i?.aborted)await u0e(e,n);throw n}}async function u0e(e,t){try{await e.cancel(t)}catch{}}function WYi(e){if(e instanceof p0e||e instanceof dR)return!1;return e instanceof Error}function l0e(e,t){let i=t>1?` after ${t} attempts`:"";if(e instanceof dR)return`${e.message}${i}`;let n=he(e,"Unknown network error");return`Failed to reach remote agent${i}: ${n}`}async function lZ(e,t={},i={}){let n=t.fetch??globalThis.fetch,r=i.signal;r?.throwIfAborted();let o={requestTimeoutMs:t.requestTimeoutMs??LYi,streamIdleTimeoutMs:t.streamIdleTimeoutMs??jYi,maxNetworkAttempts:t.maxNetworkAttempts??zYi},s=$Yi(e.agent),a=cn(i.userPermissionLevel);if(!s.ok){let p=t.entityService?await IYe(t.entityService,e.agent,a):void 0;if(typeof p==="string")return{success:!1,error:p};if(!p)return{success:!1,error:s.error}}if(!t.entityService)return{success:!1,error:"Agent directory is unavailable. Add the agent first, then try again."};let c=s.ok?s.agentId:e.agent.trim(),l=s.ok?await t.entityService.getEntity({entityType:"agent",id:c,visibilityScope:a}):null;if(r?.throwIfAborted(),!l&&!_Ye(c)){let p=await IYe(t.entityService,e.agent,a);if(r?.throwIfAborted(),typeof p==="string")return{success:!1,error:p};if(p)l=p,c=p.id}if(!l){if(i.requireSaved)return{success:!1,error:`Agent ${c} is not saved or approved.`,code:"agent_not_saved"};if(!_Ye(c))return{success:!1,error:`Agent ${e.agent} is not an exact domain-like id and is not saved. Connect or clarify the agent first.`,code:"agent_not_saved"};let p=await $h(c,{fetch:n,timeoutMs:o.requestTimeoutMs,signal:r});if(!p.ok){if(gw(p.reason))return{success:!1,error:p.error};return{success:!1,error:`Could not verify an A2A Agent Card for ${c}. Connect/save it first if you want to add it to the directory.`,code:"agent_card_unavailable"}}let m=await TYe(p.card.url,e.message,n,t.requestSigner,o,r);if("success"in m&&m.success===!0){let h=typeof m.data==="object"&&m.data!==null?m.data:{};return{...m,data:{...h,agentCall:{mode:"one-shot",agent:c},agentContactCandidate:{source:{kind:"url",url:(s.ok?s.sourceUrl:void 0)??c}}}}}return m}if(l.metadata.status==="archived")return{success:!1,error:`Agent ${c} is archived and cannot be contacted until it is restored and approved.`,code:"agent_archived"};if(!await t.isContactApproved?.(c))return{success:!1,error:`Agent ${c} is discovered but not approved yet. Approve it first.`,code:"agent_not_approved"};let d=await $h(c,{fetch:n,timeoutMs:o.requestTimeoutMs,signal:r});if(!d.ok){if(gw(d.reason))return{success:!1,error:d.error};return{success:!1,error:`Could not fetch Agent Card from https://${c}`}}return TYe(d.card.url,e.message,n,t.requestSigner,o,r)}function FYe(e={}){return{name:"agent_call",description:"Call a remote A2A agent by exact domain-like target, saved local agent id, or the name of a saved contact as the user calls it, such as Yeehaa. A domain-like id is bare text with a dot and no slash/protocol, such as partner-brain.example or save-it-regression.example; .example test domains are exact domain-like ids. When the user asks to ask, message, talk to, or contact that id, asks what it has to say, or asks that agent for its skills/capabilities, call this tool directly in the same turn with no system_list/system_get preflight: the tool reports structured errors such as invalid Agent Card, not approved, or archived. Do not stop after listing the agent, drafting the question, searching local content, or reading its saved entity. If the user provides an HTTPS URL such as https://docs.example/a2a, pass only the hostname docs.example. Never pass a full URL, a brain's display name like Brain, or a non-HTTPS URL; for a non-HTTPS URL, ask for the HTTPS agent URL or exact id instead. For saved agents, the tool enforces approved/not-archived status before network contact; a discovered but not approved agent must be approved first, so do not call it. For unsaved exact domains, the tool verifies the A2A Agent Card over HTTPS and may perform a one-shot call without saving; after success you may offer to save/connect it, but never auto-save. Answer from the agent's response without supplementing it with reads of the agent entity unless the user asks for its directory/profile details, and never save the user's question as a note in the same turn. If the call fails (auth, network, an invalid or unverifiable Agent Card, an unavailable agent), report that failure directly: do not say the agent was saved or connected, do not answer from memory, local docs, or general knowledge, and do not create a wish, reminder, todo, note, or other entity; you may offer to add the contact using the word add. Each new turn that asks the same id something, including short follow-ups like 'tell me more' and even after a refusal or error, needs its own fresh call with that same id. If a name matches several saved agents, ask a concise clarification naming their ids and end the turn without calling; never choose the first match.",inputSchema:UYi,visibility:"trusted",sideEffects:"external",handler:async(t,i)=>{let n=qYi.safeParse(t);if(!n.success)return{success:!1,error:`Invalid input: ${n.error.message}`};return lZ(n.data,e,{userPermissionLevel:i.userPermissionLevel,...i.signal?{signal:i.signal}:{}})}}}var ZYi=30000,VYi=u.looseObject({result:u.looseObject({parts:u.array(u.looseObject({kind:u.string(),data:u.unknown()}))})});function E0(e,t){return{status:"refused",code:e,error:t}}async function NYe(e,t,i){let n=e.trim().toLowerCase(),r=await i.entityService?.getEntity({entityType:"agent",id:n,visibilityScope:cn("admin")});if(!r)return E0("agent_not_saved",`Agent ${n} is not saved.`);if(r.metadata.status==="archived")return E0("agent_archived",`Agent ${n} is archived.`);if(!await i.isContactApproved?.(n))return E0("agent_not_approved",`Agent ${n} is not approved yet. Approve it first.`);let{requestSigner:o}=i;if(!o)return E0("unsigned","This brain cannot sign A2A requests, and a peer shares only with callers it can verify.");let s=i.fetch??fetch,a=i.requestTimeoutMs??ZYi,c=await $h(n,{fetch:s,timeoutMs:a});if(!c.ok)return E0("agent_card_unavailable",c.error);if(!c.card.extensions.includes(Ik))return E0("not_offered",`${n} does not offer shared entities.`);let l={"Content-Type":"application/json","X-A2A-Extensions":Ik},d=JSON.stringify({jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/send",params:{message:{kind:"message",messageId:crypto.randomUUID(),role:"user",parts:[{kind:"data",data:t}]}}});await o({method:"POST",url:c.card.url,headers:l,body:d});let p;try{p=await s(c.card.url,{method:"POST",headers:l,body:d,signal:AbortSignal.timeout(a)})}catch(h){return E0("peer_failed",he(h,`${n} did not answer`))}if(p.status===404)return{status:"not-found"};if(!p.ok)return E0("peer_failed",`${n} answered HTTP ${p.status}`);let m=VYi.safeParse(await p.json().catch(()=>null));return{status:"answered",agentId:n,data:m.success?m.data.result.parts.filter((h)=>h.kind==="data").map((h)=>h.data):[],fetchFn:s,timeoutMs:a}}async function LYe(e,t){let i=await NYe(e.agent,{op:"list"},t);if(i.status!=="answered")return i;let n=i.data.map((r)=>MYe.safeParse(r)).find((r)=>r.success)?.data;return n?{status:"found",entities:n.entities}:E0("unreadable_answer",`${i.agentId} did not answer with a list.`)}async function jYe(e,t){let i=await NYe(e.agent,{op:"get",entityType:e.entityType,id:e.id},t);if(i.status!=="answered")return i;let{agentId:n,fetchFn:r,timeoutMs:o}=i,s=i.data.map((c)=>OYe.safeParse(c)).find((c)=>c.success)?.data;if(s?.entityType!==e.entityType||s.id!==e.id)return E0("unreadable_answer",`${n} did not answer with the entity asked for.`);let a=E0("unverified",`${n} did not sign what it served, so it was not taken.`);if(s.contentHash!==Ht(s.markdown))return a;try{if((await rYe(rZ(s),s.attestation.signature,s.attestation.keyId,new cR({fetch:(l)=>r(l,{signal:AbortSignal.timeout(o)})}))).domain!==n)return a}catch{return a}return{status:"found",entity:s}}var KYi=new Set(["agent_not_saved","agent_not_approved","agent_archived"]);function UYe(e,t){let i="code"in e&&KYi.has(e.code??"")?"permission_denied":"handler_failed",n="error"in e?e.error:t;return new bi(i,{publicMessage:TC(n)})}function YYi(e){return[e,"","Asked on behalf of a visitor to another brain's site. Answer briefly, from your own public content, and cite what you draw on."].join(`
|
|
1037
1037
|
`)}async function zYe(e,t,i,n){let r=AbortSignal.timeout(n),o=(c)=>new bi("deadline_exceeded",{publicMessage:`${t} did not answer within ${n} ms`,cause:c}),s;try{s=await lZ({agent:t,message:i},{...e,maxNetworkAttempts:1},{requireSaved:!0,signal:r})}catch(c){if(r.aborted)throw o(c);throw new bi("handler_failed",{message:he(c,`${t} did not answer`),publicMessage:`${t} did not answer`,cause:c})}if(r.aborted)throw o();if(!("success"in s)||s.success!==!0)throw UYe(s,`${t} did not answer`);let a=m0e.safeParse(s.data);if(!a.success)throw new bi("handler_failed",{publicMessage:`${t} gave no readable answer`});if(a.data.state!=="completed")throw new bi("handler_failed",{publicMessage:TC(`${t} did not answer: ${a.data.response}`)});return a.data}var uZ={everyProcess:!0};function qYe(e,t,i={networkAskTimeoutMs:30000,turnTimeoutMs:90000}){e.answer(dZ,({request:{agent:n,question:r}})=>zYe(t,n,YYi(r),i.networkAskTimeoutMs),uZ),e.answer(pZ,({request:{agent:n,message:r}})=>zYe(t,n,r,i.turnTimeoutMs),uZ),e.answer(fZ,({request:n})=>jYe(n,t),uZ),e.answer(xZ,({request:n})=>LYe(n,t),uZ),e.answer(mZ,async({request:{agent:n,instruction:r,selection:o,userPermissionLevel:s}})=>{let a=await lZ({agent:n,message:["A Studio author is asking about selected markdown.",`Instruction: ${r}`,"","Selected markdown:",o].join(`
|
|
1038
|
-
`)},t,{requireSaved:!0,userPermissionLevel:s});if(!("success"in a)||a.success!==!0)throw UYe(a,"Agent call failed");let c=m0e.safeParse(a.data);if(!c.success)throw new bi("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(hZ,async({request:{userPermissionLevel:n}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:cn(n)}}})).filter((s)=>s.metadata.status==="approved").map((s)=>{let a=s.metadata.name;return{id:s.id,label:typeof a==="string"&&a.length>0?a:s.id}}).sort((s,a)=>s.label.localeCompare(a.label))}})}var $Ye={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.853",dependencies:{"@a2a-js/sdk":"^0.3.13","@brains/contracts":"workspace:*","@brains/http-signatures":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*",hono:"^4.13.13"},devDependencies:{"@brains/auth-service":"workspace:*","@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};function gZ(e,t){let i=new Headers(e.headers);for(let[n,r]of Object.entries(t))i.set(n,r);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:i})}var QYi={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Signature, Signature-Input, Content-Digest, Date","X-Content-Type-Options":"nosniff"},fd=(e)=>gZ(e,QYi);function XYi(e){let t=e.auth();if(!t)return;let i=t.getIssuer();if(Gh(i)||new URL(i).protocol!=="https:")return;return async(n)=>{let r=await t.getA2ASigningKey();await tYe(n,r.privateJwk,r.keyId)}}function eJi(e){let t=e.auth();if(!t)return;let i=t.getIssuer();if(Gh(i)||new URL(i).protocol!=="https:")return;return async(n)=>{let r=await t.getA2ASigningKey();return{keyId:r.keyId,signature:nYe(n,r.privateJwk)}}}function h0e(e,t,i){let n=XYi(e);return{...n?{requestSigner:n}:{},...i.fetch?{fetch:i.fetch}:{},requestTimeoutMs:t.requestTimeoutMs,streamIdleTimeoutMs:t.streamIdleTimeoutMs,maxNetworkAttempts:t.maxNetworkAttempts,entityService:e.entityReads,isContactApproved:i.isContactApproved??((r)=>e.classRuntimeState.scoped({namespace:yZ,schema:bZ}).has(r.trim().toLowerCase()))}}async function tJi(e,t,i){if(!i.cardReady)return;return xYe({character:e.identity.get(),profile:e.identity.getProfile(),version:$Ye.version,...e.domain?{domain:e.domain}:{},...t.organization?{organization:t.organization}:{},profileKind:e.profileKinds.getResolved(),tools:e.tools.listForPermissionLevel("public"),skills:await e.publicSkills.list(),authEnabled:!1})}async function iJi(e,t,i,n){let r=new URL(i.url),o=new URL(`${r.pathname}${r.search}`,xg(i)),s=await iYe({method:i.method,url:o.toString(),headers:i.headers,body:n},t.jwksResolver);if(s){let a=await e.auth()?.getA2APeerTrust(s.domain);return{permissionLevel:a?.keyFingerprint===s.keyFingerprint?a.grantedLevel:"public",isAnchor:e.permissions.isAnchor("a2a",s.domain),callerDomain:s.domain}}return{permissionLevel:"public",isAnchor:!1,callerDomain:null}}function nJi(e,t,i){let n=new GYe,r=e.agent;return n.get("/.well-known/agent-card.json",async(o)=>{let s=await tJi(e,t,i);if(!s)return fd(o.json({error:"Agent Card not ready"},503));return fd(o.json(s))}),n.get("/.well-known/agent-directory.json",async(o)=>{let s=await gYe(e.entityReads);return fd(o.json(s))}),n.get("/a2a",(o)=>fd(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),n.options("/a2a",()=>fd(new Response(null,{status:204}))),n.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return fd(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await iJi(e,i,o.req.raw,s)}catch{return fd(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return fd(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let l=EYe.safeParse(c);if(!l.success)return fd(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(GKe(o.req.raw.headers)){let p=l.data.method==="message/send"?WKe(l.data.params):void 0,m=p?.op==="list"?await KKe(e.entityReads,a.permissionLevel):await VKe(e.entityReads,a.permissionLevel,p,eJi(e));if(!m)return fd(o.json({error:"Not found"},404));return fd(o.json({jsonrpc:"2.0",id:l.data.id,result:{kind:"message",messageId:crypto.randomUUID(),role:"agent",parts:[{kind:"data",data:m}]}}))}if(l.data.method==="message/stream"){let p=BYe.safeParse(l.data.params??{});if(!p.success)return fd(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:l.data.id}));let m=CYe(l.data.id,p.data.message,{taskManager:i.taskManager,turnSupervisor:i.turnSupervisor,agentService:r,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:i.publicAsks});if("error"in m)return fd(o.json(m));return fd(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await wYe(l.data,{taskManager:i.taskManager,turnSupervisor:i.turnSupervisor,agentService:r,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:i.publicAsks});return fd(o.json(d))}),n}function f0e(e={}){let t=Hh({id:"a2a",config:hYe,setup:(o)=>{let{config:s}=o,a=xs(o),{servesHttp:c}=a,l=h0e(a,s,e),d={cardReady:!1,servesHttp:c,taskManager:new s0e,turnSupervisor:new a0e,jwksResolver:new cR(e.fetch?{fetch:e.fetch}:{}),clientDeps:l,publicAsks:new o0e(s.publicAsks,a.classRuntimeState)};if(c)a.endpoint({label:"A2A",url:"/a2a",priority:25}),a.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),a.logger.info("A2A interface registered",{domain:a.domain});else a.logger.info("A2A interface registered in tool-only mode",{domain:a.domain});return a.ready(()=>{d.cardReady=!0}),d}}),i=HYe(t,(o)=>{let s=xs(o);qYe(s,h0e(s,o.config,e),{networkAskTimeoutMs:o.config.networkAskTimeoutMs,turnTimeoutMs:o.config.turnTimeoutMs})}),n=Do(i,(o)=>{let{config:s,state:a}=o;if(!a.servesHttp)return[];let c=xs(o),l=nJi(c,s,a),d=(m)=>Promise.resolve(l.fetch(m)),p=(m,h)=>({path:m,method:h,public:!0,handler:d});return[p("/.well-known/agent-card.json","GET"),p("/.well-known/agent-directory.json","GET"),p("/a2a","GET"),p("/a2a","POST"),p("/a2a","OPTIONS")]}),r=fg(n,(o)=>{let{state:s}=o,{logger:a}=xs(o);return{id:"a2a",start:async()=>{if(s.servesHttp)a.info("A2A mounted on shared webserver host");else a.info("A2A running without webserver routes")},stop:async()=>{await s.turnSupervisor.close(),a.info("A2A server stopped")}}});return Or(r,(o)=>{let{config:s}=o,a=xs(o),c=()=>FYe(h0e(a,s,e));return[{...c(),handler:(l,d)=>c().handler(l,d)}]})}var rJi=f0e(),WYe=rJi;function Wh(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function Aw(e,t){return{registration:e,actionIds:t.map((i)=>i.name)}}var oJi=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function Zh(e){return oJi.format(new Date(e))}function Sm(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function qc(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function AZ(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function Nk(e){if(!e)return"This brain";let t="did:web:";if(!e.startsWith(t))return e;let i=e.slice(t.length);if(i.length===0)return e;return i.split(":").map(decodeURIComponent).join("/")}var sJi={"auth.a2a_peer_trust.granted":"Trusted an A2A peer","auth.a2a_peer_trust.revoked":"Revoked A2A peer trust","auth.access.reinitialized":"Reinitialized access from configuration","auth.external_peer.invited":"Invited a person from an external peer","auth.external_peer.linked":"Linked an external peer","auth.external_peer.unlinked":"Unlinked an external peer","auth.invitation.created":"Person invited","auth.invitation.cancelled":"Invitation cancelled","auth.invitation.manual_delivery_confirmed":"Manual delivery confirmed","auth.invitation.resent":"Invitation resent","auth.identity.attached":"Connected an identity","auth.identity.detached":"Disconnected an identity","auth.identity.delivery_bound":"Bound a verified delivery channel","auth.passkey.authentication_failed":"Recorded a failed passkey sign-in","auth.passkey.migrated":"Migrated a passkey","auth.passkey.registered":"Registered a passkey","auth.passkey.registration_failed":"Recorded a failed passkey registration","auth.passkey.registration_started":"Created a passkey setup link","auth.passkey.revoked":"Revoked a passkey","auth.setup_token.generated":"Generated a setup token","auth.user.created":"Created an account","auth.user.deleted":"Deleted a suspended account","auth.user.grants_revoked":"Revoked account grants","auth.user.role_updated":"Role changed","auth.user.status_updated":"Changed account status"};function J0e(e){let t=sJi[e];if(t)return t;let i=e.replaceAll(/[._-]+/g," ").trim();return i.length===0?e:fo(i)}var Q0e=u.strictObject({actorUserId:u.string().trim().min(1).max(120).optional(),action:u.string().trim().min(1).max(200).optional(),selected:u.string().trim().min(1).max(120).optional(),offset:u.preprocess(Wh,u.number().int().min(0).max(1e5)).default(0),limit:u.preprocess(Wh,u.number().int().min(1).max(100)).default(25)}),ZYe=u.strictObject({id:u.string().min(1),actorUserId:u.string().min(1).optional(),action:u.string().min(1),targetType:u.string().min(1).optional(),targetId:u.string().min(1).optional(),targetUserId:u.string().min(1).optional(),createdAt:u.number().int().nonnegative()}),aJi=u.strictObject({userId:u.string().min(1),displayName:u.string().min(1)}),cJi=u.strictObject({query:Q0e,events:u.array(ZYe),selectedEvent:ZYe.optional(),users:u.array(aJi),actions:u.array(u.strictObject({value:u.string().min(1),label:u.string().min(1),count:u.number().int().nonnegative()})),total:u.number().int().nonnegative()});function VYe(e){let t=e.metadata?.userId;return{...typeof t==="string"&&t?{targetUserId:t}:{},id:e.id,...e.actorUserId?{actorUserId:e.actorUserId}:{},action:e.action,...e.targetType?{targetType:e.targetType}:{},...e.targetId?{targetId:e.targetId}:{},createdAt:e.createdAt}}function KYe(e,t){return e?t.get(e)??"Former Admin":"System"}function YYe(e,t){if(e.targetId)return t.get(e.targetId)??(e.targetUserId?t.get(e.targetUserId):void 0)??e.targetType??e.targetId;return e.targetType??"Access"}var Y0e=Fo({id:"audit",label:"Audit",priority:90,permission:"admin",query:Q0e,data:cJi,actions:[],view:({data:e})=>{let t=new Map(e.users.map((o)=>[o.userId,o.displayName])),i=e.selectedEvent,r=[{type:"query",id:"audit-filters",...{controls:[{key:"actorUserId",label:"Actor",value:e.query.actorUserId,allLabel:"All actors",options:e.users.map((o)=>({value:o.userId,label:o.displayName}))},{key:"action",label:"Action",value:e.query.action,allLabel:"All actions",options:e.actions}],...e.total>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.total}}:{}}},{type:"detail",id:"audit-detail",queryKey:"selected",empty:"Select an event to inspect its audit record.",...i?{open:{forId:i.id,title:J0e(i.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:KYe(i.actorUserId,t)},{label:"Action",value:i.action},{label:"Target",value:YYe(i,t)},{label:"Occurred",value:Zh(i.createdAt)},{label:"Event ID",value:i.id},{label:"Action ID",value:i.action},...i.targetId?[{label:"Target ID",value:i.targetId}]:[],...i.actorUserId?[{label:"Actor ID",value:i.actorUserId}]:[]]}]}}:{},master:{type:"list",id:"audit-events",presentation:"standard",empty:"No audit events match these filters.",items:e.events.map((o)=>({id:o.id,title:J0e(o.action),description:`${KYe(o.actorUserId,t)} \u2192 ${YYe(o,t)}`,metadata:[new Date(o.createdAt).toISOString()],links:[{label:"Details",target:{detail:{itemId:o.id}}}]}))}}];return{kicker:"Security history",title:"Audit",description:"Who changed access, what changed, and when.",status:{label:`${e.total} matching ${e.total===1?"event":"events"}`,tone:"neutral"},blocks:r}}});function JYe(e){let t=e.studio.source({definition:Y0e,bind:(i)=>Y0e.bind(i,{load:async({query:n})=>{let r=Sm(e),o=n.get(Q0e),[s,a]=await Promise.all([r.queryAuditEvents({...o.actorUserId?{actorUserId:o.actorUserId}:{},...o.action?{action:o.action}:{},...o.selected?{selectedId:o.selected}:{},offset:o.offset,limit:o.limit}),r.listUsers()]);return{query:o,events:s.events.map(VYe),...s.selectedEvent?{selectedEvent:VYe(s.selectedEvent)}:{},users:AZ(a),actions:s.actions.map(({action:c,count:l})=>({value:c,label:J0e(c),count:l})).sort((c,l)=>c.label.localeCompare(l.label)),total:s.total}},actions:[]})});return Aw(t,Y0e.actions)}var v0=u.strictObject({status:u.string()}),wZ=u.strictObject({status:u.string(),setupUrl:u.url(),expiresAt:u.string()});function OC(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var SZ=u.strictObject({type:u.string(),displayName:u.string(),subjectLabel:u.string(),deliveryModes:u.array(u.enum(["automatic","manual"]))});function kZ(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function BZ(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function CZ(e,t){return{deliveryType:{label:"Delivery channel",control:"select",options:e.map((i)=>({value:i.type,label:i.displayName}))},deliverySubject:{label:"Delivery destination",labelBy:{field:"deliveryType",values:e.map((i)=>({value:i.type,label:i.subjectLabel}))},control:"text"},deliveryLabel:{label:"Delivery label (optional)",control:"text"},deliveryMode:{label:"Delivery mode",control:"select",options:t.map((i)=>({value:i,label:i==="automatic"?"Automatic":"Manual"}))}}}import{randomUUID as lJi}from"crypto";var QYe=new Set(["claimed","expired","cancelled"]),uJi=new Set(["claimed","cancelled"]),nxe=u.strictObject({state:u.enum(["pending","history"]).optional().default("pending"),selected:u.string().trim().min(1).max(200).optional(),offset:u.preprocess(Wh,u.number().int().min(0)).optional().default(0),limit:u.preprocess(Wh,u.number().int().min(1).max(100)).optional().default(25)}),iJe=u.strictObject({status:u.string(),setupUrl:u.url().nullable(),expiresAt:u.string().nullable()}),dJi=u.strictObject({idempotencyKey:u.string().min(1),displayName:u.string().trim().min(1).max(200),role:u.enum(["admin","trusted"]),deliveryType:u.string().trim().min(1).max(100),deliverySubject:u.string().trim().min(1).max(500),deliveryLabel:u.string().trim().max(200).optional(),deliveryMode:u.enum(["automatic","manual"])}),nJe=u.strictObject({invitationId:u.string().min(1)}),pJi=u.strictObject({invitationId:u.string().min(1),deliveryAttemptId:u.string().min(1)}),rJe=u.strictObject({invitationId:u.string(),state:u.string()}),txe=Vi({name:"create-invitation",label:"Add a person",permission:"admin",input:dJi,output:iJe}),rxe=Vi({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:nJe,output:iJe}),oxe=Vi({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:nJe,output:rJe}),sxe=Vi({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:pJi,output:rJe}),XYe=u.strictObject({id:u.string(),displayName:u.string(),role:u.string(),state:u.string(),destination:u.string(),updatedAt:u.number(),deliveryAttemptId:u.string().optional()}),mJi=u.strictObject({query:nxe,idempotencyKey:u.string(),channels:u.array(SZ),invitations:u.array(XYe),selectedInvitation:XYe.optional(),selectedTotal:u.number().int().nonnegative(),pendingCount:u.number().int().nonnegative(),historyCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()});function ixe(e,t){let i=e.filter((n)=>n.id===t);if(i.length!==1||!i[0])throw Error(`Invitations tab composition requires block "${t}" exactly once`);return i[0]}function X0e(e,t){let i=ixe(e,t);switch(i.type){case"tabs":case"detail":case"columns":throw Error(`Invitations tab composition block "${t}" must be a region`);default:return i}}function oJe(e,t){let i=ixe(e,"invitation-totals");if(i.type!=="stats")throw Error('Invitations tab composition block "invitation-totals" must be stats');let n=e.some((a)=>a.id==="create-invitation-unavailable")?[X0e(e,"create-invitation-unavailable")]:[],r=ixe(e,"invitations");if(r.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=X0e(e,"invitation-delivery");if(o.type!=="card")throw Error("Invitations composition requires delivery capabilities");let s=t.flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[...n,X0e(e,"invitation-filters"),r,{...o,presentation:"disclosure",blocks:[...o.blocks,i,...s]}]}}var sJe=OC("Invitation setup");function hJi(e){if(uJi.has(e.state))return[];return[...e.deliveryAttemptId?[{action:sxe,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:rxe,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:sJe}]:[],...e.state!=="expired"?[{action:oxe,input:{invitationId:e.id}}]:[]]}function eJe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return fo(e.state)}var exe=Fo({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:nxe,data:mJi,actions:[txe,rxe,oxe,sxe],badge:({data:e})=>e.pendingCount,view:({data:e})=>{let t=[{type:"stats",id:"invitation-totals",items:[{label:"Pending",value:e.pendingCount},{label:"History",value:e.historyCount},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"neutral"}]}],i=kZ(e.channels),n;if(e.channels.length>0&&i.length>0)n={action:txe,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:BZ("Role"),...CZ(e.channels,i)}},result:sJe};else t.push({type:"notice",id:"create-invitation-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});let r=e.selectedInvitation;return t.push({type:"query",id:"invitation-filters",controls:[{key:"state",label:"View",value:e.query.state,options:[{value:"pending",label:"Pending",count:e.pendingCount},{value:"history",label:"History",count:e.historyCount}]}],...e.selectedTotal>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.selectedTotal}}:{}},{type:"detail",id:"invitations",queryKey:"selected",empty:"Select an invitation to review its delivery.",master:{type:"list",id:"invitation-records",presentation:"standard",empty:e.query.state==="pending"?"No pending invitations.":"No invitation history yet.",items:e.invitations.map((o)=>({id:o.id,title:o.displayName,description:`${fo(o.role)} \xB7 ${eJe(o)}`,metadata:[o.destination,`Updated ${new Date(o.updatedAt).toISOString()}`],links:[{label:"Review",target:{detail:{itemId:o.id}}}]}))},...r?{open:{forId:r.id,title:r.displayName,blocks:[{type:"key-values",id:"invitation-fields",items:[{label:"Role",value:fo(r.role)},{label:"Delivery",value:eJe(r)},{label:"Destination",value:r.destination},{label:"Updated",value:Zh(r.updatedAt)}]},{type:"actions",id:"invitation-actions",items:hJi(r)}]}}:e.query.selected?{open:{forId:e.query.selected,title:"Invitation unavailable",blocks:[{type:"notice",tone:"neutral",text:"This invitation is no longer available. Return to the list to choose another."}]}}:{}},{type:"card",id:"invitation-delivery",label:"Delivery capabilities",blocks:[{type:"key-values",items:e.channels.map((o)=>({label:o.displayName,value:o.deliveryModes.map(fo).join(" \xB7 ")}))}]}),{kicker:"Access administration",title:"Invitations",description:"Create, deliver, retry, and revoke passkey invitations without moving auth authority into Studio.",status:{label:`${e.pendingCount} pending`,tone:e.failureCount>0?"warn":"neutral"},...n?{primaryAction:n}:{},blocks:t}}});function tJe(e){return{status:e.invitation.state==="sent"?"Delivery provider accepted the invitation.":e.invitation.state==="failed"?"Invitation saved, but delivery failed.":"Manual delivery is waiting for confirmation.",setupUrl:e.registration?.setupUrl??null,expiresAt:e.registration?new Date(e.registration.expiresAt*1000).toISOString():null}}function aJe(e){let t=Sm(e),i=new Map,n=e.studio.source({definition:exe,bind:(r)=>{let o=txe.bind(r,async({input:l,caller:d})=>{let p=await t.createInvitation({idempotencyKey:l.idempotencyKey,displayName:l.displayName,role:l.role,delivery:{type:l.deliveryType,subject:l.deliverySubject,...l.deliveryLabel?{label:l.deliveryLabel}:{},mode:l.deliveryMode}},qc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)i.set(p.invitation.id,p.registration.deliveryAttemptId);return tJe(p)}),s=rxe.bind(r,async({input:l,caller:d})=>{let p=await t.resendInvitation(l.invitationId,qc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)i.set(p.invitation.id,p.registration.deliveryAttemptId);return tJe(p)}),a=oxe.bind(r,async({input:l,caller:d})=>{let p=await t.cancelInvitation(l.invitationId,qc(d));return i.delete(l.invitationId),{invitationId:p.id,state:p.state}},({input:l})=>({summary:"Cancel this invitation and revoke its pending setup link?",revision:l.invitationId})),c=sxe.bind(r,async({input:l,caller:d})=>{let p=await t.confirmManualInvitationDelivery(l.invitationId,l.deliveryAttemptId,qc(d));return i.delete(l.invitationId),{invitationId:p.id,state:p.state}});return exe.bind(r,{actions:[o,s,a,c],load:async({query:l})=>{let d=l.get(nxe),[p,m]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),h=m.filter((T)=>T.deliveryModes.length>0),f=p.filter((T)=>T.invitation!==void 0),g=f.filter((T)=>T.invitation&&!QYe.has(T.invitation.state)),y=f.filter((T)=>T.invitation&&QYe.has(T.invitation.state)),b=d.state==="pending"?g:y,v=f.flatMap((T)=>{let F=T.invitation;if(!F)return[];let k=T.identities.find((L)=>L.type!=="passkey")?.label??T.externalPeers[0]?.peerId??"Not recorded",N=i.get(F.id);return[{id:F.id,displayName:T.displayName,role:T.role,state:F.state,destination:k,updatedAt:F.claimedAt??F.cancelledAt??F.expiredAt??F.sentAt??F.updatedAt,...N?{deliveryAttemptId:N}:{}}]}),w=new Map(v.map((T)=>[T.id,T])),B=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:lJi(),channels:h.map((T)=>({type:T.type,displayName:T.displayName,subjectLabel:T.subjectLabel,deliveryModes:T.deliveryModes})),invitations:b.slice(d.offset,d.offset+d.limit).flatMap((T)=>{let F=T.invitation?w.get(T.invitation.id):void 0;return F?[F]:[]}),...B?{selectedInvitation:B}:{},selectedTotal:b.length,pendingCount:g.length,historyCount:y.length,failureCount:g.filter((T)=>T.invitation?.state==="failed").length}}})}});return Aw(n,exe.actions)}var uxe=u.strictObject({peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional()}),fJi=u.strictObject({peerId:u.string().trim().min(1).max(2000),displayName:u.string().trim().min(1).max(200),role:u.enum(["admin","trusted"]),deliveryType:u.string().trim().min(1).max(64),deliverySubject:u.string().trim().min(1).max(1000),deliveryLabel:u.string().trim().min(1).max(200).optional(),deliveryMode:u.enum(["automatic","manual"])}),xJi=u.strictObject({peerId:u.string().trim().min(1).max(2000),userId:u.string().min(1)}),cxe=Vi({name:"invite-external-peer-person",label:"Invite peer person",permission:"admin",confirmation:{kind:"static",message:"Create this local member and bind them to the external peer?"},input:fJi,output:wZ}),lxe=Vi({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:xJi,output:v0}),gJi=u.strictObject({query:uxe,peers:u.array(u.strictObject({peerId:u.string(),displayName:u.string(),role:u.enum(["admin","trusted","public"]),verificationStatus:u.enum(["unverified","verified"]),createdAt:u.number()})),people:u.array(u.strictObject({userId:u.string(),displayName:u.string()})),channels:u.array(SZ)});function DZ(e,t){let i=e.filter((r)=>r.id===t);if(i.length!==1)throw Error(`Peer tab composition requires block "${t}" exactly once`);let n=i[0];if(!n)throw Error(`Peer tab composition requires block "${t}" exactly once`);switch(n.type){case"tabs":case"detail":case"columns":throw Error(`Peer tab composition block "${t}" must be a region`);default:return n}}function dxe(e){let t=e.some((i)=>i.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[DZ(e,"peers"),DZ(e,"link-peer"),DZ(e,t)],invitations:[DZ(e,t)]}}var yJi=OC("Peer invitation setup"),axe=Fo({id:"peers",label:"Peers",priority:12,permission:"admin",query:uxe,data:gJi,actions:[cxe,lxe],view:({data:e})=>{let t=kZ(e.channels),i=[{type:"stats",id:"peer-summary",items:[{label:"Linked peers",value:e.peers.length},{label:"Verified",value:e.peers.filter((n)=>n.verificationStatus==="verified").length},{label:"Available people",value:e.people.length}]}];if(e.channels.length>0&&t.length>0)i.push({type:"card",id:"invite-peer",label:"Peer-first invitation",blocks:[{type:"text",text:"Create a local member for a person known first through another brain, then issue their single-use passkey setup link."},{type:"action",action:cxe,input:{...e.query.peerId?{peerId:e.query.peerId}:{},...e.query.displayName?{displayName:e.query.displayName}:{}},form:{presentation:"disclosure",submitLabel:"Invite peer person",fields:{peerId:{label:"External peer ID",control:"text"},displayName:{label:"Display name",control:"text"},role:BZ("Local role"),...CZ(e.channels,t)}},result:yJi}]});else i.push({type:"notice",id:"invite-peer-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});return i.push({type:"card",id:"link-peer",label:"Link an existing person",blocks:[{type:"action",action:lxe,input:{...e.query.peerId?{peerId:e.query.peerId}:{}},form:{submitLabel:"Link peer",fields:{peerId:{label:"External peer ID",control:"text"},userId:{label:"Local person",control:"select",options:e.people.map((n)=>({value:n.userId,label:n.displayName}))}}}}]},{type:"table",id:"peers",empty:"No external peers linked.",columns:[{key:"peer",label:"Peer"},{key:"person",label:"Local person"},{key:"role",label:"Local role"},{key:"verification",label:"Verification"},{key:"linked",label:"Linked"}],rows:e.peers.map((n)=>({id:`${n.peerId}:${n.displayName}`,cells:{peer:Nk(n.peerId),person:n.displayName,role:n.role,verification:n.verificationStatus,linked:Zh(n.createdAt)},compact:{title:Nk(n.peerId),metadata:[n.displayName,fo(n.role),Zh(n.createdAt)],badges:[{label:fo(n.verificationStatus),tone:n.verificationStatus==="verified"?"good":"warn"}]}}))}),{kicker:"Network administration",title:"Peers",description:"List external brain relationships, invite peer-first people, and link known peers to existing members.",status:{label:`${e.peers.length} linked`},blocks:i}}});function cJe(e){let t=Sm(e),i=e.studio.source({definition:axe,bind:(n)=>{let r=cxe.bind(n,async({input:s,caller:a})=>{let c=await t.inviteExternalPeerPerson({peerId:s.peerId,displayName:s.displayName,role:s.role,delivery:{type:s.deliveryType,subject:s.deliverySubject,...s.deliveryLabel?{label:s.deliveryLabel}:{},mode:s.deliveryMode}},qc(a));return{status:`Created ${c.user.displayName} and linked ${c.peer.peerId}. Deliver only through ${c.registration.delivery.label}.`,setupUrl:c.registration.setupUrl,expiresAt:new Date(c.registration.expiresAt*1000).toISOString()}}),o=lxe.bind(n,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},qc(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((l)=>l.userId===s.userId)?.displayName??"person";return{summary:`Link ${s.peerId} to ${c}? Local access does not change.`,revision:`${s.peerId}:${s.userId}`}});return axe.bind(n,{actions:[r,o],load:async({query:s})=>{let a=s.get(uxe),[c,l]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),d=c.filter((p)=>p.status!=="invited");return{query:a,peers:c.flatMap((p)=>p.externalPeers.map((m)=>({peerId:m.peerId,displayName:p.displayName,role:p.role,verificationStatus:m.verificationStatus,createdAt:m.createdAt}))),people:AZ(d),channels:l.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return Aw(i,axe.actions)}function pxe(e,t){let i=e.filter((n)=>n.id===t);if(i.length!==1||!i[0])throw Error(`People tab composition requires block "${t}" exactly once`);return i[0]}function lJe(e,t,i){let n=pxe(e,"people-summary");if(n.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let r=pxe(e,"people");if(r.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=pxe(e,"brain-anchor");if(o.type!=="card")throw Error('People tab composition block "brain-anchor" must be a card');let s=[t,...i].flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[r,{type:"card",id:"people-peers",label:"External brains",presentation:"disclosure",blocks:s},{...o,label:"Access reference",presentation:"disclosure",blocks:[n,...o.blocks]}]}}var Axe=u.strictObject({selected:u.string().trim().min(1).max(200).optional()}),wxe=u.strictObject({userId:u.string().min(1)}),bJi=u.strictObject({userId:u.string().min(1),role:u.enum(["admin","trusted","public"])}),EJi=u.strictObject({userId:u.string().min(1),status:u.enum(["active","suspended"])});function vJi(e){return e.revokedAt===void 0&&e.type!=="passkey"}function AJi(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var wJi=u.strictObject({userId:u.string().min(1),credentialId:u.string().min(1)}),SJi=u.strictObject({userId:u.string().min(1),type:u.string().trim().min(1).max(64),subject:u.string().trim().min(1).max(2000),issuer:u.string().trim().min(1).max(2000).optional(),label:u.string().trim().min(1).max(200).optional()}),kJi=u.strictObject({userId:u.string().min(1),identityId:u.string().min(1)}),BJi=u.strictObject({userId:u.string().min(1),peerId:u.string().trim().min(1).max(2000)}),fxe=Vi({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:bJi,output:v0}),xxe=Vi({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:EJi,output:v0}),gxe=Vi({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:wxe,output:v0}),yxe=Vi({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:wJi,output:v0}),Sxe=Vi({name:"start-person-passkey-registration",label:"Create setup link",permission:"admin",confirmation:{kind:"static",message:"Create a single-use passkey setup link for this person?"},input:wxe,output:wZ}),bxe=Vi({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:wxe,output:v0}),kxe=Vi({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:SJi,output:v0}),Exe=Vi({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:kJi,output:v0}),vxe=Vi({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:BJi,output:v0}),CJi=u.strictObject({userId:u.string(),displayName:u.string(),role:u.enum(["admin","trusted","public"]),status:u.enum(["active","suspended"]),isAnchor:u.boolean(),isSelf:u.boolean(),profileEntityId:u.string().optional(),passkeys:u.array(u.strictObject({id:u.string(),kind:u.string(),createdAt:u.number()})),identities:u.array(u.strictObject({id:u.string(),type:u.string(),displayName:u.string(),label:u.string(),verified:u.boolean()})),peers:u.array(u.strictObject({peerId:u.string(),verificationStatus:u.enum(["unverified","verified"])}))}),DJi=u.strictObject({query:Axe,anchor:u.strictObject({kind:u.enum(["person","collective"]),configuredKind:u.enum(["person","team","organization"]),displayName:u.string(),administeredBy:u.number().int().nonnegative()}),people:u.array(CJi),activeCount:u.number().int().nonnegative(),activeAdminCount:u.number().int().nonnegative(),suspendedCount:u.number().int().nonnegative(),channelTypes:u.array(u.strictObject({type:u.string(),displayName:u.string()}))}),IJi=OC("Passkey setup");function _Ji(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function mxe(e){return{type:"notice",tone:"warn",text:e}}function TJi(e){return{type:"action",action:Sxe,input:{userId:e},result:IJi}}function PJi(e,t){return{type:"action",action:kxe,input:{userId:e},form:{submitLabel:"Attach channel",fields:{type:{label:"Channel type",control:"select",options:t.map((i)=>({value:i.type,label:i.displayName}))},subject:{label:"Channel subject",control:"text"},issuer:{label:"Issuer (optional)",control:"url"},label:{label:"Display label (optional)",control:"text"}}}}}function RJi(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var hxe=Fo({id:"people",label:"People",priority:10,permission:"admin",query:Axe,data:DJi,actions:[fxe,xxe,gxe,yxe,Sxe,bxe,kxe,Exe,vxe],badge:({data:e})=>e.suspendedCount,view:({data:e})=>{let t=e.people.find((r)=>r.userId===e.query.selected),i=[];if(t){let r=t.role==="admin"&&t.status==="active"&&e.activeAdminCount<=1,o=t.isAnchor?"The protected brain identity must remain an active Admin.":t.status==="suspended"?"Reactivate this person before changing access.":r?"Add another active Admin before changing this role.":void 0,s=t.isAnchor?"The protected brain identity cannot be suspended.":r?"Add another active Admin before suspending this person.":void 0;if(i.push({type:"key-values",id:"person-summary",items:[{label:"Role",value:fo(t.role)},{label:"Status",value:fo(t.status)},{label:"Protected brain identity",value:t.isAnchor},{label:"Brain relationship",value:t.peers.length>0?"External peer + local member":"Hosted member"}]}),o)i.push({type:"notice",tone:"warn",text:o});else i.push({type:"card",id:"person-role",label:"Permission role",blocks:[{type:"action",action:fxe,input:{userId:t.userId,role:t.role},form:{submitLabel:"Change role",fields:{role:{label:"Role",control:"select",options:[{value:"admin",label:"Admin"},{value:"trusted",label:"Trusted"},{value:"public",label:"Public"}]}}}}]});i.push({type:"card",id:"person-access",label:"Access",blocks:[{type:"actions",items:[{action:xxe,input:{userId:t.userId,status:t.status==="suspended"?"active":"suspended"},capability:{id:t.status==="suspended"?"reactivate-person":"suspend-person",label:t.status==="suspended"?"Reactivate person":"Suspend person"},disabled:t.status==="active"&&s!==void 0},...t.status==="active"&&!t.isSelf?[{action:bxe,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:gxe,input:{userId:t.userId}}]:[]]},...t.isSelf?[_Ji()]:[],...s&&t.status==="active"?[mxe(s)]:[]]}),i.push({type:"card",id:"person-sign-in",label:"Sign-in",blocks:[{type:"table",id:"person-passkeys",empty:"No passkeys registered.",columns:[{key:"kind",label:"Passkey"},{key:"created",label:"Added"}],rows:t.passkeys.map((a)=>({id:a.id,cells:{kind:a.kind,created:Zh(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${Zh(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:yxe,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[TJi(t.userId)]:[mxe("A verified channel is required for setup delivery.")]:[]]}),i.push({type:"card",id:"person-channels",label:"Linked identities",blocks:[{type:"table",id:"person-identities",empty:"No linked identity.",columns:[{key:"channel",label:"Channel"},{key:"identity",label:"Identity"},{key:"assurance",label:"Assurance"}],rows:t.identities.map((a)=>({id:a.id,cells:{channel:a.displayName,identity:a.label,assurance:a.verified?"Verified":"Asserted"},compact:{title:a.label,metadata:[a.displayName],badges:[{label:a.verified?"Verified":"Asserted",tone:a.verified?"good":"neutral"}]},actions:[{action:Exe,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[PJi(t.userId,e.channelTypes)]:[mxe("No attachable channel type is configured.")]]}),i.push({type:"notice",tone:"neutral",text:"External peer links record provenance from another brain. They do not grant or change this person's local access."}),i.push({type:"list",id:"person-peers",empty:"No external peer linked; this person is hosted locally.",items:t.peers.map((a)=>({id:a.peerId,title:Nk(a.peerId),description:`Vouched in by ${Nk(a.peerId)} \xB7 ${a.peerId}`,metadata:[fo(a.verificationStatus)],actions:[{action:vxe,input:{userId:t.userId,peerId:a.peerId}}]}))})}let n=[{type:"stats",id:"people-summary",items:[{label:"Active members",value:e.activeCount},{label:"Active Admins",value:e.activeAdminCount},{label:"Suspended",value:e.suspendedCount,tone:e.suspendedCount>0?"warn":"neutral"}]},{type:"card",id:"brain-anchor",label:"Brain identity",blocks:[{type:"key-values",items:[{label:"Name",value:e.anchor.displayName},{label:"Kind",value:e.anchor.configuredKind},{label:"Ownership",value:e.anchor.kind},{label:"Administered by",value:e.anchor.administeredBy}]}]},{type:"detail",id:"people",queryKey:"selected",empty:"Select a person to inspect their access.",master:{type:"list",id:"people-roster",presentation:"standard",empty:"No people are available.",items:[...e.people].sort((r,o)=>Number(o.isSelf)-Number(r.isSelf)||Number(r.isAnchor)-Number(o.isAnchor)||r.displayName.localeCompare(o.displayName)).map((r)=>({id:r.userId,title:r.displayName,description:[fo(r.role),fo(r.status),...r.isSelf?["You"]:[],...r.isAnchor?["Protected brain identity"]:[]].join(" \xB7 "),metadata:[r.identities.length===0?"No linked identities":r.identities.length===1?"One linked identity":`${r.identities.length} linked identities`,...r.peers.length>0?[`Arrived via ${Nk(r.peers[0]?.peerId)}`]:[]],...r.isSelf?{link:{detail:{itemId:r.userId}}}:{},links:[{label:r.isSelf?"Account \u2192":r.isAnchor?"View protection":"Manage person",target:r.isSelf?{launch:{target:"account-settings"}}:{detail:{itemId:r.userId}}}]}))},...t?{open:{forId:t.userId,title:t.displayName,blocks:i}}:{}}];return{kicker:"Access administration",title:"People",description:"Manage people\u2019s access to this brain, linked identities, and account recovery. Use Account for your own profile and sign-in settings.",status:{label:`${e.activeCount} active`,tone:e.suspendedCount>0?"warn":"neutral"},blocks:n}}});function IZ(e,t){return e.find((i)=>i.userId===t)?.displayName??"person"}async function FJi(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function uJe(e){let t=Sm(e),i=e.studio.source({definition:hxe,bind:(n)=>{let r=fxe.bind(n,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,qc(f)),{status:`Role changed to ${fo(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${IZ(f,h.userId)}\u2019s role to ${fo(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=xxe.bind(n,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,qc(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${IZ(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=gxe.bind(n,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,qc(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${IZ(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=yxe.bind(n,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,qc(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=Sxe.bind(n,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,qc(f));return{status:`Bound to ${g.delivery.label}. Deliver only through that confirmed private channel.`,setupUrl:g.setupUrl,expiresAt:new Date(g.expiresAt*1000).toISOString()}}),l=bxe.bind(n,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,qc(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${IZ(f,h.userId)} out everywhere?`,revision:h.userId}}),d=kxe.bind(n,async({input:h,caller:f})=>(await t.attachIdentity({userId:h.userId,type:h.type,subject:h.subject,...h.issuer?{issuer:h.issuer}:{},...h.label?{label:h.label}:{},verifiedAt:Date.now(),source:{kind:"admin"}},qc(f)),{status:"Verified channel attached."})),p=Exe.bind(n,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,qc(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=vxe.bind(n,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,qc(f)),{status:"External peer unlinked from the local person."}),({input:h})=>({summary:`Unlink ${h.peerId}? Local access will not change.`,revision:`${h.peerId}:${h.userId}`}));return hxe.bind(n,{actions:[r,o,s,a,c,l,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(Axe),[y,b,v]=await Promise.all([FJi(t),t.listAdminUsers(),t.listInvitationChannels()]),w=b.filter((N)=>N.status!=="invited"),B=w.find((N)=>N.isAnchor)??w.find((N)=>N.role==="admin"&&N.status==="active"),T=y??RJi(B?.displayName??"Brain owner",w.filter((N)=>N.role==="admin"&&N.status==="active").length),F=w.filter((N)=>N.status==="active"),k=new Map(v.map((N)=>[N.type,N.displayName]));return{query:g,anchor:{kind:T.kind,configuredKind:T.configuredKind,displayName:T.displayName,administeredBy:T.administeredBy},people:w.flatMap((N)=>{if(N.status==="invited")return[];return[{userId:N.userId,displayName:N.displayName,role:N.role,status:N.status,isAnchor:N.isAnchor,isSelf:f?.actor.id===N.userId,...N.profileEntityId?{profileEntityId:N.profileEntityId}:{},passkeys:N.passkeys.map((L)=>({id:L.id,kind:AJi(L),createdAt:L.createdAt})),identities:N.identities.filter(vJi).map((L)=>({id:L.id,type:L.type,displayName:k.get(L.type)??fo(L.type),label:L.label??"Connected identity",verified:L.verifiedAt!==void 0})),peers:N.externalPeers.map((L)=>({peerId:L.peerId,verificationStatus:L.verificationStatus}))}]}),activeCount:F.length,activeAdminCount:F.filter((N)=>N.role==="admin").length,suspendedCount:w.length-F.length,channelTypes:v.map((N)=>({type:N.type,displayName:N.displayName}))}}})}});return Aw(i,hxe.actions)}var MJi=u.strictObject({tab:u.enum(["people","invitations","audit"]).default("people"),selected:u.string().trim().min(1).max(200).optional(),state:u.enum(["pending","history"]).optional(),offset:u.preprocess(Wh,u.number().int().min(0).max(1e5)).optional(),limit:u.preprocess(Wh,u.number().int().min(1).max(100)).optional(),peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional(),actorUserId:u.string().trim().min(1).max(120).optional(),action:u.string().trim().min(1).max(200).optional()});function OJi(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function NJi(e){if(e===null||typeof e!=="object")return!1;let t=Reflect.get(e,"view");if(t===null||typeof t!=="object")return!1;return Array.isArray(Reflect.get(t,"blocks"))}function LJi(e,t){if(!NJi(e))throw Error(`${t} tab returned invalid workspace data`);return e}function dJe(e,t){let i=[];for(let n of e){if(n.type==="tabs")throw Error(`${t} tab cannot contribute nested tabs`);i.push(n)}return i}function Bxe(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function AR(e,t,i,n){return LJi(await e.dataProvider(t,i,n),e.label)}async function jJi(e,t,i,n){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,i,n)}function zJi(e){let t=new Map;for(let i of e)for(let n of i.actionIds){if(t.has(n))throw Error(`Administration action "${n}" is declared by more than one source`);if(!i.registration.actionHandler)throw Error(`Administration source "${i.registration.label}" declares actions without a handler`);t.set(n,i.registration)}return t}function pJe(e){return{suspended:e.filter((t)=>t.status==="suspended").length,pendingInvitations:e.filter((t)=>t.invitation!==void 0&&!["claimed","expired","cancelled"].includes(t.invitation.state)).length}}function UJi(e){return[...e.pendingInvitations>0?[{id:"invitations",title:`${e.pendingInvitations} ${e.pendingInvitations===1?"invitation":"invitations"} waiting`,detail:"Not yet accepted.",severity:"info",action:{label:"Review invitations",query:{tab:"invitations"}}}]:[],...e.suspended>0?[{id:"suspended",title:`${e.suspended} ${e.suspended===1?"person":"people"} suspended`,severity:"info",action:{label:"Review people",query:{tab:"people"}}}]:[]]}async function mJe(e){if(!e.studio.isAvailable())return;let t=uJe(e),i=aJe(e),n=cJe(e),r=JYe(e),o=zJi([t,i,n,r]),s=t.registration,a=i.registration,c=n.registration,l=r.registration;return e.studio.register({id:"admin:administration",label:"Administration",rendererName:FC,priority:10,permission:"admin",section:"brain",urlQuery:!0,aliases:[{id:"admin:people",query:{tab:"people"}},{id:"admin:invitations",query:{tab:"invitations"}},{id:"admin:peers",query:{tab:"people"}},{id:"admin:audit",query:{tab:"audit"}}],entityTypes:[],accessHandler:(d)=>s.accessHandler(d),dataProvider:async(d,p,m)=>{let h=MJi.parse(p??{}),f,g=Bxe("People"),y=Bxe("Invitations"),b=Bxe("Audit");if(h.tab==="people"){let[v,w]=await Promise.all([AR(s,d,{...h.selected?{selected:h.selected}:{}},m),AR(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),B=dxe(w.view.blocks);g=[...lJe(dJe(v.view.blocks,"People"),{type:"notice",id:"people-peer-note",tone:"neutral",title:"External brain relationships",text:"A peer link records how a locally administered person relates to another brain. It does not grant or change local access."},B.people).blocks]}else if(h.tab==="invitations"){let[v,w]=await Promise.all([AR(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...Zr({offset:h.offset,limit:h.limit})},m),AR(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),B=dxe(w.view.blocks),T=oJe(v.view.blocks,B.invitations);f=v.view.primaryAction,y=[...T.blocks]}else{let v=await AR(l,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...Zr({offset:h.offset,limit:h.limit})},m);b=dJe(v.view.blocks,"Audit")}return{view:{kicker:"Access administration",title:"Administration",description:"Manage people, invitations, and access to this brain. Use Account for your own profile, sign-in security, and personal settings.",...f?{primaryAction:f}:{},blocks:[{type:"tabs",id:"administration-tabs",label:"Administration sections",defaultTab:h.tab,queryKey:"tab",tabs:[{id:"people",label:"People",blocks:g},{id:"invitations",label:"Invitations",blocks:y},{id:"audit",label:"Access activity",blocks:b}]}]}}},actionHandler:async(d,p,m)=>{let h=OJi(d);if(!h)throw new bi("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new bi("not_found",{publicMessage:`Unknown Administration action: ${h}`});return jJi(f,d,p,m)},badgeProvider:async()=>{let d=pJe(await Sm(e).listAdminUsers());return d.suspended+d.pendingInvitations},attentionProvider:async()=>UJi(pJe(await Sm(e).listAdminUsers()))})}var qJi=259200000,$Ji=u.strictObject({id:u.string(),displayName:u.string(),state:u.string(),reason:u.enum(["expiring","delivery-failed"]),expiresAt:u.number().optional()}),HJi=u.strictObject({invitations:u.array($Ji),expiringCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()}),hJe=oo({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:HJi,digest:({data:e})=>({items:[{label:"Expiring soon",value:String(e.expiringCount),...e.expiringCount>0?{tone:"warn"}:{}},{label:"Delivery failures",value:String(e.failureCount),...e.failureCount>0?{tone:"warn"}:{}}],attention:e.invitations.length}),view:({data:e})=>({blocks:[{type:"stats",items:[{label:"Expiring soon",value:e.expiringCount,tone:e.expiringCount>0?"warn":"good"},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"good"}]},{type:"list",id:"invitation-attention",empty:"No invitation setup links need attention.",items:e.invitations.map((t)=>({id:t.id,title:t.displayName,description:t.reason==="delivery-failed"?"Invitation delivery failed. Resend or cancel it.":"The single-use setup link expires soon.",metadata:[t.state,...t.expiresAt!==void 0?[`Expires ${Zh(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function GJi(e,t){let i=e.flatMap((n)=>{let r=n.invitation;if(!r)return[];if(r.state==="failed")return[{id:r.id,displayName:n.displayName,state:r.state,reason:"delivery-failed",...r.expiresAt!==void 0?{expiresAt:r.expiresAt}:{}}];if(!["pending","sending","sent"].includes(r.state)||r.expiresAt===void 0||r.expiresAt<=t||r.expiresAt>t+qJi)return[];return[{id:r.id,displayName:n.displayName,state:r.state,reason:"expiring",expiresAt:r.expiresAt}]});return i.sort((n,r)=>(n.expiresAt??Number.MAX_SAFE_INTEGER)-(r.expiresAt??Number.MAX_SAFE_INTEGER)||n.displayName.localeCompare(r.displayName)),{invitations:i,expiringCount:i.filter((n)=>n.reason==="expiring").length,failureCount:i.filter((n)=>n.reason==="delivery-failed").length}}async function fJe(e,t){t.throwIfAborted();let i=await Sm(e).listAdminUsers();return t.throwIfAborted(),GJi(i,Date.now())}var WJi=u.strictObject({}),ZJi=zt({id:"admin",config:WJi},{subscriptions:(e)=>{let t=ft(e);return t.registered(async()=>{await mJe(t)}),[]},dashboardWidgets:(e)=>{let t=ft(e);return[hJe.bind(e,({signal:i})=>fJe(t,i))]}}),Cxe=ZJi;var Jn="agent",xJe="agent-network",gJe="agent-proximity",Wxe="agent-discovery:entities",yJe="agent-discovery:proximity-map",Zxe="proximity-map",Vxe="agent-list",Kxe="agent-detail",$c="skill",bJe=30,EJe=120;var TZ="skill-derivation",vJe="skill-derivation",Yxe="skill:skill-derivation",AJe="skills";var VJi=u.string().trim().min(1).max(EJe),Jxe=u.array(VJi).max(bJe),Sw=u.object({name:u.string(),description:u.string(),tags:Jxe,examples:u.array(u.string())}),TR=Sw,kw=A0.extend({entityType:u.literal($c),metadata:TR});var PZ=u.object({name:u.string(),description:u.string(),tags:Jxe}),oE=u.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),KJi=Mk,w0=u.object({name:u.string(),kind:KJi,organization:u.string().optional(),brainName:u.string().describe("Name of the brain instance"),shownAs:u.string().min(1).optional().describe("The name this brain shows the agent under, in place of its own name"),url:u.string().url().describe("Brain endpoint URL"),repoDid:u.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:u.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:u.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:u.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:u.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:u.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:u.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:u.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:oE,discoveredAt:u.string().datetime().meta({description:"When this agent was first discovered",studioWidget:"provenance"}),introducedBy:u.array(u.string()).optional().meta({description:"Agent ids of the peers whose directories reported this agent",studioWidget:"provenance"}),hops:u.number().int().min(2).optional().meta({description:"Discovery order: 2 = sighted through a first-order peer",studioWidget:"provenance"})}),PR=u.object({name:u.string(),shownAs:u.string().min(1).optional(),url:u.string().url(),status:oE,discoveredAt:u.string().datetime().optional(),slug:u.string(),repoDid:u.string().optional(),brainDid:u.string().optional(),cardUri:u.string().optional(),cardCid:u.string().optional(),cardLastError:u.string().optional(),cardFailureCount:u.number().int().nonnegative().optional(),cardUnavailableAt:u.string().datetime().optional(),cardStaleAfter:u.string().datetime().optional()}),Lr=A0.extend({entityType:u.literal(Jn),metadata:PR}),YJi=ji.extend({entityType:u.literal(Jn),metadata:PR}),RR=YJi.extend({frontmatter:w0,about:u.string(),skills:u.array(PZ),notes:u.string()}),JJi=RR.extend({url:u.string().optional(),typeLabel:u.string().optional()}),QJi=RR.extend({url:u.string(),typeLabel:u.string()});var XJi=u.record(u.string(),u.unknown());function eQi(e){try{return Nr(e,XJi).content}catch{return e}}function Qxe(e){return{name:e.name,...e.shownAs&&{shownAs:e.shownAs},url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:LC(e.url),...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter}}}function wJe(e){return Ys(Jn,e,w0)}function FR(e){return{content:e,metadata:Qxe(wJe(e))}}function jC(e){let t={name:e.name,kind:e.kind,...e.organization&&{organization:e.organization},brainName:e.brainName,...e.shownAs&&{shownAs:e.shownAs},url:e.url,...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter},status:oE.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},i=V0e({about:e.about,skills:e.skills,notes:e.notes});return pr(i,t)}function Dm(e,t={}){return jC({...e.frontmatter,...e.body,...t})}function MR(e){return vR(eQi(e))}function Js(e){return{frontmatter:wJe(e.content),body:MR(e.content)}}function Xxe(e){return pr("",e)}function iQi(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function SJe(e,t,i={}){let n=i.minCount??1,r=i.topN??12,o=new Map,s=(a)=>{for(let c of gc(a))o.set(c,(o.get(c)??0)+1)};for(let a of e)s(a.metadata.tags);for(let a of t){let c=MR(a.content);s(c.skills.flatMap((l)=>l.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=n).sort(iQi).slice(0,r)}function kJe(e){if(e.length===0)return"";return["Current agent-directory tag vocabulary (reuse existing tags where they fit; propose new only when nothing does):",...e.map(({tag:t,count:i})=>`- ${t} (${i})`)].join(`
|
|
1038
|
+
`)},t,{requireSaved:!0,userPermissionLevel:s});if(!("success"in a)||a.success!==!0)throw UYe(a,"Agent call failed");let c=m0e.safeParse(a.data);if(!c.success)throw new bi("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(hZ,async({request:{userPermissionLevel:n}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:cn(n)}}})).filter((s)=>s.metadata.status==="approved").map((s)=>{let a=s.metadata.name;return{id:s.id,label:typeof a==="string"&&a.length>0?a:s.id}}).sort((s,a)=>s.label.localeCompare(a.label))}})}var $Ye={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.854",dependencies:{"@a2a-js/sdk":"^0.3.13","@brains/contracts":"workspace:*","@brains/http-signatures":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*",hono:"^4.13.13"},devDependencies:{"@brains/auth-service":"workspace:*","@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};function gZ(e,t){let i=new Headers(e.headers);for(let[n,r]of Object.entries(t))i.set(n,r);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:i})}var QYi={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Signature, Signature-Input, Content-Digest, Date","X-Content-Type-Options":"nosniff"},fd=(e)=>gZ(e,QYi);function XYi(e){let t=e.auth();if(!t)return;let i=t.getIssuer();if(Gh(i)||new URL(i).protocol!=="https:")return;return async(n)=>{let r=await t.getA2ASigningKey();await tYe(n,r.privateJwk,r.keyId)}}function eJi(e){let t=e.auth();if(!t)return;let i=t.getIssuer();if(Gh(i)||new URL(i).protocol!=="https:")return;return async(n)=>{let r=await t.getA2ASigningKey();return{keyId:r.keyId,signature:nYe(n,r.privateJwk)}}}function h0e(e,t,i){let n=XYi(e);return{...n?{requestSigner:n}:{},...i.fetch?{fetch:i.fetch}:{},requestTimeoutMs:t.requestTimeoutMs,streamIdleTimeoutMs:t.streamIdleTimeoutMs,maxNetworkAttempts:t.maxNetworkAttempts,entityService:e.entityReads,isContactApproved:i.isContactApproved??((r)=>e.classRuntimeState.scoped({namespace:yZ,schema:bZ}).has(r.trim().toLowerCase()))}}async function tJi(e,t,i){if(!i.cardReady)return;return xYe({character:e.identity.get(),profile:e.identity.getProfile(),version:$Ye.version,...e.domain?{domain:e.domain}:{},...t.organization?{organization:t.organization}:{},profileKind:e.profileKinds.getResolved(),tools:e.tools.listForPermissionLevel("public"),skills:await e.publicSkills.list(),authEnabled:!1})}async function iJi(e,t,i,n){let r=new URL(i.url),o=new URL(`${r.pathname}${r.search}`,xg(i)),s=await iYe({method:i.method,url:o.toString(),headers:i.headers,body:n},t.jwksResolver);if(s){let a=await e.auth()?.getA2APeerTrust(s.domain);return{permissionLevel:a?.keyFingerprint===s.keyFingerprint?a.grantedLevel:"public",isAnchor:e.permissions.isAnchor("a2a",s.domain),callerDomain:s.domain}}return{permissionLevel:"public",isAnchor:!1,callerDomain:null}}function nJi(e,t,i){let n=new GYe,r=e.agent;return n.get("/.well-known/agent-card.json",async(o)=>{let s=await tJi(e,t,i);if(!s)return fd(o.json({error:"Agent Card not ready"},503));return fd(o.json(s))}),n.get("/.well-known/agent-directory.json",async(o)=>{let s=await gYe(e.entityReads);return fd(o.json(s))}),n.get("/a2a",(o)=>fd(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),n.options("/a2a",()=>fd(new Response(null,{status:204}))),n.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return fd(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await iJi(e,i,o.req.raw,s)}catch{return fd(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return fd(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let l=EYe.safeParse(c);if(!l.success)return fd(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(GKe(o.req.raw.headers)){let p=l.data.method==="message/send"?WKe(l.data.params):void 0,m=p?.op==="list"?await KKe(e.entityReads,a.permissionLevel):await VKe(e.entityReads,a.permissionLevel,p,eJi(e));if(!m)return fd(o.json({error:"Not found"},404));return fd(o.json({jsonrpc:"2.0",id:l.data.id,result:{kind:"message",messageId:crypto.randomUUID(),role:"agent",parts:[{kind:"data",data:m}]}}))}if(l.data.method==="message/stream"){let p=BYe.safeParse(l.data.params??{});if(!p.success)return fd(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:l.data.id}));let m=CYe(l.data.id,p.data.message,{taskManager:i.taskManager,turnSupervisor:i.turnSupervisor,agentService:r,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:i.publicAsks});if("error"in m)return fd(o.json(m));return fd(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await wYe(l.data,{taskManager:i.taskManager,turnSupervisor:i.turnSupervisor,agentService:r,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:i.publicAsks});return fd(o.json(d))}),n}function f0e(e={}){let t=Hh({id:"a2a",config:hYe,setup:(o)=>{let{config:s}=o,a=xs(o),{servesHttp:c}=a,l=h0e(a,s,e),d={cardReady:!1,servesHttp:c,taskManager:new s0e,turnSupervisor:new a0e,jwksResolver:new cR(e.fetch?{fetch:e.fetch}:{}),clientDeps:l,publicAsks:new o0e(s.publicAsks,a.classRuntimeState)};if(c)a.endpoint({label:"A2A",url:"/a2a",priority:25}),a.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),a.logger.info("A2A interface registered",{domain:a.domain});else a.logger.info("A2A interface registered in tool-only mode",{domain:a.domain});return a.ready(()=>{d.cardReady=!0}),d}}),i=HYe(t,(o)=>{let s=xs(o);qYe(s,h0e(s,o.config,e),{networkAskTimeoutMs:o.config.networkAskTimeoutMs,turnTimeoutMs:o.config.turnTimeoutMs})}),n=Do(i,(o)=>{let{config:s,state:a}=o;if(!a.servesHttp)return[];let c=xs(o),l=nJi(c,s,a),d=(m)=>Promise.resolve(l.fetch(m)),p=(m,h)=>({path:m,method:h,public:!0,handler:d});return[p("/.well-known/agent-card.json","GET"),p("/.well-known/agent-directory.json","GET"),p("/a2a","GET"),p("/a2a","POST"),p("/a2a","OPTIONS")]}),r=fg(n,(o)=>{let{state:s}=o,{logger:a}=xs(o);return{id:"a2a",start:async()=>{if(s.servesHttp)a.info("A2A mounted on shared webserver host");else a.info("A2A running without webserver routes")},stop:async()=>{await s.turnSupervisor.close(),a.info("A2A server stopped")}}});return Or(r,(o)=>{let{config:s}=o,a=xs(o),c=()=>FYe(h0e(a,s,e));return[{...c(),handler:(l,d)=>c().handler(l,d)}]})}var rJi=f0e(),WYe=rJi;function Wh(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function Aw(e,t){return{registration:e,actionIds:t.map((i)=>i.name)}}var oJi=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function Zh(e){return oJi.format(new Date(e))}function Sm(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function qc(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function AZ(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function Nk(e){if(!e)return"This brain";let t="did:web:";if(!e.startsWith(t))return e;let i=e.slice(t.length);if(i.length===0)return e;return i.split(":").map(decodeURIComponent).join("/")}var sJi={"auth.a2a_peer_trust.granted":"Trusted an A2A peer","auth.a2a_peer_trust.revoked":"Revoked A2A peer trust","auth.access.reinitialized":"Reinitialized access from configuration","auth.external_peer.invited":"Invited a person from an external peer","auth.external_peer.linked":"Linked an external peer","auth.external_peer.unlinked":"Unlinked an external peer","auth.invitation.created":"Person invited","auth.invitation.cancelled":"Invitation cancelled","auth.invitation.manual_delivery_confirmed":"Manual delivery confirmed","auth.invitation.resent":"Invitation resent","auth.identity.attached":"Connected an identity","auth.identity.detached":"Disconnected an identity","auth.identity.delivery_bound":"Bound a verified delivery channel","auth.passkey.authentication_failed":"Recorded a failed passkey sign-in","auth.passkey.migrated":"Migrated a passkey","auth.passkey.registered":"Registered a passkey","auth.passkey.registration_failed":"Recorded a failed passkey registration","auth.passkey.registration_started":"Created a passkey setup link","auth.passkey.revoked":"Revoked a passkey","auth.setup_token.generated":"Generated a setup token","auth.user.created":"Created an account","auth.user.deleted":"Deleted a suspended account","auth.user.grants_revoked":"Revoked account grants","auth.user.role_updated":"Role changed","auth.user.status_updated":"Changed account status"};function J0e(e){let t=sJi[e];if(t)return t;let i=e.replaceAll(/[._-]+/g," ").trim();return i.length===0?e:fo(i)}var Q0e=u.strictObject({actorUserId:u.string().trim().min(1).max(120).optional(),action:u.string().trim().min(1).max(200).optional(),selected:u.string().trim().min(1).max(120).optional(),offset:u.preprocess(Wh,u.number().int().min(0).max(1e5)).default(0),limit:u.preprocess(Wh,u.number().int().min(1).max(100)).default(25)}),ZYe=u.strictObject({id:u.string().min(1),actorUserId:u.string().min(1).optional(),action:u.string().min(1),targetType:u.string().min(1).optional(),targetId:u.string().min(1).optional(),targetUserId:u.string().min(1).optional(),createdAt:u.number().int().nonnegative()}),aJi=u.strictObject({userId:u.string().min(1),displayName:u.string().min(1)}),cJi=u.strictObject({query:Q0e,events:u.array(ZYe),selectedEvent:ZYe.optional(),users:u.array(aJi),actions:u.array(u.strictObject({value:u.string().min(1),label:u.string().min(1),count:u.number().int().nonnegative()})),total:u.number().int().nonnegative()});function VYe(e){let t=e.metadata?.userId;return{...typeof t==="string"&&t?{targetUserId:t}:{},id:e.id,...e.actorUserId?{actorUserId:e.actorUserId}:{},action:e.action,...e.targetType?{targetType:e.targetType}:{},...e.targetId?{targetId:e.targetId}:{},createdAt:e.createdAt}}function KYe(e,t){return e?t.get(e)??"Former Admin":"System"}function YYe(e,t){if(e.targetId)return t.get(e.targetId)??(e.targetUserId?t.get(e.targetUserId):void 0)??e.targetType??e.targetId;return e.targetType??"Access"}var Y0e=Fo({id:"audit",label:"Audit",priority:90,permission:"admin",query:Q0e,data:cJi,actions:[],view:({data:e})=>{let t=new Map(e.users.map((o)=>[o.userId,o.displayName])),i=e.selectedEvent,r=[{type:"query",id:"audit-filters",...{controls:[{key:"actorUserId",label:"Actor",value:e.query.actorUserId,allLabel:"All actors",options:e.users.map((o)=>({value:o.userId,label:o.displayName}))},{key:"action",label:"Action",value:e.query.action,allLabel:"All actions",options:e.actions}],...e.total>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.total}}:{}}},{type:"detail",id:"audit-detail",queryKey:"selected",empty:"Select an event to inspect its audit record.",...i?{open:{forId:i.id,title:J0e(i.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:KYe(i.actorUserId,t)},{label:"Action",value:i.action},{label:"Target",value:YYe(i,t)},{label:"Occurred",value:Zh(i.createdAt)},{label:"Event ID",value:i.id},{label:"Action ID",value:i.action},...i.targetId?[{label:"Target ID",value:i.targetId}]:[],...i.actorUserId?[{label:"Actor ID",value:i.actorUserId}]:[]]}]}}:{},master:{type:"list",id:"audit-events",presentation:"standard",empty:"No audit events match these filters.",items:e.events.map((o)=>({id:o.id,title:J0e(o.action),description:`${KYe(o.actorUserId,t)} \u2192 ${YYe(o,t)}`,metadata:[new Date(o.createdAt).toISOString()],links:[{label:"Details",target:{detail:{itemId:o.id}}}]}))}}];return{kicker:"Security history",title:"Audit",description:"Who changed access, what changed, and when.",status:{label:`${e.total} matching ${e.total===1?"event":"events"}`,tone:"neutral"},blocks:r}}});function JYe(e){let t=e.studio.source({definition:Y0e,bind:(i)=>Y0e.bind(i,{load:async({query:n})=>{let r=Sm(e),o=n.get(Q0e),[s,a]=await Promise.all([r.queryAuditEvents({...o.actorUserId?{actorUserId:o.actorUserId}:{},...o.action?{action:o.action}:{},...o.selected?{selectedId:o.selected}:{},offset:o.offset,limit:o.limit}),r.listUsers()]);return{query:o,events:s.events.map(VYe),...s.selectedEvent?{selectedEvent:VYe(s.selectedEvent)}:{},users:AZ(a),actions:s.actions.map(({action:c,count:l})=>({value:c,label:J0e(c),count:l})).sort((c,l)=>c.label.localeCompare(l.label)),total:s.total}},actions:[]})});return Aw(t,Y0e.actions)}var v0=u.strictObject({status:u.string()}),wZ=u.strictObject({status:u.string(),setupUrl:u.url(),expiresAt:u.string()});function OC(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var SZ=u.strictObject({type:u.string(),displayName:u.string(),subjectLabel:u.string(),deliveryModes:u.array(u.enum(["automatic","manual"]))});function kZ(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function BZ(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function CZ(e,t){return{deliveryType:{label:"Delivery channel",control:"select",options:e.map((i)=>({value:i.type,label:i.displayName}))},deliverySubject:{label:"Delivery destination",labelBy:{field:"deliveryType",values:e.map((i)=>({value:i.type,label:i.subjectLabel}))},control:"text"},deliveryLabel:{label:"Delivery label (optional)",control:"text"},deliveryMode:{label:"Delivery mode",control:"select",options:t.map((i)=>({value:i,label:i==="automatic"?"Automatic":"Manual"}))}}}import{randomUUID as lJi}from"crypto";var QYe=new Set(["claimed","expired","cancelled"]),uJi=new Set(["claimed","cancelled"]),nxe=u.strictObject({state:u.enum(["pending","history"]).optional().default("pending"),selected:u.string().trim().min(1).max(200).optional(),offset:u.preprocess(Wh,u.number().int().min(0)).optional().default(0),limit:u.preprocess(Wh,u.number().int().min(1).max(100)).optional().default(25)}),iJe=u.strictObject({status:u.string(),setupUrl:u.url().nullable(),expiresAt:u.string().nullable()}),dJi=u.strictObject({idempotencyKey:u.string().min(1),displayName:u.string().trim().min(1).max(200),role:u.enum(["admin","trusted"]),deliveryType:u.string().trim().min(1).max(100),deliverySubject:u.string().trim().min(1).max(500),deliveryLabel:u.string().trim().max(200).optional(),deliveryMode:u.enum(["automatic","manual"])}),nJe=u.strictObject({invitationId:u.string().min(1)}),pJi=u.strictObject({invitationId:u.string().min(1),deliveryAttemptId:u.string().min(1)}),rJe=u.strictObject({invitationId:u.string(),state:u.string()}),txe=Vi({name:"create-invitation",label:"Add a person",permission:"admin",input:dJi,output:iJe}),rxe=Vi({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:nJe,output:iJe}),oxe=Vi({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:nJe,output:rJe}),sxe=Vi({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:pJi,output:rJe}),XYe=u.strictObject({id:u.string(),displayName:u.string(),role:u.string(),state:u.string(),destination:u.string(),updatedAt:u.number(),deliveryAttemptId:u.string().optional()}),mJi=u.strictObject({query:nxe,idempotencyKey:u.string(),channels:u.array(SZ),invitations:u.array(XYe),selectedInvitation:XYe.optional(),selectedTotal:u.number().int().nonnegative(),pendingCount:u.number().int().nonnegative(),historyCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()});function ixe(e,t){let i=e.filter((n)=>n.id===t);if(i.length!==1||!i[0])throw Error(`Invitations tab composition requires block "${t}" exactly once`);return i[0]}function X0e(e,t){let i=ixe(e,t);switch(i.type){case"tabs":case"detail":case"columns":throw Error(`Invitations tab composition block "${t}" must be a region`);default:return i}}function oJe(e,t){let i=ixe(e,"invitation-totals");if(i.type!=="stats")throw Error('Invitations tab composition block "invitation-totals" must be stats');let n=e.some((a)=>a.id==="create-invitation-unavailable")?[X0e(e,"create-invitation-unavailable")]:[],r=ixe(e,"invitations");if(r.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=X0e(e,"invitation-delivery");if(o.type!=="card")throw Error("Invitations composition requires delivery capabilities");let s=t.flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[...n,X0e(e,"invitation-filters"),r,{...o,presentation:"disclosure",blocks:[...o.blocks,i,...s]}]}}var sJe=OC("Invitation setup");function hJi(e){if(uJi.has(e.state))return[];return[...e.deliveryAttemptId?[{action:sxe,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:rxe,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:sJe}]:[],...e.state!=="expired"?[{action:oxe,input:{invitationId:e.id}}]:[]]}function eJe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return fo(e.state)}var exe=Fo({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:nxe,data:mJi,actions:[txe,rxe,oxe,sxe],badge:({data:e})=>e.pendingCount,view:({data:e})=>{let t=[{type:"stats",id:"invitation-totals",items:[{label:"Pending",value:e.pendingCount},{label:"History",value:e.historyCount},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"neutral"}]}],i=kZ(e.channels),n;if(e.channels.length>0&&i.length>0)n={action:txe,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:BZ("Role"),...CZ(e.channels,i)}},result:sJe};else t.push({type:"notice",id:"create-invitation-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});let r=e.selectedInvitation;return t.push({type:"query",id:"invitation-filters",controls:[{key:"state",label:"View",value:e.query.state,options:[{value:"pending",label:"Pending",count:e.pendingCount},{value:"history",label:"History",count:e.historyCount}]}],...e.selectedTotal>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.selectedTotal}}:{}},{type:"detail",id:"invitations",queryKey:"selected",empty:"Select an invitation to review its delivery.",master:{type:"list",id:"invitation-records",presentation:"standard",empty:e.query.state==="pending"?"No pending invitations.":"No invitation history yet.",items:e.invitations.map((o)=>({id:o.id,title:o.displayName,description:`${fo(o.role)} \xB7 ${eJe(o)}`,metadata:[o.destination,`Updated ${new Date(o.updatedAt).toISOString()}`],links:[{label:"Review",target:{detail:{itemId:o.id}}}]}))},...r?{open:{forId:r.id,title:r.displayName,blocks:[{type:"key-values",id:"invitation-fields",items:[{label:"Role",value:fo(r.role)},{label:"Delivery",value:eJe(r)},{label:"Destination",value:r.destination},{label:"Updated",value:Zh(r.updatedAt)}]},{type:"actions",id:"invitation-actions",items:hJi(r)}]}}:e.query.selected?{open:{forId:e.query.selected,title:"Invitation unavailable",blocks:[{type:"notice",tone:"neutral",text:"This invitation is no longer available. Return to the list to choose another."}]}}:{}},{type:"card",id:"invitation-delivery",label:"Delivery capabilities",blocks:[{type:"key-values",items:e.channels.map((o)=>({label:o.displayName,value:o.deliveryModes.map(fo).join(" \xB7 ")}))}]}),{kicker:"Access administration",title:"Invitations",description:"Create, deliver, retry, and revoke passkey invitations without moving auth authority into Studio.",status:{label:`${e.pendingCount} pending`,tone:e.failureCount>0?"warn":"neutral"},...n?{primaryAction:n}:{},blocks:t}}});function tJe(e){return{status:e.invitation.state==="sent"?"Delivery provider accepted the invitation.":e.invitation.state==="failed"?"Invitation saved, but delivery failed.":"Manual delivery is waiting for confirmation.",setupUrl:e.registration?.setupUrl??null,expiresAt:e.registration?new Date(e.registration.expiresAt*1000).toISOString():null}}function aJe(e){let t=Sm(e),i=new Map,n=e.studio.source({definition:exe,bind:(r)=>{let o=txe.bind(r,async({input:l,caller:d})=>{let p=await t.createInvitation({idempotencyKey:l.idempotencyKey,displayName:l.displayName,role:l.role,delivery:{type:l.deliveryType,subject:l.deliverySubject,...l.deliveryLabel?{label:l.deliveryLabel}:{},mode:l.deliveryMode}},qc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)i.set(p.invitation.id,p.registration.deliveryAttemptId);return tJe(p)}),s=rxe.bind(r,async({input:l,caller:d})=>{let p=await t.resendInvitation(l.invitationId,qc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)i.set(p.invitation.id,p.registration.deliveryAttemptId);return tJe(p)}),a=oxe.bind(r,async({input:l,caller:d})=>{let p=await t.cancelInvitation(l.invitationId,qc(d));return i.delete(l.invitationId),{invitationId:p.id,state:p.state}},({input:l})=>({summary:"Cancel this invitation and revoke its pending setup link?",revision:l.invitationId})),c=sxe.bind(r,async({input:l,caller:d})=>{let p=await t.confirmManualInvitationDelivery(l.invitationId,l.deliveryAttemptId,qc(d));return i.delete(l.invitationId),{invitationId:p.id,state:p.state}});return exe.bind(r,{actions:[o,s,a,c],load:async({query:l})=>{let d=l.get(nxe),[p,m]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),h=m.filter((T)=>T.deliveryModes.length>0),f=p.filter((T)=>T.invitation!==void 0),g=f.filter((T)=>T.invitation&&!QYe.has(T.invitation.state)),y=f.filter((T)=>T.invitation&&QYe.has(T.invitation.state)),b=d.state==="pending"?g:y,v=f.flatMap((T)=>{let F=T.invitation;if(!F)return[];let k=T.identities.find((L)=>L.type!=="passkey")?.label??T.externalPeers[0]?.peerId??"Not recorded",N=i.get(F.id);return[{id:F.id,displayName:T.displayName,role:T.role,state:F.state,destination:k,updatedAt:F.claimedAt??F.cancelledAt??F.expiredAt??F.sentAt??F.updatedAt,...N?{deliveryAttemptId:N}:{}}]}),w=new Map(v.map((T)=>[T.id,T])),B=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:lJi(),channels:h.map((T)=>({type:T.type,displayName:T.displayName,subjectLabel:T.subjectLabel,deliveryModes:T.deliveryModes})),invitations:b.slice(d.offset,d.offset+d.limit).flatMap((T)=>{let F=T.invitation?w.get(T.invitation.id):void 0;return F?[F]:[]}),...B?{selectedInvitation:B}:{},selectedTotal:b.length,pendingCount:g.length,historyCount:y.length,failureCount:g.filter((T)=>T.invitation?.state==="failed").length}}})}});return Aw(n,exe.actions)}var uxe=u.strictObject({peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional()}),fJi=u.strictObject({peerId:u.string().trim().min(1).max(2000),displayName:u.string().trim().min(1).max(200),role:u.enum(["admin","trusted"]),deliveryType:u.string().trim().min(1).max(64),deliverySubject:u.string().trim().min(1).max(1000),deliveryLabel:u.string().trim().min(1).max(200).optional(),deliveryMode:u.enum(["automatic","manual"])}),xJi=u.strictObject({peerId:u.string().trim().min(1).max(2000),userId:u.string().min(1)}),cxe=Vi({name:"invite-external-peer-person",label:"Invite peer person",permission:"admin",confirmation:{kind:"static",message:"Create this local member and bind them to the external peer?"},input:fJi,output:wZ}),lxe=Vi({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:xJi,output:v0}),gJi=u.strictObject({query:uxe,peers:u.array(u.strictObject({peerId:u.string(),displayName:u.string(),role:u.enum(["admin","trusted","public"]),verificationStatus:u.enum(["unverified","verified"]),createdAt:u.number()})),people:u.array(u.strictObject({userId:u.string(),displayName:u.string()})),channels:u.array(SZ)});function DZ(e,t){let i=e.filter((r)=>r.id===t);if(i.length!==1)throw Error(`Peer tab composition requires block "${t}" exactly once`);let n=i[0];if(!n)throw Error(`Peer tab composition requires block "${t}" exactly once`);switch(n.type){case"tabs":case"detail":case"columns":throw Error(`Peer tab composition block "${t}" must be a region`);default:return n}}function dxe(e){let t=e.some((i)=>i.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[DZ(e,"peers"),DZ(e,"link-peer"),DZ(e,t)],invitations:[DZ(e,t)]}}var yJi=OC("Peer invitation setup"),axe=Fo({id:"peers",label:"Peers",priority:12,permission:"admin",query:uxe,data:gJi,actions:[cxe,lxe],view:({data:e})=>{let t=kZ(e.channels),i=[{type:"stats",id:"peer-summary",items:[{label:"Linked peers",value:e.peers.length},{label:"Verified",value:e.peers.filter((n)=>n.verificationStatus==="verified").length},{label:"Available people",value:e.people.length}]}];if(e.channels.length>0&&t.length>0)i.push({type:"card",id:"invite-peer",label:"Peer-first invitation",blocks:[{type:"text",text:"Create a local member for a person known first through another brain, then issue their single-use passkey setup link."},{type:"action",action:cxe,input:{...e.query.peerId?{peerId:e.query.peerId}:{},...e.query.displayName?{displayName:e.query.displayName}:{}},form:{presentation:"disclosure",submitLabel:"Invite peer person",fields:{peerId:{label:"External peer ID",control:"text"},displayName:{label:"Display name",control:"text"},role:BZ("Local role"),...CZ(e.channels,t)}},result:yJi}]});else i.push({type:"notice",id:"invite-peer-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});return i.push({type:"card",id:"link-peer",label:"Link an existing person",blocks:[{type:"action",action:lxe,input:{...e.query.peerId?{peerId:e.query.peerId}:{}},form:{submitLabel:"Link peer",fields:{peerId:{label:"External peer ID",control:"text"},userId:{label:"Local person",control:"select",options:e.people.map((n)=>({value:n.userId,label:n.displayName}))}}}}]},{type:"table",id:"peers",empty:"No external peers linked.",columns:[{key:"peer",label:"Peer"},{key:"person",label:"Local person"},{key:"role",label:"Local role"},{key:"verification",label:"Verification"},{key:"linked",label:"Linked"}],rows:e.peers.map((n)=>({id:`${n.peerId}:${n.displayName}`,cells:{peer:Nk(n.peerId),person:n.displayName,role:n.role,verification:n.verificationStatus,linked:Zh(n.createdAt)},compact:{title:Nk(n.peerId),metadata:[n.displayName,fo(n.role),Zh(n.createdAt)],badges:[{label:fo(n.verificationStatus),tone:n.verificationStatus==="verified"?"good":"warn"}]}}))}),{kicker:"Network administration",title:"Peers",description:"List external brain relationships, invite peer-first people, and link known peers to existing members.",status:{label:`${e.peers.length} linked`},blocks:i}}});function cJe(e){let t=Sm(e),i=e.studio.source({definition:axe,bind:(n)=>{let r=cxe.bind(n,async({input:s,caller:a})=>{let c=await t.inviteExternalPeerPerson({peerId:s.peerId,displayName:s.displayName,role:s.role,delivery:{type:s.deliveryType,subject:s.deliverySubject,...s.deliveryLabel?{label:s.deliveryLabel}:{},mode:s.deliveryMode}},qc(a));return{status:`Created ${c.user.displayName} and linked ${c.peer.peerId}. Deliver only through ${c.registration.delivery.label}.`,setupUrl:c.registration.setupUrl,expiresAt:new Date(c.registration.expiresAt*1000).toISOString()}}),o=lxe.bind(n,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},qc(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((l)=>l.userId===s.userId)?.displayName??"person";return{summary:`Link ${s.peerId} to ${c}? Local access does not change.`,revision:`${s.peerId}:${s.userId}`}});return axe.bind(n,{actions:[r,o],load:async({query:s})=>{let a=s.get(uxe),[c,l]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),d=c.filter((p)=>p.status!=="invited");return{query:a,peers:c.flatMap((p)=>p.externalPeers.map((m)=>({peerId:m.peerId,displayName:p.displayName,role:p.role,verificationStatus:m.verificationStatus,createdAt:m.createdAt}))),people:AZ(d),channels:l.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return Aw(i,axe.actions)}function pxe(e,t){let i=e.filter((n)=>n.id===t);if(i.length!==1||!i[0])throw Error(`People tab composition requires block "${t}" exactly once`);return i[0]}function lJe(e,t,i){let n=pxe(e,"people-summary");if(n.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let r=pxe(e,"people");if(r.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=pxe(e,"brain-anchor");if(o.type!=="card")throw Error('People tab composition block "brain-anchor" must be a card');let s=[t,...i].flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[r,{type:"card",id:"people-peers",label:"External brains",presentation:"disclosure",blocks:s},{...o,label:"Access reference",presentation:"disclosure",blocks:[n,...o.blocks]}]}}var Axe=u.strictObject({selected:u.string().trim().min(1).max(200).optional()}),wxe=u.strictObject({userId:u.string().min(1)}),bJi=u.strictObject({userId:u.string().min(1),role:u.enum(["admin","trusted","public"])}),EJi=u.strictObject({userId:u.string().min(1),status:u.enum(["active","suspended"])});function vJi(e){return e.revokedAt===void 0&&e.type!=="passkey"}function AJi(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var wJi=u.strictObject({userId:u.string().min(1),credentialId:u.string().min(1)}),SJi=u.strictObject({userId:u.string().min(1),type:u.string().trim().min(1).max(64),subject:u.string().trim().min(1).max(2000),issuer:u.string().trim().min(1).max(2000).optional(),label:u.string().trim().min(1).max(200).optional()}),kJi=u.strictObject({userId:u.string().min(1),identityId:u.string().min(1)}),BJi=u.strictObject({userId:u.string().min(1),peerId:u.string().trim().min(1).max(2000)}),fxe=Vi({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:bJi,output:v0}),xxe=Vi({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:EJi,output:v0}),gxe=Vi({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:wxe,output:v0}),yxe=Vi({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:wJi,output:v0}),Sxe=Vi({name:"start-person-passkey-registration",label:"Create setup link",permission:"admin",confirmation:{kind:"static",message:"Create a single-use passkey setup link for this person?"},input:wxe,output:wZ}),bxe=Vi({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:wxe,output:v0}),kxe=Vi({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:SJi,output:v0}),Exe=Vi({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:kJi,output:v0}),vxe=Vi({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:BJi,output:v0}),CJi=u.strictObject({userId:u.string(),displayName:u.string(),role:u.enum(["admin","trusted","public"]),status:u.enum(["active","suspended"]),isAnchor:u.boolean(),isSelf:u.boolean(),profileEntityId:u.string().optional(),passkeys:u.array(u.strictObject({id:u.string(),kind:u.string(),createdAt:u.number()})),identities:u.array(u.strictObject({id:u.string(),type:u.string(),displayName:u.string(),label:u.string(),verified:u.boolean()})),peers:u.array(u.strictObject({peerId:u.string(),verificationStatus:u.enum(["unverified","verified"])}))}),DJi=u.strictObject({query:Axe,anchor:u.strictObject({kind:u.enum(["person","collective"]),configuredKind:u.enum(["person","team","organization"]),displayName:u.string(),administeredBy:u.number().int().nonnegative()}),people:u.array(CJi),activeCount:u.number().int().nonnegative(),activeAdminCount:u.number().int().nonnegative(),suspendedCount:u.number().int().nonnegative(),channelTypes:u.array(u.strictObject({type:u.string(),displayName:u.string()}))}),IJi=OC("Passkey setup");function _Ji(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function mxe(e){return{type:"notice",tone:"warn",text:e}}function TJi(e){return{type:"action",action:Sxe,input:{userId:e},result:IJi}}function PJi(e,t){return{type:"action",action:kxe,input:{userId:e},form:{submitLabel:"Attach channel",fields:{type:{label:"Channel type",control:"select",options:t.map((i)=>({value:i.type,label:i.displayName}))},subject:{label:"Channel subject",control:"text"},issuer:{label:"Issuer (optional)",control:"url"},label:{label:"Display label (optional)",control:"text"}}}}}function RJi(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var hxe=Fo({id:"people",label:"People",priority:10,permission:"admin",query:Axe,data:DJi,actions:[fxe,xxe,gxe,yxe,Sxe,bxe,kxe,Exe,vxe],badge:({data:e})=>e.suspendedCount,view:({data:e})=>{let t=e.people.find((r)=>r.userId===e.query.selected),i=[];if(t){let r=t.role==="admin"&&t.status==="active"&&e.activeAdminCount<=1,o=t.isAnchor?"The protected brain identity must remain an active Admin.":t.status==="suspended"?"Reactivate this person before changing access.":r?"Add another active Admin before changing this role.":void 0,s=t.isAnchor?"The protected brain identity cannot be suspended.":r?"Add another active Admin before suspending this person.":void 0;if(i.push({type:"key-values",id:"person-summary",items:[{label:"Role",value:fo(t.role)},{label:"Status",value:fo(t.status)},{label:"Protected brain identity",value:t.isAnchor},{label:"Brain relationship",value:t.peers.length>0?"External peer + local member":"Hosted member"}]}),o)i.push({type:"notice",tone:"warn",text:o});else i.push({type:"card",id:"person-role",label:"Permission role",blocks:[{type:"action",action:fxe,input:{userId:t.userId,role:t.role},form:{submitLabel:"Change role",fields:{role:{label:"Role",control:"select",options:[{value:"admin",label:"Admin"},{value:"trusted",label:"Trusted"},{value:"public",label:"Public"}]}}}}]});i.push({type:"card",id:"person-access",label:"Access",blocks:[{type:"actions",items:[{action:xxe,input:{userId:t.userId,status:t.status==="suspended"?"active":"suspended"},capability:{id:t.status==="suspended"?"reactivate-person":"suspend-person",label:t.status==="suspended"?"Reactivate person":"Suspend person"},disabled:t.status==="active"&&s!==void 0},...t.status==="active"&&!t.isSelf?[{action:bxe,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:gxe,input:{userId:t.userId}}]:[]]},...t.isSelf?[_Ji()]:[],...s&&t.status==="active"?[mxe(s)]:[]]}),i.push({type:"card",id:"person-sign-in",label:"Sign-in",blocks:[{type:"table",id:"person-passkeys",empty:"No passkeys registered.",columns:[{key:"kind",label:"Passkey"},{key:"created",label:"Added"}],rows:t.passkeys.map((a)=>({id:a.id,cells:{kind:a.kind,created:Zh(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${Zh(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:yxe,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[TJi(t.userId)]:[mxe("A verified channel is required for setup delivery.")]:[]]}),i.push({type:"card",id:"person-channels",label:"Linked identities",blocks:[{type:"table",id:"person-identities",empty:"No linked identity.",columns:[{key:"channel",label:"Channel"},{key:"identity",label:"Identity"},{key:"assurance",label:"Assurance"}],rows:t.identities.map((a)=>({id:a.id,cells:{channel:a.displayName,identity:a.label,assurance:a.verified?"Verified":"Asserted"},compact:{title:a.label,metadata:[a.displayName],badges:[{label:a.verified?"Verified":"Asserted",tone:a.verified?"good":"neutral"}]},actions:[{action:Exe,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[PJi(t.userId,e.channelTypes)]:[mxe("No attachable channel type is configured.")]]}),i.push({type:"notice",tone:"neutral",text:"External peer links record provenance from another brain. They do not grant or change this person's local access."}),i.push({type:"list",id:"person-peers",empty:"No external peer linked; this person is hosted locally.",items:t.peers.map((a)=>({id:a.peerId,title:Nk(a.peerId),description:`Vouched in by ${Nk(a.peerId)} \xB7 ${a.peerId}`,metadata:[fo(a.verificationStatus)],actions:[{action:vxe,input:{userId:t.userId,peerId:a.peerId}}]}))})}let n=[{type:"stats",id:"people-summary",items:[{label:"Active members",value:e.activeCount},{label:"Active Admins",value:e.activeAdminCount},{label:"Suspended",value:e.suspendedCount,tone:e.suspendedCount>0?"warn":"neutral"}]},{type:"card",id:"brain-anchor",label:"Brain identity",blocks:[{type:"key-values",items:[{label:"Name",value:e.anchor.displayName},{label:"Kind",value:e.anchor.configuredKind},{label:"Ownership",value:e.anchor.kind},{label:"Administered by",value:e.anchor.administeredBy}]}]},{type:"detail",id:"people",queryKey:"selected",empty:"Select a person to inspect their access.",master:{type:"list",id:"people-roster",presentation:"standard",empty:"No people are available.",items:[...e.people].sort((r,o)=>Number(o.isSelf)-Number(r.isSelf)||Number(r.isAnchor)-Number(o.isAnchor)||r.displayName.localeCompare(o.displayName)).map((r)=>({id:r.userId,title:r.displayName,description:[fo(r.role),fo(r.status),...r.isSelf?["You"]:[],...r.isAnchor?["Protected brain identity"]:[]].join(" \xB7 "),metadata:[r.identities.length===0?"No linked identities":r.identities.length===1?"One linked identity":`${r.identities.length} linked identities`,...r.peers.length>0?[`Arrived via ${Nk(r.peers[0]?.peerId)}`]:[]],...r.isSelf?{link:{detail:{itemId:r.userId}}}:{},links:[{label:r.isSelf?"Account \u2192":r.isAnchor?"View protection":"Manage person",target:r.isSelf?{launch:{target:"account-settings"}}:{detail:{itemId:r.userId}}}]}))},...t?{open:{forId:t.userId,title:t.displayName,blocks:i}}:{}}];return{kicker:"Access administration",title:"People",description:"Manage people\u2019s access to this brain, linked identities, and account recovery. Use Account for your own profile and sign-in settings.",status:{label:`${e.activeCount} active`,tone:e.suspendedCount>0?"warn":"neutral"},blocks:n}}});function IZ(e,t){return e.find((i)=>i.userId===t)?.displayName??"person"}async function FJi(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function uJe(e){let t=Sm(e),i=e.studio.source({definition:hxe,bind:(n)=>{let r=fxe.bind(n,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,qc(f)),{status:`Role changed to ${fo(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${IZ(f,h.userId)}\u2019s role to ${fo(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=xxe.bind(n,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,qc(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${IZ(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=gxe.bind(n,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,qc(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${IZ(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=yxe.bind(n,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,qc(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=Sxe.bind(n,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,qc(f));return{status:`Bound to ${g.delivery.label}. Deliver only through that confirmed private channel.`,setupUrl:g.setupUrl,expiresAt:new Date(g.expiresAt*1000).toISOString()}}),l=bxe.bind(n,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,qc(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${IZ(f,h.userId)} out everywhere?`,revision:h.userId}}),d=kxe.bind(n,async({input:h,caller:f})=>(await t.attachIdentity({userId:h.userId,type:h.type,subject:h.subject,...h.issuer?{issuer:h.issuer}:{},...h.label?{label:h.label}:{},verifiedAt:Date.now(),source:{kind:"admin"}},qc(f)),{status:"Verified channel attached."})),p=Exe.bind(n,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,qc(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=vxe.bind(n,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,qc(f)),{status:"External peer unlinked from the local person."}),({input:h})=>({summary:`Unlink ${h.peerId}? Local access will not change.`,revision:`${h.peerId}:${h.userId}`}));return hxe.bind(n,{actions:[r,o,s,a,c,l,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(Axe),[y,b,v]=await Promise.all([FJi(t),t.listAdminUsers(),t.listInvitationChannels()]),w=b.filter((N)=>N.status!=="invited"),B=w.find((N)=>N.isAnchor)??w.find((N)=>N.role==="admin"&&N.status==="active"),T=y??RJi(B?.displayName??"Brain owner",w.filter((N)=>N.role==="admin"&&N.status==="active").length),F=w.filter((N)=>N.status==="active"),k=new Map(v.map((N)=>[N.type,N.displayName]));return{query:g,anchor:{kind:T.kind,configuredKind:T.configuredKind,displayName:T.displayName,administeredBy:T.administeredBy},people:w.flatMap((N)=>{if(N.status==="invited")return[];return[{userId:N.userId,displayName:N.displayName,role:N.role,status:N.status,isAnchor:N.isAnchor,isSelf:f?.actor.id===N.userId,...N.profileEntityId?{profileEntityId:N.profileEntityId}:{},passkeys:N.passkeys.map((L)=>({id:L.id,kind:AJi(L),createdAt:L.createdAt})),identities:N.identities.filter(vJi).map((L)=>({id:L.id,type:L.type,displayName:k.get(L.type)??fo(L.type),label:L.label??"Connected identity",verified:L.verifiedAt!==void 0})),peers:N.externalPeers.map((L)=>({peerId:L.peerId,verificationStatus:L.verificationStatus}))}]}),activeCount:F.length,activeAdminCount:F.filter((N)=>N.role==="admin").length,suspendedCount:w.length-F.length,channelTypes:v.map((N)=>({type:N.type,displayName:N.displayName}))}}})}});return Aw(i,hxe.actions)}var MJi=u.strictObject({tab:u.enum(["people","invitations","audit"]).default("people"),selected:u.string().trim().min(1).max(200).optional(),state:u.enum(["pending","history"]).optional(),offset:u.preprocess(Wh,u.number().int().min(0).max(1e5)).optional(),limit:u.preprocess(Wh,u.number().int().min(1).max(100)).optional(),peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional(),actorUserId:u.string().trim().min(1).max(120).optional(),action:u.string().trim().min(1).max(200).optional()});function OJi(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function NJi(e){if(e===null||typeof e!=="object")return!1;let t=Reflect.get(e,"view");if(t===null||typeof t!=="object")return!1;return Array.isArray(Reflect.get(t,"blocks"))}function LJi(e,t){if(!NJi(e))throw Error(`${t} tab returned invalid workspace data`);return e}function dJe(e,t){let i=[];for(let n of e){if(n.type==="tabs")throw Error(`${t} tab cannot contribute nested tabs`);i.push(n)}return i}function Bxe(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function AR(e,t,i,n){return LJi(await e.dataProvider(t,i,n),e.label)}async function jJi(e,t,i,n){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,i,n)}function zJi(e){let t=new Map;for(let i of e)for(let n of i.actionIds){if(t.has(n))throw Error(`Administration action "${n}" is declared by more than one source`);if(!i.registration.actionHandler)throw Error(`Administration source "${i.registration.label}" declares actions without a handler`);t.set(n,i.registration)}return t}function pJe(e){return{suspended:e.filter((t)=>t.status==="suspended").length,pendingInvitations:e.filter((t)=>t.invitation!==void 0&&!["claimed","expired","cancelled"].includes(t.invitation.state)).length}}function UJi(e){return[...e.pendingInvitations>0?[{id:"invitations",title:`${e.pendingInvitations} ${e.pendingInvitations===1?"invitation":"invitations"} waiting`,detail:"Not yet accepted.",severity:"info",action:{label:"Review invitations",query:{tab:"invitations"}}}]:[],...e.suspended>0?[{id:"suspended",title:`${e.suspended} ${e.suspended===1?"person":"people"} suspended`,severity:"info",action:{label:"Review people",query:{tab:"people"}}}]:[]]}async function mJe(e){if(!e.studio.isAvailable())return;let t=uJe(e),i=aJe(e),n=cJe(e),r=JYe(e),o=zJi([t,i,n,r]),s=t.registration,a=i.registration,c=n.registration,l=r.registration;return e.studio.register({id:"admin:administration",label:"Administration",rendererName:FC,priority:10,permission:"admin",section:"brain",urlQuery:!0,aliases:[{id:"admin:people",query:{tab:"people"}},{id:"admin:invitations",query:{tab:"invitations"}},{id:"admin:peers",query:{tab:"people"}},{id:"admin:audit",query:{tab:"audit"}}],entityTypes:[],accessHandler:(d)=>s.accessHandler(d),dataProvider:async(d,p,m)=>{let h=MJi.parse(p??{}),f,g=Bxe("People"),y=Bxe("Invitations"),b=Bxe("Audit");if(h.tab==="people"){let[v,w]=await Promise.all([AR(s,d,{...h.selected?{selected:h.selected}:{}},m),AR(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),B=dxe(w.view.blocks);g=[...lJe(dJe(v.view.blocks,"People"),{type:"notice",id:"people-peer-note",tone:"neutral",title:"External brain relationships",text:"A peer link records how a locally administered person relates to another brain. It does not grant or change local access."},B.people).blocks]}else if(h.tab==="invitations"){let[v,w]=await Promise.all([AR(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...Zr({offset:h.offset,limit:h.limit})},m),AR(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),B=dxe(w.view.blocks),T=oJe(v.view.blocks,B.invitations);f=v.view.primaryAction,y=[...T.blocks]}else{let v=await AR(l,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...Zr({offset:h.offset,limit:h.limit})},m);b=dJe(v.view.blocks,"Audit")}return{view:{kicker:"Access administration",title:"Administration",description:"Manage people, invitations, and access to this brain. Use Account for your own profile, sign-in security, and personal settings.",...f?{primaryAction:f}:{},blocks:[{type:"tabs",id:"administration-tabs",label:"Administration sections",defaultTab:h.tab,queryKey:"tab",tabs:[{id:"people",label:"People",blocks:g},{id:"invitations",label:"Invitations",blocks:y},{id:"audit",label:"Access activity",blocks:b}]}]}}},actionHandler:async(d,p,m)=>{let h=OJi(d);if(!h)throw new bi("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new bi("not_found",{publicMessage:`Unknown Administration action: ${h}`});return jJi(f,d,p,m)},badgeProvider:async()=>{let d=pJe(await Sm(e).listAdminUsers());return d.suspended+d.pendingInvitations},attentionProvider:async()=>UJi(pJe(await Sm(e).listAdminUsers()))})}var qJi=259200000,$Ji=u.strictObject({id:u.string(),displayName:u.string(),state:u.string(),reason:u.enum(["expiring","delivery-failed"]),expiresAt:u.number().optional()}),HJi=u.strictObject({invitations:u.array($Ji),expiringCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()}),hJe=oo({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:HJi,digest:({data:e})=>({items:[{label:"Expiring soon",value:String(e.expiringCount),...e.expiringCount>0?{tone:"warn"}:{}},{label:"Delivery failures",value:String(e.failureCount),...e.failureCount>0?{tone:"warn"}:{}}],attention:e.invitations.length}),view:({data:e})=>({blocks:[{type:"stats",items:[{label:"Expiring soon",value:e.expiringCount,tone:e.expiringCount>0?"warn":"good"},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"good"}]},{type:"list",id:"invitation-attention",empty:"No invitation setup links need attention.",items:e.invitations.map((t)=>({id:t.id,title:t.displayName,description:t.reason==="delivery-failed"?"Invitation delivery failed. Resend or cancel it.":"The single-use setup link expires soon.",metadata:[t.state,...t.expiresAt!==void 0?[`Expires ${Zh(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function GJi(e,t){let i=e.flatMap((n)=>{let r=n.invitation;if(!r)return[];if(r.state==="failed")return[{id:r.id,displayName:n.displayName,state:r.state,reason:"delivery-failed",...r.expiresAt!==void 0?{expiresAt:r.expiresAt}:{}}];if(!["pending","sending","sent"].includes(r.state)||r.expiresAt===void 0||r.expiresAt<=t||r.expiresAt>t+qJi)return[];return[{id:r.id,displayName:n.displayName,state:r.state,reason:"expiring",expiresAt:r.expiresAt}]});return i.sort((n,r)=>(n.expiresAt??Number.MAX_SAFE_INTEGER)-(r.expiresAt??Number.MAX_SAFE_INTEGER)||n.displayName.localeCompare(r.displayName)),{invitations:i,expiringCount:i.filter((n)=>n.reason==="expiring").length,failureCount:i.filter((n)=>n.reason==="delivery-failed").length}}async function fJe(e,t){t.throwIfAborted();let i=await Sm(e).listAdminUsers();return t.throwIfAborted(),GJi(i,Date.now())}var WJi=u.strictObject({}),ZJi=zt({id:"admin",config:WJi},{subscriptions:(e)=>{let t=ft(e);return t.registered(async()=>{await mJe(t)}),[]},dashboardWidgets:(e)=>{let t=ft(e);return[hJe.bind(e,({signal:i})=>fJe(t,i))]}}),Cxe=ZJi;var Jn="agent",xJe="agent-network",gJe="agent-proximity",Wxe="agent-discovery:entities",yJe="agent-discovery:proximity-map",Zxe="proximity-map",Vxe="agent-list",Kxe="agent-detail",$c="skill",bJe=30,EJe=120;var TZ="skill-derivation",vJe="skill-derivation",Yxe="skill:skill-derivation",AJe="skills";var VJi=u.string().trim().min(1).max(EJe),Jxe=u.array(VJi).max(bJe),Sw=u.object({name:u.string(),description:u.string(),tags:Jxe,examples:u.array(u.string())}),TR=Sw,kw=A0.extend({entityType:u.literal($c),metadata:TR});var PZ=u.object({name:u.string(),description:u.string(),tags:Jxe}),oE=u.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),KJi=Mk,w0=u.object({name:u.string(),kind:KJi,organization:u.string().optional(),brainName:u.string().describe("Name of the brain instance"),shownAs:u.string().min(1).optional().describe("The name this brain shows the agent under, in place of its own name"),url:u.string().url().describe("Brain endpoint URL"),repoDid:u.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:u.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:u.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:u.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:u.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:u.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:u.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:u.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:oE,discoveredAt:u.string().datetime().meta({description:"When this agent was first discovered",studioWidget:"provenance"}),introducedBy:u.array(u.string()).optional().meta({description:"Agent ids of the peers whose directories reported this agent",studioWidget:"provenance"}),hops:u.number().int().min(2).optional().meta({description:"Discovery order: 2 = sighted through a first-order peer",studioWidget:"provenance"})}),PR=u.object({name:u.string(),shownAs:u.string().min(1).optional(),url:u.string().url(),status:oE,discoveredAt:u.string().datetime().optional(),slug:u.string(),repoDid:u.string().optional(),brainDid:u.string().optional(),cardUri:u.string().optional(),cardCid:u.string().optional(),cardLastError:u.string().optional(),cardFailureCount:u.number().int().nonnegative().optional(),cardUnavailableAt:u.string().datetime().optional(),cardStaleAfter:u.string().datetime().optional()}),Lr=A0.extend({entityType:u.literal(Jn),metadata:PR}),YJi=ji.extend({entityType:u.literal(Jn),metadata:PR}),RR=YJi.extend({frontmatter:w0,about:u.string(),skills:u.array(PZ),notes:u.string()}),JJi=RR.extend({url:u.string().optional(),typeLabel:u.string().optional()}),QJi=RR.extend({url:u.string(),typeLabel:u.string()});var XJi=u.record(u.string(),u.unknown());function eQi(e){try{return Nr(e,XJi).content}catch{return e}}function Qxe(e){return{name:e.name,...e.shownAs&&{shownAs:e.shownAs},url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:LC(e.url),...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter}}}function wJe(e){return Ys(Jn,e,w0)}function FR(e){return{content:e,metadata:Qxe(wJe(e))}}function jC(e){let t={name:e.name,kind:e.kind,...e.organization&&{organization:e.organization},brainName:e.brainName,...e.shownAs&&{shownAs:e.shownAs},url:e.url,...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter},status:oE.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},i=V0e({about:e.about,skills:e.skills,notes:e.notes});return pr(i,t)}function Dm(e,t={}){return jC({...e.frontmatter,...e.body,...t})}function MR(e){return vR(eQi(e))}function Js(e){return{frontmatter:wJe(e.content),body:MR(e.content)}}function Xxe(e){return pr("",e)}function iQi(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function SJe(e,t,i={}){let n=i.minCount??1,r=i.topN??12,o=new Map,s=(a)=>{for(let c of gc(a))o.set(c,(o.get(c)??0)+1)};for(let a of e)s(a.metadata.tags);for(let a of t){let c=MR(a.content);s(c.skills.flatMap((l)=>l.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=n).sort(iQi).slice(0,r)}function kJe(e){if(e.length===0)return"";return["Current agent-directory tag vocabulary (reuse existing tags where they fit; propose new only when nothing does):",...e.map(({tag:t,count:i})=>`- ${t} (${i})`)].join(`
|
|
1039
1039
|
`)}function zC(e,t={}){let i=e.anchor?.name??e.brainName,n=e.anchor?.category??"person",r=[];if(e.anchor?.description)r.push(e.anchor.description);if(e.description)r.push(e.description);let o=t.status??"discovered",s=new Date().toISOString();return{content:jC({name:i,kind:n,...e.anchor?.organization&&{organization:e.anchor.organization},brainName:e.brainName,url:e.url,status:o,discoveredAt:s,...t.provenance&&{introducedBy:t.provenance.introducedBy,hops:t.provenance.hops},about:r.join(`
|
|
1040
1040
|
|
|
1041
1041
|
`),skills:e.skills.map((c)=>({name:c.name,description:c.description,tags:gc(c.tags)})),notes:""}),metadata:{name:i,url:e.url,status:o,discoveredAt:s,slug:LC(e.url)},anchorName:i}}function bg(e){let t=e.trim();if(t.startsWith("http://")||t.startsWith("https://"))try{return new URL(t).hostname}catch{return t}let i=t.match(/https?:\/\/[^\s]+?(?=[.,;:!?)]*(?:\s|$))/);if(i)try{return new URL(i[0]).hostname}catch{return i[0]}if(/^[^\s]+\.[^\s]+$/.test(t))return t;return""}var nQi=u.object({prompt:u.string().optional(),url:u.string().optional(),content:u.string().optional(),skipAi:u.boolean().optional(),status:u.enum(["discovered","approved","archived"]).optional()});function BJe(e){return{input:nQi,generate:async({input:t})=>{let i=bg(t.url??t.prompt??"");if(!i)return{success:!1,error:"No URL or domain provided. Use: system_create agent with a domain like yeehaa.io"};let n=await $h(i,{fetch:e??globalThis.fetch});if(!n.ok)return{success:!1,error:gw(n.reason)?n.error:`Could not fetch Agent Card from ${i}. Make sure the agent is running and accessible.`};let{content:r,metadata:o}=zC(n.card,{...t.status!==void 0?{status:t.status}:{}});return{success:!0,id:i,content:r,metadata:o}}}}var rQi=100,CJe=50000,tge="connect",DJe="dismiss";function ege(e){let t=Lr.parse(e),i=oQi(t);return i?{entity:t,parsed:i}:void 0}function IJe(e){return{sourceId:"agent-sightings",displayName:"Agent sightings",list:async({records:i})=>(await i.list()).flatMap((n)=>{let r=ege(n);return r?[r]:[]}).sort((n,r)=>r.parsed.frontmatter.discoveredAt.localeCompare(n.parsed.frontmatter.discoveredAt)).slice(0,rQi).map(({entity:n,parsed:r})=>sQi(n,r)),resolveDetail:async(i,{records:n,signal:r})=>{r.throwIfAborted();let o=ege(await n.get(i));if(r.throwIfAborted(),!o)throw Error("Agent sighting not found");let s=cQi(o.entity,o.parsed);return{kind:"plain",text:s.slice(0,CJe),truncated:s.length>CJe}},act:async(i,n,{records:r,edits:o})=>{if(n!==tge&&n!==DJe)throw Error("Invalid agent sighting Inbox action");let s=await r.get(i),a=s?ege(s):void 0;if(!s||!a)throw Error("Agent sighting not found");let c=n===tge?"approved":"archived";if(c==="approved")await e.approve(s.id);else await e.revoke(s.id);await o.update(s,{content:Dm(a.parsed,{status:c,...c==="approved"?{introducedBy:void 0,hops:void 0}:{}}),metadata:{...s.metadata,status:c}})}}}function oQi(e){let t=Js(e);return t.frontmatter.status==="discovered"&&(t.frontmatter.introducedBy?.length??0)>0?t:void 0}function sQi(e,t){let i=S0(t.frontmatter.name),n=S0(e.id),r=_Je(i===n?i:`${i} \xB7 ${n}`,160);return{id:e.id,title:r,summary:aQi(t),receivedAt:t.frontmatter.discoveredAt,urgency:"normal",entityRef:{entityType:Jn,entityId:e.id},actions:[{id:tge,label:"Connect",confirm:!0},{id:DJe,label:"Dismiss",confirm:!0}]}}function aQi(e){let t=e.frontmatter.introducedBy??[],i=`Introduced by ${ige(t.map(S0))}.`,n=S0(e.body.about),r=e.body.skills.map((s)=>S0(s.name)).filter(Boolean).slice(0,4),o=r.length>0?` Declared skills: ${ige(r)}.`:"";return _Je(`${i}${n?` ${n}`:""}${o}`,1000)}function cQi(e,t){let i=[`Agent: ${S0(t.frontmatter.name)}`,`Domain: ${S0(e.id)}`,`Introduced by: ${ige((t.frontmatter.introducedBy??[]).map(S0))}`],n=S0(t.body.about);if(n)i.push(`About: ${n}`);if(t.body.skills.length>0)i.push("Skills:",...t.body.skills.map((r)=>{let o=S0(r.description);return`- ${S0(r.name)}${o?`: ${o}`:""}`}));return i.join(`
|
|
@@ -5508,7 +5508,7 @@ ${r}
|
|
|
5508
5508
|
`),n=e.body??"",r=n?`${n}
|
|
5509
5509
|
|
|
5510
5510
|
${i}`:i;if(!e.formatted_body)return{...e,body:r};let o=t.map((s)=>`<p>${MCr(s)}</p>`).join("");return{...e,body:r,formatted_body:`${e.formatted_body}${o}`}}collectLinkOnlyAttachmentLines(e){let t=[];for(let i of e){if(Boolean(i.data)||typeof i.fetchData==="function")continue;if(!i.url)continue;let r=i.name??i.type;t.push(`${r}: ${i.url}`)}return t}async collectUploads(e,t){let i=[],n=this.extractFilesFromMessage(e);for(let r of n)i.push({data:this.normalizeUploadData(r.data),fileName:r.filename,info:{mimetype:Dn(r.mimeType),size:this.binarySize(r.data)},msgtype:this.messageTypeForMimeType(Dn(r.mimeType))});for(let r of t){let o=await this.readAttachmentData(r);if(!o)continue;let s=Dn(r.name)??this.defaultAttachmentName(r);i.push({data:this.normalizeUploadData(o),fileName:s,info:{h:r.height,mimetype:Dn(r.mimeType),size:r.size??this.binarySize(o),w:r.width},msgtype:this.messageTypeForAttachment(r),type:r.type})}return i}extractFilesFromMessage(e){if(typeof e!=="object"||e===null)return[];if(!("files"in e)||!Array.isArray(e.files))return[];return e.files.flatMap((t)=>{let i=this.normalizeFileUpload(t);return i?[i]:[]})}normalizeFileUpload(e){if(!Ny(e))return null;let t=Dn(typeof e.filename==="string"?e.filename:void 0);if(!t)return null;let i=this.normalizeFileUploadData(e.data);if(!i)return this.logger.warn("Skipping invalid Matrix file upload",{filename:t}),null;return{filename:t,data:i,mimeType:typeof e.mimeType==="string"?Dn(e.mimeType):void 0}}normalizeFileUploadData(e){if(Buffer.isBuffer(e)||e instanceof Blob||e instanceof ArrayBuffer)return e;if(e instanceof Uint8Array)return Buffer.from(e);return null}extractAttachmentsFromMessage(e){if(typeof e!=="object"||e===null)return[];if(!("attachments"in e)||!Array.isArray(e.attachments))return[];return e.attachments.filter((t)=>Ny(t))}async readAttachmentData(e){if(typeof e.fetchData==="function")return e.fetchData();return e.data??null}normalizeUploadData(e){if(e instanceof Blob)return e;if(this.isNodeBuffer(e))return new Blob([new Uint8Array(e)]);return new Blob([e])}binarySize(e){if(e instanceof ArrayBuffer)return e.byteLength;if(this.isNodeBuffer(e))return e.length;return e.size}isNodeBuffer(e){return typeof Buffer<"u"&&Buffer.isBuffer(e)}messageTypeForAttachment(e){switch(e.type){case"image":return ll.Image;case"video":return ll.Video;case"audio":return ll.Audio;default:return this.messageTypeForMimeType(Dn(e.mimeType))}}messageTypeForMimeType(e){if(!e)return ll.File;if(e.startsWith("image/"))return ll.Image;if(e.startsWith("video/"))return ll.Video;if(e.startsWith("audio/"))return ll.Audio;return ll.File}defaultAttachmentName(e){switch(e.type){case"image":return"image";case"video":return"video";case"audio":return"audio";default:return"file"}}mustGetEventByID(e,t){let n=this.requireRoom(e).findEventById(t);if(!n)throw Error(`Sent Matrix event not found in local timeline: ${t}`);return n}resolveSentEvent(e,t,i){try{return this.mustGetEventByID(e,t)}catch(n){return this.logger.warn("Sent Matrix event not found in local timeline; using synthetic fallback",{error:n,eventId:t,roomId:e}),new mh({content:i.content,event_id:t,origin_server_ts:Date.now(),room_id:i.roomID,sender:i.sender??"",type:wo.RoomMessage})}}isUsableDirectRoom(e){let t=this.requireClient().getRoom(e);if(!t)return!1;let i=t.getMyMembership();return i==="join"||i==="invite"}makeUser(e,t){let i=t?this.client?.getRoom(t)??void 0:void 0,n=this.readRoomMember(i,e),r=ogi(e),o=Roe(n?.rawDisplayName)??Roe(n?.name)??r,s=e===this.userID?!0:"unknown";return{userId:e,userName:r,fullName:o,isBot:s,isMe:e===this.userID}}rawEmoji(e){return typeof e==="string"?e:e.toString()}myReactionKey(e,t,i){return`${e}::${t}::${i}`}get persistenceSessionPrefix(){return`${this.persistenceConfig.keyPrefix}:session:${encodeURIComponent(this.baseURL)}`}get persistenceStorePrefix(){return`${this.persistenceConfig.keyPrefix}:store`}get sessionBasePrefix(){return this.persistenceSessionPrefix}getSessionStorageKey(e){return`${this.sessionBasePrefix}:user:${encodeURIComponent(e)}`}getSessionUsernameTemporaryKey(){if(this.auth.type!=="password")return null;return`${this.sessionBasePrefix}:username:${encodeURIComponent(this.auth.username)}`}async loadPersistedSession(){if(!this.stateAdapter)return null;if(this.auth.userID){let t=await this.stateAdapter.get(this.getSessionStorageKey(this.auth.userID)),i=this.decodeStoredSession(t);if(this.isValidStoredSession(i))return i}let e=this.getSessionUsernameTemporaryKey();if(e){let t=await this.stateAdapter.get(e),i=this.decodeStoredSession(t);if(this.isValidStoredSession(i))return i}return null}async persistSession(e,t){if(!this.stateAdapter)return;let i=new Date().toISOString(),n={accessToken:e.accessToken,authType:this.auth.type,baseURL:this.baseURL,createdAt:t??i,deviceID:e.deviceID,e2eeEnabled:this.e2eeEnabled,recoveryKeyPresent:Boolean(this.e2eeConfig?.storagePassword),updatedAt:i,userID:e.userID,username:this.auth.type==="password"?this.auth.username:void 0},r=this.encodeStoredSession(n),o=this.getSessionStorageKey(e.userID);await this.stateAdapter.set(o,r,this.persistenceConfig.session.ttlMs);let s=this.getSessionUsernameTemporaryKey();if(s&&s!==o)await this.stateAdapter.set(s,r,this.persistenceConfig.session.ttlMs)}encodeStoredSession(e){if(!this.persistenceConfig.session.encrypt)return e;let t=this.persistenceConfig.session.encrypt(JSON.stringify(e)),{accessToken:i,...n}=e;return{...n,encryptedPayload:t}}decodeStoredSession(e){if(!e||!e.encryptedPayload)return e;if(!this.persistenceConfig.session.decrypt)return null;try{let t=this.persistenceConfig.session.decrypt(e.encryptedPayload),i=JSON.parse(t);if(!this.isValidStoredSession(i))return null;return i}catch(t){return this.logger.warn("Failed to decrypt persisted Matrix session",{error:t}),null}}isValidStoredSession(e){if(!Ny(e))return!1;return typeof e.accessToken==="string"&&typeof e.userID==="string"&&typeof e.baseURL==="string"&&e.baseURL===this.baseURL}getSecretStorageKeyFromRecoveryKey(e){if(!this.recoveryKey)return null;let i=Object.keys(e.keys??{})[0];if(!i)return null;try{let n=cgi(this.recoveryKey);return[i,n]}catch{return this.logger.warn("Invalid recovery key format, unable to decode"),null}}validateConfig(e){if(!e.baseURL?.trim())throw Error("baseURL is required.");if(e.persistence?.session?.ttlMs!==void 0&&e.persistence.session.ttlMs<=0)throw Error("persistence.session.ttlMs must be a positive number.");if(e.persistence?.sync?.persistIntervalMs!==void 0&&e.persistence.sync.persistIntervalMs<=0)throw Error("persistence.sync.persistIntervalMs must be a positive number.");if(e.persistence?.sync?.snapshotTtlMs!==void 0&&e.persistence.sync.snapshotTtlMs<=0)throw Error("persistence.sync.snapshotTtlMs must be a positive number.");if(e.persistence?.session?.encrypt&&!e.persistence?.session?.decrypt||!e.persistence?.session?.encrypt&&e.persistence?.session?.decrypt)throw Error("persistence.session.encrypt and persistence.session.decrypt must be provided together.")}async resolveDeviceID(...e){let t=Dn(this.deviceID);if(t)return this.deviceID=t,t;for(let r of e){let o=Dn(r);if(o)return this.deviceID=o,await this.persistDeviceID(o),o}let i=await this.loadPersistedDeviceID();if(i)return this.deviceID=i,i;let n=FCr();return this.deviceID=n,await this.persistDeviceID(n),n}getDeviceIDStorageKey(e){let t=`${this.persistenceConfig.keyPrefix}:device:${encodeURIComponent(this.baseURL)}`,i=e??this.auth.userID??(this.auth.type==="password"?`username:${this.auth.username}`:"default");return`${t}:${encodeURIComponent(i)}`}async loadPersistedDeviceID(){if(!this.stateAdapter)return null;let e=new Set([this.getDeviceIDStorageKey(),this.getDeviceIDStorageKey(this.auth.userID)]);for(let t of e){if(!t)continue;let i=await this.stateAdapter.get(t),n=Dn(i);if(n)return n}return null}async persistDeviceID(e,t){if(!this.stateAdapter)return;await this.stateAdapter.set(this.getDeviceIDStorageKey(t),e)}async persistDeviceIDForResolvedUser(e,t){let i=Dn(t)??this.deviceID;if(!i)return;this.deviceID=i,await this.persistDeviceID(i,e);let n=this.getDeviceIDStorageKey(),r=this.getDeviceIDStorageKey(e);if(this.stateAdapter&&n!==r)await this.stateAdapter.delete(n)}configureMatrixSDKLogging(){if(ngi)return;let e=this.matrixSDKLogLevel;if(!e)return;let t=lgi[e];if(t===void 0)return;let i=Reflect.get(Vt,"setLevel");if(typeof i==="function")i.call(Vt,t,!1);ngi=!0}};function ugi(e){if(e){let s=Dn(e.deviceID);return new rgi({...e,deviceID:s})}let t=process.env.MATRIX_BASE_URL;if(!t)throw Error("baseURL is required. Set MATRIX_BASE_URL.");let i=process.env.MATRIX_RECOVERY_KEY,n=RCr(process.env.MATRIX_INVITE_AUTOJOIN_ALLOWLIST),r=PCr(process.env.MATRIX_INVITE_AUTOJOIN,n.length>0),o=TCr();return new rgi({baseURL:t,auth:o,userName:process.env.MATRIX_BOT_USERNAME??"bot",deviceID:Dn(process.env.MATRIX_DEVICE_ID),commandPrefix:process.env.MATRIX_COMMAND_PREFIX,recoveryKey:i,inviteAutoJoin:r?{inviterAllowlist:n}:void 0,matrixSDKLogLevel:jCr(process.env.MATRIX_SDK_LOG_LEVEL)??"error"})}function _Cr(e){return{keyPrefix:Dn(e?.keyPrefix)??CCr,session:{decrypt:e?.session?.decrypt,encrypt:e?.session?.encrypt,ttlMs:e?.session?.ttlMs},sync:{persistIntervalMs:e?.sync?.persistIntervalMs??DCr,snapshotTtlMs:e?.sync?.snapshotTtlMs}}}function TCr(){let e=process.env.MATRIX_USERNAME,t=process.env.MATRIX_PASSWORD;if(e&&t)return{type:"password",username:e,password:t,userID:process.env.MATRIX_USER_ID};let i=process.env.MATRIX_ACCESS_TOKEN,n=process.env.MATRIX_USER_ID;if(!i)throw Error("Set MATRIX_USERNAME+MATRIX_PASSWORD for password auth, or MATRIX_ACCESS_TOKEN for access token auth.");return{type:"accessToken",accessToken:i,userID:n}}function PCr(e,t=!1){if(!e)return t;let i=e.trim().toLowerCase();return i==="1"||i==="true"||i==="yes"||i==="on"}function RCr(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter((t)=>t.length>0)}function FCr(e=8){let i=ACr(e),n="chatsdk_";for(let r=0;r<e;r+=1)n+="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[i[r]%36];return n}function Dn(e){if(!e)return;let t=e.trim();return t.length>0?t:void 0}function Roe(e){return typeof e==="string"?Dn(e):void 0}function ogi(e){return e.startsWith("@")?e.slice(1).split(":")[0]??e:e}function k7e(e){return e.replace(/([\\`*_{}\[\]()#+\-.!|>])/gu,"\\$1")}function sgi(e){return e.replace(/([\\\]])/gu,"\\$1")}function MCr(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function OCr(e){if(!e||e.length===0)return[];return e.map((t)=>Dn(t)).filter((t)=>Boolean(t))}function NCr(){return typeof globalThis.indexedDB<"u"&&globalThis.indexedDB!==null}function LCr(e){return e in lgi}function jCr(e){if(!e)return;let t=e.trim().toLowerCase();return LCr(t)?t:void 0}function agi(e,t=1e4,i=5000){if(e.size<=t)return;let n=e.size-i,r=0;for(let o of e.keys()){if(r>=n)break;e.delete(o),r++}}function Ny(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var zCr=class{subscriptions=new Set;locks=new Map;cache=new Map;queues=new Map;connected=!1;connectPromise=null;async connect(){if(this.connected)return;if(!this.connectPromise)this.connectPromise=Promise.resolve().then(()=>{this.connected=!0});await this.connectPromise}async disconnect(){this.connected=!1,this.connectPromise=null,this.subscriptions.clear(),this.locks.clear(),this.queues.clear()}async subscribe(e){this.ensureConnected(),this.subscriptions.add(e)}async unsubscribe(e){this.ensureConnected(),this.subscriptions.delete(e)}async isSubscribed(e){return this.ensureConnected(),this.subscriptions.has(e)}async acquireLock(e,t){this.ensureConnected(),this.cleanExpiredLocks();let i=this.locks.get(e);if(i&&i.expiresAt>Date.now())return null;let n={threadId:e,token:UCr(),expiresAt:Date.now()+t};return this.locks.set(e,n),n}async forceReleaseLock(e){this.ensureConnected(),this.locks.delete(e)}async releaseLock(e){this.ensureConnected();let t=this.locks.get(e.threadId);if(t&&t.token===e.token)this.locks.delete(e.threadId)}async extendLock(e,t){this.ensureConnected();let i=this.locks.get(e.threadId);if(!i||i.token!==e.token)return!1;if(i.expiresAt<Date.now())return this.locks.delete(e.threadId),!1;return i.expiresAt=Date.now()+t,!0}async get(e){this.ensureConnected();let t=this.cache.get(e);if(!t)return null;if(t.expiresAt!==null&&t.expiresAt<=Date.now())return this.cache.delete(e),null;return t.value}async set(e,t,i){this.ensureConnected(),this.cache.set(e,{value:t,expiresAt:i?Date.now()+i:null})}async setIfNotExists(e,t,i){this.ensureConnected();let n=this.cache.get(e);if(n)if(n.expiresAt!==null&&n.expiresAt<=Date.now())this.cache.delete(e);else return!1;return this.cache.set(e,{value:t,expiresAt:i?Date.now()+i:null}),!0}async delete(e){this.ensureConnected(),this.cache.delete(e)}async appendToList(e,t,i){this.ensureConnected();let n=this.cache.get(e),r;if(n&&n.expiresAt!==null&&n.expiresAt<=Date.now())r=[];else if(n&&Array.isArray(n.value))r=n.value;else r=[];if(r.push(t),i?.maxLength&&r.length>i.maxLength)r=r.slice(r.length-i.maxLength);this.cache.set(e,{value:r,expiresAt:i?.ttlMs?Date.now()+i.ttlMs:null})}async enqueue(e,t,i){this.ensureConnected();let n=this.queues.get(e);if(!n)n=[],this.queues.set(e,n);if(n.push(t),n.length>i)n.splice(0,n.length-i);return n.length}async dequeue(e){this.ensureConnected();let t=this.queues.get(e);if(!t||t.length===0)return null;let i=t.shift();if(t.length===0)this.queues.delete(e);return i??null}async queueDepth(e){return this.ensureConnected(),this.queues.get(e)?.length??0}async getList(e){this.ensureConnected();let t=this.cache.get(e);if(!t)return[];if(t.expiresAt!==null&&t.expiresAt<=Date.now())return this.cache.delete(e),[];if(Array.isArray(t.value))return t.value;return[]}ensureConnected(){if(!this.connected)throw Error("MemoryStateAdapter is not connected. Call connect() first.")}cleanExpiredLocks(){let e=Date.now();for(let[t,i]of this.locks)if(i.expiresAt<=e)this.locks.delete(t)}_getSubscriptionCount(){return this.subscriptions.size}_getLockCount(){return this.cleanExpiredLocks(),this.locks.size}};function UCr(){return`mem_${Date.now()}_${Math.random().toString(36).substring(2,15)}`}function Foe(e){return new zCr}var qCr=u.object({subscribedAt:u.string().datetime(),routingMode:u.enum(["auto","mention-required"]).optional(),mentionRequiredNoticeSent:u.boolean().optional()});var $Cr="chat.discord.subscriptions",HCr="chat.slack.subscriptions",GCr="chat.matrix.subscriptions",WCr="chat.matrix.adapter-state",ZCr=u.object({value:u.unknown(),expiresAt:u.number().optional()}),VCr="matrix:";function KCr(e){switch(e){case"discord":return $Cr;case"slack":return HCr;case"matrix":return GCr}}function qU(e,t){return e.scoped({namespace:KCr(t),schema:qCr})}function pgi(e){return qU(e,"discord")}function mgi(e){return qU(e,"slack")}function hgi(e,t,i=Foe()){let n=new Map;for(let o of t)n.set(o,qU(e,o));let r=t.includes("matrix")?e.scoped({namespace:WCr,schema:ZCr}):void 0;return new fgi(i,n,r)}class fgi{memoryState;subscriptions;durable;constructor(e,t,i){this.memoryState=e,this.subscriptions=t,this.durable=i}durableFor(e){return e.startsWith(VCr)?this.durable:void 0}connect(){return this.memoryState.connect()}disconnect(){return this.memoryState.disconnect()}async subscribe(e){let t=this.getSubscriptionStore(e);if(!t)return this.memoryState.subscribe(e);await t.set(e,{subscribedAt:new Date().toISOString()})}async unsubscribe(e){let t=this.getSubscriptionStore(e);if(!t)return this.memoryState.unsubscribe(e);await t.delete(e)}isSubscribed(e){let t=this.getSubscriptionStore(e);return t?t.has(e):this.memoryState.isSubscribed(e)}acquireLock(e,t){return this.memoryState.acquireLock(e,t)}appendToList(e,t,i){return this.memoryState.appendToList(e,t,i)}async delete(e){let t=this.durableFor(e);if(!t)return this.memoryState.delete(e);await t.delete(e)}dequeue(e){return this.memoryState.dequeue(e)}enqueue(e,t,i){return this.memoryState.enqueue(e,t,i)}extendLock(e,t){return this.memoryState.extendLock(e,t)}forceReleaseLock(e){return this.memoryState.forceReleaseLock(e)}async get(e){let t=this.durableFor(e);if(!t)return this.memoryState.get(e);let i=await t.get(e);if(!i)return null;if(i.expiresAt!==void 0&&i.expiresAt<=Date.now())return await t.delete(e),null;return i.value}getList(e){return this.memoryState.getList(e)}queueDepth(e){return this.memoryState.queueDepth(e)}releaseLock(e){return this.memoryState.releaseLock(e)}set(e,t,i){let n=this.durableFor(e);if(!n)return this.memoryState.set(e,t,i);return n.set(e,dgi(t,i))}async setIfNotExists(e,t,i){let n=this.durableFor(e);if(!n)return this.memoryState.setIfNotExists(e,t,i);return await this.get(e),n.setIfNotExists(e,dgi(t,i))}getSubscriptionStore(e){let t=e.split(":")[0];if(t!=="discord"&&t!=="slack"&&t!=="matrix")return;return this.subscriptions.get(t)}}function dgi(e,t){return t===void 0?{value:e}:{value:e,expiresAt:Date.now()+t}}function xgi(e,t){if(!e)throw Error(t);return e}function ggi(e){let{discord:t,slack:i,matrix:n}=e,r=t?Fri({botToken:t.botToken,publicKey:t.publicKey,applicationId:t.applicationId,mentionRoleIds:t.mentionRoleIds}):void 0;if(r)e.gatewayLoop.setAdapter(r);let o=r,a=i?hpi(i.mode==="socket"?{botToken:i.botToken,mode:"socket",appToken:xgi(i.appToken,"Slack app token is required in socket mode")}:{botToken:i.botToken,signingSecret:xgi(i.signingSecret,"Slack signing secret is required in webhook mode")}):void 0;if(a&&i?.mode==="socket")e.slackSocketLoop.setAdapter(a);let l=n?ugi({baseURL:n.baseUrl,auth:{type:"password",username:n.userId.slice(1).split(":")[0]??"",get password(){return e.matrixCredentials?.password??n.password??""},userID:n.userId},userName:e.userName,inviteAutoJoin:{accept:e.acceptMatrixInvite??((h)=>Promise.resolve(h.isDirect&&n.allowDMs))},matrixSDKLogLevel:"warn"}):void 0,d={...o?{discord:o}:{},...a?{slack:a}:{},...l?{matrix:l}:{}},p=[...t?["discord"]:[],...i?["slack"]:[],...n?["matrix"]:[]],m=p.length>0?hgi(e.runtimeState,p):Foe();return new uwt({userName:e.userName,adapters:d,...p.length>0?{concurrency:{strategy:"queue",maxQueueSize:5,onQueueFull:"drop-oldest"}}:{},state:m})}function Mf(e){let t=e.split(":");if(t[0]!=="discord")return{};return{...t[1]?{guildId:t[1]}:{},...t[2]?{channelId:t[2]}:{},...t[3]?{threadId:t[3]}:{}}}function Moe(e){return e.channelId}function Ooe(e,t){let i=Mf(t.id);return i.channelId?`${e}:${i.channelId}`:t.channelId}function YCr(e){let t=e.raw;if(!ga(t))return;let i=t.channel_id;return typeof i==="string"?i:void 0}function bgi(e,t){if(e.isDM)return!1;let i=Mf(e.id);if(!i.threadId)return!1;let n=YCr(t);return n!==void 0&&n!==i.threadId}function Egi(e){let[t,i]=e.split(":");if(!i)return;if(t==="slack")return i;if(t==="matrix")return decodeURIComponent(i);return}function $U(e,t){if(t.allowedChannels.length===0||e.isDM)return!0;let i=Mf(e.id);return[e.id,e.channelId,i.channelId,i.threadId,Egi(e.id)].some((n)=>typeof n==="string"&&t.allowedChannels.includes(n))}function Q6(e){return e.isBot===!0||ygi(e.userId)}function HU(e,t,i){if(e.isDM&&!i.allowDMs)return!1;if(t.author.isMe)return!1;if(Q6(t.author)&&!t.isMention)return!1;return $U(e,i)}function Noe(e,t){if(!t)return!1;if(e.isDM&&!t.allowDMs)return!1;return $U(e,t)}function D_(e,t){return{channelId:Mf(e.id).channelId??Egi(e.id)??e.channelId,isBot:Q6(t.author)}}function vgi(e){return e.isDM?"DM":e.channelId}var JCr="I\u2019ll stop auto-replying now that more people joined. Mention me if you need me.";class C7e{deps;constructor(e){this.deps=e}async subscribeOwnedThread(e,t){if(!this.deps.isBotCreatedThread(e,t))return;await this.subscribeThread(e)}async subscribeThread(e){try{await e.subscribe(),await this.getSubscriptions(e)?.set(e.id,{subscribedAt:new Date().toISOString()})}catch(t){this.deps.logger.debug("Chat thread subscription failed",{error:t,threadId:e.id})}}async shouldRouteSubscribedMessage(e,t){let i=this.getSubscriptions(e);if(!i)return!1;if(e.isDM)return!0;let n=await i.get(e.id);if(!n)return!1;if(n.routingMode==="mention-required"){if(!t.isMention&&!n.mentionRequiredNoticeSent)await this.postMentionRequiredNotice(e,n);return Boolean(t.isMention)}if(!await this.shouldRequireMentionInSubscribedThread(e))return!0;let o={...n,routingMode:"mention-required"};if(!t.isMention&&!n.mentionRequiredNoticeSent)await this.postMentionRequiredNotice(e,o);else await i.set(e.id,o);return Boolean(t.isMention)}async postMentionRequiredNotice(e,t){await e.post(JCr),await this.getSubscriptions(e)?.set(e.id,{...t,routingMode:"mention-required",mentionRequiredNoticeSent:!0})}async shouldRequireMentionInSubscribedThread(e){try{return(await e.getParticipants()).filter((n)=>!Q6(n)&&!n.isMe).length>1}catch(t){return this.deps.logger.debug("Failed to inspect chat thread participants",{error:t,threadId:e.id}),!1}}getSubscriptions(e){return this.deps.getSubscriptions(this.deps.getPlatform(e))}}function X6(e,t){return`${e}-${t}`}function wgi(e,t){let i=Agi({message:e,skippedMessages:(t?.skipped??[]).map((n)=>({id:n.id,text:n.text,authorName:n.author.fullName||n.author.userName}))});return i.metadata?{message:i.message,metadata:{...i.metadata}}:{message:i.message}}function D7e(e,t,i,n,r,o){return{actor:_7e(e,{userId:n.author.userId,userName:n.author.userName,fullName:n.author.fullName,isBot:n.author.isBot},o),source:kgi(t,{messageId:n.id,channelName:i,...r?{metadata:r}:{}})}}function Sgi(e,t,i,n,r,o){let s=Mf(t.id);return{spaceId:Ooe(e,t),actor:_7e(e,{userId:r.author.userId,userName:r.author.userName,fullName:r.author.fullName,isBot:r.author.isBot},o),source:GU({messageId:r.id,channelId:n,channelName:i,...s.threadId?{threadId:s.threadId}:{},metadata:{...s.guildId?{guildId:s.guildId}:{}}})}}function I7e(e,t,i,n,r){return{actor:_7e(e,{userId:n.user.userId,userName:n.user.userName,fullName:n.user.fullName,isBot:n.user.isBot},r),source:kgi(t,{messageId:n.messageId,channelName:i,metadata:{actionId:n.actionId,...n.value?{actionValue:n.value}:{}}})}}function _7e(e,t,i){return Loe({identity:i?{kind:"user",userId:i.userId,...i.canonicalId?{canonicalId:i.canonicalId}:{}}:{kind:"external",externalActorId:jy(e,t.userId)},interfaceType:e,displayName:i?.displayName??(t.fullName||t.userName),username:t.userName,isBot:t.isBot})}function kgi(e,t){let i=Mf(e.id);return GU({messageId:t.messageId,channelId:e.id,channelName:t.channelName,...i.threadId?{threadId:i.threadId}:{},metadata:{...t.metadata??{},...i.guildId?{guildId:i.guildId}:{}}})}var Bgi="https://discord.com/api/v10";async function Cgi(e){let t=Mf(e.threadId),i=t.threadId??t.channelId;if(!i)return;let n=e.fetchFn??fetch;try{let r=await n(`${Bgi}/channels/${i}/messages/${e.messageId}`,{method:"PATCH",headers:{Authorization:`Bot ${e.botToken}`,"Content-Type":"application/json"},body:JSON.stringify({components:[]})});if(!r.ok)e.logger.debug("Failed to clear Discord message components",{messageId:e.messageId,channelId:i,status:r.status})}catch(r){e.logger.debug("Failed to clear Discord message components",{error:r,messageId:e.messageId,channelId:i})}}async function Dgi(e){let t=Mf(e.threadId),i=t.threadId??t.channelId;if(!i)return;let n=e.fetchFn??fetch;try{let r=await n(`${Bgi}/channels/${i}/messages/${e.messageId}/reactions/${encodeURIComponent(e.emoji)}/@me`,{method:"PUT",headers:{Authorization:`Bot ${e.botToken}`}});if(!r.ok)e.logger.debug("Failed to add Discord reaction",{messageId:e.messageId,channelId:i,status:r.status})}catch(r){e.logger.debug("Failed to add Discord reaction",{error:r,messageId:e.messageId,channelId:i})}}function _gi(e){return{type:"card",title:e.title,children:[...e.lines.map((t)=>({type:"text",content:t})),...e.actions.length>0?[{type:"actions",children:e.actions.map((t)=>({type:"button",id:jX,label:t.label,value:t.value}))}]:[]]}}async function Tgi(e,t){if(!e.app)throw Error("The chat app is not built");let i=await e.app.channel(t.channelId).post({card:_gi(t)}),n=e.discordBotToken;if(t.interfaceType==="discord"&&n)await Promise.all(t.reactions.map((r)=>Dgi({threadId:t.channelId,messageId:r.messageId,emoji:r.emoji,botToken:n,logger:e.logger,...e.fetchFn?{fetchFn:e.fetchFn}:{}})));return{messageId:i.id}}async function Pgi(e,t){if(!t.thread||!t.value)return;let i=await e({conversationId:X6(t.adapter.name,Moe(t.thread)),noticeMessageId:t.messageId,value:t.value,by:t.user.fullName||t.user.userName}),n=Igi.safeParse(i);if(!n.success)return;await t.adapter.editMessage(t.threadId,t.messageId,{card:_gi(n.data)})}class T7e{names=new Map;async nameOf(e){let t=vgi({...e,id:e.channelId});if(e.isDM||!e.channel)return t;let i=e.channel,n=this.names.get(e.channelId)??i.fetchMetadata().then((o)=>{let s=o.name?.trim();return s===""?void 0:s},()=>{return});this.names.set(e.channelId,n);let r=await n;if(!r)this.names.delete(e.channelId);return r??t}}function Rgi(e){return async(t)=>{if(!t.inviter)return!1;if(t.isDirect)return e.allowDMs;let[i,n]=QCr(t.inviter);if(i!==I_||!n)return!1;return(await e.peerTrust()?.getA2APeerTrust(n))?.grantedLevel==="trusted"}}function QCr(e){let t=e.indexOf(":");return t<0?[e.slice(1),void 0]:[e.slice(1,t),e.slice(t+1)]}async function WU(e,t,i,n,r){let o=await r?.resolveIdentityAccess({type:t,subject:i});if(o?.state==="resolved")return{permissionLevel:o.principal.permissionLevel,isAnchor:o.principal.isAnchor,principal:o.principal};if(o?.state==="denied")return{permissionLevel:"public",isAnchor:!1};return{permissionLevel:e.getUserLevel(t,i,n),isAnchor:e.isAnchor(t,i)}}var XCr=/https?:\/\/\S+/i,e4r=/[\s\S]+/;class P7e{deps;constructor(e){this.deps=e}registerHandlers(e){e.onDirectMessage(async(t,i,n,r)=>{await this.handleRoutedMessage(t,i,r)}),e.onNewMention(async(t,i,n)=>{let r=this.getPlatformConfig(t),o=this.getPlatform(t);if(o==="discord"&&this.deps.config.adapters.discord&&r&&HU(t,i,r)&&!t.isDM&&this.deps.config.adapters.discord.useThreads)await this.deps.subscriptionRouter.subscribeOwnedThread(t,i);else if((o==="slack"||o==="matrix")&&r&&HU(t,i,r)&&!t.isDM)await this.deps.subscriptionRouter.subscribeThread(t);await this.handleRoutedMessage(t,i,n)}),e.onSubscribedMessage(async(t,i,n)=>{if(!await this.deps.subscriptionRouter.shouldRouteSubscribedMessage(t,i))return;await this.handleRoutedMessage(t,i,n)}),e.onNewMessage(XCr,async(t,i)=>{await this.handlePassiveUrlCapture(t,i)}),e.onNewMessage(e4r,async(t,i,n)=>{let r=this.getPlatformConfig(t);if(r&&!r.requireMention)await this.handleRoutedMessage(t,i,n);await this.capturePassiveSpaceMessage(t,i).catch((o)=>this.deps.logger.error("Passive space capture failed",{error:o,channelId:t.channelId}))}),e.onAction([LX,Ake],async(t)=>{await this.handleApprovalAction(t)}),e.onAction(tL,async(t)=>{await this.handlePromptAction(t)}),e.onAction(async(t)=>{if(!t.actionId.startsWith(`${tL}:`))return;await this.handlePromptAction(t)}),e.onAction(jX,async(t)=>{let{context:i}=this.deps.host;if(!t.thread)return;if(!rA(this.deps.config,t.adapter.name))return;let n=this.getPlatformConfig(t.thread);if(!Noe(t.thread,n))return;await Pgi(async(r)=>{let o=await i.gather(joe,r);return o.status==="answered"?o.answers.find((s)=>s!==null):void 0},t)})}async handlePromptAction(e){let{context:t}=this.deps.host;if(!e.thread||!e.value)return;let i=e.adapter.name;if(!rA(this.deps.config,i))return;let n=e.thread;if(!Noe(n,this.getPlatformConfig(n)))return;let r=this.deps.promptActions.get(e.value);if(r?.threadId!==n.id){await n.post(MD("That suggested action is no longer available.","Action unavailable"));return}this.deps.promptActions.consume(e.value);let o=await WU(t.permissions,i,e.user.userId,D_(n,{author:{userId:e.user.userId,isMe:e.user.isMe,isBot:e.user.isBot}}),this.deps.identityAccess()),{permissionLevel:s,isAnchor:a}=o,c=X6(i,n.id),l=n.id,d=await this.deps.channelNames.nameOf(n);await this.runAgentTurn({thread:n,channelId:l,logLabel:"Error handling chat prompt action",body:async()=>{let p=this.deps.host.context,m=await this.deps.uploadCoordinator.selectPriorUploads({platform:i,conversationId:c,currentAttachments:[],canRestore:s==="admin"||s==="trusted"}),h=await p.agent.chat(r.prompt,c,{userPermissionLevel:s,isAnchor:a,interfaceType:i,channelId:l,channelName:d,...I7e(i,n,d,e,o.principal),...m.length>0?{attachments:m}:{}});await this.deps.responseCoordinator.renderAgentResponse({thread:n,channelId:l,conversationId:c,response:h,userPermissionLevel:s})}})}async handleApprovalAction(e){let{context:t}=this.deps.host;if(!e.thread||!e.value)return;let i=e.adapter.name;if(!rA(this.deps.config,i))return;let n=e.thread;if(!Noe(n,this.getPlatformConfig(n)))return;let r=X6(i,n.id);if(!(await this.deps.responseCoordinator.getPendingApprovalIds(r)).has(e.value)){await n.post(MD("That approval is no longer pending."));return}let s=await WU(t.permissions,i,e.user.userId,D_(n,{author:{userId:e.user.userId,isMe:e.user.isMe,isBot:e.user.isBot}}),this.deps.identityAccess());await this.deps.responseCoordinator.confirmApproval({thread:n,conversationId:r,approvalId:e.value,confirmed:e.actionId===LX,userPermissionLevel:s.permissionLevel,isAnchor:s.isAnchor,metadata:I7e(i,n,await this.deps.channelNames.nameOf(n),e,s.principal)})}async handleRoutedMessage(e,t,i){let n=this.getPlatform(e);if(!rA(this.deps.config,n))return;let r=this.getPlatformConfig(e);if(!r)return;if(!HU(e,t,r))return;await this.routeToAgent(n,e,t,i)}async runAgentTurn(e){this.deps.host.startProcessingInput(e.channelId);try{if(this.getPlatformConfig(e.thread)?.showTypingIndicator)await e.thread.startTyping().catch((t)=>this.deps.logger.debug("Typing indicator failed",{error:t,channelId:e.channelId}));await e.body()}catch(t){this.deps.logger.error(e.logLabel,{error:t,channelId:e.channelId}),await this.postTurnError(e.thread,e.channelId,t)}finally{this.deps.host.endProcessingInput()}}async postTurnError(e,t,i){let n=Tvt(i),r=gv(t,n);if(r!==void 0){await e.post(r);return}let o=typeof n==="string"?n:"Message failed.";for(let s of FD(t,o))await e.post(J1(t,s))}async routeToAgent(e,t,i,n){let r=this.deps.host.context;this.deps.threadRegistry.set(t);let o=X6(e,t.id),s=t.id,a=await this.deps.channelNames.nameOf(t),c=D_(t,i),l=await WU(r.permissions,e,i.author.userId,c,this.deps.identityAccess()),{permissionLevel:d,isAnchor:p}=l,m=await this.deps.chatInputBuilder.build(e,t,i,d),h=[...m.attachments];if(await this.deps.uploadCoordinator.attachPriorUploads(e,o,m,d),await this.postUploadNotices(t,m.notices),!m.message&&m.attachments.length===0)return;this.deps.uploadCoordinator.remember(e,o,h),await this.runAgentTurn({thread:t,channelId:s,logLabel:"Error handling chat message",body:async()=>{let f=this.deps.host.context,g=await this.deps.responseCoordinator.getPendingApprovalIds(o);if(g.size>0){if(await this.deps.responseCoordinator.handleConfirmationResponse({message:m.message,conversationId:o,thread:t,approvalIds:g,userPermissionLevel:d,isAnchor:p,metadata:D7e(e,t,a,i,void 0,l.principal)}))return}let y=wgi(m.message,n),b=await f.agent.chat(y.message,o,{userPermissionLevel:d,isAnchor:p,interfaceType:e,channelId:s,channelName:a,...D7e(e,t,a,i,y.metadata,l.principal),...m.attachments.length>0?{attachments:m.attachments}:{}});await this.deps.responseCoordinator.renderAgentResponse({thread:t,channelId:s,conversationId:o,response:b,userPermissionLevel:d})}})}async capturePassiveSpaceMessage(e,t){let{context:i}=this.deps.host,n=this.getPlatform(e);if(!rA(this.deps.config,n))return;let r=this.getPlatformConfig(e);if(!r)return;if(e.isDM)return;if(t.author.isMe||Q6(t.author))return;if(!$U(e,r))return;let o=Ooe(n,e);if(!i.spaces.some((m)=>fR(m,o)))return;let s=Moe(e),a=HU(e,t,r)&&(!r.requireMention||t.isMention);if(s===e.id&&a)return;let c=t.text.trim();if(!c)return;let l=X6(n,s),d=await WU(i.permissions,n,t.author.userId,D_(e,t),this.deps.identityAccess()),p=await this.deps.channelNames.nameOf(e);await i.conversations.start({sessionId:l,interfaceType:n,channelId:s,metadata:{channelName:p,interfaceType:n,channelId:s}}),await i.conversations.addMessage({conversationId:l,role:"user",content:c,metadata:Sgi(n,e,p,s,t,d.principal)})}async handlePassiveUrlCapture(e,t){let i=this.getPlatform(e);if(!rA(this.deps.config,i))return;let n=this.getPlatformConfig(e);if(!n?.captureUrls)return;if(!n.requireMention)return;if(!$U(e,n))return;if(t.author.isMe)return;if(Q6(t.author))return;if(t.isMention)return;let r=this.deps.host.extractCaptureableUrls(t.text,n.blockedUrlDomains);if(r.length===0)return;this.deps.threadRegistry.set(e);let o=D_(e,t);for(let s of r)await this.deps.host.captureUrlViaAgent(s,e.id,t.author.userId,i,o).catch((a)=>this.deps.logger.error("URL capture failed",{error:a,url:s}))}async postUploadNotices(e,t){let i=[...new Set(t)];if(i.length===0)return;await e.post(["Some uploads were skipped:",...i.map((n)=>`- ${n}`)].join(`
|
|
5511
|
-
`))}getPlatform(e){return e.adapter.name}getPlatformConfig(e){let t=this.getPlatform(e);if(t==="discord")return this.deps.config.adapters.discord;if(t==="slack")return this.deps.config.adapters.slack;if(t==="matrix")return this.deps.config.adapters.matrix;return}}function rA(e,t){let i=new Set;if(e.adapters.discord)i.add("discord");if(e.adapters.slack)i.add("slack");if(e.adapters.matrix)i.add("matrix");return kvt(t,i)}var t4r=1000,eB="chat";async function Fgi(e){let t=await e.request(Uoe,{});if(t.status!=="answered")throw Error("No Matrix password: set adapters.matrix.password, or add the matrix bundle so the brain's homeserver provides it");return t.data.password}function i4r(e,t,i){let n=new gke({baseUrl:e.baseUrl,userId:e.userId,password:e.password??i,...t?{fetch:t}:{}});return{isAvailable:()=>Promise.resolve(!0),send:(r)=>n.send(r)}}function n4r(e){if(e.preferLocalUrls&&e.localSiteUrl)return e.localSiteUrl;return e.siteUrl??e.localSiteUrl}async function Mgi(e,{channelId:t,message:i}){let n=e.threadRegistry.get(t);if(!n)return;return(await Pke(n,t,i,{onSent:(o)=>e.threadRegistry.trackMessage(n.id,o)}))?.id}function R7e(e={}){let t=Hh({id:eB,config:bke,setup:async(o)=>{let{config:s}=o,a=xs(o),{logger:c,messages:l}=a;for(let B of $vt)await a.retireUploads(B).catch((T)=>{c.warn("Could not delete retired chat uploads",{namespace:B,error:T})});let d=new MX,p=new Eke(t4r),m=new vke(d),h=new Tke({host:a,logger:c}),f={password:void 0},g={threadRegistry:d,toolStatusMessenger:m,compactingSlackApprovalToolStatuses:new Set,uploadCoordinator:h,responseCoordinator:new Ike({host:a,getDisplayBaseUrl:()=>n4r(a),registerPromptAction:(B,T)=>p.register(B,T),clearMessageComponents:async(B,T)=>{let F=s.adapters.discord?.botToken;if(!F)return;await Cgi({threadId:B,messageId:T,botToken:F,logger:c,...e.fetch?{fetchFn:e.fetch}:{}})},sendMessageWithId:(B)=>Mgi(g,B),handleAgentResponseToolStatuses:(B,T)=>l.handleAgentResponseToolStatuses(B,T),trackAgentResponseForJob:(B,T,F)=>{l.trackAgentResponseForJob(B,T,F)},threadRegistry:d,logger:c}),gatewayLoop:new Rke({getApp:()=>g.chatApp.instance,gatewayRunMs:s.gatewayRunMs,gatewayRestartDelayMs:s.gatewayRestartDelayMs,logger:c}),slackSocketLoop:new Fke({listenerRunMs:s.gatewayRunMs,restartDelayMs:s.gatewayRestartDelayMs,logger:c}),chatApp:new Mke({slack:s.adapters.slack,buildApp:(B)=>ggi({userName:s.userName,discord:s.adapters.discord,slack:s.adapters.slack,matrix:s.adapters.matrix,matrixCredentials:f,...s.adapters.matrix?{acceptMatrixInvite:Rgi({allowDMs:s.adapters.matrix.allowDMs,peerTrust:()=>a.auth()})}:{},gatewayLoop:g.gatewayLoop,slackSocketLoop:g.slackSocketLoop,runtimeState:B})}),matrixCredentials:f,prepareMatrix:async()=>{let B=s.adapters.matrix;if(!B)return;f.password??=B.password??await Fgi(a),await xvt({baseUrl:B.baseUrl,userId:B.userId,password:f.password,fetch:e.fetch})},logger:c,startRetry:void 0,chatAppRunning:!1},y,b,v=s.adapters.matrix?qU(a.classRuntimeState,"matrix"):void 0;if(s.adapters.discord)y=pgi(a.classRuntimeState);if(s.adapters.slack)b=mgi(a.classRuntimeState);return new P7e({identityAccess:e.identityAccess??(()=>a.auth()),config:s,host:{context:a,startProcessingInput:(B)=>{l.startProcessingInput(B)},endProcessingInput:()=>{l.endProcessingInput()},extractCaptureableUrls:(B,T)=>Ogi(B,T),captureUrlViaAgent:(B,T,F,k,N)=>Ngi(a,B,T,F,k,N)},promptActions:p,threadRegistry:d,subscriptionRouter:new C7e({getSubscriptions:(B)=>B==="discord"?y:B==="slack"?b:B==="matrix"?v:void 0,getPlatform:(B)=>B.adapter.name,isBotCreatedThread:bgi,logger:c}),chatInputBuilder:new _ke({getUploadStore:(B)=>B==="discord"||B==="slack"?h.getCanonicalStore():void 0,getThreadIdParts:Mf,logger:c,fetch:(B,T)=>(e.fetch??fetch)(B,T)}),uploadCoordinator:h,responseCoordinator:g.responseCoordinator,channelNames:new T7e,logger:{debug:(B,T)=>c.debug(B,T),error:(B,T)=>c.error(B,T)}}).registerHandlers(g.chatApp.build(a.classRuntimeState)),a.answer(zoe,async({request:B})=>Tgi({app:g.chatApp.instance,discordBotToken:s.adapters.discord?.botToken,logger:c,fetchFn:e.fetch},B)),g}}),i=$oe(t,(o)=>{let{config:s}=o;return[...s.adapters.discord?[{descriptor:{type:"discord",displayName:"Discord",subjectLabel:"Discord user ID",subjectPattern:{source:"^[0-9]{17,20}$"},manualDelivery:!0}}]:[],...s.adapters.slack?[{descriptor:{type:"slack",displayName:"Slack",subjectLabel:"Slack member ID",subjectPattern:{source:"^[UW][A-Z0-9]+$"},manualDelivery:!0}}]:[],...s.adapters.matrix?[{descriptor:{type:"matrix",displayName:"Matrix",subjectLabel:"Matrix user ID",subjectPattern:{source:XN.source}},delivery:i4r(s.adapters.matrix,e.fetch,()=>Fgi(xs(o)))}]:[]]}),n=Do(i,({state:o})=>o.chatApp.getWebRoutes()),r=fg(n,({config:o,state:s})=>{let a=Boolean(o.adapters.discord),c=o.adapters.slack?.mode==="socket";if(!a&&!o.adapters.slack&&!o.adapters.matrix)return;return{id:eB,start:async()=>{let l=async()=>{if(await s.prepareMatrix(),await s.chatApp.initialize(),s.chatAppRunning=!0,a)s.gatewayLoop.start();if(c)s.slackSocketLoop.start()};if(!o.adapters.matrix)return l();let d=async(p)=>{try{await l()}catch(m){s.logger.warn("Chat could not start yet; trying again",{error:m,retryInMs:p}),s.startRetry=setTimeout(()=>void d(Math.min(p*2,30000)),p)}};await d(o.gatewayRestartDelayMs)},stop:async()=>{clearTimeout(s.startRetry),s.startRetry=void 0,await s.gatewayLoop.stop(),await s.slackSocketLoop.stop(),s.threadRegistry.clear(),s.uploadCoordinator.clear(),s.responseCoordinator.clear(),s.toolStatusMessenger.clear(),await s.chatApp.shutdown(),s.chatAppRunning=!1},healthCheck:async()=>{let l=s.chatAppRunning&&(!a||s.gatewayLoop.isRunning())&&(!c||s.slackSocketLoop.isRunning());return{status:l?"healthy":"error",message:l?"Chat SDK app running":"Chat SDK app stopped",lastCheck:new Date}}}});return qoe(r,(o)=>{let{config:s,state:a}=o,c=xs(o),{logger:l}=c;return{send:({channelId:d,message:p})=>{let m=a.threadRegistry.get(d);if(!m)return;Pke(m,d,p).catch((h)=>l.error("Failed to send chat message",{error:h,channelId:d}))},sendWithId:(d)=>Mgi(a,d),edit:async({channelId:d,messageId:p,message:m})=>{let h=a.threadRegistry.getMessage(d,p);if(!h)return!1;try{let f=await h.edit(gv(d,m)??J1(d,typeof m==="string"?m:""));if(d)a.threadRegistry.trackMessage(d,f);return!0}catch{return!1}},formatProgress:(d)=>wke(d),formatCompletion:(d)=>wke(d),progressEvent:async(d,p)=>{let m=d.metadata.interfaceType,h=d;if(m&&m!==eB){if(!rA(s,m))return;h={...d,metadata:{...d.metadata,interfaceType:eB}}}await p(h),await a.responseCoordinator.deliverCompletedJobArtifacts(h)},toolActivity:async(d,p)=>{if(d.interfaceType===eB){await p(d);return}if(!rA(s,d.interfaceType))return;await p({...d,interfaceType:eB})},toolStatus:async(d)=>{if(d.interfaceType!==eB||!d.channelId)return;let p=iL(d.channelId)==="slack",m=p&&a.responseCoordinator.isActiveSlackConfirmation(d.conversationId);if(p&&a.compactingSlackApprovalToolStatuses.has(eL(d))||m||p&&d.state==="completed"){await a.toolStatusMessenger.dismiss(d);return}await a.toolStatusMessenger.handle(d)},agentResponseToolStatuses:async(d,p,m)=>{let h=new Set([...(d.pendingConfirmations??[]).map((g)=>g.toolName),...(d.cards??[]).filter((g)=>g.kind==="tool-approval").map((g)=>g.toolName)]),f=p.startsWith("slack-")?[...h].map((g)=>`${p}:${g}`):[];for(let g of f)a.compactingSlackApprovalToolStatuses.add(g);try{await m()}finally{for(let g of f)a.compactingSlackApprovalToolStatuses.delete(g)}}}})}function F7e(e,t={}){let i={...r4r(e,t),...o4r(e)};return Object.keys(i).length>0?{adapters:i}:{}}function r4r(e,t){let{DISCORD_BOT_TOKEN:i,DISCORD_PUBLIC_KEY:n,DISCORD_APPLICATION_ID:r}=e;if(!i||!n||!r)return{};return{discord:{botToken:i,publicKey:n,applicationId:r,...t}}}function o4r(e){let{MATRIX_BASE_URL:t,MATRIX_USER_ID:i,MATRIX_PASSWORD:n}=e;if(!t||!i)return{};return{matrix:{baseUrl:t,userId:i,...n?{password:n}:{}}}}var s4r=R7e(),Lgi=s4r;var N7e="note";function a4r(e){if(!(e instanceof u.ZodDiscriminatedUnion))return;let{discriminator:t}=e.def,i=e.def.options.map((n)=>{let r=O7e(n),o=r?VU(r[t]):void 0;if(!r||typeof o!=="string")return;return{value:o,label:Of(o),fields:Object.entries(r).filter(([s])=>s!==t).map(([s,a])=>Cx(s,a))}});return i.every((n)=>n!==void 0)?{discriminator:t,variants:i}:void 0}var c4r=["date","excerpt","cover"];function l4r(e){let t=tB(e)?.studioColumn;return c4r.find((i)=>i===t)}var u4r=new Set(["description","excerpt","summary","tagline","story"]);function oA(e,t){return e===N7e&&!t.isGroupingContributor(e)}function Woe(e){return{kind:e==="site-content"?"page":"folder",nested:e!==N7e}}function pl(e,t){if(e==="grouping-definitions")return{label:t?.label??"Groupings",pluralLabel:"Groupings"};let i=e===N7e?"Note":Of(e),n=t?.label??i;return{label:n,pluralLabel:zgi(n)}}function d4r(e){let t=tB(e)?.studioCondition;if(!Br(t)||typeof t.field!=="string"||!Object.hasOwn(t,"value"))return;return{field:t.field,value:t.value}}var p4r=["members","people","provenance","hidden","text"];function m4r(e){let t=tB(e)?.studioWidget;return p4r.find((i)=>i===t)}function h4r(e){return e==="imageId"||e.endsWith("ImageId")}function Cx(e,t){let{inner:i,required:n,defaultValue:r}=Goe(t),o=Hoe(i),s=r??VU(i),a=d4r(t),c=l4r(t),l={name:e,label:Of(e),widget:"string",...!n&&{required:!1},...s!==void 0&&{default:s},...a&&{condition:a},...tB(t)?.studioSecret===!0&&{secret:!0},...c&&{column:c}},d=m4r(t);if(d)return{...l,widget:d};switch(o){case"string":{if(h4r(e))return{...l,widget:"image"};if(M7e(i,"datetime"))return{...l,widget:"datetime"};if(M7e(i,"date"))return{...l,widget:"date"};if(u4r.has(e))return{...l,widget:"text"};return{...l,widget:"string"}}case"number":return{...l,widget:"number"};case"boolean":return{...l,widget:"boolean"};case"enum":{let p=ZU(i);return{...l,widget:"select",...p?{options:p}:{}}}case"array":{let p=jgi(i),m=Cx("item",p);if(m.widget==="object"&&m.fields)return{...l,widget:"list",fields:m.fields};if(m.widget==="variant")return{...l,widget:"list",field:{...m,name:e,label:Of(e)}};return{...l,widget:"list",field:{name:e,label:Of(e),widget:m.widget}}}case"object":{let p=Object.entries(O7e(i)??{}).map(([m,h])=>Cx(m,h));return{...l,widget:"object",fields:p}}case"union":{let p=a4r(i);return p?{...l,widget:"variant",...p}:{...l,widget:"object"}}case"record":{if(!(i instanceof u.ZodRecord))return{...l,widget:"object"};let p=Cx("value",i.def.valueType);if(p.widget==="object"&&!p.fields)return{...l,widget:"object"};let m=ZU(i.def.keyType);return{...l,widget:"map",field:p,...m&&{keys:m}}}case"unknown":case"any":return{...l,widget:"object"};case"literal":return{...l,widget:"string"};default:return{...l,widget:"string"}}}var Zoe=160;function Oe(e,t=200){return Ugi(e,{status:t,headers:{"Cache-Control":"no-store"}})}function iB(e){return{interfaceType:"studio",userId:e.principal.userId,displayName:e.principal.displayName,actor:e.actor,userPermissionLevel:e.permissionLevel,visibilityScope:e.visibilityScope,isAnchor:e.isAnchor}}async function ml(e,t,i,n,r,o,s){if(!e)return;await e({actorUserId:t.principal.userId,action:`studio.entity.${i}.${n}`,targetType:"entity",...o?{targetId:o}:{},metadata:{entityType:r,interfaceType:"studio",outcome:n,...s?{reason:s}:{}}})}function __(e){return{eventContext:{actor:e.actor,interfaceType:"studio"}}}function qgi(e){return e.permissionLevel==="public"?Oe({error:"Trusted Studio capability required"},403):null}function $gi(e){return e.permissionLevel==="admin"?null:Oe({error:"Admin Studio capability required"},403)}function Nf(e,t,i,n){try{return e.permissions.assertEntityActionAllowed(t,i,{userPermissionLevel:n.permissionLevel}),null}catch(r){return Oe({error:he(r,`Studio ${i} permission denied`)},403)}}function u8(e,t,i,n){try{return e.permissions.assertEntityActionAllowed(t,i,{userPermissionLevel:n.permissionLevel}),!0}catch{return!1}}function L7e(e,t,i,n){let r=u8(e,t,"create",n),o=u8(e,t,"update",n),s=u8(e,t,"delete",n),a=u8(e,t,"extract",n),c=u8(e,t,"publish",n),l=i>0||r||o||s||a||c;if(!l)return;return{canRead:l,canCreate:r,canUpdate:o,canDelete:s,canExtract:a,canPublish:c,canAssist:o}}async function Qd(e,t,i){if(!e.entities.getEffectiveFrontmatterSchema(t))return;let n=await e.entityService.countEntities({entityType:t,options:{filter:{visibilityScope:i.visibilityScope}}});return L7e(e,t,n,i)}var Xd="grouping-definitions",KU=20,j7e=u.strictObject({label:Xb.shape.label,excludeTypes:u.array(Xb.shape.types.element).max(100).refine((e)=>new Set(e).size===e.length,"Excluded types must be unique.").optional(),multiple:u.boolean(),values:u.array(u.string().min(1)).min(1).superRefine((e,t)=>{let i=new Set;e.forEach((n,r)=>{if(i.has(n))t.addIssue({code:"custom",path:[r],message:"Values must be unique (matching is exact)."});i.add(n)})}).optional()}),Voe=u.object({groupings:u.record(Xb.shape.key,j7e).refine((e)=>Object.keys(e).length<=KU,`Define at most ${KU} groupings.`).default({})});function YU(e){let{visibility:t,...i}=e;return i}function z7e(e,t){if(!Object.hasOwn(e,"visibility"))return{success:!0,visibility:t};let i=yu.safeParse(e.visibility);return i.success?{success:!0,visibility:i.data}:{success:!1,response:Oe({error:"Invalid content visibility"},400)}}function U7e(e,t){let{visibility:i,...n}=e;return t==="public"?n:{...n,visibility:t}}function q7e(e,t,i){if(i===void 0)return null;if(!e.shapes.hasBody(t))return Oe({error:`Entity type ${t} does not have a body`},400);return null}function Lf(e,t,i){if(e===Xd)try{let n=ki(t,{cache:!1});return{frontmatter:n.frontmatter,body:n.content}}catch{return{frontmatter:{groupings:t},body:"",malformed:!0}}if(oA(e,i.entities))return{frontmatter:{},body:t};try{let n=Nr(t,u.record(u.string(),u.unknown()));return{frontmatter:n.metadata,body:n.content}}catch{return{frontmatter:{},body:t}}}async function Hgi(e,t,i){let n=e.entityService.getEntityTypes().find((r)=>e.entityService.getEntityTypeConfig(r).containedIn===t);if(n===void 0)return;return await Qd(e,n,i)?n:void 0}var f4r=100;async function Ggi(e,t){let i=(m,h)=>e.entityService.queryEntityHierarchy({...t.base,entityType:m,...h}),{container:n,contained:r,prefix:o,limit:s,offset:a}=t;if(t.searching){if(o&&o.length>0){let g=await i(r,{prefix:o,includeDescendants:!0,limit:s,offset:a});return{prefix:o,folders:[],entities:g.entities,total:g.totalEntities}}let m=await i(n,{prefix:null,includeDescendants:!0,limit:s,offset:a}),h=s-m.entities.length,f=await i(r,{prefix:null,includeDescendants:!0,limit:Math.max(1,h),offset:Math.max(0,a-m.totalEntities)});return{prefix:null,folders:[],entities:[...m.entities,...h>0?f.entities.slice(0,h):[]],total:m.totalEntities+f.totalEntities}}if(!o||o.length===0){let[m,h]=await Promise.all([Wgi(i,n),i(r,{prefix:null,limit:1,offset:0})]),f=new Map(h.folders.map((g)=>[g.name,g.descendantCount]));return{prefix:null,folders:m.map(({entity:g})=>({path:[g.id],name:g.id,title:t.titleOf(g)??g.id,descendantCount:f.get(g.id)??0})),entities:[],total:0}}let[c]=o,l=c?await e.entityService.getEntity({entityType:n,id:c,visibilityScope:t.base.visibilityScope,source:!0}):null,d=o.length===1&&l?[l]:[],p=await i(r,{prefix:o,limit:a<d.length?Math.max(1,s-d.length):s,offset:Math.max(0,a-d.length)});return{prefix:p.prefix,folders:p.folders,entities:[...a<d.length?d.map((m)=>({entity:m,path:Vh(m.id)})):[],...p.entities].slice(0,s),total:p.totalEntities+d.length,trail:[l?t.titleOf(l)??l.id:null,...o.slice(1).map(()=>null)]}}async function Wgi(e,t,i=0){let n=await e(t,{prefix:null,limit:f4r,offset:i}),r=i+n.entities.length;if(n.entities.length===0||r>=n.totalEntities)return n.entities;return[...n.entities,...await Wgi(e,t,r)]}var x4r=u.object({issues:u.array(u.object({path:u.array(u.union([u.string(),u.number()])).default([]),message:u.string()}))});function T_(e){if(!Lk(e))return;let t=x4r.safeParse(Br(e)&&Object.hasOwn(e,"originalError")?e.originalError:e);return Oe({error:"Invalid entity data",issues:t.success?t.data.issues:[]},400)}function g4r(e){return e===void 0||e===null||typeof e==="string"&&e.trim()===""||Array.isArray(e)&&e.length===0}function $7e(e,t){return Oe({error:"Invalid frontmatter",issues:e.issues.map((i)=>{let n=i.path[0];return i.path.length===1&&typeof n==="string"&&g4r(t[n])?{...i,message:"Required."}:i})},400)}async function H7e(e,t){let i=e.shapes.folderTitles(t.entityType),n=t.prefix??[];if(!i)return{folders:t.folders,trail:n.map(()=>null)};let r=async(a)=>{let l=(await e.entityService.queryEntityHierarchy({entityType:t.entityType,prefix:a,includeDescendants:!0,limit:1,offset:0,source:!0,visibilityScope:t.visibilityScope,...t.signal&&{signal:t.signal}})).entities[0]?.entity;if(!l)return[];let d=i(l);return d.length===Vh(l.id).length-1?d:[]},[o,s]=await Promise.all([t.prefix?r(t.prefix):Promise.resolve([]),Promise.all(t.folders.map(async(a)=>{let c=a.title??(await r(a.path)).at(a.path.length-1);return c===void 0?a:{...a,title:c}}))]);return{folders:s,trail:n.map((a,c)=>o[c]??null)}}var Zgi=25;var G7e=u.object({prefix:u.tuple([u.string()],u.string()).nullable().default(null),scope:u.enum(["folder","collection"]).default("folder"),q:u.string().trim().max(200).default(""),visibility:u.enum(["all","public","shared","restricted"]).default("all"),status:u.string().trim().max(100).default(""),sort:u.enum(["updated-desc","updated-asc","created-desc","created-asc"]).default("updated-desc"),offset:u.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),limit:u.coerce.number().int().min(1).max(100).default(Zgi)});function W7e(e){let t=e.get("prefix"),i=null;if(t!==null)try{i=JSON.parse(t)}catch{i=t}return{prefix:i,scope:e.get("scope")??void 0,q:e.get("q")??void 0,visibility:e.get("visibility")??void 0,status:e.get("status")??void 0,sort:e.get("sort")??void 0,offset:e.get("offset")??void 0,limit:e.get("limit")??void 0}}function Tc(e,t){let i=e.shapes.metadataFromFrontmatter(t.entityType);return e.shapes.displayTitle(i?{...t,content:Lf(t.entityType,t.content,e).body}:t)}function Yoe(e,t){return e.entityService.getEntityRaw({...t,source:!0})}var y4r=u.object({id:u.string().min(1),width:u.literal(String(Zoe)).optional()});async function b4r(e){if(!/^image\/(png|jpeg|webp|gif|avif)$/i.test(e.headers.get("Content-Type")??""))return e;let t=new Uint8Array(await e.arrayBuffer());try{let i=await new Bun.Image(t).resize(Zoe,void 0,{withoutEnlargement:!0}).webp({quality:80}).bytes();return new Response(new Uint8Array(i),{headers:{"Content-Type":"image/webp","Content-Length":String(i.byteLength),"X-Content-Type-Options":"nosniff"}})}catch{return new Response(t,{headers:e.headers})}}async function Kgi(e,t,i){let n=new URL(t.url).searchParams,r=y4r.safeParse({id:n.get("id"),width:n.get("width")??void 0});if(!r.success)return Oe({error:n.get("id")?`Images are served whole or ${Zoe}px wide`:"Image id is required"},400);let o=e.entityService.getEntityTypes().includes("image")?await e.entityService.getEntityRaw({entityType:"image",id:r.data.id,visibilityScope:i.visibilityScope}):null,s=o&&await p8(e.entityService,{entityType:"image",id:o.id,entity:o,disposition:"inline"});if(!s)return Oe({error:"Image unavailable"},404);let a=r.data.width?await b4r(s):s;return a.headers.set("Cache-Control","no-store"),a}var E4r=u.object({entityType:u.string(),id:u.string(),frontmatter:u.record(u.string(),u.unknown()),body:u.string().optional(),baseContentHash:u.string().min(1)}),Ygi=u.object({entityType:u.string(),idPath:NC.optional(),frontmatter:u.record(u.string(),u.unknown()),body:u.string().optional()}),v4r=Ygi.extend({idPath:NC});function Jgi(e,t){let i=typeof t==="object"&&t!==null&&"idPath"in t?t.idPath:null,n=Array.isArray(i)?i.length-1:0;return Oe({error:"Invalid destination or entry fields",...e instanceof u.ZodError&&{issues:e.issues.map((r)=>({...r,path:r.path[0]==="idPath"?[r.path.length<2||r.path[1]===n?"segment":"prefix"]:r.path}))}},400)}async function Qgi(e,t,i,n){let r=await e.messaging.request(Koe,{entityType:t,entityId:i,metadata:n.metadata,content:n.content});return r.status==="answered"?r.data:null}async function Xgi(e,t,i){let n,r;try{n=await t.json(),r=v4r.parse(n)}catch(m){return Jgi(m,n)}if(!e.entities.getEffectiveFrontmatterSchema(r.entityType))return Oe({error:"Unknown entity type"},404);let o=Nf(e,r.entityType,"create",i);if(o)return o;await e.entities.ensureGroupingsCurrent();let s=ryi(e,r);if(s instanceof Response)return s;if(!km(i.permissionLevel,s.visibility))return Oe({error:"Cannot create at this visibility"},403);let a=ww(r.idPath),c=await Qgi(e,r.entityType,a,s),[l,...d]=r.idPath,p=ww([d.at(-1)??l]);return Oe({idPath:r.idPath,entityId:a,entityLeaf:{start:a.length-p.length,end:a.length},filePath:c?.relativePath??null,fileLeaf:c?.leaf??null,fileWritable:c?.writable??null,fileOwner:c?.owner??null})}var A4r=u.object({confirmed:u.literal(!0)});async function eyi(e,t,i,n){let r=new URL(t.url).searchParams,o=r.get("type");if(!o)return Oe({error:"type query parameter is required"},400);if(!await Qd(e,o,i))return Oe({error:`Unknown entity type: ${o}`},404);let s=r.get("id");if(s){let m=await Yoe(e,{entityType:o,id:s,visibilityScope:i.visibilityScope});if(!m)return Oe({error:`Entity not found: ${s}`},404);let{frontmatter:h,body:f}=Lf(o,m.content,e);return Oe({entity:{id:m.id,entityType:m.entityType,frontmatter:{...h,visibility:m.visibility},displayTitle:Tc(e,m),body:f,contentHash:m.contentHash,created:m.created,updated:m.updated}})}let a=G7e.safeParse(W7e(r));if(!a.success)return Oe({error:"Invalid entity page"},400);let c={visibilityScope:i.visibilityScope,...a.data.visibility!=="all"?{visibility:a.data.visibility}:{},...a.data.q?{contentContains:a.data.q}:{},...a.data.status?{metadata:{status:a.data.status}}:{}},[l,d]=await Promise.all([e.entityService.listEntities({entityType:o,options:{source:!0,offset:a.data.offset,limit:a.data.limit,sortFields:[{field:a.data.sort.startsWith("created")?"created":"updated",direction:a.data.sort.endsWith("asc")?"asc":"desc"}],filter:c}}),e.entityService.countEntities({entityType:o,options:{filter:c}})]),p=await n?.(o,l)??null;return Oe({total:d,entities:l.map((m)=>{let h=p?.get(m.id),{frontmatter:f}=Lf(o,m.content,e);return{id:m.id,entityType:m.entityType,frontmatter:{...f,visibility:m.visibility},displayTitle:Tc(e,m),updated:m.updated,...h&&{members:h}}})})}async function tyi(e,t,i,n){let r=new URL(t.url).searchParams,o=r.get("type");if(!o)return Oe({error:"type query parameter is required"},400);if(!await Qd(e,o,i))return Oe({error:`Unknown entity type: ${o}`},404);let s=G7e.safeParse(W7e(r));if(!s.success)return Oe({error:"Invalid folder query"},400);let{prefix:a,scope:c,q:l,visibility:d,status:p,sort:m,limit:h,offset:f}=s.data,g={visibilityScope:i.visibilityScope,source:!0,filter:{...l&&{contentContains:l},...d!=="all"&&{visibility:d},...p&&{metadata:{status:p}}},sortFields:[{field:m.startsWith("created")?"created":"updated",direction:m.endsWith("asc")?"asc":"desc"}],signal:t.signal},y=c==="collection"||Boolean(l),b=(w)=>({entity:B,path:T})=>{let F=B.entityType===o?w?.get(B.id):void 0;return{id:B.id,entityType:B.entityType,path:T,frontmatter:{...Lf(B.entityType,B.content,e).frontmatter,visibility:B.visibility},displayTitle:Tc(e,B),updated:B.updated,...F&&{members:F}}},v=async(w)=>await n?.(o,w.map(({entity:B})=>B).filter((B)=>B.entityType===o))??null;try{let w=await Hgi(e,o,i);if(w!==void 0){let F=await Ggi(e,{container:o,contained:w,prefix:c==="collection"?null:a,searching:y,limit:h,offset:f,base:g,titleOf:(L)=>Tc(e,L)}),k=await H7e(e,{entityType:w,prefix:F.prefix,folders:F.folders,visibilityScope:i.visibilityScope,signal:t.signal}),N=k.trail.map((L,G)=>F.trail?.[G]??L);return Oe({prefix:F.prefix,folders:k.folders,total:F.total,entities:F.entities.map(b(await v(F.entities))),...N.some((L)=>L!==null)&&{trail:N}})}let B=await e.entityService.queryEntityHierarchy({...g,entityType:o,prefix:c==="collection"?null:a,limit:h,offset:f,includeDescendants:y}),T=await H7e(e,{entityType:o,prefix:B.prefix,folders:B.folders,visibilityScope:i.visibilityScope,signal:t.signal});return Oe({prefix:B.prefix,folders:T.folders,total:B.totalEntities,entities:B.entities.map(b(await v(B.entities))),...T.trail.some((F)=>F!==null)&&{trail:T.trail}})}catch(w){if(w instanceof u.ZodError)return Oe({error:"Invalid folder prefix"},400);throw w}}async function iyi(e,t,i,n){let r;try{r=E4r.parse(await t.json())}catch{return Oe({error:"Invalid update payload"},400)}let{entityType:o,id:s}=r,a=e.entities.getEffectiveFrontmatterSchema(o);if(!a)return Oe({error:`Unknown entity type: ${o}`},404);let c=await Yoe(e,{entityType:o,id:s,visibilityScope:i.visibilityScope});if(!c)return Oe({error:`Entity not found: ${s}`},404);let l=q7e(e,o,r.body);if(l)return l;let d=oA(o,e.entities),p=YU(r.frontmatter);if(d&&Object.keys(p).length>0)return Oe({error:`Entity type ${o} is raw markdown without frontmatter`},400);let m=z7e(r.frontmatter,c.visibility);if(!m.success)return m.response;let h=d?u.object({}).safeParse({}):a.safeParse(p);if(!h.success)return $7e(h.error,p);let f=Lf(o,c.content,e),g=r.body??f.body,y=Object.fromEntries(Object.entries(h.data).filter(([L])=>Object.hasOwn(a.shape,L))),b=d?g:pr(g,U7e(y,m.visibility)),v=d||f.malformed?b:Pxe(c.content,b,a,[]),w=nyi(e,o,v);if(w instanceof Response)return w;let B={...c,...w,id:c.id,entityType:c.entityType,content:v,metadata:YU(w.metadata??c.metadata),visibility:m.visibility},T=()=>Uk(o,c,B,e.entityService).map((L)=>Nf(e,o,L,i)).find((L)=>L!==null)??null,F=T();if(F)return await ml(n,i,"update","denied",o,s,"entity-action-policy"),F;if(!km(i.permissionLevel,B.visibility))return await ml(n,i,"update","denied",o,s,"visibility-policy"),Oe({error:`Cannot set entity visibility to "${B.visibility}" at ${i.permissionLevel} permission.`},403);if(r.baseContentHash!==c.contentHash){if(v===c.content&&B.visibility===c.visibility)return Oe({entityId:s,jobId:"",skipped:!0});return Vgi(e,i,{existing:c,base:r.baseContentHash,text:v,declared:B.visibility})}let k=T();if(k)return await ml(n,i,"update","denied",o,s,"entity-action-policy"),k;let N;try{N=await e.entityService.updateEntity({entity:B,options:{...__(i),expectedContentHash:r.baseContentHash}})}catch(L){let G=T_(L);if(G)return G;throw L}if(N.skipReason==="content-conflict")return Vgi(e,i,{existing:c,base:r.baseContentHash,text:v,declared:B.visibility});return await ml(n,i,"update","allowed",o,s),Oe({entityId:N.entityId,jobId:N.jobId,skipped:N.skipped})}async function Vgi(e,t,i){let{existing:n,base:r,text:o,declared:s}=i,a=await Yoe(e,{entityType:n.entityType,id:n.id,visibilityScope:t.visibilityScope})??n,c=await e.messaging.request(d8,{entityType:a.entityType,entityId:a.id,origin:"studio",actor:t.principal.userId,base:r,current:a.contentHash,text:o,targetVisibility:a.visibility,...s!==a.visibility&&{declaredVisibility:s}});return Oe({error:c.status==="answered"?"This entry changed since it was opened. Your version is kept as a conflict in the Inbox; reload to review the current one.":"This entry changed since it was opened. Reload to review before saving again.",currentContentHash:a.contentHash,...c.status==="answered"&&{conflictId:c.data.conflictId}},409)}function nyi(e,t,i){try{return e.entityService.deserializeEntity(i,t)}catch(n){let r=T_(n);if(r)return r;throw n}}function ryi(e,t){let{entityType:i}=t,n=e.entities.getEffectiveFrontmatterSchema(i);if(!n)return Oe({error:`Unknown entity type: ${i}`},404);let r=q7e(e,i,t.body);if(r)return r;let o=oA(i,e.entities),s=YU(t.frontmatter);if(o&&Object.keys(s).length>0)return Oe({error:`Entity type ${i} is raw markdown without frontmatter`},400);let a=z7e(t.frontmatter,i===Xd?"shared":"public");if(!a.success)return a.response;let c=o?u.object({}).safeParse({}):n.safeParse(s);if(!c.success)return $7e(c.error,s);let l=o?t.body??"":pr(t.body??"",U7e(Object.fromEntries(Object.entries(c.data).filter(([p])=>Object.hasOwn(n.shape,p))),a.visibility)),d=nyi(e,i,l);if(d instanceof Response)return d;return{...d,...t.idPath&&{id:ww(t.idPath)},entityType:i,content:l,metadata:YU(d.metadata??{}),visibility:a.visibility}}async function oyi(e,t,i,n){let r,o;try{o=await t.json(),r=Ygi.parse(o)}catch(m){return Jgi(m,o)}let{entityType:s}=r;if(!e.entities.getEffectiveFrontmatterSchema(s))return Oe({error:`Unknown entity type: ${s}`},404);let c=Nf(e,s,"create",i);if(c)return await ml(n,i,"create","denied",s,void 0,"entity-action-policy"),c;await e.entities.ensureGroupingsCurrent();let l=ryi(e,r);if(l instanceof Response)return l;if(!km(i.permissionLevel,l.visibility))return await ml(n,i,"create","denied",s,void 0,"visibility-policy"),Oe({error:`Cannot set entity visibility to "${l.visibility}" at ${i.permissionLevel} permission.`},403);let d=Nf(e,s,"create",i);if(d)return await ml(n,i,"create","denied",s,void 0,"entity-action-policy"),d;if(r.idPath){let m=await Qgi(e,s,ww(r.idPath),l);if(m?.writable===!1){await ml(n,i,"create","denied",s,void 0,"invalid-placement");let h=r.idPath.length>1,f=m.owner?`reads as ${m.owner.entityType}/${m.owner.id}`:"was refused by directory-sync";return Oe({error:`This destination cannot be exported: ${m.relativePath} ${f}.`,issues:[{path:[h?"prefix":"segment"],message:h?"Choose a different folder for this entry.":"Choose a different segment."}]},400)}}let p;try{p=await e.entityService.createEntity({entity:l,options:{...__(i),...r.idPath&&{conditionalWrite:{expectedRevision:null}}}})}catch(m){let h=T_(m);if(h)return h;if(m instanceof Error&&m.name==="EntityWriteConflictError")return Oe({error:"An entry already exists at this destination.",issues:[{path:["segment"],message:"Choose a different segment."}]},409);throw m}return await ml(n,i,"create","allowed",s,p.entityId),Oe({entityId:p.entityId,jobId:p.jobId},201)}async function syi(e,t,i,n){try{A4r.parse(await t.json())}catch{return Oe({error:"Explicit delete confirmation required"},400)}let r=new URL(t.url).searchParams,o=r.get("type"),s=r.get("id");if(!o||!s)return Oe({error:"type and id query parameters are required"},400);if(!await Yoe(e,{entityType:o,id:s,visibilityScope:i.visibilityScope}))return Oe({error:`Entity not found: ${s}`},404);let c=Nf(e,o,"delete",i);if(c)return await ml(n,i,"delete","denied",o,s,"entity-action-policy"),c;let l=await e.entityService.deleteEntity({entityType:o,id:s,options:__(i)});if(l)await ml(n,i,"delete","allowed",o,s);return Oe({deleted:l})}var w4r=new Set(["string","text"]);async function ayi(e,t,i){if(!e.entityService.getEntityTypes().includes(t.entityType))return null;let n=await e.entityService.getEntityRaw({entityType:t.entityType,id:t.entityId,visibilityScope:t.visibilityScope,source:!0});if(!n)return null;let r=oA(t.entityType,e.entities)?void 0:e.entities.getEffectiveFrontmatterSchema(t.entityType),o=Object.entries(r?.shape??{}).flatMap(([s,a])=>{let c=Cx(s,a);return w4r.has(c.widget)&&!c.secret?[{name:s,label:c.label}]:[]});return{title:Tc(e,n)??n.id,typeLabel:pl(t.entityType,{...i?{label:i}:{}}).label.toLowerCase(),markdown:n.content,fields:[...o,{name:"body",label:"Body"}].slice(0,40)}}function Joe(e){let t=e.startsWith("/")?e:`/${e}`;return t==="/"?"":t.replace(/\/+$/,"")}function cyi(e,t){return`${Joe(e)}/entities/${encodeURIComponent(t)}`}function P_(e,t,i){return`${cyi(e,t)}/${encodeURIComponent(i)}`}function lyi(e,t,i){let n=new URL(cyi(e,t),"https://brains.invalid");if(n.searchParams.set("mode","create"),i!==void 0)n.searchParams.set("starter",i);return`${n.pathname}${n.search}`}function m8(e,t){return`${Joe(e)}/workspaces/${encodeURIComponent(t)}`}var uyi=(e)=>u.string().trim().min(1).max(e).refine((t)=>!/[\p{Cc}\p{Cf}]/u.test(t)),S4r=(e)=>u.string().trim().min(1).max(e).refine((t)=>Array.from(t).every((i)=>i===`
|
|
5511
|
+
`))}getPlatform(e){return e.adapter.name}getPlatformConfig(e){let t=this.getPlatform(e);if(t==="discord")return this.deps.config.adapters.discord;if(t==="slack")return this.deps.config.adapters.slack;if(t==="matrix")return this.deps.config.adapters.matrix;return}}function rA(e,t){let i=new Set;if(e.adapters.discord)i.add("discord");if(e.adapters.slack)i.add("slack");if(e.adapters.matrix)i.add("matrix");return kvt(t,i)}var t4r=1000,eB="chat";async function Fgi(e){let t=await e.request(Uoe,{});if(t.status!=="answered")throw Error("No Matrix password: set adapters.matrix.password, or add the matrix bundle so the brain's homeserver provides it");return t.data.password}function i4r(e,t,i){let n=new gke({baseUrl:e.baseUrl,userId:e.userId,password:e.password??i,...t?{fetch:t}:{}});return{isAvailable:()=>Promise.resolve(!0),send:(r)=>n.send(r)}}function n4r(e){if(e.preferLocalUrls&&e.localSiteUrl)return e.localSiteUrl;return e.siteUrl??e.localSiteUrl}async function Mgi(e,{channelId:t,message:i}){let n=e.threadRegistry.get(t);if(!n)return;return(await Pke(n,t,i,{onSent:(o)=>e.threadRegistry.trackMessage(n.id,o)}))?.id}function R7e(e={}){let t=Hh({id:eB,config:bke,setup:async(o)=>{let{config:s}=o,a=xs(o),{logger:c,messages:l}=a;for(let B of $vt)await a.retireUploads(B).catch((T)=>{c.warn("Could not delete retired chat uploads",{namespace:B,error:T})});let d=new MX,p=new Eke(t4r),m=new vke(d),h=new Tke({host:a,logger:c}),f={password:void 0},g={threadRegistry:d,toolStatusMessenger:m,compactingSlackApprovalToolStatuses:new Set,uploadCoordinator:h,responseCoordinator:new Ike({host:a,getDisplayBaseUrl:()=>n4r(a),registerPromptAction:(B,T)=>p.register(B,T),clearMessageComponents:async(B,T)=>{let F=s.adapters.discord?.botToken;if(!F)return;await Cgi({threadId:B,messageId:T,botToken:F,logger:c,...e.fetch?{fetchFn:e.fetch}:{}})},sendMessageWithId:(B)=>Mgi(g,B),handleAgentResponseToolStatuses:(B,T)=>l.handleAgentResponseToolStatuses(B,T),trackAgentResponseForJob:(B,T,F)=>{l.trackAgentResponseForJob(B,T,F)},threadRegistry:d,logger:c}),gatewayLoop:new Rke({getApp:()=>g.chatApp.instance,gatewayRunMs:s.gatewayRunMs,gatewayRestartDelayMs:s.gatewayRestartDelayMs,logger:c}),slackSocketLoop:new Fke({listenerRunMs:s.gatewayRunMs,restartDelayMs:s.gatewayRestartDelayMs,logger:c}),chatApp:new Mke({slack:s.adapters.slack,buildApp:(B)=>ggi({userName:s.userName,discord:s.adapters.discord,slack:s.adapters.slack,matrix:s.adapters.matrix,matrixCredentials:f,...s.adapters.matrix?{acceptMatrixInvite:Rgi({allowDMs:s.adapters.matrix.allowDMs,peerTrust:()=>a.auth()})}:{},gatewayLoop:g.gatewayLoop,slackSocketLoop:g.slackSocketLoop,runtimeState:B})}),matrixCredentials:f,prepareMatrix:async()=>{let B=s.adapters.matrix;if(!B)return;f.password??=B.password??await Fgi(a),await xvt({baseUrl:B.baseUrl,userId:B.userId,password:f.password,fetch:e.fetch})},logger:c,startRetry:void 0,chatAppRunning:!1},y,b,v=s.adapters.matrix?qU(a.classRuntimeState,"matrix"):void 0;if(s.adapters.discord)y=pgi(a.classRuntimeState);if(s.adapters.slack)b=mgi(a.classRuntimeState);return new P7e({identityAccess:e.identityAccess??(()=>a.auth()),config:s,host:{context:a,startProcessingInput:(B)=>{l.startProcessingInput(B)},endProcessingInput:()=>{l.endProcessingInput()},extractCaptureableUrls:(B,T)=>Ogi(B,T),captureUrlViaAgent:(B,T,F,k,N)=>Ngi(a,B,T,F,k,N)},promptActions:p,threadRegistry:d,subscriptionRouter:new C7e({getSubscriptions:(B)=>B==="discord"?y:B==="slack"?b:B==="matrix"?v:void 0,getPlatform:(B)=>B.adapter.name,isBotCreatedThread:bgi,logger:c}),chatInputBuilder:new _ke({getUploadStore:(B)=>B==="discord"||B==="slack"?h.getCanonicalStore():void 0,getThreadIdParts:Mf,logger:c,fetch:(B,T)=>(e.fetch??fetch)(B,T)}),uploadCoordinator:h,responseCoordinator:g.responseCoordinator,channelNames:new T7e,logger:{debug:(B,T)=>c.debug(B,T),error:(B,T)=>c.error(B,T)}}).registerHandlers(g.chatApp.build(a.classRuntimeState)),a.answer(zoe,async({request:B})=>Tgi({app:g.chatApp.instance,discordBotToken:s.adapters.discord?.botToken,logger:c,fetchFn:e.fetch},B)),g}}),i=$oe(t,(o)=>{let{config:s}=o;return[...s.adapters.discord?[{descriptor:{type:"discord",displayName:"Discord",subjectLabel:"Discord user ID",subjectPattern:{source:"^[0-9]{17,20}$"},manualDelivery:!0}}]:[],...s.adapters.slack?[{descriptor:{type:"slack",displayName:"Slack",subjectLabel:"Slack member ID",subjectPattern:{source:"^[UW][A-Z0-9]+$"},manualDelivery:!0}}]:[],...s.adapters.matrix?[{descriptor:{type:"matrix",displayName:"Matrix",subjectLabel:"Matrix user ID",subjectPattern:{source:XN.source}},delivery:i4r(s.adapters.matrix,e.fetch,()=>Fgi(xs(o)))}]:[]]}),n=Do(i,({state:o})=>o.chatApp.getWebRoutes()),r=fg(n,({config:o,state:s})=>{let a=Boolean(o.adapters.discord),c=o.adapters.slack?.mode==="socket";if(!a&&!o.adapters.slack&&!o.adapters.matrix)return;return{id:eB,start:async()=>{let l=async()=>{if(await s.prepareMatrix(),await s.chatApp.initialize(),s.chatAppRunning=!0,a)s.gatewayLoop.start();if(c)s.slackSocketLoop.start()};if(!o.adapters.matrix)return l();let d=async(p)=>{try{await l()}catch(m){s.logger.warn("Chat could not start yet; trying again",{error:m,retryInMs:p}),s.startRetry=setTimeout(()=>void d(Math.min(p*2,30000)),p)}};await d(o.gatewayRestartDelayMs)},stop:async()=>{clearTimeout(s.startRetry),s.startRetry=void 0,await s.gatewayLoop.stop(),await s.slackSocketLoop.stop(),s.threadRegistry.clear(),s.uploadCoordinator.clear(),s.responseCoordinator.clear(),s.toolStatusMessenger.clear(),await s.chatApp.shutdown(),s.chatAppRunning=!1},healthCheck:async()=>{let l=s.chatAppRunning&&(!a||s.gatewayLoop.isRunning())&&(!c||s.slackSocketLoop.isRunning());return{status:l?"healthy":"error",message:l?"Chat SDK app running":"Chat SDK app stopped",lastCheck:new Date}}}});return qoe(r,(o)=>{let{config:s,state:a}=o,c=xs(o),{logger:l}=c;return{send:({channelId:d,message:p})=>{let m=a.threadRegistry.get(d);if(!m)return;Pke(m,d,p).catch((h)=>l.error("Failed to send chat message",{error:h,channelId:d}))},sendWithId:(d)=>Mgi(a,d),edit:async({channelId:d,messageId:p,message:m})=>{let h=a.threadRegistry.getMessage(d,p);if(!h)return!1;try{let f=await h.edit(gv(d,m)??J1(d,typeof m==="string"?m:""));if(d)a.threadRegistry.trackMessage(d,f);return!0}catch{return!1}},formatProgress:(d)=>wke(d),formatCompletion:(d)=>wke(d),progressEvent:async(d,p)=>{let m=d.metadata.interfaceType,h=d;if(m&&m!==eB){if(!rA(s,m))return;h={...d,metadata:{...d.metadata,interfaceType:eB}}}await p(h),await a.responseCoordinator.deliverCompletedJobArtifacts(h)},toolActivity:async(d,p)=>{if(d.interfaceType===eB){await p(d);return}if(!rA(s,d.interfaceType))return;await p({...d,interfaceType:eB})},toolStatus:async(d)=>{if(d.interfaceType!==eB||!d.channelId)return;let p=iL(d.channelId)==="slack",m=p&&a.responseCoordinator.isActiveSlackConfirmation(d.conversationId);if(p&&a.compactingSlackApprovalToolStatuses.has(eL(d))||m||p&&d.state==="completed"){await a.toolStatusMessenger.dismiss(d);return}await a.toolStatusMessenger.handle(d)},agentResponseToolStatuses:async(d,p,m)=>{let h=new Set([...(d.pendingConfirmations??[]).map((g)=>g.toolName),...(d.cards??[]).filter((g)=>g.kind==="tool-approval").map((g)=>g.toolName)]),f=p.startsWith("slack-")?[...h].map((g)=>`${p}:${g}`):[];for(let g of f)a.compactingSlackApprovalToolStatuses.add(g);try{await m()}finally{for(let g of f)a.compactingSlackApprovalToolStatuses.delete(g)}}}})}function F7e(e,t={}){let i={...r4r(e,t),...o4r(e)};return Object.keys(i).length>0?{adapters:i}:{}}function r4r(e,t){let{DISCORD_BOT_TOKEN:i,DISCORD_PUBLIC_KEY:n,DISCORD_APPLICATION_ID:r}=e;if(!i||!n||!r)return{};return{discord:{botToken:i,publicKey:n,applicationId:r,...t}}}function o4r(e){let{MATRIX_BASE_URL:t,MATRIX_USER_ID:i,MATRIX_PASSWORD:n}=e;if(!t||!i)return{};return{matrix:{baseUrl:t,userId:i,...n?{password:n}:{}}}}var s4r=R7e(),Lgi=s4r;var N7e="note";function a4r(e){if(!(e instanceof u.ZodDiscriminatedUnion))return;let{discriminator:t}=e.def,i=e.def.options.map((n)=>{let r=O7e(n),o=r?VU(r[t]):void 0;if(!r||typeof o!=="string")return;return{value:o,label:Of(o),fields:Object.entries(r).filter(([s])=>s!==t).map(([s,a])=>Cx(s,a))}});return i.every((n)=>n!==void 0)?{discriminator:t,variants:i}:void 0}var c4r=["date","excerpt","cover"];function l4r(e){let t=tB(e)?.studioColumn;return c4r.find((i)=>i===t)}var u4r=new Set(["description","excerpt","summary","tagline","story"]);function oA(e,t){return e===N7e&&!t.isGroupingContributor(e)}function Woe(e){return{kind:e==="site-content"?"page":"folder",nested:e!==N7e}}function pl(e,t){if(e==="grouping-definitions")return{label:t?.label??"Groupings",pluralLabel:"Groupings"};let i=e===N7e?"Note":Of(e),n=t?.label??i;return{label:n,pluralLabel:zgi(n)}}function d4r(e){let t=tB(e)?.studioCondition;if(!Br(t)||typeof t.field!=="string"||!Object.hasOwn(t,"value"))return;return{field:t.field,value:t.value}}var p4r=["members","people","provenance","hidden","text"];function m4r(e){let t=tB(e)?.studioWidget;return p4r.find((i)=>i===t)}function h4r(e){return e==="imageId"||e.endsWith("ImageId")}function Cx(e,t){let{inner:i,required:n,defaultValue:r}=Goe(t),o=Hoe(i),s=r??VU(i),a=d4r(t),c=l4r(t),l={name:e,label:Of(e),widget:"string",...!n&&{required:!1},...s!==void 0&&{default:s},...a&&{condition:a},...tB(t)?.studioSecret===!0&&{secret:!0},...c&&{column:c}},d=m4r(t);if(d)return{...l,widget:d};switch(o){case"string":{if(h4r(e))return{...l,widget:"image"};if(M7e(i,"datetime"))return{...l,widget:"datetime"};if(M7e(i,"date"))return{...l,widget:"date"};if(u4r.has(e))return{...l,widget:"text"};return{...l,widget:"string"}}case"number":return{...l,widget:"number"};case"boolean":return{...l,widget:"boolean"};case"enum":{let p=ZU(i);return{...l,widget:"select",...p?{options:p}:{}}}case"array":{let p=jgi(i),m=Cx("item",p);if(m.widget==="object"&&m.fields)return{...l,widget:"list",fields:m.fields};if(m.widget==="variant")return{...l,widget:"list",field:{...m,name:e,label:Of(e)}};return{...l,widget:"list",field:{name:e,label:Of(e),widget:m.widget}}}case"object":{let p=Object.entries(O7e(i)??{}).map(([m,h])=>Cx(m,h));return{...l,widget:"object",fields:p}}case"union":{let p=a4r(i);return p?{...l,widget:"variant",...p}:{...l,widget:"object"}}case"record":{if(!(i instanceof u.ZodRecord))return{...l,widget:"object"};let p=Cx("value",i.def.valueType);if(p.widget==="object"&&!p.fields)return{...l,widget:"object"};let m=ZU(i.def.keyType);if(p.widget==="map"&&p.field){let{keys:h,field:f}=p;return{...l,widget:"grid",...m&&{rows:m},...h&&{columns:h},field:f}}return{...l,widget:"map",field:p,...m&&{keys:m}}}case"unknown":case"any":return{...l,widget:"object"};case"literal":return{...l,widget:"string"};default:return{...l,widget:"string"}}}var Zoe=160;function Oe(e,t=200){return Ugi(e,{status:t,headers:{"Cache-Control":"no-store"}})}function iB(e){return{interfaceType:"studio",userId:e.principal.userId,displayName:e.principal.displayName,actor:e.actor,userPermissionLevel:e.permissionLevel,visibilityScope:e.visibilityScope,isAnchor:e.isAnchor}}async function ml(e,t,i,n,r,o,s){if(!e)return;await e({actorUserId:t.principal.userId,action:`studio.entity.${i}.${n}`,targetType:"entity",...o?{targetId:o}:{},metadata:{entityType:r,interfaceType:"studio",outcome:n,...s?{reason:s}:{}}})}function __(e){return{eventContext:{actor:e.actor,interfaceType:"studio"}}}function qgi(e){return e.permissionLevel==="public"?Oe({error:"Trusted Studio capability required"},403):null}function $gi(e){return e.permissionLevel==="admin"?null:Oe({error:"Admin Studio capability required"},403)}function Nf(e,t,i,n){try{return e.permissions.assertEntityActionAllowed(t,i,{userPermissionLevel:n.permissionLevel}),null}catch(r){return Oe({error:he(r,`Studio ${i} permission denied`)},403)}}function u8(e,t,i,n){try{return e.permissions.assertEntityActionAllowed(t,i,{userPermissionLevel:n.permissionLevel}),!0}catch{return!1}}function L7e(e,t,i,n){let r=u8(e,t,"create",n),o=u8(e,t,"update",n),s=u8(e,t,"delete",n),a=u8(e,t,"extract",n),c=u8(e,t,"publish",n),l=i>0||r||o||s||a||c;if(!l)return;return{canRead:l,canCreate:r,canUpdate:o,canDelete:s,canExtract:a,canPublish:c,canAssist:o}}async function Qd(e,t,i){if(!e.entities.getEffectiveFrontmatterSchema(t))return;let n=await e.entityService.countEntities({entityType:t,options:{filter:{visibilityScope:i.visibilityScope}}});return L7e(e,t,n,i)}var Xd="grouping-definitions",KU=20,j7e=u.strictObject({label:Xb.shape.label,excludeTypes:u.array(Xb.shape.types.element).max(100).refine((e)=>new Set(e).size===e.length,"Excluded types must be unique.").optional(),multiple:u.boolean(),values:u.array(u.string().min(1)).min(1).superRefine((e,t)=>{let i=new Set;e.forEach((n,r)=>{if(i.has(n))t.addIssue({code:"custom",path:[r],message:"Values must be unique (matching is exact)."});i.add(n)})}).optional()}),Voe=u.object({groupings:u.record(Xb.shape.key,j7e).refine((e)=>Object.keys(e).length<=KU,`Define at most ${KU} groupings.`).default({})});function YU(e){let{visibility:t,...i}=e;return i}function z7e(e,t){if(!Object.hasOwn(e,"visibility"))return{success:!0,visibility:t};let i=yu.safeParse(e.visibility);return i.success?{success:!0,visibility:i.data}:{success:!1,response:Oe({error:"Invalid content visibility"},400)}}function U7e(e,t){let{visibility:i,...n}=e;return t==="public"?n:{...n,visibility:t}}function q7e(e,t,i){if(i===void 0)return null;if(!e.shapes.hasBody(t))return Oe({error:`Entity type ${t} does not have a body`},400);return null}function Lf(e,t,i){if(e===Xd)try{let n=ki(t,{cache:!1});return{frontmatter:n.frontmatter,body:n.content}}catch{return{frontmatter:{groupings:t},body:"",malformed:!0}}if(oA(e,i.entities))return{frontmatter:{},body:t};try{let n=Nr(t,u.record(u.string(),u.unknown()));return{frontmatter:n.metadata,body:n.content}}catch{return{frontmatter:{},body:t}}}async function Hgi(e,t,i){let n=e.entityService.getEntityTypes().find((r)=>e.entityService.getEntityTypeConfig(r).containedIn===t);if(n===void 0)return;return await Qd(e,n,i)?n:void 0}var f4r=100;async function Ggi(e,t){let i=(m,h)=>e.entityService.queryEntityHierarchy({...t.base,entityType:m,...h}),{container:n,contained:r,prefix:o,limit:s,offset:a}=t;if(t.searching){if(o&&o.length>0){let g=await i(r,{prefix:o,includeDescendants:!0,limit:s,offset:a});return{prefix:o,folders:[],entities:g.entities,total:g.totalEntities}}let m=await i(n,{prefix:null,includeDescendants:!0,limit:s,offset:a}),h=s-m.entities.length,f=await i(r,{prefix:null,includeDescendants:!0,limit:Math.max(1,h),offset:Math.max(0,a-m.totalEntities)});return{prefix:null,folders:[],entities:[...m.entities,...h>0?f.entities.slice(0,h):[]],total:m.totalEntities+f.totalEntities}}if(!o||o.length===0){let[m,h]=await Promise.all([Wgi(i,n),i(r,{prefix:null,limit:1,offset:0})]),f=new Map(h.folders.map((g)=>[g.name,g.descendantCount]));return{prefix:null,folders:m.map(({entity:g})=>({path:[g.id],name:g.id,title:t.titleOf(g)??g.id,descendantCount:f.get(g.id)??0})),entities:[],total:0}}let[c]=o,l=c?await e.entityService.getEntity({entityType:n,id:c,visibilityScope:t.base.visibilityScope,source:!0}):null,d=o.length===1&&l?[l]:[],p=await i(r,{prefix:o,limit:a<d.length?Math.max(1,s-d.length):s,offset:Math.max(0,a-d.length)});return{prefix:p.prefix,folders:p.folders,entities:[...a<d.length?d.map((m)=>({entity:m,path:Vh(m.id)})):[],...p.entities].slice(0,s),total:p.totalEntities+d.length,trail:[l?t.titleOf(l)??l.id:null,...o.slice(1).map(()=>null)]}}async function Wgi(e,t,i=0){let n=await e(t,{prefix:null,limit:f4r,offset:i}),r=i+n.entities.length;if(n.entities.length===0||r>=n.totalEntities)return n.entities;return[...n.entities,...await Wgi(e,t,r)]}var x4r=u.object({issues:u.array(u.object({path:u.array(u.union([u.string(),u.number()])).default([]),message:u.string()}))});function T_(e){if(!Lk(e))return;let t=x4r.safeParse(Br(e)&&Object.hasOwn(e,"originalError")?e.originalError:e);return Oe({error:"Invalid entity data",issues:t.success?t.data.issues:[]},400)}function g4r(e){return e===void 0||e===null||typeof e==="string"&&e.trim()===""||Array.isArray(e)&&e.length===0}function $7e(e,t){return Oe({error:"Invalid frontmatter",issues:e.issues.map((i)=>{let n=i.path[0];return i.path.length===1&&typeof n==="string"&&g4r(t[n])?{...i,message:"Required."}:i})},400)}async function H7e(e,t){let i=e.shapes.folderTitles(t.entityType),n=t.prefix??[];if(!i)return{folders:t.folders,trail:n.map(()=>null)};let r=async(a)=>{let l=(await e.entityService.queryEntityHierarchy({entityType:t.entityType,prefix:a,includeDescendants:!0,limit:1,offset:0,source:!0,visibilityScope:t.visibilityScope,...t.signal&&{signal:t.signal}})).entities[0]?.entity;if(!l)return[];let d=i(l);return d.length===Vh(l.id).length-1?d:[]},[o,s]=await Promise.all([t.prefix?r(t.prefix):Promise.resolve([]),Promise.all(t.folders.map(async(a)=>{let c=a.title??(await r(a.path)).at(a.path.length-1);return c===void 0?a:{...a,title:c}}))]);return{folders:s,trail:n.map((a,c)=>o[c]??null)}}var Zgi=25;var G7e=u.object({prefix:u.tuple([u.string()],u.string()).nullable().default(null),scope:u.enum(["folder","collection"]).default("folder"),q:u.string().trim().max(200).default(""),visibility:u.enum(["all","public","shared","restricted"]).default("all"),status:u.string().trim().max(100).default(""),sort:u.enum(["updated-desc","updated-asc","created-desc","created-asc"]).default("updated-desc"),offset:u.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),limit:u.coerce.number().int().min(1).max(100).default(Zgi)});function W7e(e){let t=e.get("prefix"),i=null;if(t!==null)try{i=JSON.parse(t)}catch{i=t}return{prefix:i,scope:e.get("scope")??void 0,q:e.get("q")??void 0,visibility:e.get("visibility")??void 0,status:e.get("status")??void 0,sort:e.get("sort")??void 0,offset:e.get("offset")??void 0,limit:e.get("limit")??void 0}}function Tc(e,t){let i=e.shapes.metadataFromFrontmatter(t.entityType);return e.shapes.displayTitle(i?{...t,content:Lf(t.entityType,t.content,e).body}:t)}function Yoe(e,t){return e.entityService.getEntityRaw({...t,source:!0})}var y4r=u.object({id:u.string().min(1),width:u.literal(String(Zoe)).optional()});async function b4r(e){if(!/^image\/(png|jpeg|webp|gif|avif)$/i.test(e.headers.get("Content-Type")??""))return e;let t=new Uint8Array(await e.arrayBuffer());try{let i=await new Bun.Image(t).resize(Zoe,void 0,{withoutEnlargement:!0}).webp({quality:80}).bytes();return new Response(new Uint8Array(i),{headers:{"Content-Type":"image/webp","Content-Length":String(i.byteLength),"X-Content-Type-Options":"nosniff"}})}catch{return new Response(t,{headers:e.headers})}}async function Kgi(e,t,i){let n=new URL(t.url).searchParams,r=y4r.safeParse({id:n.get("id"),width:n.get("width")??void 0});if(!r.success)return Oe({error:n.get("id")?`Images are served whole or ${Zoe}px wide`:"Image id is required"},400);let o=e.entityService.getEntityTypes().includes("image")?await e.entityService.getEntityRaw({entityType:"image",id:r.data.id,visibilityScope:i.visibilityScope}):null,s=o&&await p8(e.entityService,{entityType:"image",id:o.id,entity:o,disposition:"inline"});if(!s)return Oe({error:"Image unavailable"},404);let a=r.data.width?await b4r(s):s;return a.headers.set("Cache-Control","no-store"),a}var E4r=u.object({entityType:u.string(),id:u.string(),frontmatter:u.record(u.string(),u.unknown()),body:u.string().optional(),baseContentHash:u.string().min(1)}),Ygi=u.object({entityType:u.string(),idPath:NC.optional(),frontmatter:u.record(u.string(),u.unknown()),body:u.string().optional()}),v4r=Ygi.extend({idPath:NC});function Jgi(e,t){let i=typeof t==="object"&&t!==null&&"idPath"in t?t.idPath:null,n=Array.isArray(i)?i.length-1:0;return Oe({error:"Invalid destination or entry fields",...e instanceof u.ZodError&&{issues:e.issues.map((r)=>({...r,path:r.path[0]==="idPath"?[r.path.length<2||r.path[1]===n?"segment":"prefix"]:r.path}))}},400)}async function Qgi(e,t,i,n){let r=await e.messaging.request(Koe,{entityType:t,entityId:i,metadata:n.metadata,content:n.content});return r.status==="answered"?r.data:null}async function Xgi(e,t,i){let n,r;try{n=await t.json(),r=v4r.parse(n)}catch(m){return Jgi(m,n)}if(!e.entities.getEffectiveFrontmatterSchema(r.entityType))return Oe({error:"Unknown entity type"},404);let o=Nf(e,r.entityType,"create",i);if(o)return o;await e.entities.ensureGroupingsCurrent();let s=ryi(e,r);if(s instanceof Response)return s;if(!km(i.permissionLevel,s.visibility))return Oe({error:"Cannot create at this visibility"},403);let a=ww(r.idPath),c=await Qgi(e,r.entityType,a,s),[l,...d]=r.idPath,p=ww([d.at(-1)??l]);return Oe({idPath:r.idPath,entityId:a,entityLeaf:{start:a.length-p.length,end:a.length},filePath:c?.relativePath??null,fileLeaf:c?.leaf??null,fileWritable:c?.writable??null,fileOwner:c?.owner??null})}var A4r=u.object({confirmed:u.literal(!0)});async function eyi(e,t,i,n){let r=new URL(t.url).searchParams,o=r.get("type");if(!o)return Oe({error:"type query parameter is required"},400);if(!await Qd(e,o,i))return Oe({error:`Unknown entity type: ${o}`},404);let s=r.get("id");if(s){let m=await Yoe(e,{entityType:o,id:s,visibilityScope:i.visibilityScope});if(!m)return Oe({error:`Entity not found: ${s}`},404);let{frontmatter:h,body:f}=Lf(o,m.content,e);return Oe({entity:{id:m.id,entityType:m.entityType,frontmatter:{...h,visibility:m.visibility},displayTitle:Tc(e,m),body:f,contentHash:m.contentHash,created:m.created,updated:m.updated}})}let a=G7e.safeParse(W7e(r));if(!a.success)return Oe({error:"Invalid entity page"},400);let c={visibilityScope:i.visibilityScope,...a.data.visibility!=="all"?{visibility:a.data.visibility}:{},...a.data.q?{contentContains:a.data.q}:{},...a.data.status?{metadata:{status:a.data.status}}:{}},[l,d]=await Promise.all([e.entityService.listEntities({entityType:o,options:{source:!0,offset:a.data.offset,limit:a.data.limit,sortFields:[{field:a.data.sort.startsWith("created")?"created":"updated",direction:a.data.sort.endsWith("asc")?"asc":"desc"}],filter:c}}),e.entityService.countEntities({entityType:o,options:{filter:c}})]),p=await n?.(o,l)??null;return Oe({total:d,entities:l.map((m)=>{let h=p?.get(m.id),{frontmatter:f}=Lf(o,m.content,e);return{id:m.id,entityType:m.entityType,frontmatter:{...f,visibility:m.visibility},displayTitle:Tc(e,m),updated:m.updated,...h&&{members:h}}})})}async function tyi(e,t,i,n){let r=new URL(t.url).searchParams,o=r.get("type");if(!o)return Oe({error:"type query parameter is required"},400);if(!await Qd(e,o,i))return Oe({error:`Unknown entity type: ${o}`},404);let s=G7e.safeParse(W7e(r));if(!s.success)return Oe({error:"Invalid folder query"},400);let{prefix:a,scope:c,q:l,visibility:d,status:p,sort:m,limit:h,offset:f}=s.data,g={visibilityScope:i.visibilityScope,source:!0,filter:{...l&&{contentContains:l},...d!=="all"&&{visibility:d},...p&&{metadata:{status:p}}},sortFields:[{field:m.startsWith("created")?"created":"updated",direction:m.endsWith("asc")?"asc":"desc"}],signal:t.signal},y=c==="collection"||Boolean(l),b=(w)=>({entity:B,path:T})=>{let F=B.entityType===o?w?.get(B.id):void 0;return{id:B.id,entityType:B.entityType,path:T,frontmatter:{...Lf(B.entityType,B.content,e).frontmatter,visibility:B.visibility},displayTitle:Tc(e,B),updated:B.updated,...F&&{members:F}}},v=async(w)=>await n?.(o,w.map(({entity:B})=>B).filter((B)=>B.entityType===o))??null;try{let w=await Hgi(e,o,i);if(w!==void 0){let F=await Ggi(e,{container:o,contained:w,prefix:c==="collection"?null:a,searching:y,limit:h,offset:f,base:g,titleOf:(L)=>Tc(e,L)}),k=await H7e(e,{entityType:w,prefix:F.prefix,folders:F.folders,visibilityScope:i.visibilityScope,signal:t.signal}),N=k.trail.map((L,G)=>F.trail?.[G]??L);return Oe({prefix:F.prefix,folders:k.folders,total:F.total,entities:F.entities.map(b(await v(F.entities))),...N.some((L)=>L!==null)&&{trail:N}})}let B=await e.entityService.queryEntityHierarchy({...g,entityType:o,prefix:c==="collection"?null:a,limit:h,offset:f,includeDescendants:y}),T=await H7e(e,{entityType:o,prefix:B.prefix,folders:B.folders,visibilityScope:i.visibilityScope,signal:t.signal});return Oe({prefix:B.prefix,folders:T.folders,total:B.totalEntities,entities:B.entities.map(b(await v(B.entities))),...T.trail.some((F)=>F!==null)&&{trail:T.trail}})}catch(w){if(w instanceof u.ZodError)return Oe({error:"Invalid folder prefix"},400);throw w}}async function iyi(e,t,i,n){let r;try{r=E4r.parse(await t.json())}catch{return Oe({error:"Invalid update payload"},400)}let{entityType:o,id:s}=r,a=e.entities.getEffectiveFrontmatterSchema(o);if(!a)return Oe({error:`Unknown entity type: ${o}`},404);let c=await Yoe(e,{entityType:o,id:s,visibilityScope:i.visibilityScope});if(!c)return Oe({error:`Entity not found: ${s}`},404);let l=q7e(e,o,r.body);if(l)return l;let d=oA(o,e.entities),p=YU(r.frontmatter);if(d&&Object.keys(p).length>0)return Oe({error:`Entity type ${o} is raw markdown without frontmatter`},400);let m=z7e(r.frontmatter,c.visibility);if(!m.success)return m.response;let h=d?u.object({}).safeParse({}):a.safeParse(p);if(!h.success)return $7e(h.error,p);let f=Lf(o,c.content,e),g=r.body??f.body,y=Object.fromEntries(Object.entries(h.data).filter(([L])=>Object.hasOwn(a.shape,L))),b=d?g:pr(g,U7e(y,m.visibility)),v=d||f.malformed?b:Pxe(c.content,b,a,[]),w=nyi(e,o,v);if(w instanceof Response)return w;let B={...c,...w,id:c.id,entityType:c.entityType,content:v,metadata:YU(w.metadata??c.metadata),visibility:m.visibility},T=()=>Uk(o,c,B,e.entityService).map((L)=>Nf(e,o,L,i)).find((L)=>L!==null)??null,F=T();if(F)return await ml(n,i,"update","denied",o,s,"entity-action-policy"),F;if(!km(i.permissionLevel,B.visibility))return await ml(n,i,"update","denied",o,s,"visibility-policy"),Oe({error:`Cannot set entity visibility to "${B.visibility}" at ${i.permissionLevel} permission.`},403);if(r.baseContentHash!==c.contentHash){if(v===c.content&&B.visibility===c.visibility)return Oe({entityId:s,jobId:"",skipped:!0});return Vgi(e,i,{existing:c,base:r.baseContentHash,text:v,declared:B.visibility})}let k=T();if(k)return await ml(n,i,"update","denied",o,s,"entity-action-policy"),k;let N;try{N=await e.entityService.updateEntity({entity:B,options:{...__(i),expectedContentHash:r.baseContentHash}})}catch(L){let G=T_(L);if(G)return G;throw L}if(N.skipReason==="content-conflict")return Vgi(e,i,{existing:c,base:r.baseContentHash,text:v,declared:B.visibility});return await ml(n,i,"update","allowed",o,s),Oe({entityId:N.entityId,jobId:N.jobId,skipped:N.skipped})}async function Vgi(e,t,i){let{existing:n,base:r,text:o,declared:s}=i,a=await Yoe(e,{entityType:n.entityType,id:n.id,visibilityScope:t.visibilityScope})??n,c=await e.messaging.request(d8,{entityType:a.entityType,entityId:a.id,origin:"studio",actor:t.principal.userId,base:r,current:a.contentHash,text:o,targetVisibility:a.visibility,...s!==a.visibility&&{declaredVisibility:s}});return Oe({error:c.status==="answered"?"This entry changed since it was opened. Your version is kept as a conflict in the Inbox; reload to review the current one.":"This entry changed since it was opened. Reload to review before saving again.",currentContentHash:a.contentHash,...c.status==="answered"&&{conflictId:c.data.conflictId}},409)}function nyi(e,t,i){try{return e.entityService.deserializeEntity(i,t)}catch(n){let r=T_(n);if(r)return r;throw n}}function ryi(e,t){let{entityType:i}=t,n=e.entities.getEffectiveFrontmatterSchema(i);if(!n)return Oe({error:`Unknown entity type: ${i}`},404);let r=q7e(e,i,t.body);if(r)return r;let o=oA(i,e.entities),s=YU(t.frontmatter);if(o&&Object.keys(s).length>0)return Oe({error:`Entity type ${i} is raw markdown without frontmatter`},400);let a=z7e(t.frontmatter,i===Xd?"shared":"public");if(!a.success)return a.response;let c=o?u.object({}).safeParse({}):n.safeParse(s);if(!c.success)return $7e(c.error,s);let l=o?t.body??"":pr(t.body??"",U7e(Object.fromEntries(Object.entries(c.data).filter(([p])=>Object.hasOwn(n.shape,p))),a.visibility)),d=nyi(e,i,l);if(d instanceof Response)return d;return{...d,...t.idPath&&{id:ww(t.idPath)},entityType:i,content:l,metadata:YU(d.metadata??{}),visibility:a.visibility}}async function oyi(e,t,i,n){let r,o;try{o=await t.json(),r=Ygi.parse(o)}catch(m){return Jgi(m,o)}let{entityType:s}=r;if(!e.entities.getEffectiveFrontmatterSchema(s))return Oe({error:`Unknown entity type: ${s}`},404);let c=Nf(e,s,"create",i);if(c)return await ml(n,i,"create","denied",s,void 0,"entity-action-policy"),c;await e.entities.ensureGroupingsCurrent();let l=ryi(e,r);if(l instanceof Response)return l;if(!km(i.permissionLevel,l.visibility))return await ml(n,i,"create","denied",s,void 0,"visibility-policy"),Oe({error:`Cannot set entity visibility to "${l.visibility}" at ${i.permissionLevel} permission.`},403);let d=Nf(e,s,"create",i);if(d)return await ml(n,i,"create","denied",s,void 0,"entity-action-policy"),d;if(r.idPath){let m=await Qgi(e,s,ww(r.idPath),l);if(m?.writable===!1){await ml(n,i,"create","denied",s,void 0,"invalid-placement");let h=r.idPath.length>1,f=m.owner?`reads as ${m.owner.entityType}/${m.owner.id}`:"was refused by directory-sync";return Oe({error:`This destination cannot be exported: ${m.relativePath} ${f}.`,issues:[{path:[h?"prefix":"segment"],message:h?"Choose a different folder for this entry.":"Choose a different segment."}]},400)}}let p;try{p=await e.entityService.createEntity({entity:l,options:{...__(i),...r.idPath&&{conditionalWrite:{expectedRevision:null}}}})}catch(m){let h=T_(m);if(h)return h;if(m instanceof Error&&m.name==="EntityWriteConflictError")return Oe({error:"An entry already exists at this destination.",issues:[{path:["segment"],message:"Choose a different segment."}]},409);throw m}return await ml(n,i,"create","allowed",s,p.entityId),Oe({entityId:p.entityId,jobId:p.jobId},201)}async function syi(e,t,i,n){try{A4r.parse(await t.json())}catch{return Oe({error:"Explicit delete confirmation required"},400)}let r=new URL(t.url).searchParams,o=r.get("type"),s=r.get("id");if(!o||!s)return Oe({error:"type and id query parameters are required"},400);if(!await Yoe(e,{entityType:o,id:s,visibilityScope:i.visibilityScope}))return Oe({error:`Entity not found: ${s}`},404);let c=Nf(e,o,"delete",i);if(c)return await ml(n,i,"delete","denied",o,s,"entity-action-policy"),c;let l=await e.entityService.deleteEntity({entityType:o,id:s,options:__(i)});if(l)await ml(n,i,"delete","allowed",o,s);return Oe({deleted:l})}var w4r=new Set(["string","text"]);async function ayi(e,t,i){if(!e.entityService.getEntityTypes().includes(t.entityType))return null;let n=await e.entityService.getEntityRaw({entityType:t.entityType,id:t.entityId,visibilityScope:t.visibilityScope,source:!0});if(!n)return null;let r=oA(t.entityType,e.entities)?void 0:e.entities.getEffectiveFrontmatterSchema(t.entityType),o=Object.entries(r?.shape??{}).flatMap(([s,a])=>{let c=Cx(s,a);return w4r.has(c.widget)&&!c.secret?[{name:s,label:c.label}]:[]});return{title:Tc(e,n)??n.id,typeLabel:pl(t.entityType,{...i?{label:i}:{}}).label.toLowerCase(),markdown:n.content,fields:[...o,{name:"body",label:"Body"}].slice(0,40)}}function Joe(e){let t=e.startsWith("/")?e:`/${e}`;return t==="/"?"":t.replace(/\/+$/,"")}function cyi(e,t){return`${Joe(e)}/entities/${encodeURIComponent(t)}`}function P_(e,t,i){return`${cyi(e,t)}/${encodeURIComponent(i)}`}function lyi(e,t,i){let n=new URL(cyi(e,t),"https://brains.invalid");if(n.searchParams.set("mode","create"),i!==void 0)n.searchParams.set("starter",i);return`${n.pathname}${n.search}`}function m8(e,t){return`${Joe(e)}/workspaces/${encodeURIComponent(t)}`}var uyi=(e)=>u.string().trim().min(1).max(e).refine((t)=>!/[\p{Cc}\p{Cf}]/u.test(t)),S4r=(e)=>u.string().trim().min(1).max(e).refine((t)=>Array.from(t).every((i)=>i===`
|
|
5512
5512
|
`||i==="\t"||!/[\p{Cc}\p{Cf}]/u.test(i))),k4r=u.strictObject({version:u.literal(2),entityType:u.literal("note"),title:uyi(160),body:S4r(1000).optional(),backlink:uyi(500).regex(/^entity:\/\/[^/]+\/.+$/)}),B4r=u.looseObject({studioCreatePrefill:k4r});function dyi(e,t,i){return B4r.parse({studioCreatePrefill:{version:2,entityType:"note",title:e,...i?{body:i}:{},backlink:t}})}function Z7e(e,t,i,n){let r=e.entityService.getEntityTypes().find((o)=>e.entityService.getEntityTypeConfig(o).consumesSources?.includes(t));if(r===void 0||!u8(e,t,"delete",i)||!u8(e,r,"create",i))return;return{entityType:r,label:pl(r,n?.[r]).label}}var C4r=u.object({entityType:u.string().min(1),ids:u.array(u.string().min(1)).min(1).max(51).refine((e)=>new Set(e).size===e.length,"Ids must be unique"),direction:u.string().max(2000).optional(),approval:u.record(u.string(),u.unknown()).optional()}).strict();async function myi(e,t,i,n){let r=C4r.safeParse(await t.json().catch(()=>{return}));if(!r.success)return Oe({error:"Invalid refine request"},400);let{entityType:o,ids:s,approval:a}=r.data;if(!e.entityService.getEntityTypes().some((h)=>e.entityService.getEntityTypeConfig(h).consumesSources?.includes(o)))return Oe({error:`Nothing refines ${o}`},400);let l=Z7e(e,o,i,n);if(!l)return Oe({error:"Refining needs delete permission"},403);let d=r.data.direction?.trim(),p=await e.messaging.request(pyi,{entityType:l.entityType,source:{entityType:o,entityIds:s},...d&&{prompt:d},...a&&{approval:a},actor:i.actor,interfaceType:"studio",userPermissionLevel:i.permissionLevel});if(p.status!=="answered")return Oe({error:"Refining is unavailable"},503);let m=p.data;if(m.status==="refused")return Oe({error:m.error},m.code==="source-not-found"?404:422);if(m.status==="confirm")return Oe({status:"confirm",summary:m.summary,approval:m.approval});return Oe({status:"queued",entityType:l.entityType,entityId:m.entityId})}var D4r=2,I4r=6,_4r=8;function T4r(e,t){let i=t.toLowerCase();return[e.title,e.sub??"",...e.keywords??[]].some((n)=>n.toLowerCase().includes(i))}function P4r(e){return{id:e.id,title:e.title,...e.sub?{sub:e.sub}:{},href:e.href}}function hyi(e){let t=e.query.trim(),i=t.toLowerCase(),n=(e.actions??[]).filter((o)=>!i||o.label.toLowerCase().includes(i)||o.workspaceLabel.toLowerCase().includes(i)).map((o)=>({id:`${o.workspaceId}:${o.name}`,title:o.label,sub:o.workspaceLabel,href:m8(e.routePath??"",o.workspaceId),run:{workspaceId:o.workspaceId,actionId:o.name}})),r=e.destinations.filter((o)=>t?T4r(o,t):o.primary===!0).slice(0,_4r).map(P4r);return{groups:[...n.length>0?[{id:"actions",label:"Actions",items:n}]:[],...r.length>0?[{id:"pages",label:"Pages",items:r}]:[],...e.entries.length>0?[{id:"entries",label:"Entries",items:[...e.entries]}]:[]]}}async function fyi(e){let t=e.query.trim();if(t.length<D4r)return[];return(await e.context.entityService.search({query:t,options:{limit:I4r,visibilityScope:e.visibilityScope}}).catch(()=>[])).map(({entity:n})=>({id:`${n.entityType}:${n.id}`,title:e.context.shapes.displayTitle(n)??n.id,sub:pl(n.entityType,e.entityDisplay?.[n.entityType]).label,href:P_(e.routePath,n.entityType,n.id)}))}var R4r="StudioAccountWorkspace",h8={id:Qoe,pluginId:"studio",label:"Account",rendererName:R4r,priority:0,permission:"public",entityTypes:[]},xyi={public:0,trusted:1,admin:2};function Xoe(e){if(xyi[e]<xyi[h8.permission])return[];return[{id:h8.id,pluginId:h8.pluginId,label:h8.label,rendererName:h8.rendererName,priority:h8.priority,permission:h8.permission,entityTypes:h8.entityTypes,section:"brain"}]}var sA="/chat",yyi="web-chat:chat";var gyi={public:0,trusted:1,admin:2};function byi(e,t){if(!t||gyi[e]<gyi.trusted)return[];return[{id:"web-chat:chat",pluginId:"studio",label:"Chat",rendererName:"StudioChatWorkspace",priority:-80,permission:"trusted",urlQuery:!0,chatApiPath:t,entityTypes:[],section:"chat"}]}var ese={public:0,trusted:1,admin:2};function tse(e){let t=e.routePath.replace(/\/+$/,""),i=ese[e.permissionLevel],n=(c)=>`${t}/workspaces/${encodeURIComponent(c)}`,r=[...e.workspaceRegistry.listOffered().filter((c)=>ese[c.permission]<=i),...Xoe(e.permissionLevel)].sort((c,l)=>c.priority-l.priority||c.id.localeCompare(l.id)).map((c)=>({id:`studio/${c.id}`,title:c.label,sub:"Studio",href:n(c.id),primary:!0})),o=e.hasChat&&i>=ese.trusted?[{id:"studio/chat",title:"Chat",sub:"Studio",href:sA,primary:!0}]:[],{entityService:s}=e.context,a=i>=ese.trusted?s.getEntityTypes().filter((c)=>s.getEntityTypeConfig(c).containedIn===void 0).map((c)=>({id:`studio/entities/${c}`,title:pl(c,e.entityDisplay?.[c]).pluralLabel,sub:s.getEntityTypeConfig(c).classification==="system"?"System":"Library",href:`${t}/entities/${encodeURIComponent(c)}`})):[];return[...r.slice(0,1),...o,...r.slice(1),...a]}import{join as nPe}from"path";var ise=u.string().regex(/^(?:studio-app-[a-zA-Z0-9]+\.(?:js|css|js\.map)|studio-chunks\/[a-zA-Z0-9_-]+\.(?:js|js\.map))$/),Eyi=u.object({version:u.literal(2),entrypoints:u.object({script:u.string().regex(/^studio-app-[a-zA-Z0-9]+\.js$/),stylesheet:u.string().regex(/^studio-app-[a-zA-Z0-9]+\.css$/)}),assets:u.record(ise,ise)}).refine((e)=>Object.values(e.entrypoints).every((t)=>e.assets[t]===t)&&Object.entries(e.assets).every(([t,i])=>t===i));var vyi=`/*
|
|
5513
5513
|
* Shared operator-console tokens and chrome.
|
|
5514
5514
|
*
|
|
@@ -9747,7 +9747,7 @@ Guidelines:
|
|
|
9747
9747
|
3. Depth: Provide enough detail to be useful as a reference, but stay focused on the topic.
|
|
9748
9748
|
4. Style: Informative and educational. Write as if explaining to yourself for future reference.
|
|
9749
9749
|
5. Length: Adjust based on topic complexity - concise for simple topics, more detailed for complex ones.
|
|
9750
|
-
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var rEo="Note entities are editable markdown notes. Use them for durable text captures, summaries, and imported markdown; raw files remain document or image entities instead of notes.",Z7=Yn(Lxe(dt({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:Rpe,markdown:Fpe,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:rEo,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:iHe(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:sHe},generation:nHe,create:{fromUpload:YNi},jobs:{"upload-import":KNi(()=>Z7)},evals:{generateNote:async(e,{ai:t})=>t.generate({template:"generation",prompt:u.object({prompt:u.string()}).parse(e).prompt,representedIdentity:"none"},u.object({title:u.string(),body:u.string()}))},atproto:tHe}),[Nxe(Ope,async({request:e,entities:t})=>{let{id:i,title:n,body:r}=e;if(await t.get(Z7,i))return{noteId:i,created:!1};return await t.create(Z7,{id:i,content:r,metadata:{title:n,titleStated:!0},visibility:"restricted"}),{noteId:i,created:!0}})]),W7);var oEo=Rn({id:"note",config:eHe,entities:[Z7]}),QNi=oEo;var sEo=u.object({type:u.literal("email"),address:u.string().max(0).optional()}).transform(()=>{return}),aEo=u.looseObject({defaultRecipient:sEo.or(XNi).optional()}),cEo=zt({id:"notifications",config:aEo},{subscriptions:(e)=>{let{config:t}=e,i=ft(e),{logger:n}=i;return i.answer(F1,async({request:r})=>{let o=r.recipient??t.defaultRecipient;if(!o)return n.warn(Npe.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=i.deliveryProvider(o.type);if(!s||!await s.isAvailable())return n.warn(Npe.transportMissing,{channelType:o.type}),{status:"failed",failure:"transport-missing"};let a=await s.send({recipient:o.address,subject:r.title,text:r.body,...r.html?{html:r.html}:{},...r.replyTo?{replyTo:r.replyTo}:{},sensitivity:r.sensitivity,idempotencyKey:r.idempotencyKey??crypto.randomUUID()});if(a.status!=="sent"){n.warn(Npe.deliveryFailed,{transportCode:a.failureCode});let c=eLi.safeParse(a.failureCode);return{status:"failed",failure:"delivery-failed",...c.success&&{transportCode:c.data}}}return a.providerDeliveryId?{status:"sent",deliveryId:a.providerDeliveryId}:{status:"sent"}},{everyProcess:!0}),[]}}),tLi=cEo;var nLi=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],lEo=u.looseObject({elements:u.array(u.looseObject({snapshotDomain:u.string(),snapshotData:u.array(u.record(u.string(),u.unknown()))})),paging:u.looseObject({links:u.array(u.looseObject({rel:u.string().optional(),href:u.string().optional()})).optional()}).optional()}),uEo="https://api.linkedin.com/rest",dEo="202312",iLi=1000,pEo=1000;function mEo(e){return e.toLowerCase().includes("no data found for this memberid")}function hEo(e,t){let i=e.paging?.links?.find((r)=>r.rel==="next")?.href,n=i?Number(new URL(i,"https://api.linkedin.com").searchParams.get("start")):Number.NaN;return Number.isInteger(n)&&n>t?n:t+1}class oG{accessToken;fetchFn;constructor(e,t=globalThis.fetch){this.accessToken=e,this.fetchFn=t}fetchProfile(){return this.fetchDomain("PROFILE")}fetchDomain(e){return this.fetchPages(e,0,0)}async fetchPages(e,t,i){if(i===iLi)throw Error(`LinkedIn snapshot exceeded ${iLi} pages`);let n=await this.fetchPage(e,t),r=(n?.elements??[]).filter((o)=>o.snapshotDomain===e).flatMap((o)=>o.snapshotData);if(!n||r.length===0)return r;return[...r,...await this.fetchPages(e,hEo(n,t),i+1)]}async fetchPage(e,t){let i=new URL(`${uEo}/memberSnapshotData`);i.searchParams.set("q","criteria"),i.searchParams.set("domain",e),i.searchParams.set("start",String(t));let n=await this.fetchFn(i,{headers:{Authorization:`Bearer ${this.accessToken}`,"Linkedin-Version":dEo}});if(n.ok)return lEo.parse(await n.json());let r=await n.text();if(n.status<500&&mEo(r))return null;throw new Lpe(n.status,r.slice(0,pEo))}}class Lpe extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var fEo=rLi({title:"LinkedIn",description:"The LinkedIn connection the LinkedIn import reads your profile with. Connect from the LinkedIn workspace, or paste a member token with the r_dma_portability_3rd_party scope.",schema:u.object({accessToken:u.string().trim().min(1),expiresAt:u.iso.datetime().optional()}),fields:{accessToken:{label:"Access token",secret:!0},expiresAt:{label:"Expires (ISO date and time)"}}});class aHe{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:fEo})}async get(e){return this.registry.getForActor(this.registration,e)}async save(e,t){await this.registry.save(this.registration.id,e,{accessToken:t.accessToken,expiresAt:t.expiresAt})}async forget(e){await this.registry.delete(this.registration.id,e)}}function cHe(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var xEo="https://www.linkedin.com/oauth/v2/authorization",gEo="https://www.linkedin.com/oauth/v2/accessToken",oLi="r_dma_portability_3rd_party",yEo=500,bEo=u.looseObject({access_token:u.string().min(1),expires_in:u.number().int().positive(),scope:u.string().optional()}),EEo=u.looseObject({error:u.string().optional(),error_description:u.string().optional()});async function vEo(e){try{return await e.json()}catch{return null}}class aG{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(xEo);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",this.config.clientId),t.searchParams.set("redirect_uri",this.config.redirectUri),t.searchParams.set("state",e),t.searchParams.set("scope",oLi),t}async exchange(e,t){let i=await this.fetchFn(gEo,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,client_id:this.config.clientId,client_secret:this.config.clientSecret,redirect_uri:this.config.redirectUri}).toString()}),n=await vEo(i);if(!i.ok){let o=EEo.safeParse(n),s=o.success?[o.data.error,o.data.error_description].filter(Boolean).join(": "):"";throw Error(`LinkedIn refused the code (${i.status})${s?`: ${s.slice(0,yEo)}`:""}`)}let r=bEo.parse(n);if(r.scope!==void 0&&r.scope!==oLi)throw Error("LinkedIn granted a token without the portability scope");return{accessToken:r.access_token,expiresAt:new Date(t+r.expires_in*1000).toISOString()}}}function aLi(e){return new sG({...sLi,now:e})}var jpe="linkedin",AEo=u.strictObject({accessToken:u.string().min(1),expiresAt:u.iso.datetime()});function lHe(e,t={}){let i=(r)=>new aG({...e,redirectUri:r},t.fetch),n=t.now??Date.now;return{id:jpe,authorizationUrl:({redirectUri:r,state:o})=>i(r).authorizationUrl(o),exchange:async({code:r,redirectUri:o})=>{let s=await i(o).exchange(r,n());return{accessToken:s.accessToken,expiresAt:s.expiresAt}}}}class uHe{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(V7.authorizations,{provider:jpe,brainState:e},"the connection");return new URL(cLi.parse(t).authorizationUrl)}async redeem(e){let t=lLi.parse(await this.post(V7.redeem,{provider:jpe,grant:e},"grant redemption"));if(t.provider!==jpe)throw Error("OAuth broker redeemed a grant for another provider");return AEo.parse(t.credential)}async post(e,t,i){let{instanceId:n,secret:r}=this.config,o=await this.fetchFn(new URL(e,this.config.url),{method:"POST",headers:{Accept:"application/json",Authorization:`Basic ${Buffer.from(`${n}:${r}`).toString("base64")}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)throw Error(`OAuth broker refused ${i} (${o.status})`);return o.json()}}function wEo(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function B9(e,t){return e.map((i)=>wEo(i[t])).find(Boolean)}function uLi(e){let t=[B9(e,"First Name"),B9(e,"Last Name")].filter(Boolean).join(" ")||void 0,i=B9(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],n={name:t,headline:B9(e,"Headline"),industry:B9(e,"Industry"),location:B9(e,"Geo Location"),website:i,story:B9(e,"Summary")};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function dLi(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new bi(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new bi("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class dHe{messaging;fetchFn;constructor(e,t){this.messaging=e,this.fetchFn=t}async preview(e){return this.previewFields(await this.imported(e))}async apply(e){let t=await this.imported(e),{revision:i}=await this.previewFields(t);return dLi(await this.messaging.request(lG,{fields:t,revision:i}))}async previewFields(e){return dLi(await this.messaging.request(cG,{fields:e}))}async imported(e){let t=new oG(e,this.fetchFn);return uLi(await t.fetchProfile())}}var pHe="/linkedin/oauth/start",dG="/linkedin/oauth/callback",pG="/linkedin/oauth/broker/return";function pLi(e){return e?.permissionLevel==="admin"&&e.isAnchor}function uG(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function hLi(e){let t=(c)=>{let l=e.workspaceUrl(),d=l.includes("?")?"&":"?";return uG(303,`${l}${d}connection=${c}`)},i=async(c,l)=>{let d=e.states.take(l),p=await e.resolveSession(c);return d&&pLi(p)&&p?.userId===d?d:null},n=async(c,l)=>{try{return await e.connections.save(c,await l()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${he(d)}`),t("failed")}},r=async(c)=>{let l=await e.resolveSession(c);if(!l)return uG(401);if(!pLi(l))return uG(403);let d=e.states.issue(l.userId),{mode:p}=e;if(p.kind==="direct")return uG(302,p.oauth.authorizationUrl(d).toString());try{return uG(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${he(m)}`),t("failed")}},o=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await i(l,d.get("state")??"");if(!p)return t("failed");if(d.has("error"))return t("declined");let m=d.get("code");if(!m)return t("failed");return n(p,()=>c.exchange(m,e.now()))},s=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await i(l,d.get("state")??""),m=mLi.safeParse(Object.fromEntries(d));if(!p||!m.success)return t("failed");if("error"in m.data)return t(m.data.error==="provider_denied"?"declined":"failed");let{grant:h}=m.data;return n(p,()=>c.redeem(h))},{mode:a}=e;return[{path:pHe,method:"GET",public:!0,handler:r},a.kind==="direct"?{path:dG,method:"GET",public:!0,handler:o(a.oauth)}:{path:pG,method:"GET",public:!0,handler:s(a.broker)}]}var SEo=/^(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)\s+\d{4}$/i,kEo=[[/^$/,"<empty-string>"],[/^urn:/i,"<urn>"],[/^[^\s@]+@[^\s@]+\.[^\s@]+$/,"<email>"],[/^https?:\/\//i,"<url>"],[/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/,"<timestamp>"],[/^\d{4}-\d{2}-\d{2}$/,"<year-month-day>"],[/^\d{4}-\d{2}$/,"<year-month>"],[/^\d{4}$/,"<year>"],[SEo,"<month-year>"]];function gLi(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return t==="boolean"||t==="number"||t==="object"?t:"string"}function fLi(e){if(typeof e!=="string")return`<${gLi(e)}>`;let t=e.trim();return kEo.find(([i])=>i.test(t))?.[1]??"<string>"}function BEo(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(fLi))].sort();return fLi(e)}function xLi([e],[t]){return e.localeCompare(t)}function CEo(e){let t=e.flatMap((o)=>Object.entries(o)),n=[...new Set(t.map(([o])=>o))].sort().map((o)=>{let s=t.filter(([a])=>a===o);return{name:o,types:[...new Set(s.map(([,a])=>gLi(a)))].sort(),presentCount:s.length}}),r=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(xLi).map(([a,c])=>[a,BEo(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:n,recordShapes:[...r].sort(xLi).map(([,o])=>o)}}async function yLi(e){let t=await Promise.all(nLi.map(async(i)=>[i,CEo(await e.fetchDomain(i))]));return Object.fromEntries(t)}var SLi={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},DEo={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},IEo={connected:{tone:"good",text:"LinkedIn is connected."},declined:{tone:"neutral",text:"LinkedIn connection was declined. Connect again when you are ready."},failed:{tone:"warn",text:"LinkedIn could not be connected. Start the connection again."}},bLi=200,xHe=Vi({name:"import-profile",label:"Import from LinkedIn",permission:"admin",confirmation:{kind:"prepared"},input:u.object({}),output:u.object({filled:u.array(u.string()),kept:u.array(u.string())})}),zpe=Vi({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:u.object({}),output:u.object({disconnected:u.boolean()})}),gHe=Vi({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:u.object({}),output:u.object({shapes:u.string()})}),yHe=u.object({connection:u.enum(["connected","declined","failed"]).optional()}),_Eo=u.object({field:u.enum(["name","headline","industry","location","website","story"]),current:u.string().nullable(),imported:u.string(),outcome:u.enum(["fill","preserve","unchanged"])}),mHe=yHe.shape.connection,TEo=u.discriminatedUnion("status",[u.object({status:u.literal("disconnected"),expired:u.boolean(),startUrl:u.string(),connection:mHe}),u.object({status:u.literal("unavailable"),message:u.string(),startUrl:u.string(),connection:mHe}),u.object({status:u.literal("ready"),fields:u.array(_Eo),connection:mHe})]);function ELi(e){if(e===null)return"\u2014";return e.length>bLi?`${e.slice(0,bLi-1)}\u2026`:e}function vLi(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function ALi(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function hHe(e){let t=e.connection?IEo[e.connection]:null;return t?[{type:"notice",...t}]:[]}var wLi=Fo({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",section:"library",query:yHe,data:TEo,actions:[xHe,zpe,gHe],view:({data:e})=>{if(e.status==="disconnected")return{kicker:"Profile import",title:"LinkedIn",description:"Connect your LinkedIn account to fill your profile from it. Only members in the European Economic Area can connect.",status:{label:"Not connected",tone:"neutral"},blocks:[...hHe(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],ALi(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...hHe(e),{type:"notice",tone:"warn",text:e.message},ALi(e.startUrl,"Connect LinkedIn again"),{type:"action",action:zpe,input:{}}]};let t=e.fields.some((i)=>i.outcome==="fill");return{kicker:"Profile import",title:"LinkedIn",description:"What LinkedIn holds for each profile field, and what an import would do with it.",status:{label:t?"Ready to import":"Profile already complete",tone:t?"good":"neutral"},...t?{primaryAction:{action:xHe,input:{}}}:{},blocks:[...hHe(e),{type:"table",id:"linkedin-fields",empty:"LinkedIn holds no profile fields for this account.",columns:[{key:"field",label:"Field"},{key:"current",label:"Your profile"},{key:"imported",label:"LinkedIn"},{key:"outcome",label:"Import"}],rows:e.fields.map((i)=>({id:i.field,cells:{field:SLi[i.field],current:ELi(i.current),imported:ELi(i.imported),outcome:DEo[i.outcome]}}))},{type:"card",id:"linkedin-shapes",label:"Data shapes",blocks:[{type:"text",text:"Field names, value types and record forms of your skills, positions, education and certifications on LinkedIn, with every value replaced, for writing import fixtures."},{type:"action",action:gHe,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:zpe,input:{}}]}}});function fHe(e){if(e?.permission!=="admin"||!e.isAnchor)throw new bi("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function PEo(e){if(e instanceof Lpe&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${he(e)}`}async function kLi(e,t){if(!e.isAvailable())return;let i=async(r)=>{let o=await t.connections.get(fHe(r));if(!o||cHe(o))throw new bi("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},n=e.source({definition:wLi,bind:(r)=>wLi.bind(r,{load:async({caller:o,query:s})=>{let a=fHe(o),{connection:c}=s.get(yHe),l=await t.connections.get(a);if(!l||cHe(l))return{status:"disconnected",expired:l!==null,startUrl:t.startUrl,connection:c};try{return{status:"ready",fields:(await t.profileImport.preview(l.accessToken)).fields,connection:c}}catch(d){return{status:"unavailable",message:PEo(d),startUrl:t.startUrl,connection:c}}},actions:[xHe.bind(r,async({caller:o})=>t.profileImport.apply((await i(o)).accessToken),async({caller:o})=>{let s=await t.profileImport.preview((await i(o)).accessToken),a=(d)=>s.fields.filter((p)=>p.outcome===d).map((p)=>SLi[p.field].toLowerCase()),c=a("fill"),l=a("preserve");if(c.length===0)throw new bi("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${vLi(c)} from LinkedIn?${l.length>0?` Your ${vLi(l)} stay as you wrote them.`:""}`,revision:s.revision}}),gHe.bind(r,async({caller:o})=>{let s=await yLi(t.clientFor((await i(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),zpe.bind(r,async({caller:o})=>(await t.connections.forget(fHe(o)),{disconnected:!0}))]})});return e.register({...n,accessHandler:async(r)=>r.isAnchor&&await n.accessHandler(r)})}var BLi={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.853",description:"Import the owner's LinkedIn profile into the anchor profile from Studio",dependencies:{"@brains/contracts":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/profile":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","bun-types":"^1.4.0",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./broker-provider":"./src/broker-provider.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var FEo="/studio",MEo=u.object({clientId:u.string().trim().min(1).describe("LinkedIn app client ID"),clientSecret:u.string().trim().min(1).describe("LinkedIn app client secret"),redirectUri:u.url({protocol:/^https?$/}).describe(`This brain's callback URL ending at ${dG}, registered with the LinkedIn app`)}),OEo=u.object({url:u.url({protocol:/^https$/}).describe("The managed broker's origin"),instanceId:u.string().trim().min(1).describe("This brain's broker instance"),secret:u.string().min(32).describe("This brain's broker instance secret"),returnUri:u.url({protocol:/^https?$/}).describe(`This brain's return URL ending at ${pG}, registered with the broker`)}),CLi=u.object({oauth:MEo.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:OEo.optional().describe("The managed broker holding the shared LinkedIn app")});function NEo(e,t){let{oauth:i,broker:n}=e;if(i&&n)throw Error("linkedin-import: configure either oauth (direct) or broker, not both");if(i&&new URL(i.redirectUri).pathname!==dG)throw Error(`linkedin-import: oauth.redirectUri must end at ${dG}`);if(n&&new URL(n.returnUri).pathname!==pG)throw Error(`linkedin-import: broker.returnUri must end at ${pG}`);if(i)return{kind:"direct",oauth:new aG(i,t.fetch)};if(n)return{kind:"broker",broker:new uHe(n,t.fetch)};return null}function DLi(e={}){let t=zt({id:"linkedin-import",config:CLi,setup:(i)=>{let{config:n}=i,r=NEo(n,e),o=n.oauth?.redirectUri??n.broker?.returnUri;if(!r||!o)return{routes:[]};let s=ft(i),a=new aHe(s.accountSettings,{pluginId:s.pluginId,packageName:BLi.name}),c=FEo;return s.registered(async()=>{let l=await kLi(s.studio,{profileImport:new dHe(s.messaging,e.fetch),clientFor:(d)=>new oG(d,e.fetch),connections:a,startUrl:new URL(pHe,o).toString()});if(l)c=l}),{routes:hLi({mode:r,states:aLi(),connections:a,resolveSession:async(l)=>s.auth()?.resolveSession(l),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return Do(t,({state:i})=>i.routes)}var bHe=DLi();import{createHash as LEo,timingSafeEqual as jEo}from"crypto";function ILi(e){return LEo("sha256").update(e).digest()}function zEo(e){if(!e?.startsWith("Basic "))return null;let t=Buffer.from(e.slice(6),"base64").toString("utf8"),i=t.indexOf(":");if(i<=0||i===t.length-1)return null;return{id:t.slice(0,i),secret:t.slice(i+1)}}class EHe{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:ILi(t.secret)}]))}authenticate(e){let t=zEo(e.headers.get("authorization")),i=t?this.instances.get(t.id):void 0;if(!t||!i)return null;return jEo(ILi(t.secret),i.secretHash)?{id:i.id,returnUris:i.returnUris}:null}}var UEo=10,qEo=600000,AHe={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function rk(e,t=200){return Response.json(e,{status:t,headers:AHe})}function _Li(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...AHe,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function TLi(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function Upe(e,t){let i=new URL(e.returnUri);return i.searchParams.set("provider",e.provider),i.searchParams.set("state",e.brainState),Object.entries(t).forEach(([n,r])=>i.searchParams.set(n,r)),new Response(null,{status:303,headers:{...AHe,Location:i.toString()}})}function FLi(e){let t=new Map(e.providers.map((c)=>[c.id,c])),i=new Map,n=(c)=>{let l=e.now(),d=(i.get(c)??[]).filter((m)=>m>l-qEo),p=d.length<UEo;return i.set(c,p?[...d,l]:d),p},r=(c)=>new URL(vHe(c),e.publicUrl).toString(),o=async(c)=>{let l=e.instances.authenticate(c);if(!l)return _Li();let d=PLi.safeParse(await TLi(c));if(!d.success)return rk({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=l.returnUris[d.data.provider];if(!p||!m)return rk({error:"Provider is unavailable for this instance"},400);if(!n(l.id))return rk({error:"Too many connections started; try later"},429);let h=e.authorizations.issue({provider:p.id,instanceId:l.id,returnUri:m,brainState:d.data.brainState}),f=p.authorizationUrl({redirectUri:r(p.id),state:h}).toString();return rk({authorizationUrl:f})},s=async(c)=>{let l=e.instances.authenticate(c);if(!l)return _Li();let d=RLi.safeParse(await TLi(c));if(!d.success)return rk({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,m=e.grants.take(d.data.grant,(h)=>h.provider===p&&h.instanceId===l.id);if(!m)return rk({error:"Invalid or expired grant"},400);return rk({provider:p,credential:m.credential})},a=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=e.authorizations.take(d.get("state")??"",(h)=>h.provider===c.id);if(!p)return rk({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return Upe(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return Upe(p,{error:"authorization_incomplete"});try{let h=await c.exchange({code:m,redirectUri:r(c.id)}),f=e.grants.issue({provider:c.id,instanceId:p.instanceId,credential:h});return Upe(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${he(h)}`),Upe(p,{error:"credential_exchange_failed"})}};return[{path:V7.authorizations,method:"POST",public:!0,handler:o},{path:V7.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:vHe(c.id),method:"GET",public:!0,handler:a(c)}))]}var $Eo=600000,HEo=120000,MLi=1000,GEo=u.object({clientId:u.string().trim().min(1),clientSecret:u.string().trim().min(1)}),WEo=u.object({id:u.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/),secret:u.string().min(32).describe("Revocable instance secret"),returnUris:u.record(wHe,u.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),OLi=u.object({publicUrl:u.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:u.record(wHe,GEo).default({}).describe("Per provider, the shared app the broker holds"),instances:u.array(WEo).default([])});function ZEo(e,t){return Object.entries(e.providers).map(([i,n])=>{let r=t.providers[i];if(!r)throw Error(`oauth-broker: no adapter for provider "${i}"`);let o=r(n);if(o.id!==i)throw Error(`oauth-broker: adapter for "${i}" reports provider "${o.id}"`);return o})}function SHe(e){let t=zt({id:"oauth-broker",config:OLi,setup:(i)=>{let{config:n}=i,r=ZEo(n,e);if(n.instances.length===0||r.length===0)return{routes:[]};return{routes:FLi({publicUrl:n.publicUrl,providers:r,instances:new EHe(n.instances),authorizations:new sG({ttlMs:$Eo,maxPending:MLi,now:e.now}),grants:new sG({ttlMs:HEo,maxPending:MLi,now:e.now}),now:e.now??Date.now,logger:ft(i).logger})}}});return Do(t,({state:i})=>i.routes)}var VEo=2592000000,mG=(e,t)=>Ht(`${e}
|
|
9750
|
+
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var rEo="Note entities are editable markdown notes. Use them for durable text captures, summaries, and imported markdown; raw files remain document or image entities instead of notes.",Z7=Yn(Lxe(dt({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:Rpe,markdown:Fpe,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:rEo,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:iHe(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:sHe},generation:nHe,create:{fromUpload:YNi},jobs:{"upload-import":KNi(()=>Z7)},evals:{generateNote:async(e,{ai:t})=>t.generate({template:"generation",prompt:u.object({prompt:u.string()}).parse(e).prompt,representedIdentity:"none"},u.object({title:u.string(),body:u.string()}))},atproto:tHe}),[Nxe(Ope,async({request:e,entities:t})=>{let{id:i,title:n,body:r}=e;if(await t.get(Z7,i))return{noteId:i,created:!1};return await t.create(Z7,{id:i,content:r,metadata:{title:n,titleStated:!0},visibility:"restricted"}),{noteId:i,created:!0}})]),W7);var oEo=Rn({id:"note",config:eHe,entities:[Z7]}),QNi=oEo;var sEo=u.object({type:u.literal("email"),address:u.string().max(0).optional()}).transform(()=>{return}),aEo=u.looseObject({defaultRecipient:sEo.or(XNi).optional()}),cEo=zt({id:"notifications",config:aEo},{subscriptions:(e)=>{let{config:t}=e,i=ft(e),{logger:n}=i;return i.answer(F1,async({request:r})=>{let o=r.recipient??t.defaultRecipient;if(!o)return n.warn(Npe.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=i.deliveryProvider(o.type);if(!s||!await s.isAvailable())return n.warn(Npe.transportMissing,{channelType:o.type}),{status:"failed",failure:"transport-missing"};let a=await s.send({recipient:o.address,subject:r.title,text:r.body,...r.html?{html:r.html}:{},...r.replyTo?{replyTo:r.replyTo}:{},sensitivity:r.sensitivity,idempotencyKey:r.idempotencyKey??crypto.randomUUID()});if(a.status!=="sent"){n.warn(Npe.deliveryFailed,{transportCode:a.failureCode});let c=eLi.safeParse(a.failureCode);return{status:"failed",failure:"delivery-failed",...c.success&&{transportCode:c.data}}}return a.providerDeliveryId?{status:"sent",deliveryId:a.providerDeliveryId}:{status:"sent"}},{everyProcess:!0}),[]}}),tLi=cEo;var nLi=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],lEo=u.looseObject({elements:u.array(u.looseObject({snapshotDomain:u.string(),snapshotData:u.array(u.record(u.string(),u.unknown()))})),paging:u.looseObject({links:u.array(u.looseObject({rel:u.string().optional(),href:u.string().optional()})).optional()}).optional()}),uEo="https://api.linkedin.com/rest",dEo="202312",iLi=1000,pEo=1000;function mEo(e){return e.toLowerCase().includes("no data found for this memberid")}function hEo(e,t){let i=e.paging?.links?.find((r)=>r.rel==="next")?.href,n=i?Number(new URL(i,"https://api.linkedin.com").searchParams.get("start")):Number.NaN;return Number.isInteger(n)&&n>t?n:t+1}class oG{accessToken;fetchFn;constructor(e,t=globalThis.fetch){this.accessToken=e,this.fetchFn=t}fetchProfile(){return this.fetchDomain("PROFILE")}fetchDomain(e){return this.fetchPages(e,0,0)}async fetchPages(e,t,i){if(i===iLi)throw Error(`LinkedIn snapshot exceeded ${iLi} pages`);let n=await this.fetchPage(e,t),r=(n?.elements??[]).filter((o)=>o.snapshotDomain===e).flatMap((o)=>o.snapshotData);if(!n||r.length===0)return r;return[...r,...await this.fetchPages(e,hEo(n,t),i+1)]}async fetchPage(e,t){let i=new URL(`${uEo}/memberSnapshotData`);i.searchParams.set("q","criteria"),i.searchParams.set("domain",e),i.searchParams.set("start",String(t));let n=await this.fetchFn(i,{headers:{Authorization:`Bearer ${this.accessToken}`,"Linkedin-Version":dEo}});if(n.ok)return lEo.parse(await n.json());let r=await n.text();if(n.status<500&&mEo(r))return null;throw new Lpe(n.status,r.slice(0,pEo))}}class Lpe extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var fEo=rLi({title:"LinkedIn",description:"The LinkedIn connection the LinkedIn import reads your profile with. Connect from the LinkedIn workspace, or paste a member token with the r_dma_portability_3rd_party scope.",schema:u.object({accessToken:u.string().trim().min(1),expiresAt:u.iso.datetime().optional()}),fields:{accessToken:{label:"Access token",secret:!0},expiresAt:{label:"Expires (ISO date and time)"}}});class aHe{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:fEo})}async get(e){return this.registry.getForActor(this.registration,e)}async save(e,t){await this.registry.save(this.registration.id,e,{accessToken:t.accessToken,expiresAt:t.expiresAt})}async forget(e){await this.registry.delete(this.registration.id,e)}}function cHe(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var xEo="https://www.linkedin.com/oauth/v2/authorization",gEo="https://www.linkedin.com/oauth/v2/accessToken",oLi="r_dma_portability_3rd_party",yEo=500,bEo=u.looseObject({access_token:u.string().min(1),expires_in:u.number().int().positive(),scope:u.string().optional()}),EEo=u.looseObject({error:u.string().optional(),error_description:u.string().optional()});async function vEo(e){try{return await e.json()}catch{return null}}class aG{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(xEo);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",this.config.clientId),t.searchParams.set("redirect_uri",this.config.redirectUri),t.searchParams.set("state",e),t.searchParams.set("scope",oLi),t}async exchange(e,t){let i=await this.fetchFn(gEo,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,client_id:this.config.clientId,client_secret:this.config.clientSecret,redirect_uri:this.config.redirectUri}).toString()}),n=await vEo(i);if(!i.ok){let o=EEo.safeParse(n),s=o.success?[o.data.error,o.data.error_description].filter(Boolean).join(": "):"";throw Error(`LinkedIn refused the code (${i.status})${s?`: ${s.slice(0,yEo)}`:""}`)}let r=bEo.parse(n);if(r.scope!==void 0&&r.scope!==oLi)throw Error("LinkedIn granted a token without the portability scope");return{accessToken:r.access_token,expiresAt:new Date(t+r.expires_in*1000).toISOString()}}}function aLi(e){return new sG({...sLi,now:e})}var jpe="linkedin",AEo=u.strictObject({accessToken:u.string().min(1),expiresAt:u.iso.datetime()});function lHe(e,t={}){let i=(r)=>new aG({...e,redirectUri:r},t.fetch),n=t.now??Date.now;return{id:jpe,authorizationUrl:({redirectUri:r,state:o})=>i(r).authorizationUrl(o),exchange:async({code:r,redirectUri:o})=>{let s=await i(o).exchange(r,n());return{accessToken:s.accessToken,expiresAt:s.expiresAt}}}}class uHe{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(V7.authorizations,{provider:jpe,brainState:e},"the connection");return new URL(cLi.parse(t).authorizationUrl)}async redeem(e){let t=lLi.parse(await this.post(V7.redeem,{provider:jpe,grant:e},"grant redemption"));if(t.provider!==jpe)throw Error("OAuth broker redeemed a grant for another provider");return AEo.parse(t.credential)}async post(e,t,i){let{instanceId:n,secret:r}=this.config,o=await this.fetchFn(new URL(e,this.config.url),{method:"POST",headers:{Accept:"application/json",Authorization:`Basic ${Buffer.from(`${n}:${r}`).toString("base64")}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)throw Error(`OAuth broker refused ${i} (${o.status})`);return o.json()}}function wEo(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function B9(e,t){return e.map((i)=>wEo(i[t])).find(Boolean)}function uLi(e){let t=[B9(e,"First Name"),B9(e,"Last Name")].filter(Boolean).join(" ")||void 0,i=B9(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],n={name:t,headline:B9(e,"Headline"),industry:B9(e,"Industry"),location:B9(e,"Geo Location"),website:i,story:B9(e,"Summary")};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}function dLi(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new bi(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new bi("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class dHe{messaging;fetchFn;constructor(e,t){this.messaging=e,this.fetchFn=t}async preview(e){return this.previewFields(await this.imported(e))}async apply(e){let t=await this.imported(e),{revision:i}=await this.previewFields(t);return dLi(await this.messaging.request(lG,{fields:t,revision:i}))}async previewFields(e){return dLi(await this.messaging.request(cG,{fields:e}))}async imported(e){let t=new oG(e,this.fetchFn);return uLi(await t.fetchProfile())}}var pHe="/linkedin/oauth/start",dG="/linkedin/oauth/callback",pG="/linkedin/oauth/broker/return";function pLi(e){return e?.permissionLevel==="admin"&&e.isAnchor}function uG(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function hLi(e){let t=(c)=>{let l=e.workspaceUrl(),d=l.includes("?")?"&":"?";return uG(303,`${l}${d}connection=${c}`)},i=async(c,l)=>{let d=e.states.take(l),p=await e.resolveSession(c);return d&&pLi(p)&&p?.userId===d?d:null},n=async(c,l)=>{try{return await e.connections.save(c,await l()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${he(d)}`),t("failed")}},r=async(c)=>{let l=await e.resolveSession(c);if(!l)return uG(401);if(!pLi(l))return uG(403);let d=e.states.issue(l.userId),{mode:p}=e;if(p.kind==="direct")return uG(302,p.oauth.authorizationUrl(d).toString());try{return uG(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${he(m)}`),t("failed")}},o=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await i(l,d.get("state")??"");if(!p)return t("failed");if(d.has("error"))return t("declined");let m=d.get("code");if(!m)return t("failed");return n(p,()=>c.exchange(m,e.now()))},s=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await i(l,d.get("state")??""),m=mLi.safeParse(Object.fromEntries(d));if(!p||!m.success)return t("failed");if("error"in m.data)return t(m.data.error==="provider_denied"?"declined":"failed");let{grant:h}=m.data;return n(p,()=>c.redeem(h))},{mode:a}=e;return[{path:pHe,method:"GET",public:!0,handler:r},a.kind==="direct"?{path:dG,method:"GET",public:!0,handler:o(a.oauth)}:{path:pG,method:"GET",public:!0,handler:s(a.broker)}]}var SEo=/^(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)\s+\d{4}$/i,kEo=[[/^$/,"<empty-string>"],[/^urn:/i,"<urn>"],[/^[^\s@]+@[^\s@]+\.[^\s@]+$/,"<email>"],[/^https?:\/\//i,"<url>"],[/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/,"<timestamp>"],[/^\d{4}-\d{2}-\d{2}$/,"<year-month-day>"],[/^\d{4}-\d{2}$/,"<year-month>"],[/^\d{4}$/,"<year>"],[SEo,"<month-year>"]];function gLi(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return t==="boolean"||t==="number"||t==="object"?t:"string"}function fLi(e){if(typeof e!=="string")return`<${gLi(e)}>`;let t=e.trim();return kEo.find(([i])=>i.test(t))?.[1]??"<string>"}function BEo(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(fLi))].sort();return fLi(e)}function xLi([e],[t]){return e.localeCompare(t)}function CEo(e){let t=e.flatMap((o)=>Object.entries(o)),n=[...new Set(t.map(([o])=>o))].sort().map((o)=>{let s=t.filter(([a])=>a===o);return{name:o,types:[...new Set(s.map(([,a])=>gLi(a)))].sort(),presentCount:s.length}}),r=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(xLi).map(([a,c])=>[a,BEo(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:n,recordShapes:[...r].sort(xLi).map(([,o])=>o)}}async function yLi(e){let t=await Promise.all(nLi.map(async(i)=>[i,CEo(await e.fetchDomain(i))]));return Object.fromEntries(t)}var SLi={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},DEo={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},IEo={connected:{tone:"good",text:"LinkedIn is connected."},declined:{tone:"neutral",text:"LinkedIn connection was declined. Connect again when you are ready."},failed:{tone:"warn",text:"LinkedIn could not be connected. Start the connection again."}},bLi=200,xHe=Vi({name:"import-profile",label:"Import from LinkedIn",permission:"admin",confirmation:{kind:"prepared"},input:u.object({}),output:u.object({filled:u.array(u.string()),kept:u.array(u.string())})}),zpe=Vi({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:u.object({}),output:u.object({disconnected:u.boolean()})}),gHe=Vi({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:u.object({}),output:u.object({shapes:u.string()})}),yHe=u.object({connection:u.enum(["connected","declined","failed"]).optional()}),_Eo=u.object({field:u.enum(["name","headline","industry","location","website","story"]),current:u.string().nullable(),imported:u.string(),outcome:u.enum(["fill","preserve","unchanged"])}),mHe=yHe.shape.connection,TEo=u.discriminatedUnion("status",[u.object({status:u.literal("disconnected"),expired:u.boolean(),startUrl:u.string(),connection:mHe}),u.object({status:u.literal("unavailable"),message:u.string(),startUrl:u.string(),connection:mHe}),u.object({status:u.literal("ready"),fields:u.array(_Eo),connection:mHe})]);function ELi(e){if(e===null)return"\u2014";return e.length>bLi?`${e.slice(0,bLi-1)}\u2026`:e}function vLi(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function ALi(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function hHe(e){let t=e.connection?IEo[e.connection]:null;return t?[{type:"notice",...t}]:[]}var wLi=Fo({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",section:"library",query:yHe,data:TEo,actions:[xHe,zpe,gHe],view:({data:e})=>{if(e.status==="disconnected")return{kicker:"Profile import",title:"LinkedIn",description:"Connect your LinkedIn account to fill your profile from it. Only members in the European Economic Area can connect.",status:{label:"Not connected",tone:"neutral"},blocks:[...hHe(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],ALi(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...hHe(e),{type:"notice",tone:"warn",text:e.message},ALi(e.startUrl,"Connect LinkedIn again"),{type:"action",action:zpe,input:{}}]};let t=e.fields.some((i)=>i.outcome==="fill");return{kicker:"Profile import",title:"LinkedIn",description:"What LinkedIn holds for each profile field, and what an import would do with it.",status:{label:t?"Ready to import":"Profile already complete",tone:t?"good":"neutral"},...t?{primaryAction:{action:xHe,input:{}}}:{},blocks:[...hHe(e),{type:"table",id:"linkedin-fields",empty:"LinkedIn holds no profile fields for this account.",columns:[{key:"field",label:"Field"},{key:"current",label:"Your profile"},{key:"imported",label:"LinkedIn"},{key:"outcome",label:"Import"}],rows:e.fields.map((i)=>({id:i.field,cells:{field:SLi[i.field],current:ELi(i.current),imported:ELi(i.imported),outcome:DEo[i.outcome]}}))},{type:"card",id:"linkedin-shapes",label:"Data shapes",blocks:[{type:"text",text:"Field names, value types and record forms of your skills, positions, education and certifications on LinkedIn, with every value replaced, for writing import fixtures."},{type:"action",action:gHe,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:zpe,input:{}}]}}});function fHe(e){if(e?.permission!=="admin"||!e.isAnchor)throw new bi("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function PEo(e){if(e instanceof Lpe&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${he(e)}`}async function kLi(e,t){if(!e.isAvailable())return;let i=async(r)=>{let o=await t.connections.get(fHe(r));if(!o||cHe(o))throw new bi("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},n=e.source({definition:wLi,bind:(r)=>wLi.bind(r,{load:async({caller:o,query:s})=>{let a=fHe(o),{connection:c}=s.get(yHe),l=await t.connections.get(a);if(!l||cHe(l))return{status:"disconnected",expired:l!==null,startUrl:t.startUrl,connection:c};try{return{status:"ready",fields:(await t.profileImport.preview(l.accessToken)).fields,connection:c}}catch(d){return{status:"unavailable",message:PEo(d),startUrl:t.startUrl,connection:c}}},actions:[xHe.bind(r,async({caller:o})=>t.profileImport.apply((await i(o)).accessToken),async({caller:o})=>{let s=await t.profileImport.preview((await i(o)).accessToken),a=(d)=>s.fields.filter((p)=>p.outcome===d).map((p)=>SLi[p.field].toLowerCase()),c=a("fill"),l=a("preserve");if(c.length===0)throw new bi("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${vLi(c)} from LinkedIn?${l.length>0?` Your ${vLi(l)} stay as you wrote them.`:""}`,revision:s.revision}}),gHe.bind(r,async({caller:o})=>{let s=await yLi(t.clientFor((await i(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),zpe.bind(r,async({caller:o})=>(await t.connections.forget(fHe(o)),{disconnected:!0}))]})});return e.register({...n,accessHandler:async(r)=>r.isAnchor&&await n.accessHandler(r)})}var BLi={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.854",description:"Import the owner's LinkedIn profile into the anchor profile from Studio",dependencies:{"@brains/contracts":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*"},devDependencies:{"@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/profile":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","bun-types":"^1.4.0",eslint:"^10.5.0",typescript:"^7.0.2"},exports:{".":"./src/index.ts","./broker-provider":"./src/broker-provider.ts","./env-schema":"./src/env-schema.ts"},private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module"};var FEo="/studio",MEo=u.object({clientId:u.string().trim().min(1).describe("LinkedIn app client ID"),clientSecret:u.string().trim().min(1).describe("LinkedIn app client secret"),redirectUri:u.url({protocol:/^https?$/}).describe(`This brain's callback URL ending at ${dG}, registered with the LinkedIn app`)}),OEo=u.object({url:u.url({protocol:/^https$/}).describe("The managed broker's origin"),instanceId:u.string().trim().min(1).describe("This brain's broker instance"),secret:u.string().min(32).describe("This brain's broker instance secret"),returnUri:u.url({protocol:/^https?$/}).describe(`This brain's return URL ending at ${pG}, registered with the broker`)}),CLi=u.object({oauth:MEo.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:OEo.optional().describe("The managed broker holding the shared LinkedIn app")});function NEo(e,t){let{oauth:i,broker:n}=e;if(i&&n)throw Error("linkedin-import: configure either oauth (direct) or broker, not both");if(i&&new URL(i.redirectUri).pathname!==dG)throw Error(`linkedin-import: oauth.redirectUri must end at ${dG}`);if(n&&new URL(n.returnUri).pathname!==pG)throw Error(`linkedin-import: broker.returnUri must end at ${pG}`);if(i)return{kind:"direct",oauth:new aG(i,t.fetch)};if(n)return{kind:"broker",broker:new uHe(n,t.fetch)};return null}function DLi(e={}){let t=zt({id:"linkedin-import",config:CLi,setup:(i)=>{let{config:n}=i,r=NEo(n,e),o=n.oauth?.redirectUri??n.broker?.returnUri;if(!r||!o)return{routes:[]};let s=ft(i),a=new aHe(s.accountSettings,{pluginId:s.pluginId,packageName:BLi.name}),c=FEo;return s.registered(async()=>{let l=await kLi(s.studio,{profileImport:new dHe(s.messaging,e.fetch),clientFor:(d)=>new oG(d,e.fetch),connections:a,startUrl:new URL(pHe,o).toString()});if(l)c=l}),{routes:hLi({mode:r,states:aLi(),connections:a,resolveSession:async(l)=>s.auth()?.resolveSession(l),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return Do(t,({state:i})=>i.routes)}var bHe=DLi();import{createHash as LEo,timingSafeEqual as jEo}from"crypto";function ILi(e){return LEo("sha256").update(e).digest()}function zEo(e){if(!e?.startsWith("Basic "))return null;let t=Buffer.from(e.slice(6),"base64").toString("utf8"),i=t.indexOf(":");if(i<=0||i===t.length-1)return null;return{id:t.slice(0,i),secret:t.slice(i+1)}}class EHe{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:ILi(t.secret)}]))}authenticate(e){let t=zEo(e.headers.get("authorization")),i=t?this.instances.get(t.id):void 0;if(!t||!i)return null;return jEo(ILi(t.secret),i.secretHash)?{id:i.id,returnUris:i.returnUris}:null}}var UEo=10,qEo=600000,AHe={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function rk(e,t=200){return Response.json(e,{status:t,headers:AHe})}function _Li(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...AHe,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function TLi(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function Upe(e,t){let i=new URL(e.returnUri);return i.searchParams.set("provider",e.provider),i.searchParams.set("state",e.brainState),Object.entries(t).forEach(([n,r])=>i.searchParams.set(n,r)),new Response(null,{status:303,headers:{...AHe,Location:i.toString()}})}function FLi(e){let t=new Map(e.providers.map((c)=>[c.id,c])),i=new Map,n=(c)=>{let l=e.now(),d=(i.get(c)??[]).filter((m)=>m>l-qEo),p=d.length<UEo;return i.set(c,p?[...d,l]:d),p},r=(c)=>new URL(vHe(c),e.publicUrl).toString(),o=async(c)=>{let l=e.instances.authenticate(c);if(!l)return _Li();let d=PLi.safeParse(await TLi(c));if(!d.success)return rk({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=l.returnUris[d.data.provider];if(!p||!m)return rk({error:"Provider is unavailable for this instance"},400);if(!n(l.id))return rk({error:"Too many connections started; try later"},429);let h=e.authorizations.issue({provider:p.id,instanceId:l.id,returnUri:m,brainState:d.data.brainState}),f=p.authorizationUrl({redirectUri:r(p.id),state:h}).toString();return rk({authorizationUrl:f})},s=async(c)=>{let l=e.instances.authenticate(c);if(!l)return _Li();let d=RLi.safeParse(await TLi(c));if(!d.success)return rk({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,m=e.grants.take(d.data.grant,(h)=>h.provider===p&&h.instanceId===l.id);if(!m)return rk({error:"Invalid or expired grant"},400);return rk({provider:p,credential:m.credential})},a=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=e.authorizations.take(d.get("state")??"",(h)=>h.provider===c.id);if(!p)return rk({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return Upe(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return Upe(p,{error:"authorization_incomplete"});try{let h=await c.exchange({code:m,redirectUri:r(c.id)}),f=e.grants.issue({provider:c.id,instanceId:p.instanceId,credential:h});return Upe(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${he(h)}`),Upe(p,{error:"credential_exchange_failed"})}};return[{path:V7.authorizations,method:"POST",public:!0,handler:o},{path:V7.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:vHe(c.id),method:"GET",public:!0,handler:a(c)}))]}var $Eo=600000,HEo=120000,MLi=1000,GEo=u.object({clientId:u.string().trim().min(1),clientSecret:u.string().trim().min(1)}),WEo=u.object({id:u.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/),secret:u.string().min(32).describe("Revocable instance secret"),returnUris:u.record(wHe,u.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),OLi=u.object({publicUrl:u.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:u.record(wHe,GEo).default({}).describe("Per provider, the shared app the broker holds"),instances:u.array(WEo).default([])});function ZEo(e,t){return Object.entries(e.providers).map(([i,n])=>{let r=t.providers[i];if(!r)throw Error(`oauth-broker: no adapter for provider "${i}"`);let o=r(n);if(o.id!==i)throw Error(`oauth-broker: adapter for "${i}" reports provider "${o.id}"`);return o})}function SHe(e){let t=zt({id:"oauth-broker",config:OLi,setup:(i)=>{let{config:n}=i,r=ZEo(n,e);if(n.instances.length===0||r.length===0)return{routes:[]};return{routes:FLi({publicUrl:n.publicUrl,providers:r,instances:new EHe(n.instances),authorizations:new sG({ttlMs:$Eo,maxPending:MLi,now:e.now}),grants:new sG({ttlMs:HEo,maxPending:MLi,now:e.now}),now:e.now??Date.now,logger:ft(i).logger})}}});return Do(t,({state:i})=>i.routes)}var VEo=2592000000,mG=(e,t)=>Ht(`${e}
|
|
9751
9751
|
${t}`);function NLi(e,t){let i=(n)=>n!==void 0&&t()-n.usedAt<VEo;return{get:async(n,r)=>{let o=await e.get(mG(n,r));return i(o)?{hash:o.hash,...o.conflictEdit!==void 0&&{conflictEdit:o.conflictEdit},...o.conflictId!==void 0&&{conflictId:o.conflictId}}:void 0},held:async(n,r,o)=>{await e.set(mG(n,r),{hash:o,usedAt:t()})},conflictKept:async(n,r,o,s)=>{let a=await e.get(mG(n,r));if(!i(a))return;await e.set(mG(n,r),{hash:a.hash,conflictEdit:o,...s!==void 0&&{conflictId:s},usedAt:t()})},forget:async(n,r)=>{await e.delete(mG(n,r))},sweep:async()=>{let n=(await e.keys()).filter(({value:r})=>!i(r));await Promise.all(n.map(({key:r})=>e.delete(r)))}}}function LLi(e=Date.now){let t=new Map;return NLi({get:async(i)=>t.get(i),set:async(i,n)=>{t.set(i,n)},delete:async(i)=>{t.delete(i)},keys:async()=>[...t].map(([i,n])=>({key:i,value:n}))},e)}var KEo="webdav.mount-base",YEo=u.object({hash:u.string().min(1),conflictEdit:u.string().min(1).optional(),conflictId:u.string().min(1).optional(),usedAt:u.number()});function jLi(e,t=Date.now){let i=e.scoped({namespace:KEo,schema:YEo});return NLi({get:async(n)=>await i.get(n)??void 0,set:async(n,r)=>{await i.set(n,r)},delete:async(n)=>{await i.delete(n)},keys:()=>i.list()},t)}var JEo=new Set([".obsidian"]),zLi=33554432;function C9(e){let[t]=e;return t!==void 0&&JEo.has(t)}function ULi(){let e=new Map,t=(i)=>{let n=e.get(i)??new Map;return e.set(i,n),n};return{load:async(i)=>[...t(i).values()],put:async(i,n)=>{t(i).set(n.path,n)},remove:async(i,n)=>{n.forEach((r)=>t(i).delete(r))}}}var QEo="webdav.kept",XEo=u.object({path:u.string().min(1),bytes:u.string().optional(),modified:u.number()});function qLi(e){let t=e.scoped({namespace:QEo,schema:XEo}),i=(r)=>`${Ht(r)}/`,n=(r,o)=>`${i(r)}${Ht(o)}`;return{load:async(r)=>(await t.list({keyPrefix:i(r)})).map(({value:o})=>({path:o.path,modified:o.modified,...o.bytes!==void 0&&{bytes:new Uint8Array(Buffer.from(o.bytes,"base64"))}})),put:async(r,o)=>{await t.set(n(r,o.path),{path:o.path,modified:o.modified,...o.bytes!==void 0&&{bytes:Buffer.from(o.bytes).toString("base64")}})},remove:async(r,o)=>{await Promise.all(o.map((s)=>t.delete(n(r,s))))}}}import{randomUUID as evo}from"crypto";var tvo=500;class kHe{run=evo().slice(0,8);keep;sequence=0;recent=[];waiting=new Set;closed=!1;constructor(e={}){this.keep=e.keep??tvo}cursor(){return`${this.run}:${this.sequence}`}record(e){this.sequence+=1,this.recent=[...this.recent.slice(-(this.keep-1)),{sequence:this.sequence,type:e}];let t=[...this.waiting];this.waiting.clear();for(let i of t)i()}close(){this.closed=!0;let e=[...this.waiting];this.waiting.clear();for(let t of e)t()}since(e){if(e===null)return{cursor:this.cursor(),types:[]};let[t,i]=e.split(":"),n=Number(i),r=this.recent[0]?.sequence??this.sequence+1;if(t!==this.run||!Number.isInteger(n)||n>this.sequence||n<r-1)return{cursor:this.cursor(),reset:!0};return{cursor:this.cursor(),types:[...new Set(this.recent.filter((o)=>o.sequence>n).map((o)=>o.type))]}}async wait(e,t,i){let n=this.since(e);if("reset"in n||n.types.length>0||e===null)return n;if(t<=0||this.closed)return n;return await new Promise((r)=>{let o=()=>{clearTimeout(s),this.waiting.delete(o),i?.removeEventListener("abort",o),r()},s=setTimeout(o,t);this.waiting.add(o),i?.addEventListener("abort",o,{once:!0})}),this.since(e)}}var HLi="obsidian",GLi="Obsidian",ivo=1024,nvo="Your brain could not answer this.",rvo=u.object({question:u.string().min(1).max(8000),conversation:u.string().min(1).max(qpe).optional(),path:u.string().min(1).max(ivo).optional()}),ovo=u.object({conversation:u.string().min(1).max(qpe),approval:u.string().min(1).max(qpe),confirmed:u.boolean()});function WLi(e){let{principal:t}=e;return{userId:t.userId,personId:t.personId,displayName:t.displayName,permissionLevel:t.permissionLevel,isAnchor:t.isAnchor,...t.canonicalId!==void 0&&{canonicalId:t.canonicalId}}}async function svo(e,t){let i=await e.entityAt(t.split("/"));if(!i)return;let n=await i.file.open();if(typeof n!=="string")return;let r=i.entity.metadata.title;return{entityType:i.entity.entityType,id:i.entity.id,title:typeof r==="string"&&r!==""?r:i.entity.id,content:n.slice(0,$Li)}}async function ZLi(e,t,i){let n=(i.cards??[]).flatMap((a)=>a.kind==="sources"?a.sources:[]),r=await Promise.all(n.map(async(a)=>{let c=a.entityType!==void 0&&a.entityId!==void 0&&a.brain===void 0?await e.pathOf(a.entityType,a.entityId):void 0;return{title:a.title??a.source,...c!==void 0&&{path:c},...a.url!==void 0&&{url:a.url},...a.excerpt!==void 0&&{excerpt:a.excerpt}}})),o=(i.pendingConfirmations??[]).map(({id:a,summary:c,preview:l})=>({id:a,summary:c,...l!==void 0&&{preview:l}})),s={conversation:t,text:i.text,...i.error!==void 0&&{error:nvo},sources:r,confirmations:o};return new Response(JSON.stringify(s),{status:200,headers:{"Content-Type":"application/json; charset=utf-8"}})}var VLi=()=>new Response("Nothing answers questions here right now.",{status:503});async function KLi(e,t){let i=rvo.safeParse(t);if(!i.success)return new Response('Ask with { "question": "\u2026" }',{status:400});let{question:n,conversation:r,path:o}=i.data,s=o===void 0?void 0:await svo(e.tree,o),a=await e.ask?.({asker:WLi(e.grant),interfaceType:HLi,channelName:GLi,question:n,...r!==void 0&&{conversationId:r},...s!==void 0&&{entry:s}});if(!a)return VLi();if("message"in a)return new Response(a.message,{status:409});return ZLi(e.tree,a.conversationId,a.response)}async function YLi(e,t){let i=ovo.safeParse(t);if(!i.success)return new Response('Answer with { "conversation": "\u2026", "approval": "\u2026", "confirmed": true }',{status:400});let{conversation:n,approval:r,confirmed:o}=i.data,s=await e.confirmAsk?.({asker:WLi(e.grant),interfaceType:HLi,channelName:GLi,conversationId:n,approvalId:r,confirmed:o});if(!s)return VLi();if("message"in s)return new Response(s.message,{status:409});return ZLi(e.tree,n,s.response)}import{createHash as dvo}from"crypto";import{posix as pvo}from"path";var avo="conflict",hG="note",cvo=100,QLi=new Set(["image","document"]);function CHe(e){return QLi.has(e)}var lvo={".md":"text/plain; charset=utf-8",".yaml":"text/plain; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml",".pdf":"application/pdf",".epub":"application/epub+zip"};class DHe{reader;scope;containment;everyType;constructor(e,t,i={}){this.reader=e,this.scope=t,this.containment=Wy(e),this.everyType=i.everyType??!1}async resolve(e){if(e.length===0)return{kind:"folder",segments:e};if(!e.every(BHe))return;let t=await this.entityAt(e);if(t)return t.file;let[i]=e;if(this.everyType&&e.length===1&&i!==void 0&&this.isFolderType(i))return{kind:"folder",segments:e};return(await this.children(e)).length>0?{kind:"folder",segments:e}:void 0}async children(e){let{folders:t,files:i}=e.length===0?await this.rootChildren():await this.typeFolderChildren(e);return[...[...new Set(t)].sort(JLi).map((n)=>({kind:"folder",segments:[...e,n]})),...i.sort((n,r)=>JLi(n.segments.join("/"),r.segments.join("/")))]}async rootChildren(){let e=new Map((await this.reader.getEntityCounts(this.scope)).map((n)=>[n.entityType,n.count])),t=this.reader.getEntityTypes().filter((n)=>this.isFolderType(n)&&(this.everyType||[n,this.containedIn(n)].some((r)=>r!==void 0&&(e.get(r)??0)>0))),i=this.reader.getEntityTypes().includes(hG)?(await this.hierarchy(hG,[])).entities:[];return{folders:t,files:await this.filesIn([],i)}}async typeFolderChildren(e){let[t,...i]=e;if(t===void 0||!this.isFolderType(t))return{folders:[],files:[]};let n=await Promise.all([t,this.containedIn(t)].filter((r)=>r!==void 0).map((r)=>this.hierarchy(r,i)));return{folders:n.flatMap((r)=>r.folders),files:await this.filesIn(e,n.flatMap((r)=>r.entities))}}async hierarchy(e,t,i=0){let[n,...r]=t,o=await this.reader.queryEntityHierarchy({entityType:e,prefix:n===void 0?null:[n,...r],visibilityScope:this.scope,limit:cvo,offset:i,source:!0}),s=o.entities.map((l)=>l.entity),a=i+s.length,c=s.length>0&&a<o.totalEntities?(await this.hierarchy(e,t,a)).entities:[];return{folders:o.folders.map((l)=>l.name),entities:[...s,...c]}}async filesIn(e,t){return(await Promise.all(t.map((n)=>this.fileOf(n)))).filter((n)=>n!==void 0).filter((n)=>n.segments.length===e.length+1&&e.every((r,o)=>n.segments[o]===r))}async related(e,t){let i=await this.entityAt(e);if(!i)return;let n=await this.nearestTo(i.entity,t);if(n==="unindexed")return n;return(await Promise.all(n.map(async(o)=>{let s=await this.reader.getEntityRaw({entityType:o.entityType,id:o.entityId,visibilityScope:this.scope,source:!0}),a=s?await this.fileOf(s):void 0;if(!s||!a)return;let c=s.metadata.title;return{path:a.segments.join("/"),title:typeof c==="string"&&c!==""?c:s.id,entityType:s.entityType,distance:o.distance}}))).filter((o)=>o!==void 0)}async nearestTo(e,t){try{return await this.reader.nearestToEntity({origin:{entityType:e.entityType,entityId:e.id},types:this.reader.getEntityTypes().filter((i)=>!CHe(i)&&i!==avo),limit:t,visibilityScope:this.scope})}catch(i){if(i instanceof RC)return"unindexed";throw i}}async pathOf(e,t){if(!this.reader.getEntityTypes().includes(e))return;let i=await this.reader.getEntityRaw({entityType:e,id:t,visibilityScope:this.scope,source:!0});return(i?await this.fileOf(i):void 0)?.segments.join("/")}async entityAt(e){if(e.length===0||!e.every(BHe))return;let{entityType:t,id:i}=PB(e.join("/"),this.containment);if(!this.reader.getEntityTypes().includes(t))return;let n=await this.reader.getEntityRaw({entityType:t,id:i,visibilityScope:this.scope,source:!0}),r=n?await this.fileOf(n):void 0;return n&&r?.segments.join("/")===e.join("/")?{entity:n,file:r}:void 0}textExtension(e){return this.reader.fileExtension(e)}placementAt(e,t){if(e.length===0||!e.every(BHe))return;let i=e.join("/"),{entityType:n,id:r}=PB(i,this.containment);if(!this.reader.getEntityTypes().includes(n))return;let o=Zy(n,r,t,this.containment);return o.writable&&o.relativePath===i?{entityType:n,id:r}:void 0}async fileOf(e){let t=B8(e,this.reader.fileExtension(e.entityType));if(!Zy(e.entityType,e.id,t,this.containment).writable)return;let n={kind:"file",segments:wT(e.id,e.entityType,t,this.containment).split("/"),contentType:lvo[t]??"application/octet-stream",etag:`"${e.contentHash}"`,modified:new Date(e.updated)};if(!QLi.has(e.entityType)||t===".md"){let a=t===".yaml"?SR(e.content):e.content;return{...n,size:Buffer.byteLength(a),open:async()=>a}}if(e.content==="")return;let r=Uc.safeParse(e.content);if(r.success){let a=await this.reader.statAsset(r.data);if(!a)return;return{...n,size:a.sizeBytes,open:async()=>uvo(await this.reader.openAsset(r.data))}}let o=/^data:[a-z0-9.+/-]+;base64,([\s\S]+)$/i.exec(e.content.trim())?.[1];if(!o)return;let s=Buffer.from(o.replace(/\s/g,""),"base64");return{...n,size:s.byteLength,open:async()=>s}}isFolderType(e){return e!==hG&&!this.containment.has(e)&&this.reader.getEntityTypes().includes(e)}folderTypeOf(e){return this.containment.get(e)??e}containedIn(e){return[...this.containment].find(([,t])=>t===e)?.[0]}}function JLi(e,t){return e<t?-1:e>t?1:0}function BHe(e){return e.length>0&&e!=="."&&e!==".."&&!/[/\\\0]/.test(e)}function uvo(e){let t=e[Symbol.asyncIterator]();return new ReadableStream({async pull(i){let n=await t.next();if(n.done)i.close();else i.enqueue(n.value)},async cancel(){await t.return?.()}})}var nji="image",mvo="document",XLi="note",IHe="webdav";async function _He(e,t){let i=pvo.extname(t.segments[t.segments.length-1]??"").toLowerCase();if(rd.includes(i))return tji(e,t,i,yvo);if(Lx.includes(i))return tji(e,t,i,bvo);let n=i===".yaml"?hvo(e,t):t;if(n===void 0)return await $pe(e,t)?ok("No entry can be stored at this path"):Hpe();if(i!==".md"&&i!==".yaml")return await $pe(e,n)?ok("The drive stores notes, entries, images, PDFs and EPUBs"):Hpe();if(n.bytes.byteLength>e.writes.maxFileBytes)return cji();let r=await e.tree.entityAt(n.segments),o=r?.entity.entityType??e.tree.placementAt(n.segments,i)?.entityType;if(o!==void 0&&CHe(o))return ok(o===nji?"An image is stored as its image file":"A document is stored as its PDF or EPUB file");return r?fvo(e,n,r):gvo(e,n,i)}function hvo(e,t){let i=e.tree.placementAt(t.segments,".yaml")?.entityType;if(i===void 0||e.tree.textExtension(i)!==".yaml")return;let n=uji(t.bytes);if(n===void 0)return t;return{...t,bytes:new Uint8Array(Buffer.from(kR(n),"utf8"))}}async function fvo(e,t,{entity:i,file:n}){let{writes:r}=e,o=t.onlyIfAbsent===!0||!THe(t.ifMatch,n.etag);if(o&&!t.keepAsConflict)return t.onlyIfAbsent?Gpe():sk();let s=sji(r,t.bytes,i.entityType);if("status"in s)return s;if(xvo(r,s.parsed,i))return await e.mount.held(i.contentHash),{status:204,etag:await aji(e,t,s.text)};let{visibility:a,...c}=s.parsed.metadata??i.metadata,l={...i,...s.parsed,id:i.id,entityType:i.entityType,content:s.text,metadata:c,visibility:s.parsed.visibility??i.visibility},d=await fG(e,t.grant,"update",l,Uk(i.entityType,i,l,e.reader));if(d)return d;if(o)return eji(e,t,{existing:i,base:t.onlyIfAbsent||t.ifMatch===null?void 0:{hash:t.ifMatch.replace(/^"|"$/g,"")},text:s.text,declared:s.parsed.visibility});if(t.ifMatch===null){let h=await e.mount.base();if(h!==void 0&&h.hash!==i.contentHash)return eji(e,t,{existing:i,base:h,text:s.text,declared:s.parsed.visibility})}let p=await Wpe(()=>r.updateEntity({entity:l,options:{expectedContentHash:i.contentHash,eventContext:xG(t.grant)}}));if(!p.ok)return lji(p.error);if(p.value.skipReason==="content-conflict")return sk();if(!p.value.skipped)await D9(r,t.grant,"update","allowed",l);let m=await e.tree.entityAt(t.segments);if(m)await e.mount.held(m.entity.contentHash);return{status:204,etag:m?.entity.content===s.text?m.file.etag:void 0}}function xvo(e,t,i){let n=RHe(()=>e.deserializeEntity(i.content,i.entityType));return n.ok&&(t.visibility??i.visibility)===i.visibility&&Bun.deepEquals(t,n.value)}async function eji(e,t,i){let{existing:n,base:r,text:o,declared:s}=i,a=Ht(o);if(r?.conflictEdit===a)return{status:204,conflictId:r.conflictId};let c=await e.recordConflict({entityType:n.entityType,entityId:n.id,origin:"drive",actor:t.grant.principal.userId,...r!==void 0&&{base:r.hash},current:n.contentHash,text:o,targetVisibility:n.visibility,...s!==void 0&&s!==n.visibility&&{declaredVisibility:s}});if(c===void 0)return sk();return await e.mount.conflictKept(a,c),{status:204,conflictId:c}}async function gvo(e,t,i){let{writes:n,tree:r}=e,{segments:o}=t;if(!await $pe(e,t))return Hpe();let s=r.placementAt(o,i);if(!s)return ok("No entry can be stored at this path");let a=sji(n,t.bytes,s.entityType);if("status"in a)return a;let{visibility:c,...l}=a.parsed.metadata??{},d=a.parsed.visibility??"public",p={...a.parsed,id:s.id,entityType:s.entityType,content:a.text,metadata:l,visibility:d},m=Fxe(s.entityType,void 0,l.status,e.reader)!=="non-publish",h=await fG(e,t.grant,"create",p,m?["create","publish"]:["create"]);if(h)return h;let f=await Wpe(()=>n.createEntity({entity:p,options:{conditionalWrite:{expectedRevision:null},eventContext:xG(t.grant)}}));if(!f.ok)return PHe(f.error);return await D9(n,t.grant,"create","allowed",p),{status:201,etag:await aji(e,t,a.text)}}var yvo={entityType:nji,noun:"image",wrongFolder:"An image can only be stored in the image folder",describe:async({bytes:e,digest:t,extension:i,existing:n})=>{let r=await DT(iji(e));if(!r)return{status:422,message:"The file is not a PNG, JPEG, GIF or WebP image"};let o=AT(r.format);if(o!==i)return{status:422,message:`These bytes are stored as ${o}; save the image under that extension`};let s=n?.status;if(typeof s==="string"&&IT(t,s))return{status:422,message:"These bytes are the old pending placeholder, not this image's bytes"};return{metadata:{...n,...r}}}},bvo={entityType:mvo,noun:"document",wrongFolder:"A PDF or an EPUB can only be stored in the document folder",describe:async({bytes:e,digest:t,extension:i,name:n,existing:r})=>{let o;try{o=VT(e)}catch(h){return{status:422,message:he(h)}}let s=a$(o.mimeType);if(s!==i)return{status:422,message:`These bytes are stored as ${s}; save the document under that extension`};if(wce(t))return{status:422,message:"These bytes are the old pending placeholder, not a document's bytes"};let{pageCount:a,sectionCount:c,status:l,processingJobId:d,processingError:p,...m}=r??{};return{metadata:{...r?m:{filename:n,attachmentType:"uploaded",origin:"uploaded"},...o}}}};async function tji(e,t,i,n){let{writes:r,tree:o}=e,{segments:s,bytes:a,grant:c}=t,l=await o.entityAt(s);if(!l&&!await $pe(e,t))return Hpe();let d=l?{entityType:l.entity.entityType,id:l.entity.id}:o.placementAt(s,i);if(d?.entityType!==n.entityType)return ok(n.wrongFolder);if(a.byteLength>r.maxAssetBytes)return cji();if(l&&t.onlyIfAbsent)return Gpe();if(l&&!THe(t.ifMatch,l.file.etag))return sk();let p=await n.describe({bytes:a,digest:dvo("sha256").update(a).digest("hex"),extension:i,name:s[s.length-1]??"",existing:l?.entity.metadata});if("status"in p)return p;let m=l?"update":"create",h={id:d.id,entityType:n.entityType,visibility:l?.entity.visibility??"public"},f=await fG(e,c,m,h,[m]);if(f)return f;if(l&&t.ifMatch===null){let T=await e.mount.base();if(T!==void 0&&T.hash!==l.entity.contentHash)return{status:409,message:`The ${n.noun} changed since this drive last read it`}}let g=await r.stageAsset(a,{maxBytes:r.maxAssetBytes,expectedSize:a.byteLength}),y={content:g.ref,metadata:{...p.metadata,sizeBytes:g.sizeBytes}},b={eventContext:xG(c)},v=await Wpe(async()=>{if(l)return(await r.updateEntity({entity:{...l.entity,...y},stagedAsset:g,options:{...b,expectedContentHash:l.entity.contentHash}})).skipReason==="content-conflict"?sk():void 0;await r.createEntity({entity:{...h,...y},stagedAsset:g,options:{...b,conditionalWrite:{expectedRevision:null}}});return}),w=v.ok?v.value:PHe(v.error);if(w)return await r.discardStagedAsset(g),w;await D9(r,c,m,"allowed",h);let B=await o.entityAt(s);if(B)await e.mount.held(B.entity.contentHash);return{status:l?204:201,etag:B?.file.etag}}async function rji(e,t){let{writes:i,tree:n}=e,r=await n.entityAt(t.from);if(!r)return{status:404,message:"Not found"};let{entity:o}=r,s=n.placementAt(t.to,".md");if(o.entityType!==XLi||s?.entityType!==XLi)return ok("The drive renames notes only, to another note's name");if(await n.entityAt(t.to))return Gpe();let a=await fG(e,t.grant,"rename",o,["update"]);if(a)return a;let c=await Wpe(()=>i.renameEntity({entityType:o.entityType,id:o.id,newId:s.id,options:{expectedContentHash:o.contentHash,eventContext:xG(t.grant)}}));if(!c.ok)return PHe(c.error);if(!c.value.renamed)return sk();return await D9(i,t.grant,"rename","allowed",o),{status:201}}async function oji(e,t){let i=await e.tree.entityAt(t.segments);if(!i)return{status:404,message:"Not found"};let{entity:n,file:r}=i;if(!THe(t.ifMatch,r.etag))return sk();let o=await fG(e,t.grant,"delete",n,["delete"]);if(o)return o;if(t.ifMatch===null){let a=await e.mount.base();if(a!==void 0&&a.hash!==n.contentHash)return{status:409,message:"The file changed since this drive last read it"}}if(!await e.writes.deleteEntity({entityType:n.entityType,id:n.id,options:{expectedContentHash:n.contentHash,eventContext:xG(t.grant)}}))return sk();return await e.mount.forget(),await D9(e.writes,t.grant,"delete","allowed",n),{status:204}}function sji(e,t,i){let n=uji(t);if(n===void 0)return{status:422,message:"The file is not UTF-8 text"};let r=RHe(()=>e.deserializeEntity(n,i));return r.ok?{text:n,parsed:r.value}:{status:422,message:he(r.error,"The file cannot be read")}}async function fG(e,t,i,n,r){let o=t.principal.permissionLevel,s=RHe(()=>r.forEach((a)=>e.writes.permissions.assertEntityActionAllowed(n.entityType,a,{userPermissionLevel:o})));if(!s.ok)return await D9(e.writes,t,i,"denied",n,"entity-action-policy"),ok(he(s.error,"Not allowed"));if(i!=="delete"&&!km(o,n.visibility))return await D9(e.writes,t,i,"denied",n,"visibility-policy"),ok(`Cannot set visibility to "${n.visibility}" at ${o} permission`);return}function D9(e,t,i,n,r,o){return e.recordAudit({actorUserId:t.principal.userId,action:`${IHe}.entity.${i}.${n}`,targetType:"entity",targetId:r.id,metadata:{entityType:r.entityType,interfaceType:IHe,outcome:n,...o?{reason:o}:{}}})}async function aji(e,t,i){let n=await e.tree.entityAt(t.segments);return n?.entity.content===i?n.file.etag:void 0}function xG(e){return{actor:{kind:"user",userId:e.principal.userId},interfaceType:IHe}}function THe(e,t){return e===null||e==="*"||e===t}function $pe(e,t){return e.folderExists(t.segments.slice(0,-1))}function Hpe(){return{status:409,message:"The folder does not exist"}}function cji(){return{status:413,message:"The file is larger than the drive accepts"}}function Gpe(){return{status:412,message:"An entry already exists at this path"}}function PHe(e){return e instanceof Error&&e.name==="EntityWriteConflictError"?Gpe():lji(e)}function ok(e){return{status:403,message:e}}function sk(){return{status:412,message:"The file changed since it was opened"}}function lji(e){if(Lk(e))return{status:422,message:he(e,"The file cannot be saved")};throw e}function uji(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}}function RHe(e){try{return{ok:!0,value:e()}}catch(t){return{ok:!1,error:t}}}async function Wpe(e){try{return{ok:!0,value:await e()}}catch(t){return{ok:!1,error:t}}}import{posix as Evo}from"path";var vvo=new Set([".md",".yaml",...rd,...Lx]),Avo=600000,wvo=16777216,dji=(e,t,i)=>!C9(e.split("/"))&&i-t>=Avo;function pji(e){return e.startsWith(".")||!vvo.has(Evo.extname(e).toLowerCase())}class FHe{files=new Map;folders=new Map;now;kept;opened=new Map;pending=Promise.resolve();constructor(e=Date.now,t=ULi()){this.now=e,this.kept=t}open(e){let t=this.opened.get(e)??this.kept.load(e).then((i)=>{i.forEach(({path:n,bytes:r,modified:o})=>{let s=n.split("/");if(r===void 0)this.foldersOf(e).set(n,o);else this.filesOf(e).set(n,{segments:s,bytes:r,modified:new Date(o),touched:o})})});return this.opened.set(e,t),t}settle(){return this.pending}persist(e){this.pending=this.pending.then(e)}get(e,t){let i=this.live(e).get(t.join("/"));if(i)i.touched=this.now();return i}list(e,t){return[...this.live(e).values()].filter((i)=>i.segments.length===t.length+1&&t.every((n,r)=>i.segments[r]===n)).sort((i,n)=>i.segments.join("/")<n.segments.join("/")?-1:1)}put(e,t,i){let n=this.live(e),r=t.join("/"),o=n.get(r),s=C9(t);if([...n.values()].filter((l)=>C9(l.segments)===s).reduce((l,d)=>l+d.bytes.byteLength,0)-(o?.bytes.byteLength??0)+i.byteLength>(s?zLi:wvo))return"full";let c=this.now();if(n.set(r,{segments:t,bytes:i,modified:new Date(c),touched:c}),this.files.set(e,n),s)t.slice(0,-1).forEach((l,d)=>this.makeFolder(e,t.slice(0,d+1))),this.persist(()=>this.kept.put(e,{path:r,bytes:i,modified:c}));return o?"replaced":"created"}delete(e,t){let i=t.join("/"),n=this.live(e).delete(i);if(n&&C9(t))this.persist(()=>this.kept.remove(e,[i]));return n}hasFolder(e,t){let i=this.liveFolders(e),n=t.join("/");if(!i.has(n))return!1;return i.set(n,this.now()),!0}listFolders(e,t){let i=t.length>0?`${t.join("/")}/`:"";return[...this.liveFolders(e).keys()].filter((n)=>n.startsWith(i)&&!n.slice(i.length).includes("/")).map((n)=>n.slice(i.length)).sort()}makeFolder(e,t){let i=this.liveFolders(e),n=t.join("/"),r=i.has(n),o=this.now();if(i.set(n,o),this.folders.set(e,i),!r&&C9(t))this.persist(()=>this.kept.put(e,{path:n,modified:o}))}removeFolder(e,t){let i=t.join("/"),n=(a)=>a===i||a.startsWith(`${i}/`),r=this.liveFolders(e);if(!r.has(i))return!1;let o=this.live(e),s=[...r.keys(),...o.keys()].filter(n);if(s.forEach((a)=>{r.delete(a),o.delete(a)}),C9(t))this.persist(()=>this.kept.remove(e,s));return!0}forgetFolders(e,t){let i=this.liveFolders(e);t.forEach((n,r)=>i.delete(t.slice(0,r+1).join("/")))}rename(e,t,i){let n=this.get(e,t);if(!n)return"missing";let r=this.put(e,i,n.bytes);if(r==="full")return"missing";return this.delete(e,t),r}foldersOf(e){let t=this.folders.get(e)??new Map;return this.folders.set(e,t),t}filesOf(e){let t=this.files.get(e)??new Map;return this.files.set(e,t),t}liveFolders(e){let t=this.folders.get(e)??new Map,i=this.now();if([...t].forEach(([n,r])=>{if(dji(n,r,i))t.delete(n)}),t.size===0)this.folders.delete(e);return t}live(e){let t=this.files.get(e)??new Map,i=this.now();if([...t].forEach(([n,r])=>{if(dji(n,r.touched,i))t.delete(n)}),t.size===0)this.files.delete(e);return t}}class MHe{expected=new Map;now;constructor(e=Date.now){this.now=e}expect(e,t){let i=this.now();for(let[n,r]of this.expected)if(r<=i)this.expected.delete(n);this.expected.set(mji(e,t),i+30000)}take(e,t){let i=mji(e,t),n=this.expected.get(i);if(n===void 0)return!1;return this.expected.delete(i),n>this.now()}}function mji(e,t){return`${e}
|
|
9752
9752
|
${t.join("/")}`}import{createHash as Svo}from"crypto";var kvo=600000,Bvo=16777216;class OHe{held=new Map;now;capBytes;constructor(e=Date.now,t=Bvo){this.now=e,this.capBytes=t}hold(e,t,i){let n=this.live(e),r=t.join("/");n.delete(r);let o=this.now();n.set(r,{...i,savedAt:new Date(o),etag:`"held-${Svo("sha256").update(i.bytes).digest("hex")}"`,until:o+kvo});let s={bytes:0,full:!1,dropped:[]},{dropped:a}=[...n].reverse().reduce((c,[l,d],p)=>{let m=c.bytes+d.bytes.byteLength;return p>0&&(c.full||m>this.capBytes)?{...c,full:!0,dropped:[...c.dropped,l]}:{...c,bytes:m}},s);a.forEach((c)=>n.delete(c))}get(e,t){return this.live(e).get(t.join("/"))}release(e,t){this.held.get(e)?.delete(t.join("/"))}live(e){let t=this.now(),i=this.held.get(e)??new Map;return[...i].forEach(([n,r])=>{if(r.until<=t)i.delete(n)}),this.held.set(e,i),i}}import{randomUUID as Cvo}from"crypto";var hji=600;class NHe{locks=new Map;now;constructor(e=Date.now){this.now=e}acquire(e,t,i){if(this.live(e))return;let n={token:`opaquelocktoken:${Cvo()}`,userId:t,seconds:i,expires:this.now()+i*1000};return this.locks.set(e.join("/"),n),n}refresh(e,t,i,n){let r=this.live(e);if(!r||!fji(r,t,i))return;return r.seconds=n,r.expires=this.now()+n*1000,r}release(e,t,i){let n=this.live(e);if(n?.userId!==t||n.token!==i)return!1;return this.locks.delete(e.join("/"))}permits(e,t,i){let n=this.live(e);return!n||fji(n,t,i??"")}live(e){let t=e.join("/"),i=this.locks.get(t);if(i&&i.expires<=this.now()){this.locks.delete(t);return}return i}}function fji(e,t,i){return e.userId===t&&i.includes(`<${e.token}>`)}function xji(e){let t=/Second-(\d+)/i.exec(e??"")?.[1];return Math.min(t?Number(t):hji,hji)}function Dvo(e){let t=Hoe(e);if(t==="enum"){let i=ZU(e);return i?{type:"enum",enumValues:i}:{type:"enum"}}if(t==="literal")return{type:"string",defaultValue:VU(e)};if(t==="string")return{type:"string"};if(t==="number")return{type:"number"};if(t==="boolean")return{type:"boolean"};if(t==="array")return{type:"array"};if(t==="date")return{type:"date"};return{type:"unknown"}}function Ivo(e){let t=[];for(let[i,n]of Object.entries(e.shape)){if(tB(n)?.studioWidget==="hidden")continue;let{inner:r,required:o,defaultValue:s}=Goe(n),a=Dvo(r),c={name:i,type:a.type,required:o},l=s!==void 0?s:a.defaultValue;if(l!==void 0)c.defaultValue=l;if(a.enumValues)c.enumValues=a.enumValues;t.push(c)}return t}function LHe(e){return e.types().flatMap((t)=>{if(e.fileExtension(t)===".yaml")return[];let i=e.frontmatterSchema(t);if(!i)return[];return[{entityType:t,singleton:e.isSingleton(t),bodyTemplate:e.bodyTemplate(t),fields:Ivo(i)}]})}var _vo={"&":"&","<":"<",">":">"};function I9(e){return e.replace(/[&<>]/g,(t)=>_vo[t]??t)}var gji="<D:lockscope><D:exclusive/></D:lockscope><D:locktype><D:write/></D:locktype>";function Tvo(e){return[`<D:supportedlock><D:lockentry>${gji}</D:lockentry></D:supportedlock>`,`<D:displayname>${I9(e.displayName)}</D:displayname>`,e.collection?"<D:resourcetype><D:collection/></D:resourcetype>":"<D:resourcetype/>",e.contentLength!==void 0?`<D:getcontentlength>${e.contentLength}</D:getcontentlength>`:"",e.contentType?`<D:getcontenttype>${I9(e.contentType)}</D:getcontenttype>`:"",e.etag?`<D:getetag>${I9(e.etag)}</D:getetag>`:"",e.lastModified?`<D:getlastmodified>${e.lastModified.toUTCString()}</D:getlastmodified>`:""].join("")}function yji(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:">${e.map((i)=>`<D:response><D:href>${I9(i.href)}</D:href><D:propstat><D:prop>${Tvo(i)}</D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>`).join("")}</D:multistatus>`}function bji(e){return`<?xml version="1.0" encoding="utf-8"?><D:error xmlns:D="DAV:"><D:${e}/></D:error>`}function Eji(e){return`<?xml version="1.0" encoding="utf-8"?><D:prop xmlns:D="DAV:"><D:lockdiscovery><D:activelock>${gji}<D:depth>0</D:depth><D:timeout>Second-${e.seconds}</D:timeout><D:locktoken><D:href>${I9(e.token)}</D:href></D:locktoken><D:lockroot><D:href>${I9(e.href)}</D:href></D:lockroot></D:activelock></D:lockdiscovery></D:prop>`}function vji(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"><D:response><D:href>${I9(e)}</D:href><D:status>HTTP/1.1 200 OK</D:status></D:response></D:multistatus>`}var Pvo=[".brain","changes"],Rvo=50,Aji=25,wji=[".brain","conflicts"],Fvo=".brain",Mvo=65536,Ovo=1024,Nvo=[".brain","publish"],Lvo=u.object({path:u.string().min(1).max(Ovo)}),Sji=".brain/ask",kji=".brain/ask/confirm",jvo=[".brain","related"],Bji=10,zvo=25,Uvo=[".brain","vault-shapes.json"],qvo=["OPTIONS","GET","HEAD","PROPFIND"],Pji=["POST","PUT","DELETE","MOVE","COPY","PROPPATCH","MKCOL","LOCK","UNLOCK"],Rji=[...qvo,...Pji],$vo=Rji.filter((e)=>e!=="POST").join(", "),Kpe='application/xml; charset="utf-8"',Hvo={"X-Content-Type-Options":"nosniff","Content-Security-Policy":"sandbox","Cache-Control":"no-store"};function Fji(e){let t={options:e,mounts:e.mounts??LLi(e.now),scratch:new FHe(e.now,e.kept),locks:new NHe(e.now),cleanups:new MHe(e.now),holds:new OHe(e.now)},i={GET:(n,r)=>Iji(n,r,!0),HEAD:(n,r)=>Iji(n,r,!1),PROPFIND:Zvo,POST:eAo,PUT:Vvo,DELETE:rAo,MOVE:aAo,COPY:async()=>Y7("The drive does not copy files"),PROPPATCH:oAo,MKCOL:sAo,LOCK:uAo,UNLOCK:dAo};return Rji.map((n)=>({path:e.basePath,match:"prefix",method:n,public:!0,handler:async(r)=>{if(n==="OPTIONS")return gG(hAo());let o=await e.resolveAppPassword(r);if(!o)return gG(fAo(e.realm));if(Cji(n)&&o.access!=="write")return gG(Y7("This app password is read-only"));let s=r.headers.get("x-brain-sync")?.trim()==="1",a={request:r,grant:o,tree:new DHe(e.reader,cn(o.principal.permissionLevel),{everyType:s}),path:$ji(e.basePath,new URL(r.url).pathname),sync:s};if(Cji(n)&&n!=="LOCK"&&n!=="UNLOCK"&&a.path&&!Mji(t,a,a.path.segments))return gG(HHe());await t.scratch.open(o.principal.userId);let c=await i[n](t,a);return await t.scratch.settle(),gG(c)}}))}function Mji(e,t,i){return e.locks.permits(i,t.grant.principal.userId,t.request.headers.get("if"))}function Cji(e){return Pji.some((t)=>t===e)}function Ype(e,t){let{path:i}=t;return i&&!i.asFolder&&K7(i.segments)?e.scratch.get(t.grant.principal.userId,i.segments):void 0}function K7(e){let t=e[e.length-1];return t!==void 0&&(Oji(e)||pji(t))}function Oji(e){return e.some((t)=>t.startsWith("."))}async function Jpe(e,t){if(!t.path)return;let i=await t.tree.resolve(t.path.segments);if(i)return i.kind==="file"&&t.path.asFolder?void 0:i;return e.scratch.hasFolder(t.grant.principal.userId,t.path.segments)?{kind:"folder",segments:t.path.segments}:void 0}async function qHe(e,t,i){return i.length===0||e.scratch.hasFolder(t.grant.principal.userId,i)||(await t.tree.resolve(i))?.kind==="folder"}async function $He(e,t,i){if(i.kind!=="file"||t.sync)return;let n=t.grant.appPasswordId,r=e.holds.get(n,i.segments);if(!r)return;let{conflictPending:o}=e.options;if((r.conflictId===void 0||o===void 0||await o(r.conflictId))&&i.etag===`"${r.storedHash}"`)return r;e.holds.release(n,i.segments);return}async function Nji(e,t,i){let n=t.request.headers.get("if-match");if(n===null)return null;if(t.sync)return n;if(!e.holds.get(t.grant.appPasswordId,i))return n;let r=await t.tree.resolve(i);return(r?await $He(e,t,r):void 0)?.etag===n?null:n}async function Gvo(e,t){let i=new URL(t.request.url).searchParams,n=Number(i.get("wait")??Aji),r=Number.isFinite(n)?Math.min(Math.max(n,0),Rvo):Aji,o=await e.wait(i.get("since"),r*1000,t.request.signal),s="reset"in o?o:{cursor:o.cursor,types:[...new Set(o.types.map((a)=>t.tree.folderTypeOf(a)))]};return new Response(JSON.stringify(s),{status:200,headers:{"Content-Type":"application/json; charset=utf-8"}})}async function Wvo(e){let t=new URL(e.request.url).searchParams,i=t.get("path")??"";if(i==="")return new Response("Name the file with ?path=",{status:400});let n=Number(t.get("limit")??Bji),r=Number.isInteger(n)&&n>0?Math.min(n,zvo):Bji,o=await e.tree.related(i.split("/"),r)??[];return new Response(JSON.stringify(o==="unindexed"?{related:[],indexed:!1}:{related:o,indexed:!0}),{status:200,headers:{"Content-Type":"application/json; charset=utf-8"}})}async function Dji(e,t,i){let n=zHe(i,e.options.basePath),r=await $He(e,t,i);return r?{...n,contentLength:r.bytes.byteLength,etag:r.etag,lastModified:r.savedAt}:n}function Lji(e,t){let i=t.grant.appPasswordId,n=(t.path?.segments??[]).join("/");return{base:()=>e.mounts.get(i,n),held:(r)=>e.mounts.held(i,n,r),conflictKept:(r,o)=>e.mounts.conflictKept(i,n,r,o),forget:()=>e.mounts.forget(i,n)}}function Qpe(e,t){return{tree:t.tree,reader:e.options.reader,writes:e.options.writes,mount:Lji(e,t),recordConflict:async(i)=>e.options.recordConflict?.(i),folderExists:(i)=>qHe(e,t,i)}}async function Iji(e,t,i){let{shapes:n,changes:r}=e.options;if(t.sync&&t.path?.segments.join("/")===jvo.join("/"))return Wvo(t);if(t.sync&&r!==void 0&&t.path?.segments.join("/")===Pvo.join("/"))return Gvo(r,t);if(t.sync&&n!==void 0&&t.path?.segments.join("/")===Uvo.join("/")){let c=JSON.stringify({shapes:LHe(n).filter((l)=>l.entityType===hG||t.tree.isFolderType(l.entityType))});return new Response(i?c:null,{status:200,headers:{"Content-Type":"application/json; charset=utf-8",ETag:`"${Ht(c)}"`}})}let o=Ype(e,t);if(o)return new Response(i?o.bytes:null,{status:200,headers:{"Content-Type":"application/octet-stream","Content-Disposition":"attachment","Content-Length":String(o.bytes.byteLength),ETag:qji(o),"Last-Modified":o.modified.toUTCString()}});let s=await Jpe(e,t);if(!s)return Mh();if(s.kind==="folder")return UHe();let a=await $He(e,t,s);if(a)return new Response(i?a.bytes:null,{status:200,headers:{"Content-Type":s.contentType,"Content-Length":String(a.bytes.byteLength),ETag:a.etag,"Last-Modified":a.savedAt.toUTCString()}});return await Lji(e,t).held(s.etag.replace(/^"|"$/g,"")),new Response(i?await s.open():null,{status:200,headers:{"Content-Type":s.contentType,"Content-Length":String(s.size),ETag:s.etag,"Last-Modified":s.modified.toUTCString()}})}async function Zvo(e,t){let i=t.request.headers.get("depth");if(i!=="0"&&i!=="1")return new Response(bji("propfind-finite-depth"),{status:403,headers:{"Content-Type":Kpe}});let{basePath:n}=e.options,r=Ype(e,t);if(r)return jHe([Tji(r,n)]);let o=await Jpe(e,t);if(!o)return Mh();if(o.kind==="file"||i==="0")return jHe([await Dji(e,t,o)]);let s=t.grant.principal.userId,a=await t.tree.children(o.segments),c=new Set(a.filter((l)=>l.kind==="folder").map((l)=>l.segments[l.segments.length-1]));return jHe([zHe(o,n),...await Promise.all(a.map((l)=>Dji(e,t,l))),...e.scratch.listFolders(s,o.segments).filter((l)=>!c.has(l)).map((l)=>zHe({kind:"folder",segments:[...o.segments,l]},n)),...e.scratch.list(s,o.segments).map((l)=>Tji(l,n))])}async function Vvo(e,t){let{path:i}=t;if(!i)return Mh();if(i.asFolder||i.segments.length===0)return UHe();let{maxFileBytes:n,maxAssetBytes:r}=e.options.writes,o=await Uji(t.request,Math.max(n,r)),s=t.grant.principal.userId,a=K7(i.segments);if(!o){if(!a)e.cleanups.expect(s,i.segments);return new Response("The file is larger than the drive accepts",{status:413})}if(a){if(await qHe(e,t,i.segments))return UHe();return zji(e.scratch.put(s,i.segments,o))}let c=await _He(Qpe(e,t),{segments:i.segments,bytes:o,ifMatch:await Nji(e,t,i.segments),onlyIfAbsent:t.request.headers.get("if-none-match")?.trim()==="*",keepAsConflict:t.sync&&t.request.headers.get("x-brain-keep")?.trim()==="conflict",grant:t.grant});if(t.sync)return Kvo(e,t,i.segments,o,c);if("message"in c||c.etag===void 0)e.cleanups.expect(s,i.segments);return await Jvo(e,t,i.segments,o,c),bG(e,t,i.segments,c)}async function Kvo(e,t,i,n,r){if("message"in r)return bG(e,t,i,r);e.holds.release(t.grant.appPasswordId,i);let o=await t.tree.entityAt(i),s={};if(o)s.ETag=o.file.etag,s["X-Brain-Stored"]=r.conflictId!==void 0?"conflict":await Yvo(o.file,n)?"as-sent":"other-form";if(r.conflictId!==void 0)s["X-Brain-Conflict"]=r.conflictId;if(r.status===201)e.scratch.forgetFolders(t.grant.principal.userId,i.slice(0,-1));return new Response(null,{status:r.status,headers:s})}async function Yvo(e,t){if(e.size!==t.byteLength)return!1;let i=new Uint8Array(await new Response(await e.open()).arrayBuffer());return Buffer.from(i).equals(Buffer.from(t))}async function Jvo(e,t,i,n,r){if("message"in r)return;let o=t.grant.appPasswordId;if(r.etag!==void 0){e.holds.release(o,i);return}let s=await t.tree.entityAt(i);if(!s)return;e.holds.hold(o,i,{bytes:n,storedHash:s.entity.contentHash,conflictId:r.conflictId})}async function Qvo(e){let t=await Uji(e,Mvo);if(!t)return jji;try{return JSON.parse(new TextDecoder().decode(t))}catch{return}}var jji=Symbol("too large");function Xvo(){return new Response("The request is too large",{status:413})}async function eAo(e,t){let i=t.sync?t.path?.segments.join("/"):void 0,n=()=>({tree:t.tree,grant:t.grant,ask:e.options.ask,confirmAsk:e.options.confirmAsk}),r=[Sji,kji,Nvo.join("/")];if(i===void 0||!r.includes(i))return new Response("The drive takes no POST here",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}});let o=await Qvo(t.request);if(o===jji)return Xvo();if(i===Sji)return KLi(n(),o);if(i===kji)return YLi(n(),o);return tAo(e,t,o)}async function tAo(e,t,i){let n=Lvo.safeParse(i);if(!n.success)return new Response('Name the file: { "path": "\u2026" }',{status:400});let r=await t.tree.entityAt(n.data.path.split("/"));if(!r)return new Response("There is no entry at this path.",{status:409});let o=await e.options.publish?.({entityType:r.entity.entityType,id:r.entity.id,userId:t.grant.principal.userId,permissionLevel:t.grant.principal.permissionLevel});if(!o)return new Response("Nothing publishes here right now.",{status:503});if("message"in o)return new Response(o.message,{status:409});return new Response(JSON.stringify(o),{status:200,headers:{"Content-Type":"application/json; charset=utf-8"}})}function iAo(e){let[t,i,n,...r]=e;return t===wji[0]&&i===wji[1]&&n!==void 0&&r.length===0?n:void 0}async function nAo(e,t,i){return await e.options.resolveConflict?.({conflictId:i,action:"keep-current",userId:t.grant.principal.userId,permissionLevel:t.grant.principal.permissionLevel})?Zpe():new Response("Conflicts cannot be settled here right now.",{status:503})}async function rAo(e,t){let{path:i}=t;if(!i)return Mh();let n=t.sync&&!i.asFolder?iAo(i.segments):void 0;if(n!==void 0)return nAo(e,t,n);let r=t.grant.principal.userId;if(e.scratch.removeFolder(r,i.segments))return Zpe();if(!i.asFolder&&K7(i.segments)){if(e.scratch.delete(r,i.segments))return Zpe()}if(i.segments.length===0||(await t.tree.resolve(i.segments))?.kind==="folder")return Y7("The drive does not delete folders");if(i.asFolder)return Mh();if(t.request.headers.get("if-match")===null&&e.cleanups.take(r,i.segments))return new Response("The file is kept: the save just before was refused or stored in another form. Delete it again to remove it.",{status:409});let o=await oji(Qpe(e,t),{segments:i.segments,ifMatch:await Nji(e,t,i.segments),grant:t.grant});if(!("message"in o))e.holds.release(t.grant.appPasswordId,i.segments);return bG(e,t,i.segments,o)}async function oAo(e,t){let i=Ype(e,t)??await Jpe(e,t);if(!i||!t.path)return Mh();let n="kind"in i&&i.kind==="folder",r=yG(t.path.segments);return new Response(vji(`${e.options.basePath}/${r}${n&&r?"/":""}`),{status:207,headers:{"Content-Type":Kpe}})}async function sAo(e,t){let{path:i}=t;if(!i)return Mh();if((await t.request.arrayBuffer()).byteLength>0)return new Response("MKCOL takes no body",{status:415});let{segments:n}=i,r=t.grant.principal.userId;if(n.length===0||await t.tree.resolve(n)||e.scratch.hasFolder(r,n)||e.scratch.get(r,n))return new Response("Already exists",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}});if(!await qHe(e,t,n.slice(0,-1)))return new Response("The parent folder does not exist",{status:409});let[o]=n;if(!Oji(n)&&(o===void 0||!t.tree.isFolderType(o)))return Y7("Only an entity type can be a folder here");return e.scratch.makeFolder(r,n),new Response(null,{status:201})}async function aAo(e,t){let i=t.request.headers.get("destination");if(!i)return new Response("Destination required",{status:400});let n=pAo(e.options.basePath,t.request,i);if(!n)return new Response("Destination is not on this drive",{status:502});let{path:r}=t;if(!r)return Mh();if(!Mji(e,t,n.segments))return HHe();let o=t.request.headers.get("overwrite")?.toUpperCase()!=="F";if(r.asFolder)return Y7("The drive does not rename files");if(!K7(r.segments))return K7(n.segments)?lAo(e,t,r.segments,n.segments,o):cAo(e,t,r.segments,n.segments);let s=t.grant.principal.userId,a=e.scratch.get(s,r.segments);if(!a)return Mh();if(K7(n.segments)){if(!o&&e.scratch.get(s,n.segments))return Vpe("The destination exists");let l=e.scratch.rename(s,r.segments,n.segments);return l==="missing"?Mh():new Response(null,{status:l==="created"?201:204})}if(!o&&await t.tree.entityAt(n.segments))return Vpe("The destination exists");let c=await _He(Qpe(e,t),{segments:n.segments,bytes:a.bytes,ifMatch:null,grant:t.grant});if(c.status<300)e.scratch.delete(s,r.segments),e.holds.release(t.grant.appPasswordId,n.segments);return bG(e,t,n.segments,c)}async function cAo(e,t,i,n){let r=await rji(Qpe(e,t),{from:i,to:n,grant:t.grant});if(r.status<300){let o=t.grant.appPasswordId,s=await e.mounts.get(o,i.join("/"));if(await e.mounts.forget(o,i.join("/")),s)await e.mounts.held(o,n.join("/"),s.hash);e.holds.release(o,i)}return bG(e,t,n,r)}async function lAo(e,t,i,n,r){let o=await t.tree.entityAt(i);if(!o)return Mh();let s=t.grant.principal.userId;if(!r&&e.scratch.get(s,n))return Vpe("The destination exists");let a=new Uint8Array(await new Response(await o.file.open()).arrayBuffer());return zji(e.scratch.put(s,n,a))}async function uAo(e,t){let{path:i}=t;if(!i||i.segments.length===0)return Mh();if(i.segments[0]===Fvo)return Y7("There is nothing to lock here");let n=t.grant.principal.userId,r=xji(t.request.headers.get("timeout")),o=t.request.headers.get("if"),s=(await t.request.arrayBuffer()).byteLength>0;if(o&&!s){let l=e.locks.refresh(i.segments,n,o,r);return l?_ji(e,i.segments,l,200):Vpe("No such lock to refresh")}let a=e.locks.acquire(i.segments,n,r);if(!a)return HHe();let c=Ype(e,t)!==void 0||await Jpe(e,t)!==void 0;return _ji(e,i.segments,a,c?200:201)}function _ji(e,t,i,n){return new Response(Eji({...i,href:`${e.options.basePath}/${yG(t)}`}),{status:n,headers:{"Content-Type":Kpe,"Lock-Token":`<${i.token}>`}})}async function dAo(e,t){let{path:i}=t;if(!i)return Mh();let n=/<([^>]+)>/.exec(t.request.headers.get("lock-token")??"")?.[1];if(!n)return new Response("Lock-Token required",{status:400});return e.locks.release(i.segments,t.grant.principal.userId,n)?Zpe():new Response("No such lock",{status:409})}function bG(e,t,i,n){if("message"in n)return new Response(n.message,{status:n.status});if(n.status===201)e.scratch.forgetFolders(t.grant.principal.userId,i.slice(0,-1));return new Response(null,{status:n.status,headers:n.etag?{ETag:n.etag}:{}})}function zji(e){return e==="full"?new Response("Too many temporary files",{status:507}):new Response(null,{status:e==="created"?201:204})}async function Uji(e,t){if(Number(e.headers.get("content-length")??0)>t)return;let i=new Uint8Array(await e.arrayBuffer());return i.byteLength>t?void 0:i}function zHe(e,t){let i=e.segments[e.segments.length-1]??"";if(e.kind==="folder"){let n=yG(e.segments);return{href:n?`${t}/${n}/`:`${t}/`,displayName:i,collection:!0}}return{href:`${t}/${yG(e.segments)}`,displayName:i,collection:!1,contentLength:e.size,contentType:e.contentType,etag:e.etag,lastModified:e.modified}}function Tji(e,t){return{href:`${t}/${yG(e.segments)}`,displayName:e.segments[e.segments.length-1]??"",collection:!1,contentLength:e.bytes.byteLength,contentType:"application/octet-stream",etag:qji(e),lastModified:e.modified}}function qji(e){return`"scratch-${e.modified.getTime()}-${e.bytes.byteLength}"`}function yG(e){return e.map(encodeURIComponent).join("/")}function $ji(e,t){if(t!==e&&!t.startsWith(`${e}/`))return;let i=t.slice(e.length+1);if(i==="")return{segments:[],asFolder:!0};let n=i.endsWith("/"),o=(n?i.slice(0,-1):i).split("/").map(mAo);return o.every((s)=>s!==void 0&&s!==""&&!/[/\\\0]/.test(s))?{segments:o.filter((s)=>s!==void 0),asFolder:n}:void 0}function pAo(e,t,i){let n=new URL(t.url),r=URL.canParse(i,n)?new URL(i,n):void 0;if(r?.host!==n.host)return;let o=$ji(e,r.pathname);return o&&!o.asFolder&&o.segments.length>0?o:void 0}function mAo(e){try{return decodeURIComponent(e)}catch{return}}function jHe(e){return new Response(yji(e),{status:207,headers:{"Content-Type":Kpe}})}function hAo(){return new Response(null,{status:200,headers:{DAV:"1, 2",Allow:$vo,"MS-Author-Via":"DAV"}})}function fAo(e){return new Response("Authentication required",{status:401,headers:{"WWW-Authenticate":`Basic realm="${e.replace(/["\\]/g,"")}", charset="UTF-8"`}})}function UHe(){return new Response("A folder has no content",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}})}function Zpe(){return new Response(null,{status:204})}function Mh(){return new Response("Not found",{status:404})}function Y7(e){return new Response(e,{status:403})}function HHe(){return new Response("The file is locked",{status:423})}function Vpe(e){return new Response(e,{status:412})}function gG(e){let t=new Headers(e.headers);return Object.entries(Hvo).forEach(([i,n])=>t.set(i,n)),new Response(e.body,{status:e.status,headers:t})}var GHe="/dav",xAo=5242880,Hji=u.strictObject({maxFileBytes:u.number().int().positive().describe("Maximum bytes of a file a client may save").default(xAo)}),gAo=zt({id:"webdav",config:Hji,setup:(e)=>{let t=ft(e);if(t.executionOnly)return{routes:[]};t.registered(()=>{if(t.entityReads.getEntityTypes().includes(ds))return;throw Error(`webdav needs the "${ds}" entity type to keep saves that lose to a newer version. Add "conflict" to this brain, which the core bundle includes.`)});let i=new kHe;for(let r of[Ds,ho,gu,Zb])t.listen(r,({payload:o})=>i.record(o.entityType),{mode:"observe"});t.listen(Cr.shuttingDown,()=>i.close(),{mode:"observe"});let n=jLi(t.classRuntimeState);return t.ready(()=>n.sweep()),t.interaction({id:yse,label:"Drive",description:"Mount the brain as a network drive over WebDAV.",href:`${GHe}/`,kind:"protocol",priority:40,visibility:"trusted"}),{routes:Fji({basePath:GHe,realm:t.identity.get().name,reader:t.entityReads,shapes:t.entityShapes,changes:i,writes:{maxFileBytes:e.config.maxFileBytes,maxAssetBytes:bT,stageAsset:(r,o)=>t.entityWrites.stageAsset(r,o),discardStagedAsset:(r)=>t.entityWrites.discardStagedAsset(r),deserializeEntity:(r,o)=>t.entityReads.deserializeEntity(r,o),createEntity:(r)=>t.entityWrites.createEntity(r),updateEntity:(r)=>t.entityWrites.updateEntity(r),deleteEntity:(r)=>t.entityWrites.deleteEntity(r),renameEntity:(r)=>t.entityWrites.renameEntity(r),permissions:t.permissions,recordAudit:async(r)=>{await t.auth()?.recordAuditEvent(r)}},resolveAppPassword:async(r)=>t.auth()?.resolveAppPassword(r),mounts:n,kept:qLi(t.classRuntimeState),recordConflict:async(r)=>{let o=await t.messaging.request(d8,r);return o.status==="answered"?o.data.conflictId:void 0},ask:async(r)=>{let o=await t.messaging.request(Xpe,r);if(o.status==="answered")return o.data;return o.status==="failed"?{message:o.error.message}:void 0},confirmAsk:async(r)=>{let o=await t.messaging.request(eme,r);if(o.status==="answered")return o.data;return o.status==="failed"?{message:o.error.message}:void 0},publish:async(r)=>{let o=await t.messaging.request(Tse,r);if(o.status==="answered")return o.data;return o.status==="failed"?{message:o.error.message}:void 0},resolveConflict:async(r)=>{let o=await t.messaging.request(F_,r);if(o.status==="answered")return{resolved:!0};return o.status==="failed"?{message:o.error.message}:void 0},conflictPending:async(r)=>await t.entityReads.getEntityRaw({entityType:ds,id:r,visibilityScope:et("ask only whether a conflict is still waiting to be resolved")})!==null})}}}),WHe=Do(gAo,({state:e})=>e.routes);var Gji=WHe;var yAo=u.object({errcode:u.string()}),bAo=u.object({session:u.string()});async function ZHe(e){let t=e.fetch??fetch,i=`${e.homeserverUrl.replace(/\/+$/,"")}/_matrix/client/v3`,n=e.userId.slice(1).split(":")[0]??"",r=(p,m)=>t(`${i}${p}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(m)}),o=await r("/login",{type:"m.login.password",identifier:{type:"m.id.user",user:n},password:e.password,device_id:"brain-bootstrap"});if(o.ok)return"exists";let s=await Wji(o);if(s!=="M_FORBIDDEN")throw Error(`Matrix bot login failed: ${s??o.status}`);let a={username:n,password:e.password,inhibit_login:!0},c=await r("/register",a),l=bAo.safeParse(await c.json().catch(()=>{return}));if(!l.success)throw Error(`Matrix bot registration did not start: ${c.status}`);let d=await r("/register",{...a,auth:{type:"m.login.registration_token",token:e.registrationToken,session:l.data.session}});if(!d.ok)throw Error(`Matrix bot registration failed: ${await Wji(d)??d.status}`);return"registered"}async function Wji(e){let t=yAo.safeParse(await e.json().catch(()=>{return}));return t.success?t.data.errcode:void 0}var VHe="matrix-homeserver";function tme(e){return`${e.replace(/\/+$/,"")}/_matrix/client/unstable/login/sso/callback/matrix-homeserver`}function Eb(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`}function KHe(e){let t=e.publicBaseUrl.replace(/\/+$/,"");return`[global]
|
|
9753
9753
|
server_name = ${Eb(e.serverName)}
|
|
@@ -11337,5 +11337,5 @@ ${Hhe}</style><link rel="stylesheet" href="${b9o}"></head><body class="guest-pag
|
|
|
11337
11337
|
`);return{kind:"text",filename:"inbox-source.txt",mediaType:"text/plain",content:l,sizeBytes:new TextEncoder().encode(l).byteLength}}catch{return cKe()}}async readEntryContext(e,t){let i=YVi(e);if(!i)return null;let n=await this.runtime.request(Ese,{...i,visibilityScope:cn(t)}).catch(()=>null);return n?.status==="answered"?n.data:null}async handleContextSessionRequest(e){let t=na(e);if(t)return t;return VZi(e,{conversations:this.runtime.conversations,resolveAccess:(i)=>this.resolveConversationAccess(i),interfaceType:hm,authorizeSource:async({sourceId:i,itemId:n,permissionLevel:r,signal:o})=>{if(i===lKe)return await this.readEntryContext(n,r)!==null;let s=this.runtime.inbox.getSource(i);if(!s?.resolveDetail)return!1;return await s.resolveDetail(n,{permissionLevel:r},o),!0}})}async handleSessionsRequest(e){return rVi(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:hm})}async handleDeleteSessionRequest(e){return oVi(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:hm})}async handleRenameSessionRequest(e){return sVi(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:hm})}async handleArchiveSessionRequest(e){return aVi(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:hm})}async handleDocumentAttachmentRequest(e){return rZi(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleImageAttachmentRequest(e){return oZi(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleJobStatusRequest(e){return JZi(e,{resolveAuthSession:this.resolveAuthSession,createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),jobs:this.runtime.jobs})}async handleMessagesRequest(e){return uVi(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:hm})}async resolveConversationAccess(e){let t=await this.resolveBrowserAccess(e);return this.toConversationAccess(t.permissionLevel,t.principal)}toConversationAccess(e,t){return{permissionLevel:e,...t?{personId:t.personId}:{}}}requireExistingWebChatConversation(e,t){return this.requireExistingBrowserConversation(e,hm,t)}ensureWebChatConversation(e,t){return this.ensureBrowserConversation(e,hm,"Web Chat",t)}async requireExistingBrowserConversation(e,t,i){let n=await this.runtime.conversations.get(e);return Db(n,i,t)?void 0:new Response("Conversation not found",{status:404})}async ensureBrowserConversation(e,t,i,n){let r=await this.runtime.conversations.get(e);if(r)return Db(r,n,t)?void 0:new Response("Conversation not found",{status:404});if(n.permissionLevel==="trusted"&&!n.personId)return new Response("Forbidden",{status:403});await this.runtime.conversations.start({sessionId:e,interfaceType:t,channelId:e,...n.personId?{personId:n.personId}:{},metadata:{channelName:i,interfaceType:t,channelId:e}});let o=await this.runtime.conversations.get(e);return Db(o,n,t)?void 0:new Response("Conversation not found",{status:404})}getActiveStream(e){if(!e)return;return this.activeStreams.get(e)}async resolveBrowserAccess(e){let t=await this.resolveAuthPrincipal(e);if(t){let n=t.status==="active"&&(t.permissionLevel==="admin"||t.permissionLevel==="trusted");return{principal:t,permissionLevel:n?t.permissionLevel:"public",hasChatAccess:n}}if(this.resolveCallerPermissionLevel){let n=await this.resolveCallerPermissionLevel(e);return{permissionLevel:n,hasChatAccess:n==="admin"||n==="trusted"}}let i=this.resolveAuthSessionOverride?await this.resolveAuthSessionOverride(e):!1;return{permissionLevel:i?"admin":"public",hasChatAccess:i}}async resolvePermissionLevel(e){return(await this.resolveBrowserAccess(e)).permissionLevel}async resolveAttachmentPermissionLevel(e){return this.resolvePermissionLevel(e)}createAuthLoginRequiredResponse(e){let t=this.runtime.auth();if(t)return t.createAuthLoginResponse(e);return new Response("Authentication required",{status:401,headers:{"Content-Type":"text/plain; charset=utf-8"}})}writeText(e,t,i){return Uhe(e,t,i,(n)=>this.createId(n))}createId(e){return`${e}-${crypto.randomUUID()}`}}function cKe(){return new Response("Inbox context is unavailable",{status:409})}function uKe(e={}){let t=Hh({id:hm,config:VVe,setup:async(r)=>{let o=xs(r),s=new XVi(r.config,e,o,r.runtimeState(ZT));return await s.register(),o.ready(()=>s.onReady()),s}}),i=Do(t,({state:r})=>r.webRoutes()),n=fg(i,({state:r})=>{let o=r.maintenanceDaemon();return{id:"guest-maintenance",start:()=>o.start(),stop:()=>o.stop(),healthCheck:()=>o.healthCheck()}});return qoe(n,({state:r})=>r.transport())}var iCo=uKe(),eKi=iCo;var dKe='Mandatory unmet-request routing: Wish entities record requested capabilities or desired end states whose literal completion is outside the available toolset. When the user asks for an unavailable product, capability, or real-world outcome no installed tool can perform, explain the limitation and call system_create with entityType "wish" unless the user declines. Availability is determined by the callable tool surface: an installed interface or transport that exposes no tool for the requested action cannot fulfill it. Authorization and ownership boundaries are not missing capabilities: when the current caller permission level, visibility policy, confirmation requirements, or system-maintained record ownership blocks an operation, explain that boundary and MUST NOT call system_create for a wish. A tool withheld from the current caller because of their permission level is also an authorization boundary, not an unmet product request. Do not search durable content to discover executable capabilities or permission workarounds; the callable tool surface and current permission context are authoritative. If you recognize that no callable tool can perform the action and no authorization or ownership boundary applies, do not end the turn after explaining the limitation; in that same turn you MUST call system_create with entityType "wish". The unmet request itself is concrete source material; do not merely decline, offer alternatives, or wait for a separate save verb. Do not invent or look for a dedicated wishlist tool; wishlist entries use the generic entity tools. They track demand, priority, and status for future capability planning; they are not a substitute for first-class entities that already support the requested action. To show the whole wishlist, call system_list once with entityType wish and omit status; only include status when the user asks for a specific wish status.';var tKi={critical:0,high:1,medium:2,low:3};function iKi(e){return[...e].sort((t,i)=>{let n=i.metadata.requested-t.metadata.requested;if(n!==0)return n;return tKi[t.metadata.priority]-tKi[i.metadata.priority]})}var yW=u.enum(["new","planned","in-progress","done","declined"]),bW=u.enum(["low","medium","high","critical"]),ife=u.object({title:u.string(),status:yW,priority:bW.default("medium"),requested:u.number().int().default(1).meta({studioWidget:"provenance"}),declinedReason:u.string().optional()}),pKe=u.object({title:u.string(),status:yW,priority:bW,requested:u.number().int().meta({studioWidget:"provenance"}),slug:u.string().optional().meta({studioWidget:"hidden"}),declinedReason:u.string().optional()});var nCo=u.object({items:u.array(u.object({id:u.string(),name:u.string(),count:u.number().int().nonnegative(),priority:bW,status:yW}))});function rCo(e){if(e==="critical")return"error";if(e==="high")return"warn";return"neutral"}var mKe=oo({id:"top-wishes",title:"Top Wishes",group:"knowledge",placement:"secondary",priority:30,permission:"public",data:nCo,digest:({data:e})=>{let t=e.items[0];return{items:t?[{label:"Top wish",value:`${t.name} \xB7 \xD7${t.count}`}]:[{label:"Wishes",value:"none yet"}]}},view:({data:e})=>({blocks:[{type:"list",id:"wishes",empty:"No wishes yet.",items:e.items.map((t)=>({id:t.id,title:t.name,count:t.count,badges:[{label:t.priority,tone:rCo(t.priority)},{label:t.status,tone:t.status==="done"?"good":"neutral"}]}))}]})});function oCo(e){return mKe.bind(e,async({entities:t,signal:i})=>(i.throwIfAborted(),{items:iKi(await t.list(_b,{limit:10})).map((r)=>({id:r.id,name:r.metadata.title,count:r.metadata.requested,priority:r.metadata.priority,status:r.metadata.status}))}))}var _b=Yn(dt({type:"wish",purpose:"A demand record the assistant proactively creates when a user requests a capability or outcome no installed tool can fulfill, unless the user declines.",metadata:pKe,markdown:{decode:({content:e,frontmatter:t})=>{let i=ife.parse(t);return{content:e,metadata:{title:i.title,status:i.status,priority:i.priority,requested:i.requested,slug:Mt(i.title),...i.declinedReason!==void 0&&{declinedReason:i.declinedReason}}}},encode:({content:e,metadata:t})=>({content:e,frontmatter:{title:t.title,status:t.status,priority:t.priority,requested:t.requested,...t.declinedReason!==void 0&&{declinedReason:t.declinedReason}}})},config:{projectionSource:!1,projectionSourceRole:"excluded"},instructions:dKe,dashboardWidgets:(e)=>[oCo(e)]}),ife);var nKi=0.3,sCo="Do these two wishes ask for the same thing?",aCo=u.object({same:u.boolean().describe("True only when delivering one would fulfil the other.")});async function cCo(e,t,i){let{same:n}=await e.generateObject([sCo,"Answer yes when both ask for the same capability, even if wording, timing or detail differ (weekly vs every Monday, calendar sync vs Google Calendar integration).","Opposite or different capabilities are different wishes, even when worded almost alike: send emails vs stop sending emails, add vs remove.","","New wish:",t,"","Existing wish:",i].join(`
|
|
11338
11338
|
`),aCo);return n}function nfe(e,t,i){return{nearest:(n,r)=>e.nearest(_b,n,{maxDistance:r}),getEntity:(n)=>t.get(_b,n),maxDistance:i,ai:e}}async function rfe(e,t){let i=(await e.nearest(t.content,e.maxDistance)).flatMap(({entity:s})=>s.visibility==="public"?[s]:[]),n=async(s)=>{let a=i[s];if(!a)return;return await cCo(e.ai,t.content,lCo(a))?a:n(s+1)},r=await n(0);if(r)return r;let o=await e.getEntity(Mt(t.title));return o?.visibility==="public"?o:null}function lCo(e){let{title:t,status:i,priority:n,requested:r,declinedReason:o}=e.metadata;return EW({title:t,status:i,priority:n,requested:r,declinedReason:o},e.content)}function EW(e,t){let i=Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0&&n!==null));return Object.keys(i).length>0?xn(i,t):t}var rKi=u.object({title:u.string(),description:u.string()}),uCo=u.object({stored:rKi,incoming:rKi}),hKe="eval-stored-wish";function oKi(e){return EW({title:e.title,status:"new",priority:"medium",requested:1},e.description)}function sKi(e){return{sameWish:async(t,i)=>{let{stored:n,incoming:r}=uCo.parse(t),{fixtures:o}=i;await o.reset(),await o.seed({id:hKe,entityType:"wish",content:oKi(n),metadata:{title:n.title,status:"new",priority:"medium",requested:1,slug:Mt(n.title)}}),await o.settleEmbeddings();let s=Ut(i),a=oKi(r),c=(await s.nearest(_b,a,{maxDistance:2})).find(({entity:d})=>d.id===hKe)?.distance;if(c===void 0)throw Error("The stored wish was not embedded");let l=await rfe(nfe(s,i.entities,e),{title:r.title,content:a});return{distance:c,shortlisted:c<=e,sameWish:l?.id===hKe}}}}async function dCo(e,t){let{input:i}=e;if(i.visibility!==void 0&&i.visibility!=="public")return{refuse:"Wish creation currently supports public visibility only; use a note for shared or restricted capture."};let n=i.title??i.prompt??"Untitled wish",r=i.content??i.prompt??"",o={title:n,status:"new",priority:"medium",requested:1},s=await rfe(nfe(Ut(e),e.entities,t),{title:n,content:EW(o,r)});if(s)return{update:{id:s.id,content:s.content.trim(),metadata:{...s.metadata,requested:s.metadata.requested+1}}};let a=Mt(n);return{create:{id:a,content:r,metadata:{...o,slug:a}}}}function aKi(e){let t={resolve:(i)=>dCo(i,e)};return{fromPrompt:t,fromContent:t,fromUpload:t}}var fKe=u.object({sameWishDistance:u.number().min(0).max(1).default(nKi)});var pCo=Rn({id:"wishlist",config:fKe,entities:[_b],configure:({config:e})=>({entities:[{entity:_b,create:aKi(e.sameWishDistance),evals:sKi(e.sameWishDistance)}]})}),cKi=pCo;var lKi="gpt-6-luna";var aw={create:"trusted",update:"trusted",delete:"admin",extract:"admin",publish:"admin"},uKi=[{member:"content-pipeline",value:{generationSchedules:{newsletter:"0 9 * * 1","social-post":"0 10 * * *"},generationConditions:{newsletter:{skipIfDraftExists:!0,minSourceEntities:1,sourceEntityType:"post"},"social-post":{skipIfDraftExists:!0,maxUnpublishedDrafts:5}}}},{member:"social-media",value:{autoGenerateOnBlogPublish:!0}}],dKi=["Use the installed publishing capabilities for professional website content, essays, projects, decks, newsletters, and social distribution workflows. Treat publishing requests as production and distribution work rather than generic shared-memory capture.",`When answering questions like "what have I written about X" or "which posts relate to this deck/source", search first and use semantic search results as candidates, not proof. Summarize only clearly relevant entities whose title or content directly matches the asked topic or has substantial overlap with the source's main themes; omit weak/tangential candidates rather than presenting them as definite matches. A match based on only an isolated shared term or pattern is not enough; when one candidate is clearly stronger than the rest, list only the strongest clear match and say the others were tangential rather than naming them as matches.`,'Draft blog posts are only post entities with status draft. If the user asks whether draft blog posts exist, call only system_list for entityType post with status draft; do not also list social-post, newsletter, deck, or other draft entity types. After telling the user there are no draft blog posts, treat follow-ups like "make one draft" or "make one a draft" as requests to change an existing published post back to draft: ask which existing published post they want changed; do not offer to create a brand-new post and do not call system_generate to create a fresh draft from that ambiguous follow-up.'],pKi=[{member:"topics",value:{extractableStatuses:["published","draft"]}},{member:"conversation-memory",value:{memoryVisibility:"shared"}},{member:"action-board",value:{cardVisibility:"shared"}}],mKi=["This is a collaborative team-memory and synthesis posture. Optimize for capturing shared context, finding what the team already knows, summarizing cross-source evidence with attribution, and coordinating with peer brains.","Do not default to personal publishing, personal branding, blog, newsletter, social-media, portfolio, or marketing workflows unless the installed capabilities and the user's request explicitly support them."];var cw="capability-bundles-v1";var xKe="core",gKe="media",yKe="automation",vW="web",bKe="chat",EKe="site",vKe="publishing",AKe="federation",wKe="team",mCo="matrix",ofe=vm({id:xKe,members:["profile","prompt","conflict","style-guide","directory-sync","note","refined-note","link","topics","unified-inbox","mcp","a2a","agents"],evalDisable:["mcp"]}),sfe=vm({id:gKe,members:["document","image"]}),afe=vm({id:yKe,members:["playbooks","onboarding"]}),cfe=vm({id:vW,members:["auth-service","admin","dashboard","studio","webdav"],http:!0,config:[{member:"dashboard",value:{routePath:"/"}}],permissions:[{member:"mcp",config:{rules:[{pattern:"mcp:http",level:"public"}]}},{member:"studio",config:{entityActions:{"grouping-definitions":{create:"admin",update:"admin",delete:"admin",publish:"never"}}}}],evalDisable:["dashboard"]}),lfe=vm({id:bKe,members:["chat","web-chat","ask-content","email","notifications","conversation-memory","faq"],permissions:[{member:"chat",config:{rules:[{pattern:"discord:*",level:"public"}]}},{member:"web-chat",config:{rules:[{pattern:"web-chat:*",level:"admin"}]}}],evalDisable:["chat","web-chat","email","faq"]}),ufe=vm({id:EKe,members:["site-info","site-content","site-builder","form","analytics"],config:[{member:"dashboard",value:{routePath:"/dashboard"},overrides:vW}]}),dfe=vm({id:vKe,members:["blog","series","portfolio","decks","content-pipeline","social-media","newsletter","stock-photo"],config:uKi,agentInstructions:dKi}),pfe=vm({id:AKe,members:["atproto","references"],evalDisable:["atproto"]}),mfe=vm({id:wKe,members:[],config:pKi,permissions:[{member:"note",config:{entityActions:{note:aw}}},{member:"refined-note",config:{entityActions:{"refined-note":aw}}},{member:"link",config:{entityActions:{link:aw}}},{member:"image",config:{entityActions:{image:aw}}},{member:"docs",config:{entityActions:{doc:aw}}},{member:"conversation-memory",config:{entityActions:{decision:aw,insight:aw,"action-item":aw}}},{member:"mcp",config:{rules:[{pattern:"mcp:http",level:"admin"}]},overrides:vW}],agentInstructions:mKi}),hCo=vm({id:mCo,members:["matrix-server"],http:!0,permissions:[{member:"chat",config:{rules:[{pattern:"matrix:*",level:"public"}]}}]}),hKi=[ofe,sfe,afe,cfe,lfe,ufe,dfe,pfe,hCo,mfe];function tC(e,t,i){let n={name:e,version:xk.version};return(r)=>Am(t,r,n,i)}function fCo(e){let{entity:t,provider:i}=ONi(e),n={name:"@brains/newsletter",version:xk.version};return[...Am(t.definition,t.config,n,{pluginId:"newsletter"}),...i?Am(i.definition,i.config,n,{pluginId:i.kind}):[]]}function Zi(e,t,i,n={},r=void 0){return[e,tC(t,i,n),r]}function AW(e,t,i,n,r={}){return[e,tC(t,i,r),n]}var fKi=zfe({name:"brain",version:xk.version,bundleContract:cw,model:lKi,reasoningEffort:"low",capabilities:[Zi("prompt","@brains/prompt",zUi,{pluginId:"prompt"}),Zi("conflict","@brains/conflict",LUi,{pluginId:"conflicts"}),Zi("profile","@brains/profile",GGe,{pluginId:"profile"}),Zi("style-guide","@brains/style-guide",GHi,{pluginId:"style-guide"}),Zi("ask-content","@brains/ask-content",ZHi,{pluginId:"ask-content"}),["image",(e)=>[...tC("@brains/image-plugin",DOi,{pluginId:"image"})(e),...tC("@brains/image-plugin",COi,{})({})],void 0],["document",(e)=>[...tC("@brains/document-plugin",g2i,{pluginId:"document"})(e),...tC("@brains/document-plugin",x2i,{})({})],void 0],Zi("note","@brains/note",QNi,{pluginId:"note"}),Zi("refined-note","@brains/refined-note",$Ui,{pluginId:"refined-note"}),Zi("link","@brains/link",HOi,{pluginId:"link"}),Zi("references","@brains/reference",aNi,{pluginId:"references",ownedTypePluginId:"reference"}),Zi("wishlist","@brains/wishlist",cKi,{pluginId:"wishlist"}),["topics",(e)=>[...Am(GGi,e,{name:"@brains/topics",version:xk.version},{pluginId:"topics"}),...Am(mVe,{},{name:"@brains/knowledge-map",version:xk.version},{pluginId:"knowledge-map"})],void 0],Zi("decks","@brains/decks",b1i,{pluginId:"decks"}),Zi("directory-sync","@brains/directory-sync",K8i,{pluginId:"directory-sync"},{seedContent:!0,seedContentPath:"./seed-content",initialSync:!0}),Zi("atproto-registry","@brains/atproto-registry",NEe,{pluginId:"atproto-registry"}),["agents",(e)=>{let{enableSkillDerivation:t,notifyOnNewAgents:i,askAllApproved:n}=hot.parse(e),r={name:"@brains/agent-discovery",version:xk.version};return[...Am(Lbe,{},r,{pluginId:"agent-discovery",ownedTypePluginId:"agent-entity"}),...Am(jbe,{notifyOnNewAgents:i,askAllApproved:n},r,{pluginId:"agent"}),...Am(t?zbe:qbe,{},r,{pluginId:"skill",ownedTypePluginId:"skill-entity"}),...Am(Ube,{},r,{pluginId:"shared-copies",ownedTypePluginId:"shared-copy"})]},void 0],["assessment",(e)=>Am(fEe.parse(e).enableSwotDerivation?xEe:gEe,{},{name:"@brains/assessment",version:xk.version},{pluginId:"swot"}),void 0],Zi("auth-service","@brains/auth-service",q1e,{pluginId:"auth-service"}),Zi("notifications","@brains/notifications",tLi,{pluginId:"notifications"}),Zi("contact","@brains/contact",MEi,{pluginId:"contact",dependencies:FEi}),Zi("quiz","@brains/quiz",ovi,{pluginId:"quiz",dependencies:rvi}),Zi("playbooks","@brains/playbooks",gGe,{pluginId:"playbooks"}),Zi("onboarding","@brains/onboarding",ZUi,{pluginId:"onboarding",dependencies:["playbook","playbooks"]}),Zi("studio","@brains/studio",_bi,{pluginId:"studio"}),Zi("dashboard","@brains/dashboard",Gwi,{pluginId:"dashboard"}),Zi("admin","@brains/admin",Cxe,{pluginId:"admin"}),Zi("site-info","@brains/site-info",SZe,{pluginId:"site-metadata"}),Zi("site-content","@brains/site-content",AHi,{pluginId:"site-content",ownedTypePluginId:"site-content-entity"}),Zi("site-builder","@brains/site-builder-plugin",bHi,{pluginId:"site-builder"}),Zi("form","@brains/form",NEi,{pluginId:"form"}),Zi("analytics","@brains/analytics",Uot,{pluginId:"analytics"}),Zi("blog","@brains/blog",fvt,{pluginId:"blog"}),Zi("series","@brains/series",n$i,{pluginId:"series"}),Zi("portfolio","@brains/portfolio",rUi,{pluginId:"portfolio"}),Zi("content-pipeline","@brains/content-pipeline",sEi,{pluginId:"content-pipeline"}),Zi("social-media","@brains/social-media",jHi,{pluginId:"social-media"}),["newsletter",fCo,void 0],Zi("stock-photo","@brains/stock-photo",$Hi,{pluginId:"stock-photo"}),["atproto",tC("@brains/atproto",kst,{pluginId:"atproto"}),(e)=>({...e.ATPROTO_APP_PASSWORD?{appPassword:e.ATPROTO_APP_PASSWORD}:{}})],Zi("conversation-memory","@brains/conversation-memory",uFe,{pluginId:"conversation-memory"}),Zi("action-board","@brains/action-board",$Ve,{pluginId:"action-board"}),Zi("faq","@brains/faq",dwi,{pluginId:"faq",ownedTypePluginId:"faq-entity"}),Zi("docs","@brains/doc",gki,{pluginId:"docs"}),Zi("guides","@brains/guide",Uki,{pluginId:"guides"}),Zi("book","@brains/book",J5i,{pluginId:"book",ownedTypePluginId:"book-entity"}),Zi("seminar","@brains/seminar",$qi,{pluginId:"seminar",ownedTypePluginId:"seminar-entity"}),Zi("email-workflows","@brains/email-workflows",oOi,{pluginId:"email-workflows"}),Zi("unified-inbox","@brains/unified-inbox",TVe,{pluginId:"unified-inbox"}),Zi("linkedin-import","@brains/linkedin-import",bHe,{pluginId:"linkedin-import"}),Zi("oauth-broker","@brains/oauth-broker",SHe({providers:{linkedin:lHe}}),{pluginId:"oauth-broker"}),Zi("webdav","@brains/webdav",Gji,{pluginId:"webdav"}),Zi("matrix-server","@brains/matrix-server",lzi,{pluginId:"matrix-server"},(e)=>XHe(e))],interfaces:[AW("mcp","@brains/mcp",xNi,(e)=>({...e.MCP_AUTH_TOKEN?{authToken:e.MCP_AUTH_TOKEN}:{}}),{pluginId:"mcp"}),AW("email","@brains/email",$Mi,()=>({}),{pluginId:"email"}),AW("web-chat","@brains/web-chat",eKi,()=>({}),{pluginId:"web-chat"}),AW("chat","@brains/chat",Lgi,(e)=>F7e(e,{captureUrls:!0}),{pluginId:"chat"}),AW("a2a","@brains/a2a",WYe,()=>({}),{pluginId:"a2a"})],bundles:hKi,permissions:{rules:[{pattern:"cli:*",level:"admin"},{pattern:"mcp:stdio",level:"admin"}]},deployment:{cdn:{enabled:!0,provider:"bunny"},dns:{enabled:!0,provider:"bunny"}}});var xCo=["headless","personal","professional","team"];var gCo={headless:{bundleContract:cw,bundles:["core"]},personal:{bundleContract:cw,anchor:"person",kind:"professional",bundles:["core","media","web","chat"],plugins:{"directory-sync":{seedContentPath:"./seed-content"}}},professional:{bundleContract:cw,anchor:"person",kind:"professional",bundles:["core","media","automation","web","chat","site","publishing","federation"],site:{package:"@brains/site-default",theme:"@rizom/theme-default"},plugins:{"directory-sync":{seedContentPath:"./seed-content"}}},team:{bundleContract:cw,anchor:"team",kind:"team",bundles:["core","media","automation","web","chat","site","team"],add:["docs","action-board"],site:{package:"@brains/site-organization",theme:"@brains/theme-rizom"},plugins:{"directory-sync":{seedContentPath:"./seed-content"}}}};function yCo(e){return structuredClone(e)}function bCo(e){return yCo(gCo[e])}var ECo=fKi,q1c=ofe,$1c=sfe,H1c=afe,G1c=cfe,W1c=lfe,Z1c=ufe,V1c=dfe,K1c=pfe,Y1c=mfe,Q1c=ECo;export{yKe as AUTOMATION_BUNDLE_ID,xCo as BRAIN_RECIPE_NAMES,cw as CANONICAL_BUNDLE_CONTRACT,bKe as CHAT_BUNDLE_ID,xKe as CORE_BUNDLE_ID,AKe as FEDERATION_BUNDLE_ID,gKe as MEDIA_BUNDLE_ID,vKe as PUBLISHING_BUNDLE_ID,EKe as SITE_BUNDLE_ID,wKe as TEAM_BUNDLE_ID,vW as WEB_BUNDLE_ID,H1c as automationBundle,ECo as canonicalBrain,W1c as chatBundle,q1c as coreBundle,Q1c as default,bCo as expandBrainRecipe,K1c as federationBundle,$1c as mediaBundle,V1c as publishingBundle,Z1c as siteBundle,Y1c as teamBundle,G1c as webBundle};
|
|
11339
11339
|
|
|
11340
|
-
//# debugId=
|
|
11340
|
+
//# debugId=5371D28B0DEC75CC64756E2164756E21
|
|
11341
11341
|
//# sourceMappingURL=model.js.map
|