@rizom/brain 0.2.0-alpha.822 → 0.2.0-alpha.823
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 +11 -7
- package/dist/chunks/{app-x5ags7n8.js → app-8p354rxy.js} +2 -2
- package/dist/chunks/{index-1xm2ws26.js → index-hhe7r0r5.js} +2 -2
- package/dist/chunks/{index-3wbg3gv2.js → index-m3fw7nkx.js} +3 -3
- package/dist/chunks/{index-3wbg3gv2.js.map → index-m3fw7nkx.js.map} +1 -1
- package/dist/chunks/{package-jj91t0jr.js → package-1xq2edaj.js} +3 -3
- package/dist/chunks/{package-jj91t0jr.js.map → package-1xq2edaj.js.map} +1 -1
- package/dist/model.js +11 -7
- package/dist/model.js.map +3 -3
- package/dist/testing.js +1 -1
- package/dist/ui/{studio-app-ybpja4vs.js → studio-app-806251hx.js} +73 -73
- package/dist/ui/{studio-app-ybpja4vs.js.map → studio-app-806251hx.js.map} +9 -9
- package/dist/ui/{studio-app-299bc21a487d86a0917e18b15021a67ce1ff646a3f4410acbf468ae724eb7697.css → studio-app-aa4b5c43029f4bcf2634cf22ce709f38c4c3f3e76ce8536c02e34f69cf4070de.css} +30 -10
- package/dist/ui/studio-asset-manifest.json +21 -21
- package/dist/ui/studio-chunks/account-view-5phxhdkh.js +3 -0
- package/dist/ui/studio-chunks/{account-view-f6tx0x5d.js.map → account-view-5phxhdkh.js.map} +5 -5
- package/dist/ui/studio-chunks/{main-dc5jm272.js → main-0abemqev.js} +3 -3
- package/dist/ui/studio-chunks/{main-dc5jm272.js.map → main-0abemqev.js.map} +3 -3
- package/dist/ui/studio-chunks/main-6g5fzsxw.js +50 -0
- package/dist/ui/studio-chunks/main-6g5fzsxw.js.map +13 -0
- package/dist/ui/studio-chunks/main-93y3c3h0.js +9 -0
- package/dist/ui/studio-chunks/{main-8qf4xha3.js.map → main-93y3c3h0.js.map} +4 -4
- package/dist/ui/studio-chunks/main-s8zdvm8f.js +4 -0
- package/dist/ui/studio-chunks/{main-111gxvm4.js.map → main-s8zdvm8f.js.map} +6 -6
- package/dist/ui/studio-chunks/main-vxh48hfv.js +4 -0
- package/dist/ui/studio-chunks/{main-rp13zvyt.js.map → main-vxh48hfv.js.map} +3 -3
- package/dist/ui/studio-chunks/{studio-ask-panel-hx4f3mhj.js → studio-ask-panel-rabq6xrz.js} +1 -1
- package/dist/ui/studio-chunks/studio-chat-workspace-pra29908.js +3 -0
- package/dist/ui/studio-chunks/{studio-chat-workspace-5vyfd9dn.js.map → studio-chat-workspace-pra29908.js.map} +3 -3
- package/package.json +1 -1
- package/dist/ui/studio-chunks/account-view-f6tx0x5d.js +0 -3
- package/dist/ui/studio-chunks/main-111gxvm4.js +0 -4
- package/dist/ui/studio-chunks/main-8qf4xha3.js +0 -9
- package/dist/ui/studio-chunks/main-hmvrv50n.js +0 -50
- package/dist/ui/studio-chunks/main-hmvrv50n.js.map +0 -13
- package/dist/ui/studio-chunks/main-rp13zvyt.js +0 -4
- package/dist/ui/studio-chunks/studio-chat-workspace-5vyfd9dn.js +0 -3
- /package/dist/chunks/{app-x5ags7n8.js.map → app-8p354rxy.js.map} +0 -0
- /package/dist/chunks/{index-1xm2ws26.js.map → index-hhe7r0r5.js.map} +0 -0
- /package/dist/ui/studio-chunks/{studio-ask-panel-hx4f3mhj.js.map → studio-ask-panel-rabq6xrz.js.map} +0 -0
package/dist/model.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunks/index-1xm2ws26.js";import{$ as Eo,$a as gvn,$b as Xvn,$c as BAn,Aa as ox,Ab as nz,Ad as JAn,Ba as Adr,Bb as Uvn,Bd as n6,C as ly,Ca as wdr,Cb as qvn,Cc as ffr,Cd as QAn,D as pEn,Da as JEn,Db as vv,Dd as XAn,E as ddr,Ea as QEn,Eb as Bdr,Ed as ewn,F as Edr,Fa as Die,Fb as ez,Fd as dy,G as wEn,Ga as XEn,Gb as $vn,Gd as iz,H as SEn,Hb as Gvn,Hd as twn,I as kEn,Ia as pIe,Ib as Hvn,Id as rwn,J as BEn,Ja as evn,Jb as Wvn,Jd as iwn,K as CEn,Ka as tvn,Kd as nwn,La as rvn,Lb as Cdr,Ld as own,M as _ie,Ma as ivn,Mb as Ddr,Md as swn,Na as nvn,Nb as Idr,Nd as awn,Oa as ovn,Ob as Tdr,Od as cwn,P as s6,Pa as svn,Pb as _dr,Pd as lwn,Q as idr,Qa as Sdr,Qb as Pdr,Qd as Rie,R as o6,Ra as avn,Rb as Rdr,Rc as jdr,Rd as vIe,S as cy,Sa as cvn,Sb as Fdr,Sc as yAn,Sd as uwn,Ta as lvn,Tb as Mdr,Tc as bAn,Td as mIe,U as bIe,Ua as uvn,Ub as Odr,Uc as EAn,Ud as dwn,V as DEn,Va as dvn,Vb as Zvn,Vc as vAn,Vd as ih,W as Vt,Wa as pvn,Wb as Vvn,Wc as i6,Wd as aie,Xa as mvn,Xb as Kvn,Xc as AAn,Xd as pwn,Y as vdr,Ya as hvn,Yb as Yvn,Yc as wAn,Z as IEn,Za as fvn,Zb as Jvn,Zc as SAn,_ as kS,_a as xvn,_b as Qvn,_c as kAn,aa as DS,ab as yvn,ac as eAn,ad as CAn,ba as il,bb as bvn,bc as tAn,bd as DAn,ca as TEn,cb as Evn,cc as rAn,cd as IAn,da as _En,db as BS,dc as iAn,dd as TAn,ea as PEn,eb as vvn,ec as nAn,ed as _An,fa as REn,fb as cIe,fc as oAn,fd as PAn,ga as FEn,gb as Avn,gc as sAn,gd as RAn,ha as MEn,hb as wvn,hc as aAn,hd as FAn,ia as OEn,ib as Svn,ic as cAn,id as MAn,ja as NEn,jb as kvn,jc as lIe,jd as OAn,ka as LEn,kb as Bvn,kc as rz,kd as NAn,la as jEn,lb as Cvn,lc as lAn,ld as LAn,ma as zEn,mb as Dvn,mc as uAn,md as jAn,na as UEn,nb as Ivn,nc as dAn,nd as zAn,oa as qEn,ob as Tvn,oc as pAn,od as UAn,pa as $En,pb as _vn,pc as mAn,qa as GEn,qb as Pvn,qc as hAn,qd as qAn,ra as HEn,rb as Rvn,rc as fAn,rd as $An,sa as WEn,sb as Fvn,sc as Ndr,sd as GAn,ta as gDe,tb as Mvn,tc as Ldr,td as adr,ua as ZEn,ub as Ovn,uc as rdr,ud as HAn,va as VEn,vb as Nvn,vc as xAn,vd as WAn,wa as KEn,wb as kdr,wc as gAn,wd as ZAn,xa as YEn,xb as Lvn,xc as EIe,xd as VAn,ya as aIe,yb as jvn,yd as KAn,za as cz,zb as zvn,zd as YAn}from"./chunks/index-femxb8zf.js";import{$d as qAr,Yd as N7,Zd as vwr,be as PRe}from"./chunks/index-k4strh3v.js";import{de as Uxe}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 z8}from"./chunks/index-3wbg3gv2.js";import{Ce as oVe,De as _Pr,Ee as SOr,Fe as Mg,Ge as JJ,He as tq,Ie as CAr,Je as Ty,Ke as t_r,Le as F7,Me as $Rr,Ne as SAr,Oe as DAr,Pe as c_r,Qe as QTr,Re as Fgt,Se as nLr,Te as aGe,Ue as cGe,Ve as lGe,We as Wvr,Xe as k7,Ye as XTr,Ze as _f,_e as M7,gf as RH,ke as KWe,le as MH,ne as Bo,oe as L5,pe as Lye,qe as qye,re as oE,se as KZ,te as YZ,ue as JZ,ve as Utt,we as QZ,xe as PC,ye as Pit,ze as ys}from"./chunks/index-d9t4trqg.js";import{jf as rfe,kf as M$r}from"./chunks/index-kcgba22z.js";import"./chunks/index-vvqfztrv.js";import{$f as Jit,$g as JA,$h as Ufe,$j as The,$l as Khe,$m as EQ,$n as Fb,Af as PV,Ag as ma,Ah as H3,Ai as ga,Aj as sqr,Ak as mP,Al as $t,An as RSe,Ao as lE,Bf as Il,Bg as fs,Bh as wQ,Bi as Qrt,Bj as aqr,Bk as zhe,Bl as _b,Bn as Byt,Bo as Ph,Cf as Jnt,Cg as lp,Ch as abt,Ci as $fe,Cj as _$r,Ck as eW,Cl as ro,Cn as _yt,Co as Yx,Df as pF,Dg as Sb,Dh as Vk,Di as Z7,Dj as kqr,Dk as Uhe,Dl as Po,Dm as aB,Dn as JO,Do as X0r,Ef as mF,Eg as Bhe,Eh as jl,Ei as U6,Ej as Bqr,Ek as qhe,El as Aw,Em as Oae,En as Uyt,Eo as Ea,Ff as gr,Fh as B1,Fi as mse,Fj as Tqr,Fk as $he,Fl as fP,Fm as TPr,Fn as QO,Gf as GC,Gh as tN,Gi as hse,Gj as Lqr,Gk as $9,Gl as Bn,Gm as TSr,Gn as KUr,Hf as RV,Hg as Nfe,Hh as k1,Hi as iP,Hj as jqr,Hk as Ghe,Hl as dt,Hm as Kse,Hn as gTe,If as YR,Ig as dn,Ih as W0,Ii as rGe,Ij as zqr,Im as zae,In as Pyt,Jg as Mn,Jh as u8e,Ji as R8,Jj as eme,Jk as Hhe,Jl as U_r,Jm as CSr,Jn as Ryt,Kf as kw,Kg as Lgt,Kh as gbt,Ki as LPe,Kj as F$r,Km as _Sr,Kn as $z,Lf as Wye,Lg as Lfe,Lh as xbt,Lj as Rqr,Lk as uo,Ll as Pi,Lm as RSr,Ln as Fyt,Mf as FV,Mh as Fre,Mi as vw,Mj as HUr,Ml as ZPr,Mn as bQ,Nf as gs,Ng as bP,Nh as wbt,Ni as XWe,Nl as z$,Nn as Myt,Of as nr,Og as l5,Oh as Jyt,Oi as cdt,Ok as i5,Ol as HPr,On as pqr,Pf as Qe,Pg as U9,Ph as Qyt,Pi as ldt,Pk as Whe,Pl as Vhe,Pn as qyt,Qf as Oo,Qg as EP,Qj as FA,Ql as Vr,Qn as Kyt,Rf as Ys,Rg as vP,Rh as AQ,Rj as t5,Rn as mqr,Sf as Gh,Sg as jfe,Sh as Sbt,Sj as Che,Sm as fde,Sn as dqr,Tf as Gye,Tg as Ib,Th as f8e,Tj as Jx,Tm as $0,Tn as Cyt,Ug as AP,Uk as hP,Ul as Db,Un as xne,Vf as Vit,Vg as u5,Vh as fPr,Vk as Zhe,Vl as bt,Vn as jz,Wf as Kit,Wg as d5,Wl as Qx,Wn as Ifr,Xg as wP,Xh as Ws,Xl as ha,Xn as ym,Yg as SP,Yi as Bb,Yj as q9,Yl as Jut,Yn as y5,Zf as Yit,Zg as zfe,Zj as Dhe,Zk as WUr,Zl as El,Zm as ZUr,Zn as Pb,_g as H9,_h as kb,_j as Ihe,_l as xP,_m as VUr,_n as Rb,ah as Mh,ak as _he,am as Yhe,an as $yt,ao as sd,bh as Tb,bi as p5,bk as pP,bl as pgr,bm as zt,bn as Gyt,bo as Qhe,ch as ew,cj as TLr,ck as Phe,cl as Eoe,cm as Kx,cn as Hyt,co as o5,dh as a1,dk as Rhe,dl as Kfr,dm as Ene,dn as G3,do as tW,eh as qTr,ei as hc,ek as Fhe,el as FH,em as vne,en as XO,fh as fot,fi as qfe,fk as Mhe,fm as nVe,gh as Ube,gk as Ohe,gm as ko,gn as jye,go as s5,hk as Nhe,hl as mm,hm as Fn,ho as a5,ii as uP,ik as Lhe,im as ePr,in as _h,jg as RLr,jh as Ane,ji as WA,jj as RA,jl as ad,jm as Jo,kh as wne,ki as tw,kj as Eqr,kl as Gfe,lg as FLr,lh as Sne,li as e7,lj as Yqr,ll as Hfe,mg as Bwr,mh as kne,mi as nGe,mj as yWe,ml as Wfe,mo as VA,nf as Mfe,nh as Wfr,ni as QWe,nj as C$r,nk as c0,nl as Zfe,no as Xhe,of as Ofe,oh as Zfr,oi as jLr,oj as D$r,ok as m5,ol as Vfe,om as VO,on as Jhe,oo as IZe,pf as She,ph as z7e,pi as iQ,pj as qU,pk as h5,pl as Kfe,pm as kyt,po as efe,qf as cp,qh as S6,qi as Boe,qj as Vf,qk as uW,ql as x5,qm as hQ,qo as HA,rf as e5,ri as Jde,rj as c9,rl as kP,rm as lme,rn as $fr,ro as Th,sf as khe,sh as fo,si as Coe,sj as Oqr,sk as f5,sl as g5,sm as ume,sn as Gfr,so as tfe,tf as z9,th as Abt,ti as Fue,tj as Nqr,tl as fa,tn as fQ,to as gP,uf as ot,ug as su,uh as Ie,ui as tQ,uj as tme,ul as Qo,un as Nyt,uo as tPr,vf as Br,vg as lP,vh as H0,vi as P8,vj as I$r,vl as BP,vm as vqr,vn as Lyt,wg as ai,wh as jn,wi as n7,wj as T$r,wk as jhe,wl as Vi,wn as Hqr,xf as xe,xg as xm,xh as SQ,xi as o7,xj as iqr,xk as ZA,xl as Yfe,xn as Wqr,yf as Bw,yg as o0,yh as Ebt,yi as H1e,yj as nqr,yk as Cb,yl as Jfe,yn as jyt,zf as ft,zg as jr,zh as Wk,zi as ZAr,zj as oqr,zk as r5,zl as gm,zn as zyt,zo as KA}from"./chunks/index-y2k296fh.js";import{$o as Eae,$p as bit,$q as OC,$r as w1,$s as po,Ap as P1r,Aq as Xoe,Ar as Di,As as PY,Bp as Bae,Bq as mMr,Br as PLr,Bs as Pne,Cp as vr,Cq as hMr,Cr as tjr,Cs as Yut,Dp as j5,Dq as TY,Dr as aV,Ep as Ht,Er as Gf,Es as hEr,Fo as O1r,Fp as dx,Fq as Knt,Fs as U1e,Go as mpe,Gp as tV,Gq as Ynt,Gr as LT,Hp as Zp,Hq as snt,Hr as Rae,Hs as Xv,Ht as up,Io as kn,Ip as vy,Iq as ant,Ir as nG,Is as m_r,It as hm,Jo as Cf,Jp as Hn,Jq as Kut,Jr as wde,Js as fue,Jt as od,Ko as eoe,Kp as Jpe,Kq as vn,Kr as Hqe,Ks as RB,Lq as md,Lr as q$,Ls as D6,Mo as kr,Mp as a$r,Mq as v8,Mr as $$,Ms as Xme,No as fi,Np as c$r,Nq as Zle,Nr as BG,Ns as bne,Oo as ZI,Oq as STr,Or as bzr,Os as NI,Ot as n5,Po as e9,Pq as Vle,Pr as CG,Ps as kfr,Qo as ppe,Qp as A_,Qq as Zye,Qr as noe,Qs as Rm,Ro as WB,Rq as CV,Rr as Rxr,Rs as c1,So as B$,Sr as Mxr,Ss as pa,To as dQ,Tq as A1,Tr as ooe,Ts as Pvr,Uo as wa,Up as cP,Uq as fe,Ur as Vue,Us as Jp,Vo as Yv,Vp as lMr,Vr as TRr,Vs as Lt,Wo as ZB,Wq as To,Wr as ode,Ws as Moe,Xo as zze,Xr as sde,Xs as W9,Yp as B$r,Yr as Uxr,Ys as ld,Zo as Cae,Zr as Oxr,Zs as mc,_o as Kv,_p as yMr,_q as br,_r as Nxr,_s as v1,ap as vae,ar as x$r,as as E0r,at as Ay,bp as vUr,bq as vhe,br as j9,bt as xEr,cp as Bse,cq as HH,cr as Gne,cs as $ue,ct as Vfr,dp as iB,dq as WH,dr as eQ,ds as zPr,dt as v7,ep as qge,eq as ZH,er as M3,es as UPr,et as fx,fp as wae,fq as VH,fs as h3,ft as xyt,gp as nB,gq as QH,gs as Ppe,gt as rw,hp as Aae,hq as XH,hr as ase,hs as Une,ht as sc,ip as o8,iq as X8,ir as jyr,is as qne,it as QI,jp as w1r,jq as nZe,jr as Ofr,js as AWe,jt as ct,kp as S1r,kq as KZe,kr as yne,ks as R$r,kt as Cu,lp as AUr,lq as Vx,lr as gne,ls as Vne,lt as mWe,mp as Zpe,mq as YZe,ms as Rpe,mt as cd,np as wUr,nq as LH,ns as que,nt as au,op as D1r,oq as KH,or as lPr,os as WT,ot as We,pp as SUr,pq as YH,pr as Sw,ps as OUe,qp as kFe,qq as PR,qr as Jz,qs as LUe,rp as BFe,rs as bRr,rt as dP,sp as xq,sq as Ade,ss as KPr,st as t0,tp as CFe,tq as Lbr,ts as ERr,tt as ehe,up as I1r,uq as us,us as YPr,vp as DFe,vq as fOr,vs as eRr,vt as ihe,wp as T1r,wq as XEr,wr as Dae,ws as Kne,xp as _1r,xq as LS,xr as J7,xs as f3,yp as Sae,yq as N0r,yr as Ine,ys as Wne,zp as kae,zq as qI,zr as Hne,zs as _Y}from"./chunks/index-63p1xma2.js";import{Qt as nUe,St as NH}from"./chunks/index-agfrkbxw.js";import{EB as Yyt,Hv as lSe,LB as Ih,MB as XC,OB as Mc,QB as Yp,RB as Kgr,SB as Yi,TB as P$r,Xx as ou,Zx as e4,jy as pc,tz as vQ,xB as et,yy as Hs}from"./chunks/index-g1c4y6gc.js";import{jD as l}from"./chunks/index-bshgrg07.js";import"./chunks/index-pmvk8xga.js";import{nD as no,oD as HQr,pD as E,qD as rg,rD as xs,sD as ce}from"./chunks/index-7ysxtpwx.js";function VKe(e){return e===0||e>=55296&&e<=57343||e>1114111}function KKe(e){if(VKe(e))return 65533;if(e>=128&&e<=159)return kVr[e-128]||e;return e}function YKe(e){return VKe(e)?65533:e}var kVr;var JKe=xs(()=>{kVr=[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 QKe(e,t,r,i,n,o){let a=e.length,c=o*90,u=0,d=()=>{let L=u0[e.charCodeAt(u++)];return L<o?L:L*91-c+u0[e.charCodeAt(u++)]},p=r-i,m=r+n,h=new Int32Array(m);h.fill(-1,i,o),h.fill(-1,o+p,m);let f=new Int32Array(m),g=new Int32Array(m);function y(L,H){let K=0,ee=H,q=H+L;while(ee<q){let S=u0[e.charCodeAt(u++)];if(S<89)K+=S,h[ee++]=K;else if(S===89){let _=u0[e.charCodeAt(u++)]+2;while(_--)h[ee++]=++K}else{let _=u0[e.charCodeAt(u++)];K+=89+(_<90?_*91+u0[e.charCodeAt(u++)]:u0[e.charCodeAt(u++)]*8281+u0[e.charCodeAt(u++)]*91+u0[e.charCodeAt(u++)]),h[ee++]=K}}}y(i,0),y(p,o);let b=new Int32Array(n*2),A=0,w=0;function B(L,H){for(let K=0;K<L;K++){let ee=H+K,q=d(),S=d();b[w*2]=q,b[w*2+1]=S,w+=1,f[ee]=A;let _=(h[q]<0?g[q]:1)+(h[S]<0?g[S]:1);g[ee]=_,A+=_}}B(n-o+i,o+p),B(o-i,i);let R=new Uint16Array(A),M=0;for(let L=0;L<w;L++)for(let H=0;H<2;H++){let K=b[L*2+H],ee=h[K];if(ee<0){let q=f[K],S=q+g[K];while(q<S)R[M++]=R[q++]}else R[M++]=ee}let k=new Uint16Array(t),N=0;while(u<a){let L=u0[e.charCodeAt(u++)];if(L>=o)L=L*91-c+u0[e.charCodeAt(u++)];let H=h[L];if(H<0){let K=f[L],ee=K+g[L];while(K<ee)k[N++]=R[K++]}else k[N++]=H}return k}var u0;var XKe=xs(()=>{u0=(()=>{let e=new Uint8Array(127),t=0;for(let r=33;r<=126;r++)if(r!==34&&r!==36&&r!==92)e[r]=t++;return e})()});var I0e;var eYe=xs(()=>{XKe();I0e=QKe("!}.&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%#%}%)#(},'%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q3!(?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 jP;var T0e=xs(()=>{jP=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 Lc;var tYe=xs(()=>{(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"})(Lc||(Lc={}))});function rYe(e){return e-lu.ZERO>>>0<=9}function BVr(e){return(e|wW)-lu.LOWER_A>>>0<=5}function CVr(e){return(e|wW)-lu.LOWER_A>>>0<=25}function DVr(e){return e===lu.EQUALS||CVr(e)||rYe(e)}class _0e{decodeTree;emitCodePoint;errors;state=cu.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=d0.Strict;runConsumed=0;constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r}startEntity(e){this.decodeMode=e,this.state=cu.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case cu.EntityStart:{if(e.charCodeAt(t)===lu.NUM)return this.state=cu.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=cu.NamedEntity,this.stateNamedEntity(e,t)}case cu.NumericStart:return this.stateNumericStart(e,t);case cu.NumericDecimal:return this.stateNumericDecimal(e,t);case cu.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)|wW)===lu.LOWER_X)return this.state=cu.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=cu.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){let r=e.length,{result:i}=this,{consumed:n}=this;while(t<r){let o=e.charCodeAt(t);if(rYe(o)||BVr(o)){let s=o<=lu.NINE?o-lu.ZERO:(o|wW)-lu.LOWER_A+10;i=i*16+s,n+=1,t+=1}else return this.result=i,this.consumed=n,this.emitNumericEntity(o,3)}return this.result=i,this.consumed=n,-1}stateNumericDecimal(e,t){let r=e.length,{result:i}=this,{consumed:n}=this;while(t<r){let o=e.charCodeAt(t)-lu.ZERO;if(o>>>0>9)return this.result=i,this.consumed=n,this.emitNumericEntity(o+lu.ZERO,2);i=i*10+o,n+=1,t+=1}return this.result=i,this.consumed=n,-1}emitNumericEntity(e,t){if(this.consumed<=t)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===lu.SEMI)this.consumed+=1;else if(this.decodeMode===d0.Strict)return 0;if(this.emitCodePoint((this.decodeTree===jP?YKe:KKe)(this.result),this.consumed),this.errors){if(e!==lu.SEMI)this.errors.missingSemicolonAfterCharacterReference();this.errors.validateNumericCharacterReference(this.result)}return this.consumed}flushAndEmitLegacyOrReject(e,t,r,i){return this.consumed=e,this.excess=t,this.result===0||this.decodeMode===d0.Attribute&&(i===0||t>1||DVr(r))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:r}=this,i=e.length,n=this.decodeMode===d0.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=r[o];while(t<i){while((c&(Lc.VALUE_LENGTH|Lc.FLAG13))===0&&(c&Lc.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&Lc.JUMP_TABLE,f=(c&Lc.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=r[o+1+g];if(y===0)return this.flushAndEmitLegacyOrReject(a,s,m,0);o=o+f+y&65535}if(c=r[o],t+=1,s+=1,t>=i)break}if(t>=i)break;if((c&(Lc.VALUE_LENGTH|Lc.FLAG13))===Lc.FLAG13){let m=(c&Lc.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&Lc.JUMP_TABLE))return this.flushAndEmitLegacyOrReject(a,s,f,0);t+=1,s+=1,h=1}while(h<m){if(t>=i)return this.treeIndex=o,this.excess=s,this.consumed=a,this.runConsumed=h,-1;let f=h-1,y=r[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=r[o];continue}let u=c>>>14,d=e.charCodeAt(t);if(u!==0){if(!n&&(c&Lc.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===lu.SEMI)return this.emitNamedEntityData(o,u,a+s);if(u===1)return this.flushAndEmitLegacyOrReject(a,s,d,u)}let p=IVr(r,c,o+(u||1),d);if(p<0)return this.flushAndEmitLegacyOrReject(a,s,d,u);o=p,c=r[o],t+=1,s+=1}if(!n&&c>>>14!==0&&(c&Lc.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,r=t[e]>>>14;return this.emitNamedEntityData(e,r,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,r){let{decodeTree:i}=this;if(this.emitCodePoint(t===1?i[e]&Lc.VALUE_MASK:i[e+1],r),t===3)this.emitCodePoint(i[e+2],r);return r}end(){switch(this.state){case cu.NamedEntity:return this.result!==0&&(this.decodeMode!==d0.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case cu.NumericDecimal:return this.emitNumericEntity(0,2);case cu.NumericHex:return this.emitNumericEntity(0,3);case cu.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function IVr(e,t,r,i){let n=(t&Lc.BRANCH_LENGTH)>>7,o=t&Lc.JUMP_TABLE;if(o){if(n===0)return i===o?r:-1;let c=i-o;if(c>>>0>=n)return-1;let u=e[r+c];return u===0?-1:r+n+u-1&65535}if(n===0)return-1;let s=n+1>>1,a=r+s+n;for(let c=0;c<n;c++){let d=e[r+(c>>1)]>>((c&1)<<3)&255;if(d===i){let p=r+s+c;return a+e[p]&65535}if(d>i)return-1}return-1}var lu,wW=32,cu,d0;var iYe=xs(()=>{JKe();T0e();tYe();eYe();T0e();(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"})(lu||(lu={}));(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"})(cu||(cu={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(d0||(d0={}))});function v5(e){return e===Er.Space||e===Er.NewLine||e===Er.Tab||e===Er.FormFeed||e===Er.CarriageReturn}function eC(e){return e===Er.Slash||e===Er.Gt||v5(e)}function TVr(e){return e>=Er.LowerA&&e<=Er.LowerZ||e>=Er.UpperA&&e<=Er.UpperZ}class tC{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:r=e},i){this.cbs=i,this.xmlMode=e,this.decodeEntities=t,this.recognizeSelfClosing=r,this.entityDecoder=new _0e(e?jP:I0e,(n,o)=>this.emitCodePoint(n,o))}reset(){this.state=Ze.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=Ze.Text,this.isSpecial=!1,this.currentSequence=ci.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===Er.Lt||!this.decodeEntities&&this.fastForwardTo(Er.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===Er.Amp)this.startEntity()}currentSequence=ci.Empty;sequenceIndex=0;enterTagBody(){if(this.currentSequence===ci.Plaintext)this.currentSequence=ci.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===ci.ScriptEnd&&t===ci.StyleEnd[3]){this.currentSequence=ci.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===ci.TitleEnd&&t===ci.TextareaEnd[3]){this.currentSequence=ci.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===ci.NoembedEnd&&t===ci.NoframesEnd[4]){this.currentSequence=ci.NoframesEnd,this.sequenceIndex=5;return}}else if(eC(e)){this.sequenceIndex=0,this.state=Ze.InTagName,this.stateInTagName(e);return}this.isSpecial=!1,this.currentSequence=ci.Empty,this.sequenceIndex=0,this.state=Ze.InTagName,this.stateInTagName(e)}stateCDATASequence(e){if(e===ci.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===ci.Cdata.length)this.state=Ze.InCommentLike,this.currentSequence=ci.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===ci.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&e===Er.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===ci.CommentEnd&&this.sequenceIndex===2&&e===Er.Gt)this.emitComment(2);else if(this.currentSequence===ci.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&e!==Er.Gt)this.sequenceIndex=Number(e===Er.Dash);else if(e===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===ci.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?!eC(e):TVr(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(eC(e)){let t=this.index-this.currentSequence.length;if(this.sectionStart<t){let r=this.index;this.index=t,this.cbs.ontext(this.sectionStart,t),this.index=r}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===ci.TitleEnd||this.currentSequence===ci.TextareaEnd){if(this.decodeEntities&&e===Er.Amp)this.startEntity()}else if(this.fastForwardTo(Er.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(e===Er.Lt)}stateBeforeTagName(e){if(e===Er.ExclamationMark)this.state=Ze.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===Er.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:_Vr.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===Er.Slash)this.state=Ze.BeforeClosingTagName;else this.state=Ze.Text,this.stateText(e)}stateInTagName(e){if(eC(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(v5(e))if(this.xmlMode);else this.state=Ze.InSpecialComment,this.sectionStart=this.index;else if(e===Er.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(eC(e))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=Ze.AfterClosingTagName,this.stateAfterClosingTagName(e)}stateAfterClosingTagName(e){if(e===Er.Gt||this.fastForwardTo(Er.Gt))this.state=Ze.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(e){if(e===Er.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(e===Er.Slash)this.state=Ze.InSelfClosingTag;else if(!v5(e))this.state=Ze.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(e){if(e===Er.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=ci.Empty}else if(!v5(e))this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===Er.Eq||eC(e))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=Ze.AfterAttributeName,this.stateAfterAttributeName(e)}stateAfterAttributeName(e){if(e===Er.Eq)this.state=Ze.BeforeAttributeValue;else if(e===Er.Slash||e===Er.Gt)this.cbs.onattribend(Em.NoValue,this.sectionStart),this.sectionStart=-1,this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!v5(e))this.cbs.onattribend(Em.NoValue,this.sectionStart),this.state=Ze.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(e){if(e===Er.DoubleQuote)this.state=Ze.InAttributeValueDq,this.sectionStart=this.index+1;else if(e===Er.SingleQuote)this.state=Ze.InAttributeValueSq,this.sectionStart=this.index+1;else if(!v5(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===Er.DoubleQuote?Em.Double:Em.Single,this.index+1),this.state=Ze.BeforeAttributeName;else if(this.decodeEntities&&e===Er.Amp)this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,Er.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,Er.SingleQuote)}stateInAttributeValueNoQuotes(e){if(v5(e)||e===Er.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(Em.Unquoted,this.index),this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(this.decodeEntities&&e===Er.Amp)this.startEntity()}stateBeforeDeclaration(e){if(e===Er.OpeningSquareBracket)this.state=Ze.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=e===Er.Dash?Ze.BeforeComment:Ze.InDeclaration;else if((e|32)===ci.Doctype[0])this.state=Ze.DeclarationSequence,this.currentSequence=ci.Doctype,this.sequenceIndex=1;else if(e===Er.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else if(e===Er.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===Er.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===Er.Gt||this.fastForwardTo(Er.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=Ze.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(e){if(e===Er.Questionmark)this.sequenceIndex=1;else if(e===Er.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(Er.Questionmark))}stateBeforeComment(e){if(e===Er.Dash)this.state=Ze.InCommentLike,this.currentSequence=ci.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=Ze.InDeclaration;else if(e===Er.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===Er.Gt||this.fastForwardTo(Er.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)===Er.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===ci.CdataEnd)if(this.xmlMode){if(this.sectionStart<e)this.cbs.oncdata(this.sectionStart,e,0)}else{let t=this.sectionStart-ci.Cdata.length-1;this.cbs.oncomment(t,e,0)}else{let t=this.xmlMode?0:Math.min(this.sequenceIndex,ci.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!==ci.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 Er,Ze,Em,ci,_Vr;var P0e=xs(()=>{iYe();(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"})(Er||(Er={}));(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"})(Em||(Em={}));ci={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])},_Vr=new Map([[ci.IframeEnd[2],ci.IframeEnd],[ci.NoembedEnd[2],ci.NoembedEnd],[ci.Plaintext[2],ci.Plaintext],[ci.ScriptEnd[2],ci.ScriptEnd],[ci.TitleEnd[2],ci.TitleEnd],[ci.XmpEnd[2],ci.XmpEnd]])});class nC{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??tC)(this.options,this),this.foreignContext=[Lb.None],this.cbs.onparserinit?.(this)}ontext(e,t){let r=this.getSlice(e,t);this.endIndex=t-1,this.cbs.ontext?.(r),this.startIndex=t}ontextentity(e,t){this.endIndex=t-1,this.cbs.ontext?.(nYe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==Lb.None}isVoidElement(e){return this.htmlMode&&RVr.has(e)}readTagName(e,t){let r=this.lowerCaseTagNames?this.getSlice(e,t).toLowerCase():this.getSlice(e,t);if(!(this.lowerCaseTagNames&&this.htmlMode))return r;if(this.foreignContext[0]===Lb.Svg)return uYe.get(r)??r;if(this.foreignContext.length>1){let i=uYe.get(r);if(i!==void 0&&this.stack.includes(i))return i}if(!this.isInForeignContext())return r==="image"?"img":r;return r}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&&PVr.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(Lb.Svg);else if(e==="math")this.foreignContext.unshift(Lb.MathML);else if(lYe.has(e))this.foreignContext.unshift(Lb.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 r=this.readTagName(e,t);if(!this.isVoidElement(r)){let i=this.stack.indexOf(r);if(i!==-1){for(let n=0;n<i;n++)this.popElement(!0);this.popElement(!1)}else if(this.htmlMode&&r==="p")this.emitOpenTag("p"),this.closeCurrentTag(!0)}else if(this.htmlMode&&r==="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&&(FVr.has(t)||lYe.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 r=this.getSlice(e,t);this.attribname=this.lowerCaseAttributeNames?r.toLowerCase():r}onattribdata(e,t){this.attribvalue+=this.getSlice(e,t)}onattribentity(e){this.attribvalue+=nYe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===Em.Double?'"':e===Em.Single?"'":e===Em.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(MVr),r=t<0?e:e.substr(0,t);if(this.lowerCaseTagNames)r=r.toLowerCase();return r}ondeclaration(e,t){this.endIndex=t;let r=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let i=this.htmlMode?this.lowerCaseTagNames?cYe:r.slice(0,cYe.length):this.getInstructionName(r);this.cbs.onprocessinginstruction(`!${i}`,`!${r}`)}this.startIndex=t+1}onprocessinginstruction(e,t){this.endIndex=t;let r=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let i=this.getInstructionName(r);this.cbs.onprocessinginstruction(`?${i}`,`?${r}`)}this.startIndex=t+1}oncomment(e,t,r){this.endIndex=t,this.cbs.oncomment?.(this.getSlice(e,t-r)),this.cbs.oncommentend?.(),this.startIndex=t+1}oncdata(e,t,r){this.endIndex=t;let i=this.getSlice(e,t-r);if(!this.htmlMode||this.options.recognizeCDATA)this.cbs.oncdatastart?.(),this.cbs.ontext?.(i),this.cbs.oncdataend?.();else if(this.isInForeignContext())this.cbs.ontext?.(i);else this.cbs.oncomment?.(`[CDATA[${i}]]`),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(Lb.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 r=this.buffers[0].slice(e-this.bufferOffset,t-this.bufferOffset);while(t-this.bufferOffset>this.buffers[0].length)this.shiftBuffer(),r+=this.buffers[0].slice(0,t-this.bufferOffset);return r}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 nYe,rC,Vs,iC,oYe,sYe,aYe,PVr,cYe="doctype",RVr,FVr,lYe,uYe,Lb,MVr;var R0e=xs(()=>{P0e();({fromCodePoint:nYe}=String),rC=new Set(["input","option","optgroup","select","button","datalist","textarea"]),Vs=new Set(["p"]),iC=new Set(["h1","h2","h3","h4","h5","h6","p"]),oYe=new Set(["thead","tbody"]),sYe=new Set(["dd","dt"]),aYe=new Set(["rt","rp"]),PVr=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",Vs],["h1",iC],["h2",iC],["h3",iC],["h4",iC],["h5",iC],["h6",iC],["select",rC],["input",rC],["output",rC],["button",rC],["datalist",rC],["textarea",rC],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",sYe],["dt",sYe],["address",Vs],["article",Vs],["aside",Vs],["blockquote",Vs],["details",Vs],["div",Vs],["dl",Vs],["fieldset",Vs],["figcaption",Vs],["figure",Vs],["footer",Vs],["form",Vs],["header",Vs],["hr",Vs],["main",Vs],["nav",Vs],["ol",Vs],["pre",Vs],["section",Vs],["table",Vs],["ul",Vs],["rt",aYe],["rp",aYe],["tbody",oYe],["tfoot",oYe]]),RVr=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),FVr=new Set(["math","svg"]),lYe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),uYe=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"})(Lb||(Lb={}));MVr=/\s|\//});var SW={};rg(SW,{CDATA:()=>q0e,Comment:()=>L0e,Directive:()=>N0e,Doctype:()=>OVr,ElementType:()=>pn,Root:()=>M0e,Script:()=>j0e,Style:()=>z0e,Tag:()=>U0e,Text:()=>O0e,isTag:()=>F0e});function F0e(e){return e.type===pn.Tag||e.type===pn.Script||e.type===pn.Style}var pn,M0e,O0e,N0e,L0e,j0e,z0e,U0e,q0e,OVr;var oC=xs(()=>{(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"})(pn||(pn={}));M0e=pn.Root,O0e=pn.Text,N0e=pn.Directive,L0e=pn.Comment,j0e=pn.Script,z0e=pn.Style,U0e=pn.Tag,q0e=pn.CDATA,OVr=pn.Doctype});class G0e{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 dYe(this,e)}}function uu(e){return F0e(e)}function _W(e){return e.type===pn.CDATA}function sw(e){return e.type===pn.Text}function H0e(e){return e.type===pn.Comment}function NVr(e){return e.type===pn.Directive}function LVr(e){return e.type===pn.Root}function dp(e){return Object.hasOwn(e,"children")}function dYe(e,t=!1){let r;if(sw(e))r=new zP(e.data);else if(H0e(e))r=new BW(e.data);else if(uu(e)){let i=t?$0e(e.children):[],n=new TW(e.name,{...e.attribs},i);for(let o of i)o.parent=n;if(e.namespace!=null)n.namespace=e.namespace;if(e["x-attribsNamespace"])n["x-attribsNamespace"]={...e["x-attribsNamespace"]};if(e["x-attribsPrefix"])n["x-attribsPrefix"]={...e["x-attribsPrefix"]};r=n}else if(_W(e)){let i=t?$0e(e.children):[],n=new IW(i);for(let o of i)o.parent=n;r=n}else if(LVr(e)){let i=t?$0e(e.children):[],n=new UP(i);for(let o of i)o.parent=n;if(e["x-mode"])n["x-mode"]=e["x-mode"];r=n}else if(NVr(e)){let i=new CW(e.name,e.data);if(e["x-name"]!=null)i["x-name"]=e["x-name"],i["x-publicId"]=e["x-publicId"],i["x-systemId"]=e["x-systemId"];r=i}else throw Error(`Not implemented yet: ${e.type}`);if(r.startIndex=e.startIndex,r.endIndex=e.endIndex,e.sourceCodeLocation!=null)r.sourceCodeLocation=e.sourceCodeLocation;return r}function $0e(e){let t=e.map((r)=>dYe(r,!0));for(let r=1;r<t.length;r++)t[r].prev=t[r-1],t[r-1].next=t[r];return t}var kW,zP,BW,CW,DW,IW,UP,TW;var W0e=xs(()=>{oC();kW=class kW extends G0e{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};zP=class zP extends kW{type=pn.Text;get nodeType(){return 3}};BW=class BW extends kW{type=pn.Comment;get nodeType(){return 8}};CW=class CW extends kW{type=pn.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};DW=class DW extends G0e{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}};IW=class IW extends DW{type=pn.CDATA;get nodeType(){return 4}};UP=class UP extends DW{type=pn.Root;get nodeType(){return 9}};TW=class TW extends DW{name;attribs;type;constructor(e,t,r=[],i=e==="script"?pn.Script:e==="style"?pn.Style:pn.Tag){super(r);this.name=e,this.attribs=t,this.type=i}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 A5{dom=[];root=new UP(this.dom);callback;options;elementCB;done=!1;tagStack=[this.root];lastNode=null;parser=null;constructor(e,t,r){if(typeof t==="function")r=t,t=pYe;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??pYe,this.elementCB=r??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new UP(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 r=this.options.xmlMode?pn.Tag:void 0,i=new TW(e,t,void 0,r);this.addNode(i),this.tagStack.push(i)}ontext(e){let{lastNode:t}=this;if(t&&t.type===pn.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let r=new zP(e);this.addNode(r),this.lastNode=r}}oncomment(e){if(this.lastNode&&this.lastNode.type===pn.Comment){this.lastNode.data+=e;return}let t=new BW(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new zP(""),t=new IW([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let r=new CW(e,t);this.addNode(r)}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],r=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),r)e.prev=r,r.next=e;e.parent=t,this.lastNode=null}}var pYe;var aw=xs(()=>{oC();W0e();W0e();pYe={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function sC(e,t,r=!0,i=Number.POSITIVE_INFINITY){return mYe(e,Array.isArray(t)?t:[t],r,i)}function mYe(e,t,r,i){let n=[],o=[Array.isArray(t)?t:[t]],s=[0];for(;;){if(s[0]>=o[0].length){if(s.length===1)return n;o.shift(),s.shift();continue}let a=o[0][s[0]++];if(e(a)){if(n.push(a),--i<=0)return n}if(r&&dp(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function PW(e,t,r=!0){let i=Array.isArray(t)?t:[t];for(let n of i){if(uu(n)&&e(n))return n;if(r&&dp(n)&&n.children.length>0){let o=PW(e,n.children,!0);if(o)return o}}return null}function hYe(e,t){return(Array.isArray(t)?t:[t]).some((r)=>uu(r)&&e(r)||dp(r)&&hYe(e,r.children))}function jVr(e,t){let r=[],i=[Array.isArray(t)?t:[t]],n=[0];for(;;){if(n[0]>=i[0].length){if(i.length===1)return r;i.shift(),n.shift();continue}let o=i[0][n[0]++];if(uu(o)&&e(o))r.push(o);if(dp(o)&&o.children.length>0)n.unshift(0),i.unshift(o.children)}}var Z0e=xs(()=>{aw()});function V0e(e,t){if(typeof t==="function")return(r)=>uu(r)&&t(r.attribs[e]);return(r)=>uu(r)&&r.attribs[e]===t}function zVr(e,t){return(r)=>e(r)||t(r)}function fYe(e){let t=Object.keys(e).map((r)=>{let i=e[r];return Object.hasOwn(RW,r)?RW[r](i):V0e(r,i)});return t.length===0?null:t.reduce(zVr)}function UVr(e,t){let r=fYe(e);return r?r(t):!0}function qVr(e,t,r,i=Number.POSITIVE_INFINITY){let n=fYe(e);return n?sC(n,t,r,i):[]}function $Vr(e,t,r=!0){if(!Array.isArray(t))t=[t];return PW(V0e("id",e),t,r)}function w5(e,t,r=!0,i=Number.POSITIVE_INFINITY){return sC(RW.tag_name(e),t,r,i)}function GVr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return sC(V0e("class",e),t,r,i)}function HVr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return sC(RW.tag_type(e),t,r,i)}var RW;var K0e=xs(()=>{aw();Z0e();RW={tag_name(e){if(typeof e==="function")return(t)=>uu(t)&&e(t.name);if(e==="*")return uu;return(t)=>uu(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)=>sw(t)&&e(t.data);return(t)=>sw(t)&&t.data===e}}});function gYe(e){return e===34?""":e===38?"&":e===39?"'":e===60?"<":e===62?">":" "}function xYe(e){return e>=128||e>=32&&e<64&&(WVr>>>e&1)===1}function FW(e){let{length:t}=e,r,i=0,n=0;while(n<t){let o=e.charCodeAt(n);if(!xYe(o)){let a=Math.min(n+32,t),c=n+1;while(c<a&&!xYe(e.charCodeAt(c)))c++;if(c<a){n=c;continue}if(c>=t)break;if(Y0e.lastIndex=c,!Y0e.test(e))break;n=Y0e.lastIndex-1;continue}if(r===void 0)r=e.substring(0,n);else if(i!==n)r+=e.substring(i,n);if(o<64){r+=gYe(o),i=n+=1;continue}let s=e.codePointAt(n);if(r+=`&#x${s.toString(16)};`,s!==o)n++;i=n+=1}if(r===void 0)return e;if(i<t)r+=e.substr(i);return r}function yYe(e,t){if(e.lastIndex=0,!e.test(t))return t;let r="",i=0;do{let n=e.lastIndex-1;if(i!==n)r+=t.substring(i,n);let o=t.charCodeAt(n);r+=gYe(o),i=n+1}while(e.test(t));return r+t.substring(i)}function J0e(e){return yYe(ZVr,e)}function Q0e(e){return yYe(VVr,e)}var WVr=1342177476,Y0e,ZVr,VVr;var bYe=xs(()=>{Y0e=/["&'<>\u0080-\uFFFF]/g;ZVr=/["&\u{A0}]/gu;VVr=/[&<>\u{A0}]/gu});var EYe,vYe;var AYe=xs(()=>{bYe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(EYe||(EYe={}));(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"})(vYe||(vYe={}))});var wYe,SYe;var kYe=xs(()=>{wYe=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])),SYe=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 XVr(e,t={}){let r="length"in e?e:[e],i=t.xmlMode??!1,n="";for(let o=0;o<r.length;o++)n+=CYe(r[o],t,i);return n}function BYe(e,t,r){let i="";for(let n=0;n<e.length;n++)i+=CYe(e[n],t,r);return i}function CYe(e,t,r){switch(e.type){case M0e:return BYe(e.children,t,r);case N0e:return`<${e.data}>`;case L0e:return`<!--${e.data}-->`;case q0e:return`<![CDATA[${e.children[0].data}]]>`;case j0e:case z0e:case U0e:return eKr(e,t,r);case O0e:{let i=e,n=i.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!r&&i.parent&&KVr.has(i.parent.name)))return r||t.encodeEntities!=="utf8"?FW(n):Q0e(n);return n}}}function eKr(e,t,r){if(r==="foreign"){if(e.name=wYe.get(e.name)??e.name,e.parent&&QVr.has(e.parent.name))r=!1}if(!r&&JVr.has(e.name))r="foreign";let{name:i,children:n}=e,o=!r&&YVr.has(i),s=`<${i}${rKr(e.attribs,t,r)}`;if(n.length===0&&(r?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=r?"/>":" />";else{if(s+=">",n.length>0)s+=BYe(n,t,r);if(!o)s+=`</${i}>`}return s}function tKr(e){return e.replaceAll('"',""")}function rKr(e,t,r){if(!e)return"";let i=(t.encodeEntities??t.decodeEntities)===!1?tKr:r||t.encodeEntities!=="utf8"?FW:J0e,n=r==="foreign",o=!!(t.emptyAttrs??r),s="";for(let a in e){if(!Object.hasOwn(e,a))continue;let c=e[a],u=n?SYe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${u}`:` ${u}="${i(c==null?"":String(c))}"`}return s}var KVr,YVr,JVr,QVr,DYe;var IYe=xs(()=>{oC();AYe();kYe();KVr=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),YVr=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),JVr=new Set(["svg","math"]),QVr=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));DYe=XVr});function TYe(e,t){return DYe(e,t)}function iKr(e,t){return dp(e)?e.children.map((r)=>TYe(r,t)).join(""):""}function MW(e){if(Array.isArray(e))return e.map(MW).join("");if(uu(e))return e.name==="br"?`
|
|
2
|
+
import"./chunks/index-hhe7r0r5.js";import{$ as Eo,$a as gvn,$b as Xvn,$c as BAn,Aa as ox,Ab as nz,Ad as JAn,Ba as Adr,Bb as Uvn,Bd as n6,C as ly,Ca as wdr,Cb as qvn,Cc as ffr,Cd as QAn,D as pEn,Da as JEn,Db as vv,Dd as XAn,E as ddr,Ea as QEn,Eb as Bdr,Ed as ewn,F as Edr,Fa as Die,Fb as ez,Fd as dy,G as wEn,Ga as XEn,Gb as $vn,Gd as iz,H as SEn,Hb as Gvn,Hd as twn,I as kEn,Ia as pIe,Ib as Hvn,Id as rwn,J as BEn,Ja as evn,Jb as Wvn,Jd as iwn,K as CEn,Ka as tvn,Kd as nwn,La as rvn,Lb as Cdr,Ld as own,M as _ie,Ma as ivn,Mb as Ddr,Md as swn,Na as nvn,Nb as Idr,Nd as awn,Oa as ovn,Ob as Tdr,Od as cwn,P as s6,Pa as svn,Pb as _dr,Pd as lwn,Q as idr,Qa as Sdr,Qb as Pdr,Qd as Rie,R as o6,Ra as avn,Rb as Rdr,Rc as jdr,Rd as vIe,S as cy,Sa as cvn,Sb as Fdr,Sc as yAn,Sd as uwn,Ta as lvn,Tb as Mdr,Tc as bAn,Td as mIe,U as bIe,Ua as uvn,Ub as Odr,Uc as EAn,Ud as dwn,V as DEn,Va as dvn,Vb as Zvn,Vc as vAn,Vd as ih,W as Vt,Wa as pvn,Wb as Vvn,Wc as i6,Wd as aie,Xa as mvn,Xb as Kvn,Xc as AAn,Xd as pwn,Y as vdr,Ya as hvn,Yb as Yvn,Yc as wAn,Z as IEn,Za as fvn,Zb as Jvn,Zc as SAn,_ as kS,_a as xvn,_b as Qvn,_c as kAn,aa as DS,ab as yvn,ac as eAn,ad as CAn,ba as il,bb as bvn,bc as tAn,bd as DAn,ca as TEn,cb as Evn,cc as rAn,cd as IAn,da as _En,db as BS,dc as iAn,dd as TAn,ea as PEn,eb as vvn,ec as nAn,ed as _An,fa as REn,fb as cIe,fc as oAn,fd as PAn,ga as FEn,gb as Avn,gc as sAn,gd as RAn,ha as MEn,hb as wvn,hc as aAn,hd as FAn,ia as OEn,ib as Svn,ic as cAn,id as MAn,ja as NEn,jb as kvn,jc as lIe,jd as OAn,ka as LEn,kb as Bvn,kc as rz,kd as NAn,la as jEn,lb as Cvn,lc as lAn,ld as LAn,ma as zEn,mb as Dvn,mc as uAn,md as jAn,na as UEn,nb as Ivn,nc as dAn,nd as zAn,oa as qEn,ob as Tvn,oc as pAn,od as UAn,pa as $En,pb as _vn,pc as mAn,qa as GEn,qb as Pvn,qc as hAn,qd as qAn,ra as HEn,rb as Rvn,rc as fAn,rd as $An,sa as WEn,sb as Fvn,sc as Ndr,sd as GAn,ta as gDe,tb as Mvn,tc as Ldr,td as adr,ua as ZEn,ub as Ovn,uc as rdr,ud as HAn,va as VEn,vb as Nvn,vc as xAn,vd as WAn,wa as KEn,wb as kdr,wc as gAn,wd as ZAn,xa as YEn,xb as Lvn,xc as EIe,xd as VAn,ya as aIe,yb as jvn,yd as KAn,za as cz,zb as zvn,zd as YAn}from"./chunks/index-femxb8zf.js";import{$d as qAr,Yd as N7,Zd as vwr,be as PRe}from"./chunks/index-k4strh3v.js";import{de as Uxe}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 z8}from"./chunks/index-m3fw7nkx.js";import{Ce as oVe,De as _Pr,Ee as SOr,Fe as Mg,Ge as JJ,He as tq,Ie as CAr,Je as Ty,Ke as t_r,Le as F7,Me as $Rr,Ne as SAr,Oe as DAr,Pe as c_r,Qe as QTr,Re as Fgt,Se as nLr,Te as aGe,Ue as cGe,Ve as lGe,We as Wvr,Xe as k7,Ye as XTr,Ze as _f,_e as M7,gf as RH,ke as KWe,le as MH,ne as Bo,oe as L5,pe as Lye,qe as qye,re as oE,se as KZ,te as YZ,ue as JZ,ve as Utt,we as QZ,xe as PC,ye as Pit,ze as ys}from"./chunks/index-d9t4trqg.js";import{jf as rfe,kf as M$r}from"./chunks/index-kcgba22z.js";import"./chunks/index-vvqfztrv.js";import{$f as Jit,$g as JA,$h as Ufe,$j as The,$l as Khe,$m as EQ,$n as Fb,Af as PV,Ag as ma,Ah as H3,Ai as ga,Aj as sqr,Ak as mP,Al as $t,An as RSe,Ao as lE,Bf as Il,Bg as fs,Bh as wQ,Bi as Qrt,Bj as aqr,Bk as zhe,Bl as _b,Bn as Byt,Bo as Ph,Cf as Jnt,Cg as lp,Ch as abt,Ci as $fe,Cj as _$r,Ck as eW,Cl as ro,Cn as _yt,Co as Yx,Df as pF,Dg as Sb,Dh as Vk,Di as Z7,Dj as kqr,Dk as Uhe,Dl as Po,Dm as aB,Dn as JO,Do as X0r,Ef as mF,Eg as Bhe,Eh as jl,Ei as U6,Ej as Bqr,Ek as qhe,El as Aw,Em as Oae,En as Uyt,Eo as Ea,Ff as gr,Fh as B1,Fi as mse,Fj as Tqr,Fk as $he,Fl as fP,Fm as TPr,Fn as QO,Gf as GC,Gh as tN,Gi as hse,Gj as Lqr,Gk as $9,Gl as Bn,Gm as TSr,Gn as KUr,Hf as RV,Hg as Nfe,Hh as k1,Hi as iP,Hj as jqr,Hk as Ghe,Hl as dt,Hm as Kse,Hn as gTe,If as YR,Ig as dn,Ih as W0,Ii as rGe,Ij as zqr,Im as zae,In as Pyt,Jg as Mn,Jh as u8e,Ji as R8,Jj as eme,Jk as Hhe,Jl as U_r,Jm as CSr,Jn as Ryt,Kf as kw,Kg as Lgt,Kh as gbt,Ki as LPe,Kj as F$r,Km as _Sr,Kn as $z,Lf as Wye,Lg as Lfe,Lh as xbt,Lj as Rqr,Lk as uo,Ll as Pi,Lm as RSr,Ln as Fyt,Mf as FV,Mh as Fre,Mi as vw,Mj as HUr,Ml as ZPr,Mn as bQ,Nf as gs,Ng as bP,Nh as wbt,Ni as XWe,Nl as z$,Nn as Myt,Of as nr,Og as l5,Oh as Jyt,Oi as cdt,Ok as i5,Ol as HPr,On as pqr,Pf as Qe,Pg as U9,Ph as Qyt,Pi as ldt,Pk as Whe,Pl as Vhe,Pn as qyt,Qf as Oo,Qg as EP,Qj as FA,Ql as Vr,Qn as Kyt,Rf as Ys,Rg as vP,Rh as AQ,Rj as t5,Rn as mqr,Sf as Gh,Sg as jfe,Sh as Sbt,Sj as Che,Sm as fde,Sn as dqr,Tf as Gye,Tg as Ib,Th as f8e,Tj as Jx,Tm as $0,Tn as Cyt,Ug as AP,Uk as hP,Ul as Db,Un as xne,Vf as Vit,Vg as u5,Vh as fPr,Vk as Zhe,Vl as bt,Vn as jz,Wf as Kit,Wg as d5,Wl as Qx,Wn as Ifr,Xg as wP,Xh as Ws,Xl as ha,Xn as ym,Yg as SP,Yi as Bb,Yj as q9,Yl as Jut,Yn as y5,Zf as Yit,Zg as zfe,Zj as Dhe,Zk as WUr,Zl as El,Zm as ZUr,Zn as Pb,_g as H9,_h as kb,_j as Ihe,_l as xP,_m as VUr,_n as Rb,ah as Mh,ak as _he,am as Yhe,an as $yt,ao as sd,bh as Tb,bi as p5,bk as pP,bl as pgr,bm as zt,bn as Gyt,bo as Qhe,ch as ew,cj as TLr,ck as Phe,cl as Eoe,cm as Kx,cn as Hyt,co as o5,dh as a1,dk as Rhe,dl as Kfr,dm as Ene,dn as G3,do as tW,eh as qTr,ei as hc,ek as Fhe,el as FH,em as vne,en as XO,fh as fot,fi as qfe,fk as Mhe,fm as nVe,gh as Ube,gk as Ohe,gm as ko,gn as jye,go as s5,hk as Nhe,hl as mm,hm as Fn,ho as a5,ii as uP,ik as Lhe,im as ePr,in as _h,jg as RLr,jh as Ane,ji as WA,jj as RA,jl as ad,jm as Jo,kh as wne,ki as tw,kj as Eqr,kl as Gfe,lg as FLr,lh as Sne,li as e7,lj as Yqr,ll as Hfe,mg as Bwr,mh as kne,mi as nGe,mj as yWe,ml as Wfe,mo as VA,nf as Mfe,nh as Wfr,ni as QWe,nj as C$r,nk as c0,nl as Zfe,no as Xhe,of as Ofe,oh as Zfr,oi as jLr,oj as D$r,ok as m5,ol as Vfe,om as VO,on as Jhe,oo as IZe,pf as She,ph as z7e,pi as iQ,pj as qU,pk as h5,pl as Kfe,pm as kyt,po as efe,qf as cp,qh as S6,qi as Boe,qj as Vf,qk as uW,ql as x5,qm as hQ,qo as HA,rf as e5,ri as Jde,rj as c9,rl as kP,rm as lme,rn as $fr,ro as Th,sf as khe,sh as fo,si as Coe,sj as Oqr,sk as f5,sl as g5,sm as ume,sn as Gfr,so as tfe,tf as z9,th as Abt,ti as Fue,tj as Nqr,tl as fa,tn as fQ,to as gP,uf as ot,ug as su,uh as Ie,ui as tQ,uj as tme,ul as Qo,un as Nyt,uo as tPr,vf as Br,vg as lP,vh as H0,vi as P8,vj as I$r,vl as BP,vm as vqr,vn as Lyt,wg as ai,wh as jn,wi as n7,wj as T$r,wk as jhe,wl as Vi,wn as Hqr,xf as xe,xg as xm,xh as SQ,xi as o7,xj as iqr,xk as ZA,xl as Yfe,xn as Wqr,yf as Bw,yg as o0,yh as Ebt,yi as H1e,yj as nqr,yk as Cb,yl as Jfe,yn as jyt,zf as ft,zg as jr,zh as Wk,zi as ZAr,zj as oqr,zk as r5,zl as gm,zn as zyt,zo as KA}from"./chunks/index-y2k296fh.js";import{$o as Eae,$p as bit,$q as OC,$r as w1,$s as po,Ap as P1r,Aq as Xoe,Ar as Di,As as PY,Bp as Bae,Bq as mMr,Br as PLr,Bs as Pne,Cp as vr,Cq as hMr,Cr as tjr,Cs as Yut,Dp as j5,Dq as TY,Dr as aV,Ep as Ht,Er as Gf,Es as hEr,Fo as O1r,Fp as dx,Fq as Knt,Fs as U1e,Go as mpe,Gp as tV,Gq as Ynt,Gr as LT,Hp as Zp,Hq as snt,Hr as Rae,Hs as Xv,Ht as up,Io as kn,Ip as vy,Iq as ant,Ir as nG,Is as m_r,It as hm,Jo as Cf,Jp as Hn,Jq as Kut,Jr as wde,Js as fue,Jt as od,Ko as eoe,Kp as Jpe,Kq as vn,Kr as Hqe,Ks as RB,Lq as md,Lr as q$,Ls as D6,Mo as kr,Mp as a$r,Mq as v8,Mr as $$,Ms as Xme,No as fi,Np as c$r,Nq as Zle,Nr as BG,Ns as bne,Oo as ZI,Oq as STr,Or as bzr,Os as NI,Ot as n5,Po as e9,Pq as Vle,Pr as CG,Ps as kfr,Qo as ppe,Qp as A_,Qq as Zye,Qr as noe,Qs as Rm,Ro as WB,Rq as CV,Rr as Rxr,Rs as c1,So as B$,Sr as Mxr,Ss as pa,To as dQ,Tq as A1,Tr as ooe,Ts as Pvr,Uo as wa,Up as cP,Uq as fe,Ur as Vue,Us as Jp,Vo as Yv,Vp as lMr,Vr as TRr,Vs as Lt,Wo as ZB,Wq as To,Wr as ode,Ws as Moe,Xo as zze,Xr as sde,Xs as W9,Yp as B$r,Yr as Uxr,Ys as ld,Zo as Cae,Zr as Oxr,Zs as mc,_o as Kv,_p as yMr,_q as br,_r as Nxr,_s as v1,ap as vae,ar as x$r,as as E0r,at as Ay,bp as vUr,bq as vhe,br as j9,bt as xEr,cp as Bse,cq as HH,cr as Gne,cs as $ue,ct as Vfr,dp as iB,dq as WH,dr as eQ,ds as zPr,dt as v7,ep as qge,eq as ZH,er as M3,es as UPr,et as fx,fp as wae,fq as VH,fs as h3,ft as xyt,gp as nB,gq as QH,gs as Ppe,gt as rw,hp as Aae,hq as XH,hr as ase,hs as Une,ht as sc,ip as o8,iq as X8,ir as jyr,is as qne,it as QI,jp as w1r,jq as nZe,jr as Ofr,js as AWe,jt as ct,kp as S1r,kq as KZe,kr as yne,ks as R$r,kt as Cu,lp as AUr,lq as Vx,lr as gne,ls as Vne,lt as mWe,mp as Zpe,mq as YZe,ms as Rpe,mt as cd,np as wUr,nq as LH,ns as que,nt as au,op as D1r,oq as KH,or as lPr,os as WT,ot as We,pp as SUr,pq as YH,pr as Sw,ps as OUe,qp as kFe,qq as PR,qr as Jz,qs as LUe,rp as BFe,rs as bRr,rt as dP,sp as xq,sq as Ade,ss as KPr,st as t0,tp as CFe,tq as Lbr,ts as ERr,tt as ehe,up as I1r,uq as us,us as YPr,vp as DFe,vq as fOr,vs as eRr,vt as ihe,wp as T1r,wq as XEr,wr as Dae,ws as Kne,xp as _1r,xq as LS,xr as J7,xs as f3,yp as Sae,yq as N0r,yr as Ine,ys as Wne,zp as kae,zq as qI,zr as Hne,zs as _Y}from"./chunks/index-63p1xma2.js";import{Qt as nUe,St as NH}from"./chunks/index-agfrkbxw.js";import{EB as Yyt,Hv as lSe,LB as Ih,MB as XC,OB as Mc,QB as Yp,RB as Kgr,SB as Yi,TB as P$r,Xx as ou,Zx as e4,jy as pc,tz as vQ,xB as et,yy as Hs}from"./chunks/index-g1c4y6gc.js";import{jD as l}from"./chunks/index-bshgrg07.js";import"./chunks/index-pmvk8xga.js";import{nD as no,oD as HQr,pD as E,qD as rg,rD as xs,sD as ce}from"./chunks/index-7ysxtpwx.js";function VKe(e){return e===0||e>=55296&&e<=57343||e>1114111}function KKe(e){if(VKe(e))return 65533;if(e>=128&&e<=159)return kVr[e-128]||e;return e}function YKe(e){return VKe(e)?65533:e}var kVr;var JKe=xs(()=>{kVr=[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 QKe(e,t,r,i,n,o){let a=e.length,c=o*90,u=0,d=()=>{let L=u0[e.charCodeAt(u++)];return L<o?L:L*91-c+u0[e.charCodeAt(u++)]},p=r-i,m=r+n,h=new Int32Array(m);h.fill(-1,i,o),h.fill(-1,o+p,m);let f=new Int32Array(m),g=new Int32Array(m);function y(L,H){let K=0,ee=H,q=H+L;while(ee<q){let S=u0[e.charCodeAt(u++)];if(S<89)K+=S,h[ee++]=K;else if(S===89){let _=u0[e.charCodeAt(u++)]+2;while(_--)h[ee++]=++K}else{let _=u0[e.charCodeAt(u++)];K+=89+(_<90?_*91+u0[e.charCodeAt(u++)]:u0[e.charCodeAt(u++)]*8281+u0[e.charCodeAt(u++)]*91+u0[e.charCodeAt(u++)]),h[ee++]=K}}}y(i,0),y(p,o);let b=new Int32Array(n*2),A=0,w=0;function B(L,H){for(let K=0;K<L;K++){let ee=H+K,q=d(),S=d();b[w*2]=q,b[w*2+1]=S,w+=1,f[ee]=A;let _=(h[q]<0?g[q]:1)+(h[S]<0?g[S]:1);g[ee]=_,A+=_}}B(n-o+i,o+p),B(o-i,i);let R=new Uint16Array(A),M=0;for(let L=0;L<w;L++)for(let H=0;H<2;H++){let K=b[L*2+H],ee=h[K];if(ee<0){let q=f[K],S=q+g[K];while(q<S)R[M++]=R[q++]}else R[M++]=ee}let k=new Uint16Array(t),N=0;while(u<a){let L=u0[e.charCodeAt(u++)];if(L>=o)L=L*91-c+u0[e.charCodeAt(u++)];let H=h[L];if(H<0){let K=f[L],ee=K+g[L];while(K<ee)k[N++]=R[K++]}else k[N++]=H}return k}var u0;var XKe=xs(()=>{u0=(()=>{let e=new Uint8Array(127),t=0;for(let r=33;r<=126;r++)if(r!==34&&r!==36&&r!==92)e[r]=t++;return e})()});var I0e;var eYe=xs(()=>{XKe();I0e=QKe("!}.&u%}'&}*'~!6*)%&,~!J~!J~%L~y<~!R,~~%Lu~~#GD~~#|)1#%}^%}2%+#.##%##%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i[vrv{z;h]eb?C2F|^iZu.vix,hZq3ah!.(?C2F|QOu!5ShXM:2<BaY?C2F|P",13494,2713,49,25,61)});var jP;var T0e=xs(()=>{jP=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 Lc;var tYe=xs(()=>{(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"})(Lc||(Lc={}))});function rYe(e){return e-lu.ZERO>>>0<=9}function BVr(e){return(e|wW)-lu.LOWER_A>>>0<=5}function CVr(e){return(e|wW)-lu.LOWER_A>>>0<=25}function DVr(e){return e===lu.EQUALS||CVr(e)||rYe(e)}class _0e{decodeTree;emitCodePoint;errors;state=cu.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=d0.Strict;runConsumed=0;constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r}startEntity(e){this.decodeMode=e,this.state=cu.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case cu.EntityStart:{if(e.charCodeAt(t)===lu.NUM)return this.state=cu.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=cu.NamedEntity,this.stateNamedEntity(e,t)}case cu.NumericStart:return this.stateNumericStart(e,t);case cu.NumericDecimal:return this.stateNumericDecimal(e,t);case cu.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)|wW)===lu.LOWER_X)return this.state=cu.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=cu.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){let r=e.length,{result:i}=this,{consumed:n}=this;while(t<r){let o=e.charCodeAt(t);if(rYe(o)||BVr(o)){let s=o<=lu.NINE?o-lu.ZERO:(o|wW)-lu.LOWER_A+10;i=i*16+s,n+=1,t+=1}else return this.result=i,this.consumed=n,this.emitNumericEntity(o,3)}return this.result=i,this.consumed=n,-1}stateNumericDecimal(e,t){let r=e.length,{result:i}=this,{consumed:n}=this;while(t<r){let o=e.charCodeAt(t)-lu.ZERO;if(o>>>0>9)return this.result=i,this.consumed=n,this.emitNumericEntity(o+lu.ZERO,2);i=i*10+o,n+=1,t+=1}return this.result=i,this.consumed=n,-1}emitNumericEntity(e,t){if(this.consumed<=t)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===lu.SEMI)this.consumed+=1;else if(this.decodeMode===d0.Strict)return 0;if(this.emitCodePoint((this.decodeTree===jP?YKe:KKe)(this.result),this.consumed),this.errors){if(e!==lu.SEMI)this.errors.missingSemicolonAfterCharacterReference();this.errors.validateNumericCharacterReference(this.result)}return this.consumed}flushAndEmitLegacyOrReject(e,t,r,i){return this.consumed=e,this.excess=t,this.result===0||this.decodeMode===d0.Attribute&&(i===0||t>1||DVr(r))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:r}=this,i=e.length,n=this.decodeMode===d0.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=r[o];while(t<i){while((c&(Lc.VALUE_LENGTH|Lc.FLAG13))===0&&(c&Lc.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&Lc.JUMP_TABLE,f=(c&Lc.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=r[o+1+g];if(y===0)return this.flushAndEmitLegacyOrReject(a,s,m,0);o=o+f+y&65535}if(c=r[o],t+=1,s+=1,t>=i)break}if(t>=i)break;if((c&(Lc.VALUE_LENGTH|Lc.FLAG13))===Lc.FLAG13){let m=(c&Lc.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&Lc.JUMP_TABLE))return this.flushAndEmitLegacyOrReject(a,s,f,0);t+=1,s+=1,h=1}while(h<m){if(t>=i)return this.treeIndex=o,this.excess=s,this.consumed=a,this.runConsumed=h,-1;let f=h-1,y=r[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=r[o];continue}let u=c>>>14,d=e.charCodeAt(t);if(u!==0){if(!n&&(c&Lc.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===lu.SEMI)return this.emitNamedEntityData(o,u,a+s);if(u===1)return this.flushAndEmitLegacyOrReject(a,s,d,u)}let p=IVr(r,c,o+(u||1),d);if(p<0)return this.flushAndEmitLegacyOrReject(a,s,d,u);o=p,c=r[o],t+=1,s+=1}if(!n&&c>>>14!==0&&(c&Lc.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,r=t[e]>>>14;return this.emitNamedEntityData(e,r,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,r){let{decodeTree:i}=this;if(this.emitCodePoint(t===1?i[e]&Lc.VALUE_MASK:i[e+1],r),t===3)this.emitCodePoint(i[e+2],r);return r}end(){switch(this.state){case cu.NamedEntity:return this.result!==0&&(this.decodeMode!==d0.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case cu.NumericDecimal:return this.emitNumericEntity(0,2);case cu.NumericHex:return this.emitNumericEntity(0,3);case cu.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function IVr(e,t,r,i){let n=(t&Lc.BRANCH_LENGTH)>>7,o=t&Lc.JUMP_TABLE;if(o){if(n===0)return i===o?r:-1;let c=i-o;if(c>>>0>=n)return-1;let u=e[r+c];return u===0?-1:r+n+u-1&65535}if(n===0)return-1;let s=n+1>>1,a=r+s+n;for(let c=0;c<n;c++){let d=e[r+(c>>1)]>>((c&1)<<3)&255;if(d===i){let p=r+s+c;return a+e[p]&65535}if(d>i)return-1}return-1}var lu,wW=32,cu,d0;var iYe=xs(()=>{JKe();T0e();tYe();eYe();T0e();(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"})(lu||(lu={}));(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"})(cu||(cu={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(d0||(d0={}))});function v5(e){return e===Er.Space||e===Er.NewLine||e===Er.Tab||e===Er.FormFeed||e===Er.CarriageReturn}function eC(e){return e===Er.Slash||e===Er.Gt||v5(e)}function TVr(e){return e>=Er.LowerA&&e<=Er.LowerZ||e>=Er.UpperA&&e<=Er.UpperZ}class tC{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:r=e},i){this.cbs=i,this.xmlMode=e,this.decodeEntities=t,this.recognizeSelfClosing=r,this.entityDecoder=new _0e(e?jP:I0e,(n,o)=>this.emitCodePoint(n,o))}reset(){this.state=Ze.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=Ze.Text,this.isSpecial=!1,this.currentSequence=ci.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===Er.Lt||!this.decodeEntities&&this.fastForwardTo(Er.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===Er.Amp)this.startEntity()}currentSequence=ci.Empty;sequenceIndex=0;enterTagBody(){if(this.currentSequence===ci.Plaintext)this.currentSequence=ci.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===ci.ScriptEnd&&t===ci.StyleEnd[3]){this.currentSequence=ci.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===ci.TitleEnd&&t===ci.TextareaEnd[3]){this.currentSequence=ci.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===ci.NoembedEnd&&t===ci.NoframesEnd[4]){this.currentSequence=ci.NoframesEnd,this.sequenceIndex=5;return}}else if(eC(e)){this.sequenceIndex=0,this.state=Ze.InTagName,this.stateInTagName(e);return}this.isSpecial=!1,this.currentSequence=ci.Empty,this.sequenceIndex=0,this.state=Ze.InTagName,this.stateInTagName(e)}stateCDATASequence(e){if(e===ci.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===ci.Cdata.length)this.state=Ze.InCommentLike,this.currentSequence=ci.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===ci.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&e===Er.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===ci.CommentEnd&&this.sequenceIndex===2&&e===Er.Gt)this.emitComment(2);else if(this.currentSequence===ci.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&e!==Er.Gt)this.sequenceIndex=Number(e===Er.Dash);else if(e===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===ci.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?!eC(e):TVr(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(eC(e)){let t=this.index-this.currentSequence.length;if(this.sectionStart<t){let r=this.index;this.index=t,this.cbs.ontext(this.sectionStart,t),this.index=r}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===ci.TitleEnd||this.currentSequence===ci.TextareaEnd){if(this.decodeEntities&&e===Er.Amp)this.startEntity()}else if(this.fastForwardTo(Er.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(e===Er.Lt)}stateBeforeTagName(e){if(e===Er.ExclamationMark)this.state=Ze.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===Er.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:_Vr.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===Er.Slash)this.state=Ze.BeforeClosingTagName;else this.state=Ze.Text,this.stateText(e)}stateInTagName(e){if(eC(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(v5(e))if(this.xmlMode);else this.state=Ze.InSpecialComment,this.sectionStart=this.index;else if(e===Er.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(eC(e))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=Ze.AfterClosingTagName,this.stateAfterClosingTagName(e)}stateAfterClosingTagName(e){if(e===Er.Gt||this.fastForwardTo(Er.Gt))this.state=Ze.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(e){if(e===Er.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(e===Er.Slash)this.state=Ze.InSelfClosingTag;else if(!v5(e))this.state=Ze.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(e){if(e===Er.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=ci.Empty}else if(!v5(e))this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===Er.Eq||eC(e))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=Ze.AfterAttributeName,this.stateAfterAttributeName(e)}stateAfterAttributeName(e){if(e===Er.Eq)this.state=Ze.BeforeAttributeValue;else if(e===Er.Slash||e===Er.Gt)this.cbs.onattribend(Em.NoValue,this.sectionStart),this.sectionStart=-1,this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!v5(e))this.cbs.onattribend(Em.NoValue,this.sectionStart),this.state=Ze.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(e){if(e===Er.DoubleQuote)this.state=Ze.InAttributeValueDq,this.sectionStart=this.index+1;else if(e===Er.SingleQuote)this.state=Ze.InAttributeValueSq,this.sectionStart=this.index+1;else if(!v5(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===Er.DoubleQuote?Em.Double:Em.Single,this.index+1),this.state=Ze.BeforeAttributeName;else if(this.decodeEntities&&e===Er.Amp)this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,Er.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,Er.SingleQuote)}stateInAttributeValueNoQuotes(e){if(v5(e)||e===Er.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(Em.Unquoted,this.index),this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(this.decodeEntities&&e===Er.Amp)this.startEntity()}stateBeforeDeclaration(e){if(e===Er.OpeningSquareBracket)this.state=Ze.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=e===Er.Dash?Ze.BeforeComment:Ze.InDeclaration;else if((e|32)===ci.Doctype[0])this.state=Ze.DeclarationSequence,this.currentSequence=ci.Doctype,this.sequenceIndex=1;else if(e===Er.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else if(e===Er.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===Er.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===Er.Gt||this.fastForwardTo(Er.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=Ze.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(e){if(e===Er.Questionmark)this.sequenceIndex=1;else if(e===Er.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(Er.Questionmark))}stateBeforeComment(e){if(e===Er.Dash)this.state=Ze.InCommentLike,this.currentSequence=ci.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=Ze.InDeclaration;else if(e===Er.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===Er.Gt||this.fastForwardTo(Er.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)===Er.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===ci.CdataEnd)if(this.xmlMode){if(this.sectionStart<e)this.cbs.oncdata(this.sectionStart,e,0)}else{let t=this.sectionStart-ci.Cdata.length-1;this.cbs.oncomment(t,e,0)}else{let t=this.xmlMode?0:Math.min(this.sequenceIndex,ci.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!==ci.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 Er,Ze,Em,ci,_Vr;var P0e=xs(()=>{iYe();(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"})(Er||(Er={}));(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"})(Em||(Em={}));ci={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])},_Vr=new Map([[ci.IframeEnd[2],ci.IframeEnd],[ci.NoembedEnd[2],ci.NoembedEnd],[ci.Plaintext[2],ci.Plaintext],[ci.ScriptEnd[2],ci.ScriptEnd],[ci.TitleEnd[2],ci.TitleEnd],[ci.XmpEnd[2],ci.XmpEnd]])});class nC{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??tC)(this.options,this),this.foreignContext=[Lb.None],this.cbs.onparserinit?.(this)}ontext(e,t){let r=this.getSlice(e,t);this.endIndex=t-1,this.cbs.ontext?.(r),this.startIndex=t}ontextentity(e,t){this.endIndex=t-1,this.cbs.ontext?.(nYe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==Lb.None}isVoidElement(e){return this.htmlMode&&RVr.has(e)}readTagName(e,t){let r=this.lowerCaseTagNames?this.getSlice(e,t).toLowerCase():this.getSlice(e,t);if(!(this.lowerCaseTagNames&&this.htmlMode))return r;if(this.foreignContext[0]===Lb.Svg)return uYe.get(r)??r;if(this.foreignContext.length>1){let i=uYe.get(r);if(i!==void 0&&this.stack.includes(i))return i}if(!this.isInForeignContext())return r==="image"?"img":r;return r}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&&PVr.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(Lb.Svg);else if(e==="math")this.foreignContext.unshift(Lb.MathML);else if(lYe.has(e))this.foreignContext.unshift(Lb.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 r=this.readTagName(e,t);if(!this.isVoidElement(r)){let i=this.stack.indexOf(r);if(i!==-1){for(let n=0;n<i;n++)this.popElement(!0);this.popElement(!1)}else if(this.htmlMode&&r==="p")this.emitOpenTag("p"),this.closeCurrentTag(!0)}else if(this.htmlMode&&r==="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&&(FVr.has(t)||lYe.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 r=this.getSlice(e,t);this.attribname=this.lowerCaseAttributeNames?r.toLowerCase():r}onattribdata(e,t){this.attribvalue+=this.getSlice(e,t)}onattribentity(e){this.attribvalue+=nYe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===Em.Double?'"':e===Em.Single?"'":e===Em.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(MVr),r=t<0?e:e.substr(0,t);if(this.lowerCaseTagNames)r=r.toLowerCase();return r}ondeclaration(e,t){this.endIndex=t;let r=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let i=this.htmlMode?this.lowerCaseTagNames?cYe:r.slice(0,cYe.length):this.getInstructionName(r);this.cbs.onprocessinginstruction(`!${i}`,`!${r}`)}this.startIndex=t+1}onprocessinginstruction(e,t){this.endIndex=t;let r=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let i=this.getInstructionName(r);this.cbs.onprocessinginstruction(`?${i}`,`?${r}`)}this.startIndex=t+1}oncomment(e,t,r){this.endIndex=t,this.cbs.oncomment?.(this.getSlice(e,t-r)),this.cbs.oncommentend?.(),this.startIndex=t+1}oncdata(e,t,r){this.endIndex=t;let i=this.getSlice(e,t-r);if(!this.htmlMode||this.options.recognizeCDATA)this.cbs.oncdatastart?.(),this.cbs.ontext?.(i),this.cbs.oncdataend?.();else if(this.isInForeignContext())this.cbs.ontext?.(i);else this.cbs.oncomment?.(`[CDATA[${i}]]`),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(Lb.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 r=this.buffers[0].slice(e-this.bufferOffset,t-this.bufferOffset);while(t-this.bufferOffset>this.buffers[0].length)this.shiftBuffer(),r+=this.buffers[0].slice(0,t-this.bufferOffset);return r}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 nYe,rC,Vs,iC,oYe,sYe,aYe,PVr,cYe="doctype",RVr,FVr,lYe,uYe,Lb,MVr;var R0e=xs(()=>{P0e();({fromCodePoint:nYe}=String),rC=new Set(["input","option","optgroup","select","button","datalist","textarea"]),Vs=new Set(["p"]),iC=new Set(["h1","h2","h3","h4","h5","h6","p"]),oYe=new Set(["thead","tbody"]),sYe=new Set(["dd","dt"]),aYe=new Set(["rt","rp"]),PVr=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",Vs],["h1",iC],["h2",iC],["h3",iC],["h4",iC],["h5",iC],["h6",iC],["select",rC],["input",rC],["output",rC],["button",rC],["datalist",rC],["textarea",rC],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",sYe],["dt",sYe],["address",Vs],["article",Vs],["aside",Vs],["blockquote",Vs],["details",Vs],["div",Vs],["dl",Vs],["fieldset",Vs],["figcaption",Vs],["figure",Vs],["footer",Vs],["form",Vs],["header",Vs],["hr",Vs],["main",Vs],["nav",Vs],["ol",Vs],["pre",Vs],["section",Vs],["table",Vs],["ul",Vs],["rt",aYe],["rp",aYe],["tbody",oYe],["tfoot",oYe]]),RVr=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),FVr=new Set(["math","svg"]),lYe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),uYe=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"})(Lb||(Lb={}));MVr=/\s|\//});var SW={};rg(SW,{CDATA:()=>q0e,Comment:()=>L0e,Directive:()=>N0e,Doctype:()=>OVr,ElementType:()=>pn,Root:()=>M0e,Script:()=>j0e,Style:()=>z0e,Tag:()=>U0e,Text:()=>O0e,isTag:()=>F0e});function F0e(e){return e.type===pn.Tag||e.type===pn.Script||e.type===pn.Style}var pn,M0e,O0e,N0e,L0e,j0e,z0e,U0e,q0e,OVr;var oC=xs(()=>{(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"})(pn||(pn={}));M0e=pn.Root,O0e=pn.Text,N0e=pn.Directive,L0e=pn.Comment,j0e=pn.Script,z0e=pn.Style,U0e=pn.Tag,q0e=pn.CDATA,OVr=pn.Doctype});class G0e{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 dYe(this,e)}}function uu(e){return F0e(e)}function _W(e){return e.type===pn.CDATA}function sw(e){return e.type===pn.Text}function H0e(e){return e.type===pn.Comment}function NVr(e){return e.type===pn.Directive}function LVr(e){return e.type===pn.Root}function dp(e){return Object.hasOwn(e,"children")}function dYe(e,t=!1){let r;if(sw(e))r=new zP(e.data);else if(H0e(e))r=new BW(e.data);else if(uu(e)){let i=t?$0e(e.children):[],n=new TW(e.name,{...e.attribs},i);for(let o of i)o.parent=n;if(e.namespace!=null)n.namespace=e.namespace;if(e["x-attribsNamespace"])n["x-attribsNamespace"]={...e["x-attribsNamespace"]};if(e["x-attribsPrefix"])n["x-attribsPrefix"]={...e["x-attribsPrefix"]};r=n}else if(_W(e)){let i=t?$0e(e.children):[],n=new IW(i);for(let o of i)o.parent=n;r=n}else if(LVr(e)){let i=t?$0e(e.children):[],n=new UP(i);for(let o of i)o.parent=n;if(e["x-mode"])n["x-mode"]=e["x-mode"];r=n}else if(NVr(e)){let i=new CW(e.name,e.data);if(e["x-name"]!=null)i["x-name"]=e["x-name"],i["x-publicId"]=e["x-publicId"],i["x-systemId"]=e["x-systemId"];r=i}else throw Error(`Not implemented yet: ${e.type}`);if(r.startIndex=e.startIndex,r.endIndex=e.endIndex,e.sourceCodeLocation!=null)r.sourceCodeLocation=e.sourceCodeLocation;return r}function $0e(e){let t=e.map((r)=>dYe(r,!0));for(let r=1;r<t.length;r++)t[r].prev=t[r-1],t[r-1].next=t[r];return t}var kW,zP,BW,CW,DW,IW,UP,TW;var W0e=xs(()=>{oC();kW=class kW extends G0e{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};zP=class zP extends kW{type=pn.Text;get nodeType(){return 3}};BW=class BW extends kW{type=pn.Comment;get nodeType(){return 8}};CW=class CW extends kW{type=pn.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};DW=class DW extends G0e{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}};IW=class IW extends DW{type=pn.CDATA;get nodeType(){return 4}};UP=class UP extends DW{type=pn.Root;get nodeType(){return 9}};TW=class TW extends DW{name;attribs;type;constructor(e,t,r=[],i=e==="script"?pn.Script:e==="style"?pn.Style:pn.Tag){super(r);this.name=e,this.attribs=t,this.type=i}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 A5{dom=[];root=new UP(this.dom);callback;options;elementCB;done=!1;tagStack=[this.root];lastNode=null;parser=null;constructor(e,t,r){if(typeof t==="function")r=t,t=pYe;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??pYe,this.elementCB=r??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new UP(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 r=this.options.xmlMode?pn.Tag:void 0,i=new TW(e,t,void 0,r);this.addNode(i),this.tagStack.push(i)}ontext(e){let{lastNode:t}=this;if(t&&t.type===pn.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let r=new zP(e);this.addNode(r),this.lastNode=r}}oncomment(e){if(this.lastNode&&this.lastNode.type===pn.Comment){this.lastNode.data+=e;return}let t=new BW(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new zP(""),t=new IW([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let r=new CW(e,t);this.addNode(r)}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],r=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),r)e.prev=r,r.next=e;e.parent=t,this.lastNode=null}}var pYe;var aw=xs(()=>{oC();W0e();W0e();pYe={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function sC(e,t,r=!0,i=Number.POSITIVE_INFINITY){return mYe(e,Array.isArray(t)?t:[t],r,i)}function mYe(e,t,r,i){let n=[],o=[Array.isArray(t)?t:[t]],s=[0];for(;;){if(s[0]>=o[0].length){if(s.length===1)return n;o.shift(),s.shift();continue}let a=o[0][s[0]++];if(e(a)){if(n.push(a),--i<=0)return n}if(r&&dp(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function PW(e,t,r=!0){let i=Array.isArray(t)?t:[t];for(let n of i){if(uu(n)&&e(n))return n;if(r&&dp(n)&&n.children.length>0){let o=PW(e,n.children,!0);if(o)return o}}return null}function hYe(e,t){return(Array.isArray(t)?t:[t]).some((r)=>uu(r)&&e(r)||dp(r)&&hYe(e,r.children))}function jVr(e,t){let r=[],i=[Array.isArray(t)?t:[t]],n=[0];for(;;){if(n[0]>=i[0].length){if(i.length===1)return r;i.shift(),n.shift();continue}let o=i[0][n[0]++];if(uu(o)&&e(o))r.push(o);if(dp(o)&&o.children.length>0)n.unshift(0),i.unshift(o.children)}}var Z0e=xs(()=>{aw()});function V0e(e,t){if(typeof t==="function")return(r)=>uu(r)&&t(r.attribs[e]);return(r)=>uu(r)&&r.attribs[e]===t}function zVr(e,t){return(r)=>e(r)||t(r)}function fYe(e){let t=Object.keys(e).map((r)=>{let i=e[r];return Object.hasOwn(RW,r)?RW[r](i):V0e(r,i)});return t.length===0?null:t.reduce(zVr)}function UVr(e,t){let r=fYe(e);return r?r(t):!0}function qVr(e,t,r,i=Number.POSITIVE_INFINITY){let n=fYe(e);return n?sC(n,t,r,i):[]}function $Vr(e,t,r=!0){if(!Array.isArray(t))t=[t];return PW(V0e("id",e),t,r)}function w5(e,t,r=!0,i=Number.POSITIVE_INFINITY){return sC(RW.tag_name(e),t,r,i)}function GVr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return sC(V0e("class",e),t,r,i)}function HVr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return sC(RW.tag_type(e),t,r,i)}var RW;var K0e=xs(()=>{aw();Z0e();RW={tag_name(e){if(typeof e==="function")return(t)=>uu(t)&&e(t.name);if(e==="*")return uu;return(t)=>uu(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)=>sw(t)&&e(t.data);return(t)=>sw(t)&&t.data===e}}});function gYe(e){return e===34?""":e===38?"&":e===39?"'":e===60?"<":e===62?">":" "}function xYe(e){return e>=128||e>=32&&e<64&&(WVr>>>e&1)===1}function FW(e){let{length:t}=e,r,i=0,n=0;while(n<t){let o=e.charCodeAt(n);if(!xYe(o)){let a=Math.min(n+32,t),c=n+1;while(c<a&&!xYe(e.charCodeAt(c)))c++;if(c<a){n=c;continue}if(c>=t)break;if(Y0e.lastIndex=c,!Y0e.test(e))break;n=Y0e.lastIndex-1;continue}if(r===void 0)r=e.substring(0,n);else if(i!==n)r+=e.substring(i,n);if(o<64){r+=gYe(o),i=n+=1;continue}let s=e.codePointAt(n);if(r+=`&#x${s.toString(16)};`,s!==o)n++;i=n+=1}if(r===void 0)return e;if(i<t)r+=e.substr(i);return r}function yYe(e,t){if(e.lastIndex=0,!e.test(t))return t;let r="",i=0;do{let n=e.lastIndex-1;if(i!==n)r+=t.substring(i,n);let o=t.charCodeAt(n);r+=gYe(o),i=n+1}while(e.test(t));return r+t.substring(i)}function J0e(e){return yYe(ZVr,e)}function Q0e(e){return yYe(VVr,e)}var WVr=1342177476,Y0e,ZVr,VVr;var bYe=xs(()=>{Y0e=/["&'<>\u0080-\uFFFF]/g;ZVr=/["&\u{A0}]/gu;VVr=/[&<>\u{A0}]/gu});var EYe,vYe;var AYe=xs(()=>{bYe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(EYe||(EYe={}));(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"})(vYe||(vYe={}))});var wYe,SYe;var kYe=xs(()=>{wYe=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])),SYe=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 XVr(e,t={}){let r="length"in e?e:[e],i=t.xmlMode??!1,n="";for(let o=0;o<r.length;o++)n+=CYe(r[o],t,i);return n}function BYe(e,t,r){let i="";for(let n=0;n<e.length;n++)i+=CYe(e[n],t,r);return i}function CYe(e,t,r){switch(e.type){case M0e:return BYe(e.children,t,r);case N0e:return`<${e.data}>`;case L0e:return`<!--${e.data}-->`;case q0e:return`<![CDATA[${e.children[0].data}]]>`;case j0e:case z0e:case U0e:return eKr(e,t,r);case O0e:{let i=e,n=i.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!r&&i.parent&&KVr.has(i.parent.name)))return r||t.encodeEntities!=="utf8"?FW(n):Q0e(n);return n}}}function eKr(e,t,r){if(r==="foreign"){if(e.name=wYe.get(e.name)??e.name,e.parent&&QVr.has(e.parent.name))r=!1}if(!r&&JVr.has(e.name))r="foreign";let{name:i,children:n}=e,o=!r&&YVr.has(i),s=`<${i}${rKr(e.attribs,t,r)}`;if(n.length===0&&(r?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=r?"/>":" />";else{if(s+=">",n.length>0)s+=BYe(n,t,r);if(!o)s+=`</${i}>`}return s}function tKr(e){return e.replaceAll('"',""")}function rKr(e,t,r){if(!e)return"";let i=(t.encodeEntities??t.decodeEntities)===!1?tKr:r||t.encodeEntities!=="utf8"?FW:J0e,n=r==="foreign",o=!!(t.emptyAttrs??r),s="";for(let a in e){if(!Object.hasOwn(e,a))continue;let c=e[a],u=n?SYe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${u}`:` ${u}="${i(c==null?"":String(c))}"`}return s}var KVr,YVr,JVr,QVr,DYe;var IYe=xs(()=>{oC();AYe();kYe();KVr=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),YVr=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),JVr=new Set(["svg","math"]),QVr=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));DYe=XVr});function TYe(e,t){return DYe(e,t)}function iKr(e,t){return dp(e)?e.children.map((r)=>TYe(r,t)).join(""):""}function MW(e){if(Array.isArray(e))return e.map(MW).join("");if(uu(e))return e.name==="br"?`
|
|
3
3
|
`:MW(e.children);if(_W(e))return MW(e.children);if(sw(e))return e.data;return""}function qP(e){if(Array.isArray(e))return e.map(qP).join("");if(dp(e)&&!H0e(e))return qP(e.children);if(sw(e))return e.data;return""}function X0e(e){if(Array.isArray(e))return e.map(X0e).join("");if(dp(e)&&(e.type===pn.Tag||_W(e)))return X0e(e.children);if(sw(e))return e.data;return""}var exe=xs(()=>{IYe();oC();aw()});function $P(e){let t=OW(cKr,e);return t?t.name==="feed"?nKr(t):oKr(t):null}function nKr(e){let t=e.children,r={type:"atom",items:w5("entry",t).map((o)=>{let{children:s}=o,a={media:_Ye(s)};pp(a,"id","id",s),pp(a,"title","title",s);let c=OW("link",s)?.attribs.href;if(c)a.link=c;let u=cw("summary",s)||cw("content",s);if(u)a.description=u;let d=cw("updated",s);if(d)a.pubDate=new Date(d);return a})};pp(r,"id","id",t),pp(r,"title","title",t);let i=OW("link",t)?.attribs.href;if(i)r.link=i;pp(r,"description","subtitle",t);let n=cw("updated",t);if(n)r.updated=new Date(n);return pp(r,"author","email",t,!0),r}function oKr(e){let t=OW("channel",e.children)?.children??[],r={type:e.name.substr(0,3),id:"",items:w5("item",e.children).map((n)=>{let{children:o}=n,s={media:_Ye(o)};pp(s,"id","guid",o),pp(s,"title","title",o),pp(s,"link","link",o),pp(s,"description","description",o);let a=cw("pubDate",o)||cw("dc:date",o);if(a)s.pubDate=new Date(a);return s})};pp(r,"title","title",t),pp(r,"link","link",t),pp(r,"description","description",t);let i=cw("lastBuildDate",t);if(i)r.updated=new Date(i);return pp(r,"author","managingEditor",t,!0),r}function _Ye(e){return w5("media:content",e).map((t)=>{let{attribs:r}=t,i={medium:r.medium,isDefault:!!r.isDefault};for(let n of sKr)if(r[n])i[n]=r[n];for(let n of aKr)if(r[n])i[n]=Number.parseInt(r[n],10);if(r.expression)i.expression=r.expression;return i})}function OW(e,t){return w5(e,t,!0,1)[0]}function cw(e,t,r=!1){return qP(w5(e,t,r,1)).trim()}function pp(e,t,r,i,n=!1){let o=cw(r,i,n);if(o)e[t]=o}function cKr(e){return e==="rss"||e==="feed"||e==="rdf:RDF"}var sKr,aKr;var PYe=xs(()=>{K0e();exe();sKr=["url","type","lang"],aKr=["fileSize","bitrate","framerate","samplingrate","channels","duration","height","width"]});function lKr(e){let t=e.length;while(--t>=0){let r=e[t];if(t>0&&e.lastIndexOf(r,t-1)>=0){e.splice(t,1);continue}for(let i=r.parent;i;i=i.parent)if(e.includes(i)){e.splice(t,1);break}}return e}function RYe(e,t){let r=[],i=[];if(e===t)return 0;let n=dp(e)?e:e.parent;while(n)r.unshift(n),n=n.parent;n=dp(t)?t:t.parent;while(n)i.unshift(n),n=n.parent;let o=Math.min(r.length,i.length),s=0;while(s<o&&r[s]===i[s])s++;if(s===0)return Oh.DISCONNECTED;let a=r[s-1],c=a.children,u=r[s],d=i[s];if(c.indexOf(u)>c.indexOf(d)){if(a===t)return Oh.FOLLOWING|Oh.CONTAINED_BY;return Oh.FOLLOWING}if(a===e)return Oh.PRECEDING|Oh.CONTAINS;return Oh.PRECEDING}function uKr(e){return e=e.filter((t,r,i)=>!i.includes(t,r+1)),e.sort((t,r)=>{let i=RYe(t,r);if(i&Oh.PRECEDING)return-1;if(i&Oh.FOLLOWING)return 1;return 0}),e}var Oh;var FYe=xs(()=>{aw();(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"})(Oh||(Oh={}))});function GP(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,r=t.lastIndexOf(e);if(r!==-1)t.splice(r,1)}e.next=null,e.prev=null,e.parent=null}function dKr(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:r}=t.parent,i=r.lastIndexOf(e);if(i===-1)return;r[i]=t,e.parent=null}}function pKr(e,t){if(GP(t),t.next=null,t.parent=e,e.children.push(t)>1){let r=e.children[e.children.length-2];r.next=t,t.prev=r}else t.prev=null}function mKr(e,t){GP(t);let{parent:r}=e,i=e.next;if(t.next=i,t.prev=e,e.next=t,t.parent=r,i){if(i.prev=t,r){let n=r.children;n.splice(n.lastIndexOf(i),0,t)}}else if(r)r.children.push(t)}function hKr(e,t){if(GP(t),t.parent=e,t.prev=null,e.children.unshift(t)===1)t.next=null;else{let r=e.children[1];r.prev=t,t.next=r}}function fKr(e,t){GP(t);let{parent:r}=e;if(r){let i=r.children;i.splice(i.indexOf(e),0,t)}if(e.prev)e.prev.next=t;t.parent=r,t.prev=e.prev,t.next=e,e.prev=t}var MYe=()=>{};function OYe(e){return dp(e)?e.children:[]}function NYe(e){return e.parent||null}function xKr(e){let t=NYe(e);if(t!=null)return OYe(t);let r=[e],{prev:i,next:n}=e;while(i!=null)r.unshift(i),{prev:i}=i;while(n!=null)r.push(n),{next:n}=n;return r}function gKr(e,t){let{attribs:r}=e;return r?.[t]}function yKr(e,t){let{attribs:r}=e;return r!=null&&Object.hasOwn(r,t)&&r[t]!=null}function bKr(e){return e.name}function EKr(e){let{next:t}=e;while(t!==null&&!uu(t))({next:t}=t);return t}function vKr(e){let{prev:t}=e;while(t!==null&&!uu(t))({prev:t}=t);return t}var LYe=xs(()=>{aw()});var txe={};rg(txe,{DocumentPosition:()=>Oh,append:()=>mKr,appendChild:()=>pKr,compareDocumentPosition:()=>RYe,existsOne:()=>hYe,filter:()=>sC,find:()=>mYe,findAll:()=>jVr,findOne:()=>PW,getAttributeValue:()=>gKr,getChildren:()=>OYe,getElementById:()=>$Vr,getElements:()=>qVr,getElementsByClassName:()=>GVr,getElementsByTagName:()=>w5,getElementsByTagType:()=>HVr,getFeed:()=>$P,getInnerHTML:()=>iKr,getName:()=>bKr,getOuterHTML:()=>TYe,getParent:()=>NYe,getSiblings:()=>xKr,getText:()=>MW,hasAttrib:()=>yKr,innerText:()=>X0e,nextElementSibling:()=>EKr,prepend:()=>fKr,prependChild:()=>hKr,prevElementSibling:()=>vKr,removeElement:()=>GP,removeSubsets:()=>lKr,replaceElement:()=>dKr,testElement:()=>UVr,textContent:()=>qP,uniqueSort:()=>uKr});var NW=xs(()=>{PYe();FYe();K0e();MYe();Z0e();exe();LYe()});var zYe={};rg(zYe,{DefaultHandler:()=>A5,DomHandler:()=>A5,DomUtils:()=>txe,ElementType:()=>SW,Parser:()=>nC,QuoteType:()=>Em,Tokenizer:()=>tC,createDocumentStream:()=>AKr,getFeed:()=>$P,parseDocument:()=>jYe,parseFeed:()=>SKr});function jYe(e,t){let r=new A5(void 0,t);return new nC(r,t).end(e),r.root}function AKr(e,t,r){let i=new A5((n)=>e(n,i.root),t,r);return new nC(i,t)}function SKr(e,t=wKr){return $P(jYe(e,t).children)}var wKr;var UYe=xs(()=>{R0e();R0e();aw();aw();oC();P0e();NW();NW();NW();wKr={xmlMode:!0}});var $Ye=E(function(E3o,qYe){qYe.exports=(e)=>{if(typeof e!=="string")throw TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}});var HYe=E(function(BKr){/*!
|
|
4
4
|
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
|
|
5
5
|
*
|
|
@@ -1035,7 +1035,7 @@ ${fA(e.cont)}`}}function Fno(e,t){return t.map((r,i,{length:n})=>Mno(e,r,i===n-1
|
|
|
1035
1035
|
`).find((b)=>b.startsWith("data: "));if(!d)continue;let p;try{let b=EHr.safeParse(JSON.parse(d.slice(6)));if(!b.success)continue;p=b.data}catch{return await yhe(i),{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 yhe(i);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:yHr(a)}}}s=await WZe(i,t,r)}return{success:!1,error:"Stream ended without a terminal event"}}class Ehe extends Error{timeoutMs;constructor(e){super(`request timed out after ${e}ms`);this.timeoutMs=e,this.name="A2ARequestTimeoutError"}}class aP extends Error{timeoutMs;constructor(e){super(`A2A stream stalled waiting for final event after ${e}ms`);this.timeoutMs=e,this.name="A2AStreamIdleTimeoutError"}}async function DHr(e,t,r,i,n){return xhe((o)=>e(t,{...r,signal:o}),{timeoutMs:i,onTimeout:()=>new Ehe(i),signal:n})}async function WZe(e,t,r){try{return await xhe(()=>e.read(),{timeoutMs:t,onTimeout:()=>new aP(t),signal:r})}catch(i){if(i instanceof aP||r?.aborted)await yhe(e,i);throw i}}async function yhe(e,t){try{await e.cancel(t)}catch{}}function IHr(e){if(e instanceof Ehe||e instanceof aP)return!1;return e instanceof Error}function ghe(e,t){let r=t>1?` after ${t} attempts`:"";if(e instanceof aP)return`${e.message}${r}`;let i=fe(e,"Unknown network error");return`Failed to reach remote agent${r}: ${i}`}async function $H(e,t={},r={}){let i=t.fetch??globalThis.fetch,n=r.signal;n?.throwIfAborted();let o={requestTimeoutMs:t.requestTimeoutMs??vHr,streamIdleTimeoutMs:t.streamIdleTimeoutMs??AHr,maxNetworkAttempts:t.maxNetworkAttempts??wHr},s=BHr(e.agent),a=ai(r.userPermissionLevel);if(!s.ok){let p=t.entityService?await $Ze(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(),u=s.ok?await t.entityService.getEntity({entityType:"agent",id:c,visibilityScope:a}):null;if(n?.throwIfAborted(),!u&&!GZe(c)){let p=await $Ze(t.entityService,e.agent,a);if(n?.throwIfAborted(),typeof p==="string")return{success:!1,error:p};if(p)u=p,c=p.id}if(!u){if(r.requireSaved)return{success:!1,error:`Agent ${c} is not saved or approved.`,code:"agent_not_saved"};if(!GZe(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 Th(c,{fetch:i,timeoutMs:o.requestTimeoutMs,signal:n});if(!p.ok){if(HA(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 HZe(p.card.url,e.message,i,t.requestSigner,o,n);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(u.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 Th(c,{fetch:i,timeoutMs:o.requestTimeoutMs,signal:n});if(!d.ok){if(HA(d.reason))return{success:!1,error:d.error};return{success:!1,error:`Could not fetch Agent Card from https://${c}`}}return HZe(d.card.url,e.message,i,t.requestSigner,o,n)}function VZe(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:SHr,visibility:"trusted",sideEffects:"external",handler:async(t,r)=>{let i=kHr.safeParse(t);if(!i.success)return{success:!1,error:`Invalid input: ${i.error.message}`};return $H(i.data,e,{userPermissionLevel:r.userPermissionLevel,...r.signal?{signal:r.signal}:{}})}}}var THr=30000,_Hr=l.looseObject({result:l.looseObject({parts:l.array(l.looseObject({kind:l.string(),data:l.unknown()}))})});function i0(e,t){return{status:"refused",code:e,error:t}}async function JZe(e,t,r){let i=e.trim().toLowerCase(),n=await r.entityService?.getEntity({entityType:"agent",id:i,visibilityScope:ai("admin")});if(!n)return i0("agent_not_saved",`Agent ${i} is not saved.`);if(n.metadata.status==="archived")return i0("agent_archived",`Agent ${i} is archived.`);if(!await r.isContactApproved?.(i))return i0("agent_not_approved",`Agent ${i} is not approved yet. Approve it first.`);let{requestSigner:o}=r;if(!o)return i0("unsigned","This brain cannot sign A2A requests, and a peer shares only with callers it can verify.");let s=r.fetch??fetch,a=r.requestTimeoutMs??THr,c=await Th(i,{fetch:s,timeoutMs:a});if(!c.ok)return i0("agent_card_unavailable",c.error);if(!c.card.extensions.includes(X8))return i0("not_offered",`${i} does not offer shared entities.`);let u={"Content-Type":"application/json","X-A2A-Extensions":X8},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:u,body:d});let p;try{p=await s(c.card.url,{method:"POST",headers:u,body:d,signal:AbortSignal.timeout(a)})}catch(h){return i0("peer_failed",fe(h,`${i} did not answer`))}if(p.status===404)return{status:"not-found"};if(!p.ok)return i0("peer_failed",`${i} answered HTTP ${p.status}`);let m=_Hr.safeParse(await p.json().catch(()=>null));return{status:"answered",agentId:i,data:m.success?m.data.result.parts.filter((h)=>h.kind==="data").map((h)=>h.data):[],fetchFn:s,timeoutMs:a}}async function QZe(e,t){let r=await JZe(e.agent,{op:"list"},t);if(r.status!=="answered")return r;let i=r.data.map((n)=>KZe.safeParse(n)).find((n)=>n.success)?.data;return i?{status:"found",entities:i.entities}:i0("unreadable_answer",`${r.agentId} did not answer with a list.`)}async function XZe(e,t){let r=await JZe(e.agent,{op:"get",entityType:e.entityType,id:e.id},t);if(r.status!=="answered")return r;let{agentId:i,fetchFn:n,timeoutMs:o}=r,s=r.data.map((c)=>YZe.safeParse(c)).find((c)=>c.success)?.data;if(s?.entityType!==e.entityType||s.id!==e.id)return i0("unreadable_answer",`${i} did not answer with the entity asked for.`);let a=i0("unverified",`${i} did not sign what it served, so it was not taken.`);if(s.contentHash!==Ht(s.markdown))return a;try{if((await yZe(LH(s),s.attestation.signature,s.attestation.keyId,new nP({fetch:(u)=>n(u,{signal:AbortSignal.timeout(o)})}))).domain!==i)return a}catch{return a}return{status:"found",entity:s}}var PHr=new Set(["agent_not_saved","agent_not_approved","agent_archived"]);function tVe(e,t){let r="code"in e&&PHr.has(e.code??"")?"permission_denied":"handler_failed",i="error"in e?e.error:t;return new br(r,{publicMessage:j9(i)})}function RHr(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 eVe(e,t,r,i){let n=AbortSignal.timeout(i),o=(c)=>new br("deadline_exceeded",{publicMessage:`${t} did not answer within ${i} ms`,cause:c}),s;try{s=await $H({agent:t,message:r},{...e,maxNetworkAttempts:1},{requireSaved:!0,signal:n})}catch(c){if(n.aborted)throw o(c);throw new br("handler_failed",{message:fe(c,`${t} did not answer`),publicMessage:`${t} did not answer`,cause:c})}if(n.aborted)throw o();if(!("success"in s)||s.success!==!0)throw tVe(s,`${t} did not answer`);let a=vhe.safeParse(s.data);if(!a.success)throw new br("handler_failed",{publicMessage:`${t} gave no readable answer`});if(a.data.state!=="completed")throw new br("handler_failed",{publicMessage:j9(`${t} did not answer: ${a.data.response}`)});return a.data}var GH={everyProcess:!0};function rVe(e,t,r={networkAskTimeoutMs:30000,turnTimeoutMs:90000}){e.answer(HH,({request:{agent:i,question:n}})=>eVe(t,i,RHr(n),r.networkAskTimeoutMs),GH),e.answer(WH,({request:{agent:i,message:n}})=>eVe(t,i,n,r.turnTimeoutMs),GH),e.answer(KH,({request:i})=>XZe(i,t),GH),e.answer(YH,({request:i})=>QZe(i,t),GH),e.answer(ZH,async({request:{agent:i,instruction:n,selection:o,userPermissionLevel:s}})=>{let a=await $H({agent:i,message:["A Studio author is asking about selected markdown.",`Instruction: ${n}`,"","Selected markdown:",o].join(`
|
|
1038
|
-
`)},t,{requireSaved:!0,userPermissionLevel:s});if(!("success"in a)||a.success!==!0)throw tVe(a,"Agent call failed");let c=vhe.safeParse(a.data);if(!c.success)throw new br("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(VH,async({request:{userPermissionLevel:i}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:ai(i)}}})).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 iVe={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.822",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 JH(e,t){let r=new Headers(e.headers);for(let[i,n]of Object.entries(t))r.set(i,n);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}var MHr={"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"},nd=(e)=>JH(e,MHr);function OHr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(Ph(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();await fZe(i,n.privateJwk,n.keyId)}}function NHr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(Ph(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();return{keyId:n.keyId,signature:gZe(i,n.privateJwk)}}}function Ahe(e,t,r){let i=OHr(e);return{...i?{requestSigner:i}:{},...r.fetch?{fetch:r.fetch}:{},requestTimeoutMs:t.requestTimeoutMs,streamIdleTimeoutMs:t.streamIdleTimeoutMs,maxNetworkAttempts:t.maxNetworkAttempts,entityService:e.entityReads,isContactApproved:r.isContactApproved??((n)=>e.classRuntimeState.scoped({namespace:QH,schema:XH}).has(n.trim().toLowerCase()))}}async function LHr(e,t,r){if(!r.cardReady)return;return TZe({character:e.identity.get(),profile:e.identity.getProfile(),version:iVe.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 jHr(e,t,r,i){let n=new URL(r.url),o=new URL(`${n.pathname}${n.search}`,Yx(r)),s=await xZe({method:r.method,url:o.toString(),headers:r.headers,body:i},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 zHr(e,t,r){let i=new oVe,n=e.agent;return i.get("/.well-known/agent-card.json",async(o)=>{let s=await LHr(e,t,r);if(!s)return nd(o.json({error:"Agent Card not ready"},503));return nd(o.json(s))}),i.get("/.well-known/agent-directory.json",async(o)=>{let s=await _Ze(e.entityReads);return nd(o.json(s))}),i.get("/a2a",(o)=>nd(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),i.options("/a2a",()=>nd(new Response(null,{status:204}))),i.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return nd(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await jHr(e,r,o.req.raw,s)}catch{return nd(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return nd(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let u=FZe.safeParse(c);if(!u.success)return nd(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(oZe(o.req.raw.headers)){let p=u.data.method==="message/send"?sZe(u.data.params):void 0,m=p?.op==="list"?await lZe(e.entityReads,a.permissionLevel):await cZe(e.entityReads,a.permissionLevel,p,NHr(e));if(!m)return nd(o.json({error:"Not found"},404));return nd(o.json({jsonrpc:"2.0",id:u.data.id,result:{kind:"message",messageId:crypto.randomUUID(),role:"agent",parts:[{kind:"data",data:m}]}}))}if(u.data.method==="message/stream"){let p=zZe.safeParse(u.data.params??{});if(!p.success)return nd(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:u.data.id}));let m=UZe(u.data.id,p.data.message,{taskManager:r.taskManager,turnSupervisor:r.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:r.publicAsks});if("error"in m)return nd(o.json(m));return nd(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await NZe(u.data,{taskManager:r.taskManager,turnSupervisor:r.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:r.publicAsks});return nd(o.json(d))}),i}function whe(e={}){let t=_h({id:"a2a",config:DZe,setup:(o)=>{let{config:s}=o,a=Jo(o),{servesHttp:c}=a,u=Ahe(a,s,e),d={cardReady:!1,servesHttp:c,taskManager:new hhe,turnSupervisor:new fhe,jwksResolver:new nP(e.fetch?{fetch:e.fetch}:{}),clientDeps:u,publicAsks:new mhe(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}}),r=nVe(t,(o)=>{let s=Jo(o);rVe(s,Ahe(s,o.config,e),{networkAskTimeoutMs:o.config.networkAskTimeoutMs,turnTimeoutMs:o.config.turnTimeoutMs})}),i=ko(r,(o)=>{let{config:s,state:a}=o;if(!a.servesHttp)return[];let c=Jo(o),u=zHr(c,s,a),d=(m)=>Promise.resolve(u.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")]}),n=Kx(i,(o)=>{let{state:s}=o,{logger:a}=Jo(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 Fn(n,(o)=>{let{config:s}=o,a=Jo(o),c=()=>VZe(Ahe(a,s,e));return[{...c(),handler:(u,d)=>c().handler(u,d)}]})}var UHr=whe(),sVe=UHr;function Rh(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function YA(e,t){return{registration:e,actionIds:t.map((r)=>r.name)}}var qHr=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function Fh(e){return qHr.format(new Date(e))}function fm(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function Oc(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function rW(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function c5(e){if(!e)return"This brain";let t="did:web:";if(!e.startsWith(t))return e;let r=e.slice(t.length);if(r.length===0)return e;return r.split(":").map(decodeURIComponent).join("/")}var $Hr={"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 nfe(e){let t=$Hr[e];if(t)return t;let r=e.replaceAll(/[._-]+/g," ").trim();return r.length===0?e:po(r)}var ofe=l.strictObject({actorUserId:l.string().trim().min(1).max(120).optional(),action:l.string().trim().min(1).max(200).optional(),selected:l.string().trim().min(1).max(120).optional(),offset:l.preprocess(Rh,l.number().int().min(0).max(1e5)).default(0),limit:l.preprocess(Rh,l.number().int().min(1).max(100)).default(25)}),aVe=l.strictObject({id:l.string().min(1),actorUserId:l.string().min(1).optional(),action:l.string().min(1),targetType:l.string().min(1).optional(),targetId:l.string().min(1).optional(),targetUserId:l.string().min(1).optional(),createdAt:l.number().int().nonnegative()}),GHr=l.strictObject({userId:l.string().min(1),displayName:l.string().min(1)}),HHr=l.strictObject({query:ofe,events:l.array(aVe),selectedEvent:aVe.optional(),users:l.array(GHr),actions:l.array(l.strictObject({value:l.string().min(1),label:l.string().min(1),count:l.number().int().nonnegative()})),total:l.number().int().nonnegative()});function cVe(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 lVe(e,t){return e?t.get(e)??"Former Admin":"System"}function uVe(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 ife=Po({id:"audit",label:"Audit",priority:90,permission:"admin",query:ofe,data:HHr,actions:[],view:({data:e})=>{let t=new Map(e.users.map((o)=>[o.userId,o.displayName])),r=e.selectedEvent,n=[{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.",...r?{open:{forId:r.id,title:nfe(r.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:lVe(r.actorUserId,t)},{label:"Action",value:r.action},{label:"Target",value:uVe(r,t)},{label:"Occurred",value:Fh(r.createdAt)},{label:"Event ID",value:r.id},{label:"Action ID",value:r.action},...r.targetId?[{label:"Target ID",value:r.targetId}]:[],...r.actorUserId?[{label:"Actor ID",value:r.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:nfe(o.action),description:`${lVe(o.actorUserId,t)} \u2192 ${uVe(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:n}}});function dVe(e){let t=e.studio.source({definition:ife,bind:(r)=>ife.bind(r,{load:async({query:i})=>{let n=fm(e),o=i.get(ofe),[s,a]=await Promise.all([n.queryAuditEvents({...o.actorUserId?{actorUserId:o.actorUserId}:{},...o.action?{action:o.action}:{},...o.selected?{selectedId:o.selected}:{},offset:o.offset,limit:o.limit}),n.listUsers()]);return{query:o,events:s.events.map(cVe),...s.selectedEvent?{selectedEvent:cVe(s.selectedEvent)}:{},users:rW(a),actions:s.actions.map(({action:c,count:u})=>({value:c,label:nfe(c),count:u})).sort((c,u)=>c.label.localeCompare(u.label)),total:s.total}},actions:[]})});return YA(t,ife.actions)}var n0=l.strictObject({status:l.string()}),iW=l.strictObject({status:l.string(),setupUrl:l.url(),expiresAt:l.string()});function G9(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var nW=l.strictObject({type:l.string(),displayName:l.string(),subjectLabel:l.string(),deliveryModes:l.array(l.enum(["automatic","manual"]))});function oW(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function sW(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function aW(e,t){return{deliveryType:{label:"Delivery channel",control:"select",options:e.map((r)=>({value:r.type,label:r.displayName}))},deliverySubject:{label:"Delivery destination",labelBy:{field:"deliveryType",values:e.map((r)=>({value:r.type,label:r.subjectLabel}))},control:"text"},deliveryLabel:{label:"Delivery label (optional)",control:"text"},deliveryMode:{label:"Delivery mode",control:"select",options:t.map((r)=>({value:r,label:r==="automatic"?"Automatic":"Manual"}))}}}import{randomUUID as WHr}from"crypto";var pVe=new Set(["claimed","expired","cancelled"]),ZHr=new Set(["claimed","cancelled"]),ufe=l.strictObject({state:l.enum(["pending","history"]).optional().default("pending"),selected:l.string().trim().min(1).max(200).optional(),offset:l.preprocess(Rh,l.number().int().min(0)).optional().default(0),limit:l.preprocess(Rh,l.number().int().min(1).max(100)).optional().default(25)}),xVe=l.strictObject({status:l.string(),setupUrl:l.url().nullable(),expiresAt:l.string().nullable()}),VHr=l.strictObject({idempotencyKey:l.string().min(1),displayName:l.string().trim().min(1).max(200),role:l.enum(["admin","trusted"]),deliveryType:l.string().trim().min(1).max(100),deliverySubject:l.string().trim().min(1).max(500),deliveryLabel:l.string().trim().max(200).optional(),deliveryMode:l.enum(["automatic","manual"])}),gVe=l.strictObject({invitationId:l.string().min(1)}),KHr=l.strictObject({invitationId:l.string().min(1),deliveryAttemptId:l.string().min(1)}),yVe=l.strictObject({invitationId:l.string(),state:l.string()}),cfe=Vr({name:"create-invitation",label:"Add a person",permission:"admin",input:VHr,output:xVe}),dfe=Vr({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:gVe,output:xVe}),pfe=Vr({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:gVe,output:yVe}),mfe=Vr({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:KHr,output:yVe}),mVe=l.strictObject({id:l.string(),displayName:l.string(),role:l.string(),state:l.string(),destination:l.string(),updatedAt:l.number(),deliveryAttemptId:l.string().optional()}),YHr=l.strictObject({query:ufe,idempotencyKey:l.string(),channels:l.array(nW),invitations:l.array(mVe),selectedInvitation:mVe.optional(),selectedTotal:l.number().int().nonnegative(),pendingCount:l.number().int().nonnegative(),historyCount:l.number().int().nonnegative(),failureCount:l.number().int().nonnegative()});function lfe(e,t){let r=e.filter((i)=>i.id===t);if(r.length!==1||!r[0])throw Error(`Invitations tab composition requires block "${t}" exactly once`);return r[0]}function sfe(e,t){let r=lfe(e,t);switch(r.type){case"tabs":case"detail":case"columns":throw Error(`Invitations tab composition block "${t}" must be a region`);default:return r}}function bVe(e,t){let r=lfe(e,"invitation-totals");if(r.type!=="stats")throw Error('Invitations tab composition block "invitation-totals" must be stats');let i=e.some((a)=>a.id==="create-invitation-unavailable")?[sfe(e,"create-invitation-unavailable")]:[],n=lfe(e,"invitations");if(n.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=sfe(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:[...i,sfe(e,"invitation-filters"),n,{...o,presentation:"disclosure",blocks:[...o.blocks,r,...s]}]}}var EVe=G9("Invitation setup");function JHr(e){if(ZHr.has(e.state))return[];return[...e.deliveryAttemptId?[{action:mfe,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:dfe,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:EVe}]:[],...e.state!=="expired"?[{action:pfe,input:{invitationId:e.id}}]:[]]}function hVe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return po(e.state)}var afe=Po({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:ufe,data:YHr,actions:[cfe,dfe,pfe,mfe],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"}]}],r=oW(e.channels),i;if(e.channels.length>0&&r.length>0)i={action:cfe,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:sW("Role"),...aW(e.channels,r)}},result:EVe};else t.push({type:"notice",id:"create-invitation-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});let n=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:`${po(o.role)} \xB7 ${hVe(o)}`,metadata:[o.destination,`Updated ${new Date(o.updatedAt).toISOString()}`],links:[{label:"Review",target:{detail:{itemId:o.id}}}]}))},...n?{open:{forId:n.id,title:n.displayName,blocks:[{type:"key-values",id:"invitation-fields",items:[{label:"Role",value:po(n.role)},{label:"Delivery",value:hVe(n)},{label:"Destination",value:n.destination},{label:"Updated",value:Fh(n.updatedAt)}]},{type:"actions",id:"invitation-actions",items:JHr(n)}]}}: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(po).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"},...i?{primaryAction:i}:{},blocks:t}}});function fVe(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 vVe(e){let t=fm(e),r=new Map,i=e.studio.source({definition:afe,bind:(n)=>{let o=cfe.bind(n,async({input:u,caller:d})=>{let p=await t.createInvitation({idempotencyKey:u.idempotencyKey,displayName:u.displayName,role:u.role,delivery:{type:u.deliveryType,subject:u.deliverySubject,...u.deliveryLabel?{label:u.deliveryLabel}:{},mode:u.deliveryMode}},Oc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return fVe(p)}),s=dfe.bind(n,async({input:u,caller:d})=>{let p=await t.resendInvitation(u.invitationId,Oc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return fVe(p)}),a=pfe.bind(n,async({input:u,caller:d})=>{let p=await t.cancelInvitation(u.invitationId,Oc(d));return r.delete(u.invitationId),{invitationId:p.id,state:p.state}},({input:u})=>({summary:"Cancel this invitation and revoke its pending setup link?",revision:u.invitationId})),c=mfe.bind(n,async({input:u,caller:d})=>{let p=await t.confirmManualInvitationDelivery(u.invitationId,u.deliveryAttemptId,Oc(d));return r.delete(u.invitationId),{invitationId:p.id,state:p.state}});return afe.bind(n,{actions:[o,s,a,c],load:async({query:u})=>{let d=u.get(ufe),[p,m]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),h=m.filter((R)=>R.deliveryModes.length>0),f=p.filter((R)=>R.invitation!==void 0),g=f.filter((R)=>R.invitation&&!pVe.has(R.invitation.state)),y=f.filter((R)=>R.invitation&&pVe.has(R.invitation.state)),b=d.state==="pending"?g:y,A=f.flatMap((R)=>{let M=R.invitation;if(!M)return[];let k=R.identities.find((L)=>L.type!=="passkey")?.label??R.externalPeers[0]?.peerId??"Not recorded",N=r.get(M.id);return[{id:M.id,displayName:R.displayName,role:R.role,state:M.state,destination:k,updatedAt:M.claimedAt??M.cancelledAt??M.expiredAt??M.sentAt??M.updatedAt,...N?{deliveryAttemptId:N}:{}}]}),w=new Map(A.map((R)=>[R.id,R])),B=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:WHr(),channels:h.map((R)=>({type:R.type,displayName:R.displayName,subjectLabel:R.subjectLabel,deliveryModes:R.deliveryModes})),invitations:b.slice(d.offset,d.offset+d.limit).flatMap((R)=>{let M=R.invitation?w.get(R.invitation.id):void 0;return M?[M]:[]}),...B?{selectedInvitation:B}:{},selectedTotal:b.length,pendingCount:g.length,historyCount:y.length,failureCount:g.filter((R)=>R.invitation?.state==="failed").length}}})}});return YA(i,afe.actions)}var gfe=l.strictObject({peerId:l.string().trim().max(2000).optional(),displayName:l.string().trim().max(200).optional()}),QHr=l.strictObject({peerId:l.string().trim().min(1).max(2000),displayName:l.string().trim().min(1).max(200),role:l.enum(["admin","trusted"]),deliveryType:l.string().trim().min(1).max(64),deliverySubject:l.string().trim().min(1).max(1000),deliveryLabel:l.string().trim().min(1).max(200).optional(),deliveryMode:l.enum(["automatic","manual"])}),XHr=l.strictObject({peerId:l.string().trim().min(1).max(2000),userId:l.string().min(1)}),ffe=Vr({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:QHr,output:iW}),xfe=Vr({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:XHr,output:n0}),eWr=l.strictObject({query:gfe,peers:l.array(l.strictObject({peerId:l.string(),displayName:l.string(),role:l.enum(["admin","trusted","public"]),verificationStatus:l.enum(["unverified","verified"]),createdAt:l.number()})),people:l.array(l.strictObject({userId:l.string(),displayName:l.string()})),channels:l.array(nW)});function cW(e,t){let r=e.filter((n)=>n.id===t);if(r.length!==1)throw Error(`Peer tab composition requires block "${t}" exactly once`);let i=r[0];if(!i)throw Error(`Peer tab composition requires block "${t}" exactly once`);switch(i.type){case"tabs":case"detail":case"columns":throw Error(`Peer tab composition block "${t}" must be a region`);default:return i}}function yfe(e){let t=e.some((r)=>r.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[cW(e,"peers"),cW(e,"link-peer"),cW(e,t)],invitations:[cW(e,t)]}}var tWr=G9("Peer invitation setup"),hfe=Po({id:"peers",label:"Peers",priority:12,permission:"admin",query:gfe,data:eWr,actions:[ffe,xfe],view:({data:e})=>{let t=oW(e.channels),r=[{type:"stats",id:"peer-summary",items:[{label:"Linked peers",value:e.peers.length},{label:"Verified",value:e.peers.filter((i)=>i.verificationStatus==="verified").length},{label:"Available people",value:e.people.length}]}];if(e.channels.length>0&&t.length>0)r.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:ffe,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:sW("Local role"),...aW(e.channels,t)}},result:tWr}]});else r.push({type:"notice",id:"invite-peer-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});return r.push({type:"card",id:"link-peer",label:"Link an existing person",blocks:[{type:"action",action:xfe,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((i)=>({value:i.userId,label:i.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((i)=>({id:`${i.peerId}:${i.displayName}`,cells:{peer:c5(i.peerId),person:i.displayName,role:i.role,verification:i.verificationStatus,linked:Fh(i.createdAt)},compact:{title:c5(i.peerId),metadata:[i.displayName,po(i.role),Fh(i.createdAt)],badges:[{label:po(i.verificationStatus),tone:i.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:r}}});function AVe(e){let t=fm(e),r=e.studio.source({definition:hfe,bind:(i)=>{let n=ffe.bind(i,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}},Oc(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=xfe.bind(i,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},Oc(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((u)=>u.userId===s.userId)?.displayName??"person";return{summary:`Link ${s.peerId} to ${c}? Local access does not change.`,revision:`${s.peerId}:${s.userId}`}});return hfe.bind(i,{actions:[n,o],load:async({query:s})=>{let a=s.get(gfe),[c,u]=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:rW(d),channels:u.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return YA(r,hfe.actions)}function bfe(e,t){let r=e.filter((i)=>i.id===t);if(r.length!==1||!r[0])throw Error(`People tab composition requires block "${t}" exactly once`);return r[0]}function wVe(e,t,r){let i=bfe(e,"people-summary");if(i.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let n=bfe(e,"people");if(n.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=bfe(e,"brain-anchor");if(o.type!=="card")throw Error('People tab composition block "brain-anchor" must be a card');let s=[t,...r].flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[n,{type:"card",id:"people-peers",label:"External brains",presentation:"disclosure",blocks:s},{...o,label:"Access reference",presentation:"disclosure",blocks:[i,...o.blocks]}]}}var Ife=l.strictObject({selected:l.string().trim().min(1).max(200).optional()}),Tfe=l.strictObject({userId:l.string().min(1)}),rWr=l.strictObject({userId:l.string().min(1),role:l.enum(["admin","trusted","public"])}),iWr=l.strictObject({userId:l.string().min(1),status:l.enum(["active","suspended"])});function nWr(e){return e.revokedAt===void 0&&e.type!=="passkey"}function oWr(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var sWr=l.strictObject({userId:l.string().min(1),credentialId:l.string().min(1)}),aWr=l.strictObject({userId:l.string().min(1),type:l.string().trim().min(1).max(64),subject:l.string().trim().min(1).max(2000),issuer:l.string().trim().min(1).max(2000).optional(),label:l.string().trim().min(1).max(200).optional()}),cWr=l.strictObject({userId:l.string().min(1),identityId:l.string().min(1)}),lWr=l.strictObject({userId:l.string().min(1),peerId:l.string().trim().min(1).max(2000)}),Afe=Vr({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:rWr,output:n0}),wfe=Vr({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:iWr,output:n0}),Sfe=Vr({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:Tfe,output:n0}),kfe=Vr({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:sWr,output:n0}),_fe=Vr({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:Tfe,output:iW}),Bfe=Vr({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:Tfe,output:n0}),Pfe=Vr({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:aWr,output:n0}),Cfe=Vr({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:cWr,output:n0}),Dfe=Vr({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:lWr,output:n0}),uWr=l.strictObject({userId:l.string(),displayName:l.string(),role:l.enum(["admin","trusted","public"]),status:l.enum(["active","suspended"]),isAnchor:l.boolean(),isSelf:l.boolean(),profileEntityId:l.string().optional(),passkeys:l.array(l.strictObject({id:l.string(),kind:l.string(),createdAt:l.number()})),identities:l.array(l.strictObject({id:l.string(),type:l.string(),displayName:l.string(),label:l.string(),verified:l.boolean()})),peers:l.array(l.strictObject({peerId:l.string(),verificationStatus:l.enum(["unverified","verified"])}))}),dWr=l.strictObject({query:Ife,anchor:l.strictObject({kind:l.enum(["person","collective"]),configuredKind:l.enum(["person","team","organization"]),displayName:l.string(),administeredBy:l.number().int().nonnegative()}),people:l.array(uWr),activeCount:l.number().int().nonnegative(),activeAdminCount:l.number().int().nonnegative(),suspendedCount:l.number().int().nonnegative(),channelTypes:l.array(l.strictObject({type:l.string(),displayName:l.string()}))}),pWr=G9("Passkey setup");function mWr(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function Efe(e){return{type:"notice",tone:"warn",text:e}}function hWr(e){return{type:"action",action:_fe,input:{userId:e},result:pWr}}function fWr(e,t){return{type:"action",action:Pfe,input:{userId:e},form:{submitLabel:"Attach channel",fields:{type:{label:"Channel type",control:"select",options:t.map((r)=>({value:r.type,label:r.displayName}))},subject:{label:"Channel subject",control:"text"},issuer:{label:"Issuer (optional)",control:"url"},label:{label:"Display label (optional)",control:"text"}}}}}function xWr(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var vfe=Po({id:"people",label:"People",priority:10,permission:"admin",query:Ife,data:dWr,actions:[Afe,wfe,Sfe,kfe,_fe,Bfe,Pfe,Cfe,Dfe],badge:({data:e})=>e.suspendedCount,view:({data:e})=>{let t=e.people.find((n)=>n.userId===e.query.selected),r=[];if(t){let n=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.":n?"Add another active Admin before changing this role.":void 0,s=t.isAnchor?"The protected brain identity cannot be suspended.":n?"Add another active Admin before suspending this person.":void 0;if(r.push({type:"key-values",id:"person-summary",items:[{label:"Role",value:po(t.role)},{label:"Status",value:po(t.status)},{label:"Protected brain identity",value:t.isAnchor},{label:"Brain relationship",value:t.peers.length>0?"External peer + local member":"Hosted member"}]}),o)r.push({type:"notice",tone:"warn",text:o});else r.push({type:"card",id:"person-role",label:"Permission role",blocks:[{type:"action",action:Afe,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"}]}}}}]});r.push({type:"card",id:"person-access",label:"Access",blocks:[{type:"actions",items:[{action:wfe,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:Bfe,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:Sfe,input:{userId:t.userId}}]:[]]},...t.isSelf?[mWr()]:[],...s&&t.status==="active"?[Efe(s)]:[]]}),r.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:Fh(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${Fh(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:kfe,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[hWr(t.userId)]:[Efe("A verified channel is required for setup delivery.")]:[]]}),r.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:Cfe,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[fWr(t.userId,e.channelTypes)]:[Efe("No attachable channel type is configured.")]]}),r.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."}),r.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:c5(a.peerId),description:`Vouched in by ${c5(a.peerId)} \xB7 ${a.peerId}`,metadata:[po(a.verificationStatus)],actions:[{action:Dfe,input:{userId:t.userId,peerId:a.peerId}}]}))})}let i=[{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((n,o)=>Number(o.isSelf)-Number(n.isSelf)||Number(n.isAnchor)-Number(o.isAnchor)||n.displayName.localeCompare(o.displayName)).map((n)=>({id:n.userId,title:n.displayName,description:[po(n.role),po(n.status),...n.isSelf?["You"]:[],...n.isAnchor?["Protected brain identity"]:[]].join(" \xB7 "),metadata:[n.identities.length===0?"No linked identities":n.identities.length===1?"One linked identity":`${n.identities.length} linked identities`,...n.peers.length>0?[`Arrived via ${c5(n.peers[0]?.peerId)}`]:[]],...n.isSelf?{link:{detail:{itemId:n.userId}}}:{},links:[{label:n.isSelf?"Account \u2192":n.isAnchor?"View protection":"Manage person",target:n.isSelf?{launch:{target:"account-settings"}}:{detail:{itemId:n.userId}}}]}))},...t?{open:{forId:t.userId,title:t.displayName,blocks:r}}:{}}];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:i}}});function lW(e,t){return e.find((r)=>r.userId===t)?.displayName??"person"}async function gWr(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function SVe(e){let t=fm(e),r=e.studio.source({definition:vfe,bind:(i)=>{let n=Afe.bind(i,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,Oc(f)),{status:`Role changed to ${po(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${lW(f,h.userId)}\u2019s role to ${po(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=wfe.bind(i,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,Oc(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${lW(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=Sfe.bind(i,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,Oc(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${lW(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=kfe.bind(i,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,Oc(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=_fe.bind(i,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,Oc(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()}}),u=Bfe.bind(i,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,Oc(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${lW(f,h.userId)} out everywhere?`,revision:h.userId}}),d=Pfe.bind(i,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"}},Oc(f)),{status:"Verified channel attached."})),p=Cfe.bind(i,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,Oc(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=Dfe.bind(i,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,Oc(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 vfe.bind(i,{actions:[n,o,s,a,c,u,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(Ife),[y,b,A]=await Promise.all([gWr(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"),R=y??xWr(B?.displayName??"Brain owner",w.filter((N)=>N.role==="admin"&&N.status==="active").length),M=w.filter((N)=>N.status==="active"),k=new Map(A.map((N)=>[N.type,N.displayName]));return{query:g,anchor:{kind:R.kind,configuredKind:R.configuredKind,displayName:R.displayName,administeredBy:R.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:oWr(L),createdAt:L.createdAt})),identities:N.identities.filter(nWr).map((L)=>({id:L.id,type:L.type,displayName:k.get(L.type)??po(L.type),label:L.label??"Connected identity",verified:L.verifiedAt!==void 0})),peers:N.externalPeers.map((L)=>({peerId:L.peerId,verificationStatus:L.verificationStatus}))}]}),activeCount:M.length,activeAdminCount:M.filter((N)=>N.role==="admin").length,suspendedCount:w.length-M.length,channelTypes:A.map((N)=>({type:N.type,displayName:N.displayName}))}}})}});return YA(r,vfe.actions)}var yWr=l.strictObject({tab:l.enum(["people","invitations","audit"]).default("people"),selected:l.string().trim().min(1).max(200).optional(),state:l.enum(["pending","history"]).optional(),offset:l.preprocess(Rh,l.number().int().min(0).max(1e5)).optional(),limit:l.preprocess(Rh,l.number().int().min(1).max(100)).optional(),peerId:l.string().trim().max(2000).optional(),displayName:l.string().trim().max(200).optional(),actorUserId:l.string().trim().min(1).max(120).optional(),action:l.string().trim().min(1).max(200).optional()});function bWr(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function EWr(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 vWr(e,t){if(!EWr(e))throw Error(`${t} tab returned invalid workspace data`);return e}function kVe(e,t){let r=[];for(let i of e){if(i.type==="tabs")throw Error(`${t} tab cannot contribute nested tabs`);r.push(i)}return r}function Rfe(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function yP(e,t,r,i){return vWr(await e.dataProvider(t,r,i),e.label)}async function AWr(e,t,r,i){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,r,i)}function wWr(e){let t=new Map;for(let r of e)for(let i of r.actionIds){if(t.has(i))throw Error(`Administration action "${i}" is declared by more than one source`);if(!r.registration.actionHandler)throw Error(`Administration source "${r.registration.label}" declares actions without a handler`);t.set(i,r.registration)}return t}function BVe(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 SWr(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 CVe(e){if(!e.studio.isAvailable())return;let t=SVe(e),r=vVe(e),i=AVe(e),n=dVe(e),o=wWr([t,r,i,n]),s=t.registration,a=r.registration,c=i.registration,u=n.registration;return e.studio.register({id:"admin:administration",label:"Administration",rendererName:q9,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=yWr.parse(p??{}),f,g=Rfe("People"),y=Rfe("Invitations"),b=Rfe("Audit");if(h.tab==="people"){let[A,w]=await Promise.all([yP(s,d,{...h.selected?{selected:h.selected}:{}},m),yP(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),B=yfe(w.view.blocks);g=[...wVe(kVe(A.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[A,w]=await Promise.all([yP(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...Hn({offset:h.offset,limit:h.limit})},m),yP(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),B=yfe(w.view.blocks),R=bVe(A.view.blocks,B.invitations);f=A.view.primaryAction,y=[...R.blocks]}else{let A=await yP(u,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...Hn({offset:h.offset,limit:h.limit})},m);b=kVe(A.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=bWr(d);if(!h)throw new br("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new br("not_found",{publicMessage:`Unknown Administration action: ${h}`});return AWr(f,d,p,m)},badgeProvider:async()=>{let d=BVe(await fm(e).listAdminUsers());return d.suspended+d.pendingInvitations},attentionProvider:async()=>SWr(BVe(await fm(e).listAdminUsers()))})}var kWr=259200000,BWr=l.strictObject({id:l.string(),displayName:l.string(),state:l.string(),reason:l.enum(["expiring","delivery-failed"]),expiresAt:l.number().optional()}),CWr=l.strictObject({invitations:l.array(BWr),expiringCount:l.number().int().nonnegative(),failureCount:l.number().int().nonnegative()}),DVe=ro({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:CWr,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 ${Fh(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function DWr(e,t){let r=e.flatMap((i)=>{let n=i.invitation;if(!n)return[];if(n.state==="failed")return[{id:n.id,displayName:i.displayName,state:n.state,reason:"delivery-failed",...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{}}];if(!["pending","sending","sent"].includes(n.state)||n.expiresAt===void 0||n.expiresAt<=t||n.expiresAt>t+kWr)return[];return[{id:n.id,displayName:i.displayName,state:n.state,reason:"expiring",expiresAt:n.expiresAt}]});return r.sort((i,n)=>(i.expiresAt??Number.MAX_SAFE_INTEGER)-(n.expiresAt??Number.MAX_SAFE_INTEGER)||i.displayName.localeCompare(n.displayName)),{invitations:r,expiringCount:r.filter((i)=>i.reason==="expiring").length,failureCount:r.filter((i)=>i.reason==="delivery-failed").length}}async function IVe(e,t){t.throwIfAborted();let r=await fm(e).listAdminUsers();return t.throwIfAborted(),DWr(r,Date.now())}var IWr=l.strictObject({}),TWr=zt({id:"admin",config:IWr},{subscriptions:(e)=>{let t=bt(e);return t.registered(async()=>{await CVe(t)}),[]},dashboardWidgets:(e)=>{let t=bt(e);return[DVe.bind(e,({signal:r})=>IVe(t,r))]}}),Ffe=TWr;var Ki="agent",TVe="agent-network",_Ve="agent-proximity",Qfe="agent-discovery:entities",PVe="agent-discovery:proximity-map",Xfe="proximity-map",e0e="agent-list",t0e="agent-detail",Nc="skill",RVe=30,FVe=120;var dW="skill-derivation",MVe="skill-derivation",r0e="skill:skill-derivation",OVe="skills";var _Wr=l.string().trim().min(1).max(FVe),i0e=l.array(_Wr).max(RVe),QA=l.object({name:l.string(),description:l.string(),tags:i0e,examples:l.array(l.string())}),CP=QA,XA=o0.extend({entityType:l.literal(Nc),metadata:CP});var pW=l.object({name:l.string(),description:l.string(),tags:i0e}),Mb=l.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),PWr=s5,s0=l.object({name:l.string(),kind:PWr,organization:l.string().optional(),brainName:l.string().describe("Name of the brain instance"),shownAs:l.string().min(1).optional().describe("The name this brain shows the agent under, in place of its own name"),url:l.string().url().describe("Brain endpoint URL"),repoDid:l.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:l.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:l.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:l.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:l.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:l.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:l.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:l.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:Mb,discoveredAt:l.string().datetime().meta({description:"When this agent was first discovered",studioWidget:"provenance"}),introducedBy:l.array(l.string()).optional().meta({description:"Agent ids of the peers whose directories reported this agent",studioWidget:"provenance"}),hops:l.number().int().min(2).optional().meta({description:"Discovery order: 2 = sighted through a first-order peer",studioWidget:"provenance"})}),DP=l.object({name:l.string(),shownAs:l.string().min(1).optional(),url:l.string().url(),status:Mb,discoveredAt:l.string().datetime().optional(),slug:l.string(),repoDid:l.string().optional(),brainDid:l.string().optional(),cardUri:l.string().optional(),cardCid:l.string().optional(),cardLastError:l.string().optional(),cardFailureCount:l.number().int().nonnegative().optional(),cardUnavailableAt:l.string().datetime().optional(),cardStaleAfter:l.string().datetime().optional()}),On=o0.extend({entityType:l.literal(Ki),metadata:DP}),RWr=jr.extend({entityType:l.literal(Ki),metadata:DP}),IP=RWr.extend({frontmatter:s0,about:l.string(),skills:l.array(pW),notes:l.string()}),FWr=IP.extend({url:l.string().optional(),typeLabel:l.string().optional()}),MWr=IP.extend({url:l.string(),typeLabel:l.string()});var OWr=l.record(l.string(),l.unknown());function NWr(e){try{return Mn(e,OWr).content}catch{return e}}function n0e(e){return{name:e.name,...e.shownAs&&{shownAs:e.shownAs},url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:W9(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 NVe(e){return Ws(Ki,e,s0)}function TP(e){return{content:e,metadata:n0e(NVe(e))}}function Z9(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:Mb.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},r=tfe({about:e.about,skills:e.skills,notes:e.notes});return dn(r,t)}function bm(e,t={}){return Z9({...e.frontmatter,...e.body,...t})}function _P(e){return gP(NWr(e))}function Zs(e){return{frontmatter:NVe(e.content),body:_P(e.content)}}function o0e(e){return dn("",e)}function jWr(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function LVe(e,t,r={}){let i=r.minCount??1,n=r.topN??12,o=new Map,s=(a)=>{for(let c of mc(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=_P(a.content);s(c.skills.flatMap((u)=>u.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=i).sort(jWr).slice(0,n)}function jVe(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:r})=>`- ${t} (${r})`)].join(`
|
|
1038
|
+
`)},t,{requireSaved:!0,userPermissionLevel:s});if(!("success"in a)||a.success!==!0)throw tVe(a,"Agent call failed");let c=vhe.safeParse(a.data);if(!c.success)throw new br("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(VH,async({request:{userPermissionLevel:i}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:ai(i)}}})).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 iVe={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.823",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 JH(e,t){let r=new Headers(e.headers);for(let[i,n]of Object.entries(t))r.set(i,n);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}var MHr={"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"},nd=(e)=>JH(e,MHr);function OHr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(Ph(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();await fZe(i,n.privateJwk,n.keyId)}}function NHr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(Ph(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();return{keyId:n.keyId,signature:gZe(i,n.privateJwk)}}}function Ahe(e,t,r){let i=OHr(e);return{...i?{requestSigner:i}:{},...r.fetch?{fetch:r.fetch}:{},requestTimeoutMs:t.requestTimeoutMs,streamIdleTimeoutMs:t.streamIdleTimeoutMs,maxNetworkAttempts:t.maxNetworkAttempts,entityService:e.entityReads,isContactApproved:r.isContactApproved??((n)=>e.classRuntimeState.scoped({namespace:QH,schema:XH}).has(n.trim().toLowerCase()))}}async function LHr(e,t,r){if(!r.cardReady)return;return TZe({character:e.identity.get(),profile:e.identity.getProfile(),version:iVe.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 jHr(e,t,r,i){let n=new URL(r.url),o=new URL(`${n.pathname}${n.search}`,Yx(r)),s=await xZe({method:r.method,url:o.toString(),headers:r.headers,body:i},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 zHr(e,t,r){let i=new oVe,n=e.agent;return i.get("/.well-known/agent-card.json",async(o)=>{let s=await LHr(e,t,r);if(!s)return nd(o.json({error:"Agent Card not ready"},503));return nd(o.json(s))}),i.get("/.well-known/agent-directory.json",async(o)=>{let s=await _Ze(e.entityReads);return nd(o.json(s))}),i.get("/a2a",(o)=>nd(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),i.options("/a2a",()=>nd(new Response(null,{status:204}))),i.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return nd(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await jHr(e,r,o.req.raw,s)}catch{return nd(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return nd(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let u=FZe.safeParse(c);if(!u.success)return nd(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(oZe(o.req.raw.headers)){let p=u.data.method==="message/send"?sZe(u.data.params):void 0,m=p?.op==="list"?await lZe(e.entityReads,a.permissionLevel):await cZe(e.entityReads,a.permissionLevel,p,NHr(e));if(!m)return nd(o.json({error:"Not found"},404));return nd(o.json({jsonrpc:"2.0",id:u.data.id,result:{kind:"message",messageId:crypto.randomUUID(),role:"agent",parts:[{kind:"data",data:m}]}}))}if(u.data.method==="message/stream"){let p=zZe.safeParse(u.data.params??{});if(!p.success)return nd(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:u.data.id}));let m=UZe(u.data.id,p.data.message,{taskManager:r.taskManager,turnSupervisor:r.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:r.publicAsks});if("error"in m)return nd(o.json(m));return nd(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await NZe(u.data,{taskManager:r.taskManager,turnSupervisor:r.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:r.publicAsks});return nd(o.json(d))}),i}function whe(e={}){let t=_h({id:"a2a",config:DZe,setup:(o)=>{let{config:s}=o,a=Jo(o),{servesHttp:c}=a,u=Ahe(a,s,e),d={cardReady:!1,servesHttp:c,taskManager:new hhe,turnSupervisor:new fhe,jwksResolver:new nP(e.fetch?{fetch:e.fetch}:{}),clientDeps:u,publicAsks:new mhe(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}}),r=nVe(t,(o)=>{let s=Jo(o);rVe(s,Ahe(s,o.config,e),{networkAskTimeoutMs:o.config.networkAskTimeoutMs,turnTimeoutMs:o.config.turnTimeoutMs})}),i=ko(r,(o)=>{let{config:s,state:a}=o;if(!a.servesHttp)return[];let c=Jo(o),u=zHr(c,s,a),d=(m)=>Promise.resolve(u.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")]}),n=Kx(i,(o)=>{let{state:s}=o,{logger:a}=Jo(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 Fn(n,(o)=>{let{config:s}=o,a=Jo(o),c=()=>VZe(Ahe(a,s,e));return[{...c(),handler:(u,d)=>c().handler(u,d)}]})}var UHr=whe(),sVe=UHr;function Rh(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function YA(e,t){return{registration:e,actionIds:t.map((r)=>r.name)}}var qHr=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function Fh(e){return qHr.format(new Date(e))}function fm(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function Oc(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function rW(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function c5(e){if(!e)return"This brain";let t="did:web:";if(!e.startsWith(t))return e;let r=e.slice(t.length);if(r.length===0)return e;return r.split(":").map(decodeURIComponent).join("/")}var $Hr={"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 nfe(e){let t=$Hr[e];if(t)return t;let r=e.replaceAll(/[._-]+/g," ").trim();return r.length===0?e:po(r)}var ofe=l.strictObject({actorUserId:l.string().trim().min(1).max(120).optional(),action:l.string().trim().min(1).max(200).optional(),selected:l.string().trim().min(1).max(120).optional(),offset:l.preprocess(Rh,l.number().int().min(0).max(1e5)).default(0),limit:l.preprocess(Rh,l.number().int().min(1).max(100)).default(25)}),aVe=l.strictObject({id:l.string().min(1),actorUserId:l.string().min(1).optional(),action:l.string().min(1),targetType:l.string().min(1).optional(),targetId:l.string().min(1).optional(),targetUserId:l.string().min(1).optional(),createdAt:l.number().int().nonnegative()}),GHr=l.strictObject({userId:l.string().min(1),displayName:l.string().min(1)}),HHr=l.strictObject({query:ofe,events:l.array(aVe),selectedEvent:aVe.optional(),users:l.array(GHr),actions:l.array(l.strictObject({value:l.string().min(1),label:l.string().min(1),count:l.number().int().nonnegative()})),total:l.number().int().nonnegative()});function cVe(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 lVe(e,t){return e?t.get(e)??"Former Admin":"System"}function uVe(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 ife=Po({id:"audit",label:"Audit",priority:90,permission:"admin",query:ofe,data:HHr,actions:[],view:({data:e})=>{let t=new Map(e.users.map((o)=>[o.userId,o.displayName])),r=e.selectedEvent,n=[{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.",...r?{open:{forId:r.id,title:nfe(r.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:lVe(r.actorUserId,t)},{label:"Action",value:r.action},{label:"Target",value:uVe(r,t)},{label:"Occurred",value:Fh(r.createdAt)},{label:"Event ID",value:r.id},{label:"Action ID",value:r.action},...r.targetId?[{label:"Target ID",value:r.targetId}]:[],...r.actorUserId?[{label:"Actor ID",value:r.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:nfe(o.action),description:`${lVe(o.actorUserId,t)} \u2192 ${uVe(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:n}}});function dVe(e){let t=e.studio.source({definition:ife,bind:(r)=>ife.bind(r,{load:async({query:i})=>{let n=fm(e),o=i.get(ofe),[s,a]=await Promise.all([n.queryAuditEvents({...o.actorUserId?{actorUserId:o.actorUserId}:{},...o.action?{action:o.action}:{},...o.selected?{selectedId:o.selected}:{},offset:o.offset,limit:o.limit}),n.listUsers()]);return{query:o,events:s.events.map(cVe),...s.selectedEvent?{selectedEvent:cVe(s.selectedEvent)}:{},users:rW(a),actions:s.actions.map(({action:c,count:u})=>({value:c,label:nfe(c),count:u})).sort((c,u)=>c.label.localeCompare(u.label)),total:s.total}},actions:[]})});return YA(t,ife.actions)}var n0=l.strictObject({status:l.string()}),iW=l.strictObject({status:l.string(),setupUrl:l.url(),expiresAt:l.string()});function G9(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var nW=l.strictObject({type:l.string(),displayName:l.string(),subjectLabel:l.string(),deliveryModes:l.array(l.enum(["automatic","manual"]))});function oW(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function sW(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function aW(e,t){return{deliveryType:{label:"Delivery channel",control:"select",options:e.map((r)=>({value:r.type,label:r.displayName}))},deliverySubject:{label:"Delivery destination",labelBy:{field:"deliveryType",values:e.map((r)=>({value:r.type,label:r.subjectLabel}))},control:"text"},deliveryLabel:{label:"Delivery label (optional)",control:"text"},deliveryMode:{label:"Delivery mode",control:"select",options:t.map((r)=>({value:r,label:r==="automatic"?"Automatic":"Manual"}))}}}import{randomUUID as WHr}from"crypto";var pVe=new Set(["claimed","expired","cancelled"]),ZHr=new Set(["claimed","cancelled"]),ufe=l.strictObject({state:l.enum(["pending","history"]).optional().default("pending"),selected:l.string().trim().min(1).max(200).optional(),offset:l.preprocess(Rh,l.number().int().min(0)).optional().default(0),limit:l.preprocess(Rh,l.number().int().min(1).max(100)).optional().default(25)}),xVe=l.strictObject({status:l.string(),setupUrl:l.url().nullable(),expiresAt:l.string().nullable()}),VHr=l.strictObject({idempotencyKey:l.string().min(1),displayName:l.string().trim().min(1).max(200),role:l.enum(["admin","trusted"]),deliveryType:l.string().trim().min(1).max(100),deliverySubject:l.string().trim().min(1).max(500),deliveryLabel:l.string().trim().max(200).optional(),deliveryMode:l.enum(["automatic","manual"])}),gVe=l.strictObject({invitationId:l.string().min(1)}),KHr=l.strictObject({invitationId:l.string().min(1),deliveryAttemptId:l.string().min(1)}),yVe=l.strictObject({invitationId:l.string(),state:l.string()}),cfe=Vr({name:"create-invitation",label:"Add a person",permission:"admin",input:VHr,output:xVe}),dfe=Vr({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:gVe,output:xVe}),pfe=Vr({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:gVe,output:yVe}),mfe=Vr({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:KHr,output:yVe}),mVe=l.strictObject({id:l.string(),displayName:l.string(),role:l.string(),state:l.string(),destination:l.string(),updatedAt:l.number(),deliveryAttemptId:l.string().optional()}),YHr=l.strictObject({query:ufe,idempotencyKey:l.string(),channels:l.array(nW),invitations:l.array(mVe),selectedInvitation:mVe.optional(),selectedTotal:l.number().int().nonnegative(),pendingCount:l.number().int().nonnegative(),historyCount:l.number().int().nonnegative(),failureCount:l.number().int().nonnegative()});function lfe(e,t){let r=e.filter((i)=>i.id===t);if(r.length!==1||!r[0])throw Error(`Invitations tab composition requires block "${t}" exactly once`);return r[0]}function sfe(e,t){let r=lfe(e,t);switch(r.type){case"tabs":case"detail":case"columns":throw Error(`Invitations tab composition block "${t}" must be a region`);default:return r}}function bVe(e,t){let r=lfe(e,"invitation-totals");if(r.type!=="stats")throw Error('Invitations tab composition block "invitation-totals" must be stats');let i=e.some((a)=>a.id==="create-invitation-unavailable")?[sfe(e,"create-invitation-unavailable")]:[],n=lfe(e,"invitations");if(n.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=sfe(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:[...i,sfe(e,"invitation-filters"),n,{...o,presentation:"disclosure",blocks:[...o.blocks,r,...s]}]}}var EVe=G9("Invitation setup");function JHr(e){if(ZHr.has(e.state))return[];return[...e.deliveryAttemptId?[{action:mfe,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:dfe,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:EVe}]:[],...e.state!=="expired"?[{action:pfe,input:{invitationId:e.id}}]:[]]}function hVe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return po(e.state)}var afe=Po({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:ufe,data:YHr,actions:[cfe,dfe,pfe,mfe],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"}]}],r=oW(e.channels),i;if(e.channels.length>0&&r.length>0)i={action:cfe,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:sW("Role"),...aW(e.channels,r)}},result:EVe};else t.push({type:"notice",id:"create-invitation-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});let n=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:`${po(o.role)} \xB7 ${hVe(o)}`,metadata:[o.destination,`Updated ${new Date(o.updatedAt).toISOString()}`],links:[{label:"Review",target:{detail:{itemId:o.id}}}]}))},...n?{open:{forId:n.id,title:n.displayName,blocks:[{type:"key-values",id:"invitation-fields",items:[{label:"Role",value:po(n.role)},{label:"Delivery",value:hVe(n)},{label:"Destination",value:n.destination},{label:"Updated",value:Fh(n.updatedAt)}]},{type:"actions",id:"invitation-actions",items:JHr(n)}]}}: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(po).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"},...i?{primaryAction:i}:{},blocks:t}}});function fVe(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 vVe(e){let t=fm(e),r=new Map,i=e.studio.source({definition:afe,bind:(n)=>{let o=cfe.bind(n,async({input:u,caller:d})=>{let p=await t.createInvitation({idempotencyKey:u.idempotencyKey,displayName:u.displayName,role:u.role,delivery:{type:u.deliveryType,subject:u.deliverySubject,...u.deliveryLabel?{label:u.deliveryLabel}:{},mode:u.deliveryMode}},Oc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return fVe(p)}),s=dfe.bind(n,async({input:u,caller:d})=>{let p=await t.resendInvitation(u.invitationId,Oc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return fVe(p)}),a=pfe.bind(n,async({input:u,caller:d})=>{let p=await t.cancelInvitation(u.invitationId,Oc(d));return r.delete(u.invitationId),{invitationId:p.id,state:p.state}},({input:u})=>({summary:"Cancel this invitation and revoke its pending setup link?",revision:u.invitationId})),c=mfe.bind(n,async({input:u,caller:d})=>{let p=await t.confirmManualInvitationDelivery(u.invitationId,u.deliveryAttemptId,Oc(d));return r.delete(u.invitationId),{invitationId:p.id,state:p.state}});return afe.bind(n,{actions:[o,s,a,c],load:async({query:u})=>{let d=u.get(ufe),[p,m]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),h=m.filter((R)=>R.deliveryModes.length>0),f=p.filter((R)=>R.invitation!==void 0),g=f.filter((R)=>R.invitation&&!pVe.has(R.invitation.state)),y=f.filter((R)=>R.invitation&&pVe.has(R.invitation.state)),b=d.state==="pending"?g:y,A=f.flatMap((R)=>{let M=R.invitation;if(!M)return[];let k=R.identities.find((L)=>L.type!=="passkey")?.label??R.externalPeers[0]?.peerId??"Not recorded",N=r.get(M.id);return[{id:M.id,displayName:R.displayName,role:R.role,state:M.state,destination:k,updatedAt:M.claimedAt??M.cancelledAt??M.expiredAt??M.sentAt??M.updatedAt,...N?{deliveryAttemptId:N}:{}}]}),w=new Map(A.map((R)=>[R.id,R])),B=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:WHr(),channels:h.map((R)=>({type:R.type,displayName:R.displayName,subjectLabel:R.subjectLabel,deliveryModes:R.deliveryModes})),invitations:b.slice(d.offset,d.offset+d.limit).flatMap((R)=>{let M=R.invitation?w.get(R.invitation.id):void 0;return M?[M]:[]}),...B?{selectedInvitation:B}:{},selectedTotal:b.length,pendingCount:g.length,historyCount:y.length,failureCount:g.filter((R)=>R.invitation?.state==="failed").length}}})}});return YA(i,afe.actions)}var gfe=l.strictObject({peerId:l.string().trim().max(2000).optional(),displayName:l.string().trim().max(200).optional()}),QHr=l.strictObject({peerId:l.string().trim().min(1).max(2000),displayName:l.string().trim().min(1).max(200),role:l.enum(["admin","trusted"]),deliveryType:l.string().trim().min(1).max(64),deliverySubject:l.string().trim().min(1).max(1000),deliveryLabel:l.string().trim().min(1).max(200).optional(),deliveryMode:l.enum(["automatic","manual"])}),XHr=l.strictObject({peerId:l.string().trim().min(1).max(2000),userId:l.string().min(1)}),ffe=Vr({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:QHr,output:iW}),xfe=Vr({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:XHr,output:n0}),eWr=l.strictObject({query:gfe,peers:l.array(l.strictObject({peerId:l.string(),displayName:l.string(),role:l.enum(["admin","trusted","public"]),verificationStatus:l.enum(["unverified","verified"]),createdAt:l.number()})),people:l.array(l.strictObject({userId:l.string(),displayName:l.string()})),channels:l.array(nW)});function cW(e,t){let r=e.filter((n)=>n.id===t);if(r.length!==1)throw Error(`Peer tab composition requires block "${t}" exactly once`);let i=r[0];if(!i)throw Error(`Peer tab composition requires block "${t}" exactly once`);switch(i.type){case"tabs":case"detail":case"columns":throw Error(`Peer tab composition block "${t}" must be a region`);default:return i}}function yfe(e){let t=e.some((r)=>r.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[cW(e,"peers"),cW(e,"link-peer"),cW(e,t)],invitations:[cW(e,t)]}}var tWr=G9("Peer invitation setup"),hfe=Po({id:"peers",label:"Peers",priority:12,permission:"admin",query:gfe,data:eWr,actions:[ffe,xfe],view:({data:e})=>{let t=oW(e.channels),r=[{type:"stats",id:"peer-summary",items:[{label:"Linked peers",value:e.peers.length},{label:"Verified",value:e.peers.filter((i)=>i.verificationStatus==="verified").length},{label:"Available people",value:e.people.length}]}];if(e.channels.length>0&&t.length>0)r.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:ffe,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:sW("Local role"),...aW(e.channels,t)}},result:tWr}]});else r.push({type:"notice",id:"invite-peer-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});return r.push({type:"card",id:"link-peer",label:"Link an existing person",blocks:[{type:"action",action:xfe,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((i)=>({value:i.userId,label:i.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((i)=>({id:`${i.peerId}:${i.displayName}`,cells:{peer:c5(i.peerId),person:i.displayName,role:i.role,verification:i.verificationStatus,linked:Fh(i.createdAt)},compact:{title:c5(i.peerId),metadata:[i.displayName,po(i.role),Fh(i.createdAt)],badges:[{label:po(i.verificationStatus),tone:i.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:r}}});function AVe(e){let t=fm(e),r=e.studio.source({definition:hfe,bind:(i)=>{let n=ffe.bind(i,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}},Oc(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=xfe.bind(i,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},Oc(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((u)=>u.userId===s.userId)?.displayName??"person";return{summary:`Link ${s.peerId} to ${c}? Local access does not change.`,revision:`${s.peerId}:${s.userId}`}});return hfe.bind(i,{actions:[n,o],load:async({query:s})=>{let a=s.get(gfe),[c,u]=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:rW(d),channels:u.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return YA(r,hfe.actions)}function bfe(e,t){let r=e.filter((i)=>i.id===t);if(r.length!==1||!r[0])throw Error(`People tab composition requires block "${t}" exactly once`);return r[0]}function wVe(e,t,r){let i=bfe(e,"people-summary");if(i.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let n=bfe(e,"people");if(n.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=bfe(e,"brain-anchor");if(o.type!=="card")throw Error('People tab composition block "brain-anchor" must be a card');let s=[t,...r].flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[n,{type:"card",id:"people-peers",label:"External brains",presentation:"disclosure",blocks:s},{...o,label:"Access reference",presentation:"disclosure",blocks:[i,...o.blocks]}]}}var Ife=l.strictObject({selected:l.string().trim().min(1).max(200).optional()}),Tfe=l.strictObject({userId:l.string().min(1)}),rWr=l.strictObject({userId:l.string().min(1),role:l.enum(["admin","trusted","public"])}),iWr=l.strictObject({userId:l.string().min(1),status:l.enum(["active","suspended"])});function nWr(e){return e.revokedAt===void 0&&e.type!=="passkey"}function oWr(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var sWr=l.strictObject({userId:l.string().min(1),credentialId:l.string().min(1)}),aWr=l.strictObject({userId:l.string().min(1),type:l.string().trim().min(1).max(64),subject:l.string().trim().min(1).max(2000),issuer:l.string().trim().min(1).max(2000).optional(),label:l.string().trim().min(1).max(200).optional()}),cWr=l.strictObject({userId:l.string().min(1),identityId:l.string().min(1)}),lWr=l.strictObject({userId:l.string().min(1),peerId:l.string().trim().min(1).max(2000)}),Afe=Vr({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:rWr,output:n0}),wfe=Vr({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:iWr,output:n0}),Sfe=Vr({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:Tfe,output:n0}),kfe=Vr({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:sWr,output:n0}),_fe=Vr({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:Tfe,output:iW}),Bfe=Vr({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:Tfe,output:n0}),Pfe=Vr({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:aWr,output:n0}),Cfe=Vr({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:cWr,output:n0}),Dfe=Vr({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:lWr,output:n0}),uWr=l.strictObject({userId:l.string(),displayName:l.string(),role:l.enum(["admin","trusted","public"]),status:l.enum(["active","suspended"]),isAnchor:l.boolean(),isSelf:l.boolean(),profileEntityId:l.string().optional(),passkeys:l.array(l.strictObject({id:l.string(),kind:l.string(),createdAt:l.number()})),identities:l.array(l.strictObject({id:l.string(),type:l.string(),displayName:l.string(),label:l.string(),verified:l.boolean()})),peers:l.array(l.strictObject({peerId:l.string(),verificationStatus:l.enum(["unverified","verified"])}))}),dWr=l.strictObject({query:Ife,anchor:l.strictObject({kind:l.enum(["person","collective"]),configuredKind:l.enum(["person","team","organization"]),displayName:l.string(),administeredBy:l.number().int().nonnegative()}),people:l.array(uWr),activeCount:l.number().int().nonnegative(),activeAdminCount:l.number().int().nonnegative(),suspendedCount:l.number().int().nonnegative(),channelTypes:l.array(l.strictObject({type:l.string(),displayName:l.string()}))}),pWr=G9("Passkey setup");function mWr(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function Efe(e){return{type:"notice",tone:"warn",text:e}}function hWr(e){return{type:"action",action:_fe,input:{userId:e},result:pWr}}function fWr(e,t){return{type:"action",action:Pfe,input:{userId:e},form:{submitLabel:"Attach channel",fields:{type:{label:"Channel type",control:"select",options:t.map((r)=>({value:r.type,label:r.displayName}))},subject:{label:"Channel subject",control:"text"},issuer:{label:"Issuer (optional)",control:"url"},label:{label:"Display label (optional)",control:"text"}}}}}function xWr(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var vfe=Po({id:"people",label:"People",priority:10,permission:"admin",query:Ife,data:dWr,actions:[Afe,wfe,Sfe,kfe,_fe,Bfe,Pfe,Cfe,Dfe],badge:({data:e})=>e.suspendedCount,view:({data:e})=>{let t=e.people.find((n)=>n.userId===e.query.selected),r=[];if(t){let n=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.":n?"Add another active Admin before changing this role.":void 0,s=t.isAnchor?"The protected brain identity cannot be suspended.":n?"Add another active Admin before suspending this person.":void 0;if(r.push({type:"key-values",id:"person-summary",items:[{label:"Role",value:po(t.role)},{label:"Status",value:po(t.status)},{label:"Protected brain identity",value:t.isAnchor},{label:"Brain relationship",value:t.peers.length>0?"External peer + local member":"Hosted member"}]}),o)r.push({type:"notice",tone:"warn",text:o});else r.push({type:"card",id:"person-role",label:"Permission role",blocks:[{type:"action",action:Afe,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"}]}}}}]});r.push({type:"card",id:"person-access",label:"Access",blocks:[{type:"actions",items:[{action:wfe,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:Bfe,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:Sfe,input:{userId:t.userId}}]:[]]},...t.isSelf?[mWr()]:[],...s&&t.status==="active"?[Efe(s)]:[]]}),r.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:Fh(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${Fh(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:kfe,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[hWr(t.userId)]:[Efe("A verified channel is required for setup delivery.")]:[]]}),r.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:Cfe,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[fWr(t.userId,e.channelTypes)]:[Efe("No attachable channel type is configured.")]]}),r.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."}),r.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:c5(a.peerId),description:`Vouched in by ${c5(a.peerId)} \xB7 ${a.peerId}`,metadata:[po(a.verificationStatus)],actions:[{action:Dfe,input:{userId:t.userId,peerId:a.peerId}}]}))})}let i=[{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((n,o)=>Number(o.isSelf)-Number(n.isSelf)||Number(n.isAnchor)-Number(o.isAnchor)||n.displayName.localeCompare(o.displayName)).map((n)=>({id:n.userId,title:n.displayName,description:[po(n.role),po(n.status),...n.isSelf?["You"]:[],...n.isAnchor?["Protected brain identity"]:[]].join(" \xB7 "),metadata:[n.identities.length===0?"No linked identities":n.identities.length===1?"One linked identity":`${n.identities.length} linked identities`,...n.peers.length>0?[`Arrived via ${c5(n.peers[0]?.peerId)}`]:[]],...n.isSelf?{link:{detail:{itemId:n.userId}}}:{},links:[{label:n.isSelf?"Account \u2192":n.isAnchor?"View protection":"Manage person",target:n.isSelf?{launch:{target:"account-settings"}}:{detail:{itemId:n.userId}}}]}))},...t?{open:{forId:t.userId,title:t.displayName,blocks:r}}:{}}];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:i}}});function lW(e,t){return e.find((r)=>r.userId===t)?.displayName??"person"}async function gWr(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function SVe(e){let t=fm(e),r=e.studio.source({definition:vfe,bind:(i)=>{let n=Afe.bind(i,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,Oc(f)),{status:`Role changed to ${po(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${lW(f,h.userId)}\u2019s role to ${po(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=wfe.bind(i,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,Oc(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${lW(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=Sfe.bind(i,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,Oc(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${lW(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=kfe.bind(i,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,Oc(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=_fe.bind(i,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,Oc(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()}}),u=Bfe.bind(i,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,Oc(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${lW(f,h.userId)} out everywhere?`,revision:h.userId}}),d=Pfe.bind(i,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"}},Oc(f)),{status:"Verified channel attached."})),p=Cfe.bind(i,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,Oc(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=Dfe.bind(i,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,Oc(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 vfe.bind(i,{actions:[n,o,s,a,c,u,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(Ife),[y,b,A]=await Promise.all([gWr(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"),R=y??xWr(B?.displayName??"Brain owner",w.filter((N)=>N.role==="admin"&&N.status==="active").length),M=w.filter((N)=>N.status==="active"),k=new Map(A.map((N)=>[N.type,N.displayName]));return{query:g,anchor:{kind:R.kind,configuredKind:R.configuredKind,displayName:R.displayName,administeredBy:R.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:oWr(L),createdAt:L.createdAt})),identities:N.identities.filter(nWr).map((L)=>({id:L.id,type:L.type,displayName:k.get(L.type)??po(L.type),label:L.label??"Connected identity",verified:L.verifiedAt!==void 0})),peers:N.externalPeers.map((L)=>({peerId:L.peerId,verificationStatus:L.verificationStatus}))}]}),activeCount:M.length,activeAdminCount:M.filter((N)=>N.role==="admin").length,suspendedCount:w.length-M.length,channelTypes:A.map((N)=>({type:N.type,displayName:N.displayName}))}}})}});return YA(r,vfe.actions)}var yWr=l.strictObject({tab:l.enum(["people","invitations","audit"]).default("people"),selected:l.string().trim().min(1).max(200).optional(),state:l.enum(["pending","history"]).optional(),offset:l.preprocess(Rh,l.number().int().min(0).max(1e5)).optional(),limit:l.preprocess(Rh,l.number().int().min(1).max(100)).optional(),peerId:l.string().trim().max(2000).optional(),displayName:l.string().trim().max(200).optional(),actorUserId:l.string().trim().min(1).max(120).optional(),action:l.string().trim().min(1).max(200).optional()});function bWr(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function EWr(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 vWr(e,t){if(!EWr(e))throw Error(`${t} tab returned invalid workspace data`);return e}function kVe(e,t){let r=[];for(let i of e){if(i.type==="tabs")throw Error(`${t} tab cannot contribute nested tabs`);r.push(i)}return r}function Rfe(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function yP(e,t,r,i){return vWr(await e.dataProvider(t,r,i),e.label)}async function AWr(e,t,r,i){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,r,i)}function wWr(e){let t=new Map;for(let r of e)for(let i of r.actionIds){if(t.has(i))throw Error(`Administration action "${i}" is declared by more than one source`);if(!r.registration.actionHandler)throw Error(`Administration source "${r.registration.label}" declares actions without a handler`);t.set(i,r.registration)}return t}function BVe(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 SWr(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 CVe(e){if(!e.studio.isAvailable())return;let t=SVe(e),r=vVe(e),i=AVe(e),n=dVe(e),o=wWr([t,r,i,n]),s=t.registration,a=r.registration,c=i.registration,u=n.registration;return e.studio.register({id:"admin:administration",label:"Administration",rendererName:q9,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=yWr.parse(p??{}),f,g=Rfe("People"),y=Rfe("Invitations"),b=Rfe("Audit");if(h.tab==="people"){let[A,w]=await Promise.all([yP(s,d,{...h.selected?{selected:h.selected}:{}},m),yP(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),B=yfe(w.view.blocks);g=[...wVe(kVe(A.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[A,w]=await Promise.all([yP(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...Hn({offset:h.offset,limit:h.limit})},m),yP(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),B=yfe(w.view.blocks),R=bVe(A.view.blocks,B.invitations);f=A.view.primaryAction,y=[...R.blocks]}else{let A=await yP(u,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...Hn({offset:h.offset,limit:h.limit})},m);b=kVe(A.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=bWr(d);if(!h)throw new br("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new br("not_found",{publicMessage:`Unknown Administration action: ${h}`});return AWr(f,d,p,m)},badgeProvider:async()=>{let d=BVe(await fm(e).listAdminUsers());return d.suspended+d.pendingInvitations},attentionProvider:async()=>SWr(BVe(await fm(e).listAdminUsers()))})}var kWr=259200000,BWr=l.strictObject({id:l.string(),displayName:l.string(),state:l.string(),reason:l.enum(["expiring","delivery-failed"]),expiresAt:l.number().optional()}),CWr=l.strictObject({invitations:l.array(BWr),expiringCount:l.number().int().nonnegative(),failureCount:l.number().int().nonnegative()}),DVe=ro({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:CWr,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 ${Fh(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function DWr(e,t){let r=e.flatMap((i)=>{let n=i.invitation;if(!n)return[];if(n.state==="failed")return[{id:n.id,displayName:i.displayName,state:n.state,reason:"delivery-failed",...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{}}];if(!["pending","sending","sent"].includes(n.state)||n.expiresAt===void 0||n.expiresAt<=t||n.expiresAt>t+kWr)return[];return[{id:n.id,displayName:i.displayName,state:n.state,reason:"expiring",expiresAt:n.expiresAt}]});return r.sort((i,n)=>(i.expiresAt??Number.MAX_SAFE_INTEGER)-(n.expiresAt??Number.MAX_SAFE_INTEGER)||i.displayName.localeCompare(n.displayName)),{invitations:r,expiringCount:r.filter((i)=>i.reason==="expiring").length,failureCount:r.filter((i)=>i.reason==="delivery-failed").length}}async function IVe(e,t){t.throwIfAborted();let r=await fm(e).listAdminUsers();return t.throwIfAborted(),DWr(r,Date.now())}var IWr=l.strictObject({}),TWr=zt({id:"admin",config:IWr},{subscriptions:(e)=>{let t=bt(e);return t.registered(async()=>{await CVe(t)}),[]},dashboardWidgets:(e)=>{let t=bt(e);return[DVe.bind(e,({signal:r})=>IVe(t,r))]}}),Ffe=TWr;var Ki="agent",TVe="agent-network",_Ve="agent-proximity",Qfe="agent-discovery:entities",PVe="agent-discovery:proximity-map",Xfe="proximity-map",e0e="agent-list",t0e="agent-detail",Nc="skill",RVe=30,FVe=120;var dW="skill-derivation",MVe="skill-derivation",r0e="skill:skill-derivation",OVe="skills";var _Wr=l.string().trim().min(1).max(FVe),i0e=l.array(_Wr).max(RVe),QA=l.object({name:l.string(),description:l.string(),tags:i0e,examples:l.array(l.string())}),CP=QA,XA=o0.extend({entityType:l.literal(Nc),metadata:CP});var pW=l.object({name:l.string(),description:l.string(),tags:i0e}),Mb=l.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),PWr=s5,s0=l.object({name:l.string(),kind:PWr,organization:l.string().optional(),brainName:l.string().describe("Name of the brain instance"),shownAs:l.string().min(1).optional().describe("The name this brain shows the agent under, in place of its own name"),url:l.string().url().describe("Brain endpoint URL"),repoDid:l.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:l.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:l.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:l.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:l.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:l.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:l.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:l.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:Mb,discoveredAt:l.string().datetime().meta({description:"When this agent was first discovered",studioWidget:"provenance"}),introducedBy:l.array(l.string()).optional().meta({description:"Agent ids of the peers whose directories reported this agent",studioWidget:"provenance"}),hops:l.number().int().min(2).optional().meta({description:"Discovery order: 2 = sighted through a first-order peer",studioWidget:"provenance"})}),DP=l.object({name:l.string(),shownAs:l.string().min(1).optional(),url:l.string().url(),status:Mb,discoveredAt:l.string().datetime().optional(),slug:l.string(),repoDid:l.string().optional(),brainDid:l.string().optional(),cardUri:l.string().optional(),cardCid:l.string().optional(),cardLastError:l.string().optional(),cardFailureCount:l.number().int().nonnegative().optional(),cardUnavailableAt:l.string().datetime().optional(),cardStaleAfter:l.string().datetime().optional()}),On=o0.extend({entityType:l.literal(Ki),metadata:DP}),RWr=jr.extend({entityType:l.literal(Ki),metadata:DP}),IP=RWr.extend({frontmatter:s0,about:l.string(),skills:l.array(pW),notes:l.string()}),FWr=IP.extend({url:l.string().optional(),typeLabel:l.string().optional()}),MWr=IP.extend({url:l.string(),typeLabel:l.string()});var OWr=l.record(l.string(),l.unknown());function NWr(e){try{return Mn(e,OWr).content}catch{return e}}function n0e(e){return{name:e.name,...e.shownAs&&{shownAs:e.shownAs},url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:W9(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 NVe(e){return Ws(Ki,e,s0)}function TP(e){return{content:e,metadata:n0e(NVe(e))}}function Z9(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:Mb.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},r=tfe({about:e.about,skills:e.skills,notes:e.notes});return dn(r,t)}function bm(e,t={}){return Z9({...e.frontmatter,...e.body,...t})}function _P(e){return gP(NWr(e))}function Zs(e){return{frontmatter:NVe(e.content),body:_P(e.content)}}function o0e(e){return dn("",e)}function jWr(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function LVe(e,t,r={}){let i=r.minCount??1,n=r.topN??12,o=new Map,s=(a)=>{for(let c of mc(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=_P(a.content);s(c.skills.flatMap((u)=>u.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=i).sort(jWr).slice(0,n)}function jVe(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:r})=>`- ${t} (${r})`)].join(`
|
|
1039
1039
|
`)}function V9(e,t={}){let r=e.anchor?.name??e.brainName,i=e.anchor?.category??"person",n=[];if(e.anchor?.description)n.push(e.anchor.description);if(e.description)n.push(e.description);let o=t.status??"discovered",s=new Date().toISOString();return{content:Z9({name:r,kind:i,...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:n.join(`
|
|
1040
1040
|
|
|
1041
1041
|
`),skills:e.skills.map((c)=>({name:c.name,description:c.description,tags:mc(c.tags)})),notes:""}),metadata:{name:r,url:e.url,status:o,discoveredAt:s,slug:W9(e.url)},anchorName:r}}function Xx(e){let t=e.trim();if(t.startsWith("http://")||t.startsWith("https://"))try{return new URL(t).hostname}catch{return t}let r=t.match(/https?:\/\/[^\s]+?(?=[.,;:!?)]*(?:\s|$))/);if(r)try{return new URL(r[0]).hostname}catch{return r[0]}if(/^[^\s]+\.[^\s]+$/.test(t))return t;return""}var zWr=l.object({prompt:l.string().optional(),url:l.string().optional(),content:l.string().optional(),skipAi:l.boolean().optional(),status:l.enum(["discovered","approved","archived"]).optional()});function zVe(e){return{input:zWr,generate:async({input:t})=>{let r=Xx(t.url??t.prompt??"");if(!r)return{success:!1,error:"No URL or domain provided. Use: system_create agent with a domain like yeehaa.io"};let i=await Th(r,{fetch:e??globalThis.fetch});if(!i.ok)return{success:!1,error:HA(i.reason)?i.error:`Could not fetch Agent Card from ${r}. Make sure the agent is running and accessible.`};let{content:n,metadata:o}=V9(i.card,{...t.status!==void 0?{status:t.status}:{}});return{success:!0,id:r,content:n,metadata:o}}}}var UWr=100,UVe=50000,a0e="connect",qVe="dismiss";function s0e(e){let t=On.parse(e),r=qWr(t);return r?{entity:t,parsed:r}:void 0}function $Ve(e){return{sourceId:"agent-sightings",displayName:"Agent sightings",list:async({records:r})=>(await r.list()).flatMap((i)=>{let n=s0e(i);return n?[n]:[]}).sort((i,n)=>n.parsed.frontmatter.discoveredAt.localeCompare(i.parsed.frontmatter.discoveredAt)).slice(0,UWr).map(({entity:i,parsed:n})=>$Wr(i,n)),resolveDetail:async(r,{records:i,signal:n})=>{n.throwIfAborted();let o=s0e(await i.get(r));if(n.throwIfAborted(),!o)throw Error("Agent sighting not found");let s=HWr(o.entity,o.parsed);return{kind:"plain",text:s.slice(0,UVe),truncated:s.length>UVe}},act:async(r,i,{records:n,edits:o})=>{if(i!==a0e&&i!==qVe)throw Error("Invalid agent sighting Inbox action");let s=await n.get(r),a=s?s0e(s):void 0;if(!s||!a)throw Error("Agent sighting not found");let c=i===a0e?"approved":"archived";if(c==="approved")await e.approve(s.id);else await e.revoke(s.id);await o.update(s,{content:bm(a.parsed,{status:c,...c==="approved"?{introducedBy:void 0,hops:void 0}:{}}),metadata:{...s.metadata,status:c}})}}}function qWr(e){let t=Zs(e);return t.frontmatter.status==="discovered"&&(t.frontmatter.introducedBy?.length??0)>0?t:void 0}function $Wr(e,t){let r=a0(t.frontmatter.name),i=a0(e.id),n=GVe(r===i?r:`${r} \xB7 ${i}`,160);return{id:e.id,title:n,summary:GWr(t),receivedAt:t.frontmatter.discoveredAt,urgency:"normal",entityRef:{entityType:Ki,entityId:e.id},actions:[{id:a0e,label:"Connect",confirm:!0},{id:qVe,label:"Dismiss",confirm:!0}]}}function GWr(e){let t=e.frontmatter.introducedBy??[],r=`Introduced by ${c0e(t.map(a0))}.`,i=a0(e.body.about),n=e.body.skills.map((s)=>a0(s.name)).filter(Boolean).slice(0,4),o=n.length>0?` Declared skills: ${c0e(n)}.`:"";return GVe(`${r}${i?` ${i}`:""}${o}`,1000)}function HWr(e,t){let r=[`Agent: ${a0(t.frontmatter.name)}`,`Domain: ${a0(e.id)}`,`Introduced by: ${c0e((t.frontmatter.introducedBy??[]).map(a0))}`],i=a0(t.body.about);if(i)r.push(`About: ${i}`);if(t.body.skills.length>0)r.push("Skills:",...t.body.skills.map((n)=>{let o=a0(n.description);return`- ${a0(n.name)}${o?`: ${o}`:""}`}));return r.join(`
|
|
@@ -1966,6 +1966,7 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
|
|
|
1966
1966
|
@media (max-width: 720px){.x1yemgb7.x1yemgb7:not(#\\#){margin:0}}
|
|
1967
1967
|
@media (max-width: 640px){.x1xnq73d.x1xnq73d:not(#\\#){padding:0 10px}}
|
|
1968
1968
|
@media (max-width: 720px){.xe3jge6.xe3jge6:not(#\\#){padding:0 10px}}
|
|
1969
|
+
@media (max-width: 640px){.x1bf66pj.x1bf66pj:not(#\\#){padding:0}}
|
|
1969
1970
|
@media (max-width: 900px){.xb1114b.xb1114b:not(#\\#){padding:0}}
|
|
1970
1971
|
@media (max-width: 640px){.xfc0hut.xfc0hut:not(#\\#){padding:12px 0 40px}}
|
|
1971
1972
|
@media (max-width: 640px){.xg8tid0.xg8tid0:not(#\\#){padding:12px 14px 0}}
|
|
@@ -2121,6 +2122,7 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
|
|
|
2121
2122
|
@media (max-width: 640px){.x17i0p7j.x17i0p7j:not(#\\#):not(#\\#){border-radius:0}}
|
|
2122
2123
|
@media (min-width: 641px){.xsucau6.xsucau6:not(#\\#):not(#\\#){border-radius:8px}}
|
|
2123
2124
|
@media (max-width: 640px){.x1olvxk8.x1olvxk8:not(#\\#):not(#\\#){border-radius:9px}}
|
|
2125
|
+
@media (max-width: 640px){.xwddm5z.xwddm5z:not(#\\#):not(#\\#){border-width:0}}
|
|
2124
2126
|
@media (max-width: 640px){.x1d3ddqg.x1d3ddqg:not(#\\#):not(#\\#){gap:10px}}
|
|
2125
2127
|
@media (max-width: 720px){.x1n3jums.x1n3jums:not(#\\#):not(#\\#){gap:10px}}
|
|
2126
2128
|
@media (max-width: 900px){.x13osz58.x13osz58:not(#\\#):not(#\\#){gap:12px 24px}}
|
|
@@ -2161,6 +2163,7 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
|
|
|
2161
2163
|
.xvmahel:not(#\\#):not(#\\#):not(#\\#){-webkit-font-smoothing:antialiased}
|
|
2162
2164
|
.x1h7i4cw:not(#\\#):not(#\\#):not(#\\#){-webkit-line-clamp:2}
|
|
2163
2165
|
.x1q9s9ta:not(#\\#):not(#\\#):not(#\\#){accent-color:var(--console-accent)}
|
|
2166
|
+
.xc26acl:not(#\\#):not(#\\#):not(#\\#){align-content:center}
|
|
2164
2167
|
.x10ukxgv:not(#\\#):not(#\\#):not(#\\#){align-content:start}
|
|
2165
2168
|
.x1pha0wt:not(#\\#):not(#\\#):not(#\\#){align-items:baseline}
|
|
2166
2169
|
.x6s0dn4:not(#\\#):not(#\\#):not(#\\#){align-items:center}
|
|
@@ -2274,6 +2277,7 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
|
|
|
2274
2277
|
.x1ypdohk:not(#\\#):not(#\\#):not(#\\#){cursor:pointer}
|
|
2275
2278
|
.x104kibb:not(#\\#):not(#\\#):not(#\\#){display:-webkit-box}
|
|
2276
2279
|
.x1lliihq:not(#\\#):not(#\\#):not(#\\#){display:block}
|
|
2280
|
+
.xjp7ctv:not(#\\#):not(#\\#):not(#\\#){display:contents}
|
|
2277
2281
|
.x78zum5:not(#\\#):not(#\\#):not(#\\#){display:flex}
|
|
2278
2282
|
.xrvj5dj:not(#\\#):not(#\\#):not(#\\#){display:grid}
|
|
2279
2283
|
.x1rg5ohu:not(#\\#):not(#\\#):not(#\\#){display:inline-block}
|
|
@@ -2282,6 +2286,7 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
|
|
|
2282
2286
|
.xtcx8v3:not(#\\#):not(#\\#):not(#\\#){display:list-item}
|
|
2283
2287
|
.x1s85apg:not(#\\#):not(#\\#):not(#\\#){display:none}
|
|
2284
2288
|
.xf5m44m:not(#\\#):not(#\\#):not(#\\#){display:table-row}
|
|
2289
|
+
.x1jn7h4n:not(#\\#):not(#\\#):not(#\\#){fill:color-mix(in srgb,var(--console-accent) 22%,transparent)}
|
|
2285
2290
|
.x63ly0w:not(#\\#):not(#\\#):not(#\\#){fill:color-mix(in srgb,var(--console-accent) 5%,transparent)}
|
|
2286
2291
|
.x1rw6qo9:not(#\\#):not(#\\#):not(#\\#){fill:color-mix(in srgb,var(--console-accent) 72%,transparent)}
|
|
2287
2292
|
.x6p09lz:not(#\\#):not(#\\#):not(#\\#){fill:color-mix(in srgb,var(--console-secondary) 2.5%,transparent)}
|
|
@@ -2289,7 +2294,6 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
|
|
|
2289
2294
|
.x1sgapc2:not(#\\#):not(#\\#):not(#\\#){fill:color-mix(in srgb,var(--console-secondary) 6%,transparent)}
|
|
2290
2295
|
.xbh8q5q:not(#\\#):not(#\\#):not(#\\#){fill:none}
|
|
2291
2296
|
.xy6m8k3:not(#\\#):not(#\\#):not(#\\#){fill:transparent}
|
|
2292
|
-
.xgeoyvb:not(#\\#):not(#\\#):not(#\\#){fill:var(--console-accent-soft)}
|
|
2293
2297
|
.x8eu9n:not(#\\#):not(#\\#):not(#\\#){fill:var(--console-accent)}
|
|
2294
2298
|
.xp8jjoe:not(#\\#):not(#\\#):not(#\\#){fill:var(--console-err)}
|
|
2295
2299
|
.x1s7eawt:not(#\\#):not(#\\#):not(#\\#){fill:var(--console-ok)}
|
|
@@ -2686,6 +2690,7 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
|
|
|
2686
2690
|
@media (max-width: 720px){.x1943nhg.x1943nhg:not(#\\#):not(#\\#):not(#\\#){align-items:stretch}}
|
|
2687
2691
|
@media (max-width: 640px){.x1ryrld4.x1ryrld4:not(#\\#):not(#\\#):not(#\\#){align-self:start}}
|
|
2688
2692
|
@media (prefers-reduced-motion: reduce){.x1aquc0h.x1aquc0h:not(#\\#):not(#\\#):not(#\\#){animation-name:none}}
|
|
2693
|
+
@media (max-width: 640px){.x1norit2.x1norit2:not(#\\#):not(#\\#):not(#\\#){background-color:transparent}}
|
|
2689
2694
|
@media (min-width: 641px){.xkktd5z.xkktd5z:not(#\\#):not(#\\#):not(#\\#){background-color:var(--console-accent-soft)}}
|
|
2690
2695
|
@media (max-width: 640px){.xlc8tcj.xlc8tcj:not(#\\#):not(#\\#):not(#\\#){box-shadow:none}}
|
|
2691
2696
|
@media (max-width: 720px){.x1uno8h5.x1uno8h5:not(#\\#):not(#\\#):not(#\\#){clip-path:inset(50%)}}
|
|
@@ -2825,11 +2830,9 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
|
|
|
2825
2830
|
.xs1s249:not(#\\#):not(#\\#):not(#\\#):not(#\\#){border-right-width:1px}
|
|
2826
2831
|
.xltl5i9:not(#\\#):not(#\\#):not(#\\#):not(#\\#){border-top-color:var(--console-rule-strong)}
|
|
2827
2832
|
.xvg7k2t:not(#\\#):not(#\\#):not(#\\#):not(#\\#){border-top-color:var(--console-rule)}
|
|
2828
|
-
.x172wxxo:not(#\\#):not(#\\#):not(#\\#):not(#\\#){border-top-color:var(--console-text-muted)}
|
|
2829
2833
|
.x13fuv20:not(#\\#):not(#\\#):not(#\\#):not(#\\#){border-top-style:solid}
|
|
2830
2834
|
.x972fbf:not(#\\#):not(#\\#):not(#\\#):not(#\\#){border-top-width:0}
|
|
2831
2835
|
.x178xt8z:not(#\\#):not(#\\#):not(#\\#):not(#\\#){border-top-width:1px}
|
|
2832
|
-
.xamhcws:not(#\\#):not(#\\#):not(#\\#):not(#\\#){border-top-width:2px}
|
|
2833
2836
|
.x1ey2m1c:not(#\\#):not(#\\#):not(#\\#):not(#\\#){bottom:0}
|
|
2834
2837
|
.xrb244j:not(#\\#):not(#\\#):not(#\\#):not(#\\#){bottom:6px}
|
|
2835
2838
|
.x5yr21d:not(#\\#):not(#\\#):not(#\\#):not(#\\#){height:100%}
|
|
@@ -3004,6 +3007,7 @@ See https://react.dev/link/invalid-hook-call for tips about how to debug and fix
|
|
|
3004
3007
|
.xoy5xpq:is([data-tone="error"]):not(#\\#):not(#\\#):not(#\\#):not(#\\#){border-top-color:var(--console-err)}
|
|
3005
3008
|
.xvw7cn:is([data-tone="good"]):not(#\\#):not(#\\#):not(#\\#):not(#\\#){border-top-color:var(--console-ok)}
|
|
3006
3009
|
.x1qaj2f5:is([data-tone="warn"]):not(#\\#):not(#\\#):not(#\\#):not(#\\#){border-top-color:var(--console-warn)}
|
|
3010
|
+
.x7nfcnm:is([data-tone="good"], [data-tone="warn"], [data-tone="error"]):not(#\\#):not(#\\#):not(#\\#):not(#\\#){border-top-width:2px}
|
|
3007
3011
|
.xxfsjeb:is(details[open] > summary):not(#\\#):not(#\\#):not(#\\#):not(#\\#){margin-bottom:14px}
|
|
3008
3012
|
.x15m6qhz:is([open]):not(#\\#):not(#\\#):not(#\\#):not(#\\#){padding-bottom:16px}
|
|
3009
3013
|
.x1s4zo15:not(:last-child):not(#\\#):not(#\\#):not(#\\#):not(#\\#){padding-right:40px}
|
|
@@ -9600,7 +9604,7 @@ Guidelines:
|
|
|
9600
9604
|
3. Depth: Provide enough detail to be useful as a reference, but stay focused on the topic.
|
|
9601
9605
|
4. Style: Informative and educational. Write as if explaining to yourself for future reference.
|
|
9602
9606
|
5. Length: Adjust based on topic complexity - concise for simple topics, more detailed for complex ones.
|
|
9603
|
-
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var xpo="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.",HT=Vi(Hfe(dt({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:jue,markdown:zue,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:xpo,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:gUe(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:vUe},generation:yUe,create:{fromUpload:NPr},jobs:{"upload-import":OPr(()=>HT)},evals:{generateNote:async(e,{ai:t})=>t.generate({template:"generation",prompt:l.object({prompt:l.string()}).parse(e).prompt,representedIdentity:"none"},l.object({title:l.string(),body:l.string()}))},atproto:xUe}),[Gfe(que,async({request:e,entities:t})=>{let{id:r,title:i,body:n}=e;if(await t.get(HT,r))return{noteId:r,created:!1};return await t.create(HT,{id:r,content:n,metadata:{title:i,titleStated:!0},visibility:"restricted"}),{noteId:r,created:!0}})]),GT);var gpo=Pi({id:"note",config:fUe,entities:[HT]}),jPr=gpo;var ypo=l.object({type:l.literal("email"),address:l.string().max(0).optional()}).transform(()=>{return}),bpo=l.looseObject({defaultRecipient:ypo.or(zPr).optional()}),Epo=zt({id:"notifications",config:bpo},{subscriptions:(e)=>{let{config:t}=e,r=bt(e),{logger:i}=r;return r.answer(h3,async({request:n})=>{let o=n.recipient??t.defaultRecipient;if(!o)return i.warn($ue.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=r.deliveryProvider(o.type);if(!s||!await s.isAvailable())return i.warn($ue.transportMissing,{channelType:o.type}),{status:"failed",failure:"transport-missing"};let a=await s.send({recipient:o.address,subject:n.title,text:n.body,...n.html?{html:n.html}:{},...n.replyTo?{replyTo:n.replyTo}:{},sensitivity:n.sensitivity,idempotencyKey:n.idempotencyKey??crypto.randomUUID()});if(a.status!=="sent"){i.warn($ue.deliveryFailed,{transportCode:a.failureCode});let c=UPr.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}),[]}}),qPr=Epo;var GPr=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],vpo=l.looseObject({elements:l.array(l.looseObject({snapshotDomain:l.string(),snapshotData:l.array(l.record(l.string(),l.unknown()))})),paging:l.looseObject({links:l.array(l.looseObject({rel:l.string().optional(),href:l.string().optional()})).optional()}).optional()}),Apo="https://api.linkedin.com/rest",wpo="202312",$Pr=1000,Spo=1000;function kpo(e){return e.toLowerCase().includes("no data found for this memberid")}function Bpo(e,t){let r=e.paging?.links?.find((n)=>n.rel==="next")?.href,i=r?Number(new URL(r,"https://api.linkedin.com").searchParams.get("start")):Number.NaN;return Number.isInteger(i)&&i>t?i:t+1}class j${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,r){if(r===$Pr)throw Error(`LinkedIn snapshot exceeded ${$Pr} pages`);let i=await this.fetchPage(e,t),n=(i?.elements??[]).filter((o)=>o.snapshotDomain===e).flatMap((o)=>o.snapshotData);if(!i||n.length===0)return n;return[...n,...await this.fetchPages(e,Bpo(i,t),r+1)]}async fetchPage(e,t){let r=new URL(`${Apo}/memberSnapshotData`);r.searchParams.set("q","criteria"),r.searchParams.set("domain",e),r.searchParams.set("start",String(t));let i=await this.fetchFn(r,{headers:{Authorization:`Bearer ${this.accessToken}`,"Linkedin-Version":wpo}});if(i.ok)return vpo.parse(await i.json());let n=await i.text();if(i.status<500&&kpo(n))return null;throw new Gue(i.status,n.slice(0,Spo))}}class Gue extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var Cpo=HPr({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:l.object({accessToken:l.string().trim().min(1),expiresAt:l.iso.datetime().optional()}),fields:{accessToken:{label:"Access token",secret:!0},expiresAt:{label:"Expires (ISO date and time)"}}});class AUe{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:Cpo})}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 wUe(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var Dpo="https://www.linkedin.com/oauth/v2/authorization",Ipo="https://www.linkedin.com/oauth/v2/accessToken",WPr="r_dma_portability_3rd_party",Tpo=500,_po=l.looseObject({access_token:l.string().min(1),expires_in:l.number().int().positive(),scope:l.string().optional()}),Ppo=l.looseObject({error:l.string().optional(),error_description:l.string().optional()});async function Rpo(e){try{return await e.json()}catch{return null}}class U${config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(Dpo);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",WPr),t}async exchange(e,t){let r=await this.fetchFn(Ipo,{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()}),i=await Rpo(r);if(!r.ok){let o=Ppo.safeParse(i),s=o.success?[o.data.error,o.data.error_description].filter(Boolean).join(": "):"";throw Error(`LinkedIn refused the code (${r.status})${s?`: ${s.slice(0,Tpo)}`:""}`)}let n=_po.parse(i);if(n.scope!==void 0&&n.scope!==WPr)throw Error("LinkedIn granted a token without the portability scope");return{accessToken:n.access_token,expiresAt:new Date(t+n.expires_in*1000).toISOString()}}}function VPr(e){return new z$({...ZPr,now:e})}var Hue="linkedin",Fpo=l.strictObject({accessToken:l.string().min(1),expiresAt:l.iso.datetime()});function SUe(e,t={}){let r=(n)=>new U$({...e,redirectUri:n},t.fetch),i=t.now??Date.now;return{id:Hue,authorizationUrl:({redirectUri:n,state:o})=>r(n).authorizationUrl(o),exchange:async({code:n,redirectUri:o})=>{let s=await r(o).exchange(n,i());return{accessToken:s.accessToken,expiresAt:s.expiresAt}}}}class kUe{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(WT.authorizations,{provider:Hue,brainState:e},"the connection");return new URL(KPr.parse(t).authorizationUrl)}async redeem(e){let t=YPr.parse(await this.post(WT.redeem,{provider:Hue,grant:e},"grant redemption"));if(t.provider!==Hue)throw Error("OAuth broker redeemed a grant for another provider");return Fpo.parse(t.credential)}async post(e,t,r){let{instanceId:i,secret:n}=this.config,o=await this.fetchFn(new URL(e,this.config.url),{method:"POST",headers:{Accept:"application/json",Authorization:`Basic ${Buffer.from(`${i}:${n}`).toString("base64")}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)throw Error(`OAuth broker refused ${r} (${o.status})`);return o.json()}}function Mpo(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function MB(e,t){return e.map((r)=>Mpo(r[t])).find(Boolean)}function JPr(e){let t=[MB(e,"First Name"),MB(e,"Last Name")].filter(Boolean).join(" ")||void 0,r=MB(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],i={name:t,headline:MB(e,"Headline"),industry:MB(e,"Industry"),location:MB(e,"Geo Location"),website:r,story:MB(e,"Summary")};return Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))}function QPr(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new br(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new br("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class BUe{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:r}=await this.previewFields(t);return QPr(await this.messaging.request($$,{fields:t,revision:r}))}async previewFields(e){return QPr(await this.messaging.request(q$,{fields:e}))}async imported(e){let t=new j$(e,this.fetchFn);return JPr(await t.fetchProfile())}}var CUe="/linkedin/oauth/start",H$="/linkedin/oauth/callback",W$="/linkedin/oauth/broker/return";function XPr(e){return e?.permissionLevel==="admin"&&e.isAnchor}function G$(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function tRr(e){let t=(c)=>{let u=e.workspaceUrl(),d=u.includes("?")?"&":"?";return G$(303,`${u}${d}connection=${c}`)},r=async(c,u)=>{let d=e.states.take(u),p=await e.resolveSession(c);return d&&XPr(p)&&p?.userId===d?d:null},i=async(c,u)=>{try{return await e.connections.save(c,await u()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${fe(d)}`),t("failed")}},n=async(c)=>{let u=await e.resolveSession(c);if(!u)return G$(401);if(!XPr(u))return G$(403);let d=e.states.issue(u.userId),{mode:p}=e;if(p.kind==="direct")return G$(302,p.oauth.authorizationUrl(d).toString());try{return G$(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${fe(m)}`),t("failed")}},o=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=await r(u,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 i(p,()=>c.exchange(m,e.now()))},s=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=await r(u,d.get("state")??""),m=eRr.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 i(p,()=>c.redeem(h))},{mode:a}=e;return[{path:CUe,method:"GET",public:!0,handler:n},a.kind==="direct"?{path:H$,method:"GET",public:!0,handler:o(a.oauth)}:{path:W$,method:"GET",public:!0,handler:s(a.broker)}]}var Opo=/^(?: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,Npo=[[/^$/,"<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>"],[Opo,"<month-year>"]];function nRr(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 rRr(e){if(typeof e!=="string")return`<${nRr(e)}>`;let t=e.trim();return Npo.find(([r])=>r.test(t))?.[1]??"<string>"}function Lpo(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(rRr))].sort();return rRr(e)}function iRr([e],[t]){return e.localeCompare(t)}function jpo(e){let t=e.flatMap((o)=>Object.entries(o)),i=[...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])=>nRr(a)))].sort(),presentCount:s.length}}),n=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(iRr).map(([a,c])=>[a,Lpo(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:i,recordShapes:[...n].sort(iRr).map(([,o])=>o)}}async function oRr(e){let t=await Promise.all(GPr.map(async(r)=>[r,jpo(await e.fetchDomain(r))]));return Object.fromEntries(t)}var dRr={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},zpo={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},Upo={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."}},sRr=200,_Ue=Vr({name:"import-profile",label:"Import from LinkedIn",permission:"admin",confirmation:{kind:"prepared"},input:l.object({}),output:l.object({filled:l.array(l.string()),kept:l.array(l.string())})}),Wue=Vr({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:l.object({}),output:l.object({disconnected:l.boolean()})}),PUe=Vr({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:l.object({}),output:l.object({shapes:l.string()})}),RUe=l.object({connection:l.enum(["connected","declined","failed"]).optional()}),qpo=l.object({field:l.enum(["name","headline","industry","location","website","story"]),current:l.string().nullable(),imported:l.string(),outcome:l.enum(["fill","preserve","unchanged"])}),DUe=RUe.shape.connection,$po=l.discriminatedUnion("status",[l.object({status:l.literal("disconnected"),expired:l.boolean(),startUrl:l.string(),connection:DUe}),l.object({status:l.literal("unavailable"),message:l.string(),startUrl:l.string(),connection:DUe}),l.object({status:l.literal("ready"),fields:l.array(qpo),connection:DUe})]);function aRr(e){if(e===null)return"\u2014";return e.length>sRr?`${e.slice(0,sRr-1)}\u2026`:e}function cRr(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function lRr(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function IUe(e){let t=e.connection?Upo[e.connection]:null;return t?[{type:"notice",...t}]:[]}var uRr=Po({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",section:"library",query:RUe,data:$po,actions:[_Ue,Wue,PUe],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:[...IUe(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],lRr(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...IUe(e),{type:"notice",tone:"warn",text:e.message},lRr(e.startUrl,"Connect LinkedIn again"),{type:"action",action:Wue,input:{}}]};let t=e.fields.some((r)=>r.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:_Ue,input:{}}}:{},blocks:[...IUe(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((r)=>({id:r.field,cells:{field:dRr[r.field],current:aRr(r.current),imported:aRr(r.imported),outcome:zpo[r.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:PUe,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:Wue,input:{}}]}}});function TUe(e){if(e?.permission!=="admin"||!e.isAnchor)throw new br("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function Gpo(e){if(e instanceof Gue&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${fe(e)}`}async function pRr(e,t){if(!e.isAvailable())return;let r=async(n)=>{let o=await t.connections.get(TUe(n));if(!o||wUe(o))throw new br("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},i=e.source({definition:uRr,bind:(n)=>uRr.bind(n,{load:async({caller:o,query:s})=>{let a=TUe(o),{connection:c}=s.get(RUe),u=await t.connections.get(a);if(!u||wUe(u))return{status:"disconnected",expired:u!==null,startUrl:t.startUrl,connection:c};try{return{status:"ready",fields:(await t.profileImport.preview(u.accessToken)).fields,connection:c}}catch(d){return{status:"unavailable",message:Gpo(d),startUrl:t.startUrl,connection:c}}},actions:[_Ue.bind(n,async({caller:o})=>t.profileImport.apply((await r(o)).accessToken),async({caller:o})=>{let s=await t.profileImport.preview((await r(o)).accessToken),a=(d)=>s.fields.filter((p)=>p.outcome===d).map((p)=>dRr[p.field].toLowerCase()),c=a("fill"),u=a("preserve");if(c.length===0)throw new br("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${cRr(c)} from LinkedIn?${u.length>0?` Your ${cRr(u)} stay as you wrote them.`:""}`,revision:s.revision}}),PUe.bind(n,async({caller:o})=>{let s=await oRr(t.clientFor((await r(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),Wue.bind(n,async({caller:o})=>(await t.connections.forget(TUe(o)),{disconnected:!0}))]})});return e.register({...i,accessHandler:async(n)=>n.isAnchor&&await i.accessHandler(n)})}var mRr={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.822",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 Wpo="/studio",Zpo=l.object({clientId:l.string().trim().min(1).describe("LinkedIn app client ID"),clientSecret:l.string().trim().min(1).describe("LinkedIn app client secret"),redirectUri:l.url({protocol:/^https?$/}).describe(`This brain's callback URL ending at ${H$}, registered with the LinkedIn app`)}),Vpo=l.object({url:l.url({protocol:/^https$/}).describe("The managed broker's origin"),instanceId:l.string().trim().min(1).describe("This brain's broker instance"),secret:l.string().min(32).describe("This brain's broker instance secret"),returnUri:l.url({protocol:/^https?$/}).describe(`This brain's return URL ending at ${W$}, registered with the broker`)}),hRr=l.object({oauth:Zpo.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:Vpo.optional().describe("The managed broker holding the shared LinkedIn app")});function Kpo(e,t){let{oauth:r,broker:i}=e;if(r&&i)throw Error("linkedin-import: configure either oauth (direct) or broker, not both");if(r&&new URL(r.redirectUri).pathname!==H$)throw Error(`linkedin-import: oauth.redirectUri must end at ${H$}`);if(i&&new URL(i.returnUri).pathname!==W$)throw Error(`linkedin-import: broker.returnUri must end at ${W$}`);if(r)return{kind:"direct",oauth:new U$(r,t.fetch)};if(i)return{kind:"broker",broker:new kUe(i,t.fetch)};return null}function fRr(e={}){let t=zt({id:"linkedin-import",config:hRr,setup:(r)=>{let{config:i}=r,n=Kpo(i,e),o=i.oauth?.redirectUri??i.broker?.returnUri;if(!n||!o)return{routes:[]};let s=bt(r),a=new AUe(s.accountSettings,{pluginId:s.pluginId,packageName:mRr.name}),c=Wpo;return s.registered(async()=>{let u=await pRr(s.studio,{profileImport:new BUe(s.messaging,e.fetch),clientFor:(d)=>new j$(d,e.fetch),connections:a,startUrl:new URL(CUe,o).toString()});if(u)c=u}),{routes:tRr({mode:n,states:VPr(),connections:a,resolveSession:async(u)=>s.auth()?.resolveSession(u),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return ko(t,({state:r})=>r.routes)}var FUe=fRr();import{createHash as Ypo,timingSafeEqual as Jpo}from"crypto";function xRr(e){return Ypo("sha256").update(e).digest()}function Qpo(e){if(!e?.startsWith("Basic "))return null;let t=Buffer.from(e.slice(6),"base64").toString("utf8"),r=t.indexOf(":");if(r<=0||r===t.length-1)return null;return{id:t.slice(0,r),secret:t.slice(r+1)}}class MUe{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:xRr(t.secret)}]))}authenticate(e){let t=Qpo(e.headers.get("authorization")),r=t?this.instances.get(t.id):void 0;if(!t||!r)return null;return Jpo(xRr(t.secret),r.secretHash)?{id:r.id,returnUris:r.returnUris}:null}}var Xpo=10,emo=600000,NUe={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function C8(e,t=200){return Response.json(e,{status:t,headers:NUe})}function gRr(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...NUe,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function yRr(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function Zue(e,t){let r=new URL(e.returnUri);return r.searchParams.set("provider",e.provider),r.searchParams.set("state",e.brainState),Object.entries(t).forEach(([i,n])=>r.searchParams.set(i,n)),new Response(null,{status:303,headers:{...NUe,Location:r.toString()}})}function vRr(e){let t=new Map(e.providers.map((c)=>[c.id,c])),r=new Map,i=(c)=>{let u=e.now(),d=(r.get(c)??[]).filter((m)=>m>u-emo),p=d.length<Xpo;return r.set(c,p?[...d,u]:d),p},n=(c)=>new URL(OUe(c),e.publicUrl).toString(),o=async(c)=>{let u=e.instances.authenticate(c);if(!u)return gRr();let d=bRr.safeParse(await yRr(c));if(!d.success)return C8({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=u.returnUris[d.data.provider];if(!p||!m)return C8({error:"Provider is unavailable for this instance"},400);if(!i(u.id))return C8({error:"Too many connections started; try later"},429);let h=e.authorizations.issue({provider:p.id,instanceId:u.id,returnUri:m,brainState:d.data.brainState}),f=p.authorizationUrl({redirectUri:n(p.id),state:h}).toString();return C8({authorizationUrl:f})},s=async(c)=>{let u=e.instances.authenticate(c);if(!u)return gRr();let d=ERr.safeParse(await yRr(c));if(!d.success)return C8({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,m=e.grants.take(d.data.grant,(h)=>h.provider===p&&h.instanceId===u.id);if(!m)return C8({error:"Invalid or expired grant"},400);return C8({provider:p,credential:m.credential})},a=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=e.authorizations.take(d.get("state")??"",(h)=>h.provider===c.id);if(!p)return C8({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return Zue(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return Zue(p,{error:"authorization_incomplete"});try{let h=await c.exchange({code:m,redirectUri:n(c.id)}),f=e.grants.issue({provider:c.id,instanceId:p.instanceId,credential:h});return Zue(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${fe(h)}`),Zue(p,{error:"credential_exchange_failed"})}};return[{path:WT.authorizations,method:"POST",public:!0,handler:o},{path:WT.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:OUe(c.id),method:"GET",public:!0,handler:a(c)}))]}var tmo=600000,rmo=120000,ARr=1000,imo=l.object({clientId:l.string().trim().min(1),clientSecret:l.string().trim().min(1)}),nmo=l.object({id:l.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/),secret:l.string().min(32).describe("Revocable instance secret"),returnUris:l.record(LUe,l.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),wRr=l.object({publicUrl:l.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:l.record(LUe,imo).default({}).describe("Per provider, the shared app the broker holds"),instances:l.array(nmo).default([])});function omo(e,t){return Object.entries(e.providers).map(([r,i])=>{let n=t.providers[r];if(!n)throw Error(`oauth-broker: no adapter for provider "${r}"`);let o=n(i);if(o.id!==r)throw Error(`oauth-broker: adapter for "${r}" reports provider "${o.id}"`);return o})}function jUe(e){let t=zt({id:"oauth-broker",config:wRr,setup:(r)=>{let{config:i}=r,n=omo(i,e);if(i.instances.length===0||n.length===0)return{routes:[]};return{routes:vRr({publicUrl:i.publicUrl,providers:n,instances:new MUe(i.instances),authorizations:new z$({ttlMs:tmo,maxPending:ARr,now:e.now}),grants:new z$({ttlMs:rmo,maxPending:ARr,now:e.now}),now:e.now??Date.now,logger:bt(r).logger})}}});return ko(t,({state:r})=>r.routes)}var smo=2592000000,Z$=(e,t)=>Ht(`${e}
|
|
9607
|
+
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var xpo="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.",HT=Vi(Hfe(dt({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:jue,markdown:zue,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:xpo,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:gUe(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:vUe},generation:yUe,create:{fromUpload:NPr},jobs:{"upload-import":OPr(()=>HT)},evals:{generateNote:async(e,{ai:t})=>t.generate({template:"generation",prompt:l.object({prompt:l.string()}).parse(e).prompt,representedIdentity:"none"},l.object({title:l.string(),body:l.string()}))},atproto:xUe}),[Gfe(que,async({request:e,entities:t})=>{let{id:r,title:i,body:n}=e;if(await t.get(HT,r))return{noteId:r,created:!1};return await t.create(HT,{id:r,content:n,metadata:{title:i,titleStated:!0},visibility:"restricted"}),{noteId:r,created:!0}})]),GT);var gpo=Pi({id:"note",config:fUe,entities:[HT]}),jPr=gpo;var ypo=l.object({type:l.literal("email"),address:l.string().max(0).optional()}).transform(()=>{return}),bpo=l.looseObject({defaultRecipient:ypo.or(zPr).optional()}),Epo=zt({id:"notifications",config:bpo},{subscriptions:(e)=>{let{config:t}=e,r=bt(e),{logger:i}=r;return r.answer(h3,async({request:n})=>{let o=n.recipient??t.defaultRecipient;if(!o)return i.warn($ue.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=r.deliveryProvider(o.type);if(!s||!await s.isAvailable())return i.warn($ue.transportMissing,{channelType:o.type}),{status:"failed",failure:"transport-missing"};let a=await s.send({recipient:o.address,subject:n.title,text:n.body,...n.html?{html:n.html}:{},...n.replyTo?{replyTo:n.replyTo}:{},sensitivity:n.sensitivity,idempotencyKey:n.idempotencyKey??crypto.randomUUID()});if(a.status!=="sent"){i.warn($ue.deliveryFailed,{transportCode:a.failureCode});let c=UPr.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}),[]}}),qPr=Epo;var GPr=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],vpo=l.looseObject({elements:l.array(l.looseObject({snapshotDomain:l.string(),snapshotData:l.array(l.record(l.string(),l.unknown()))})),paging:l.looseObject({links:l.array(l.looseObject({rel:l.string().optional(),href:l.string().optional()})).optional()}).optional()}),Apo="https://api.linkedin.com/rest",wpo="202312",$Pr=1000,Spo=1000;function kpo(e){return e.toLowerCase().includes("no data found for this memberid")}function Bpo(e,t){let r=e.paging?.links?.find((n)=>n.rel==="next")?.href,i=r?Number(new URL(r,"https://api.linkedin.com").searchParams.get("start")):Number.NaN;return Number.isInteger(i)&&i>t?i:t+1}class j${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,r){if(r===$Pr)throw Error(`LinkedIn snapshot exceeded ${$Pr} pages`);let i=await this.fetchPage(e,t),n=(i?.elements??[]).filter((o)=>o.snapshotDomain===e).flatMap((o)=>o.snapshotData);if(!i||n.length===0)return n;return[...n,...await this.fetchPages(e,Bpo(i,t),r+1)]}async fetchPage(e,t){let r=new URL(`${Apo}/memberSnapshotData`);r.searchParams.set("q","criteria"),r.searchParams.set("domain",e),r.searchParams.set("start",String(t));let i=await this.fetchFn(r,{headers:{Authorization:`Bearer ${this.accessToken}`,"Linkedin-Version":wpo}});if(i.ok)return vpo.parse(await i.json());let n=await i.text();if(i.status<500&&kpo(n))return null;throw new Gue(i.status,n.slice(0,Spo))}}class Gue extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var Cpo=HPr({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:l.object({accessToken:l.string().trim().min(1),expiresAt:l.iso.datetime().optional()}),fields:{accessToken:{label:"Access token",secret:!0},expiresAt:{label:"Expires (ISO date and time)"}}});class AUe{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:Cpo})}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 wUe(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var Dpo="https://www.linkedin.com/oauth/v2/authorization",Ipo="https://www.linkedin.com/oauth/v2/accessToken",WPr="r_dma_portability_3rd_party",Tpo=500,_po=l.looseObject({access_token:l.string().min(1),expires_in:l.number().int().positive(),scope:l.string().optional()}),Ppo=l.looseObject({error:l.string().optional(),error_description:l.string().optional()});async function Rpo(e){try{return await e.json()}catch{return null}}class U${config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(Dpo);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",WPr),t}async exchange(e,t){let r=await this.fetchFn(Ipo,{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()}),i=await Rpo(r);if(!r.ok){let o=Ppo.safeParse(i),s=o.success?[o.data.error,o.data.error_description].filter(Boolean).join(": "):"";throw Error(`LinkedIn refused the code (${r.status})${s?`: ${s.slice(0,Tpo)}`:""}`)}let n=_po.parse(i);if(n.scope!==void 0&&n.scope!==WPr)throw Error("LinkedIn granted a token without the portability scope");return{accessToken:n.access_token,expiresAt:new Date(t+n.expires_in*1000).toISOString()}}}function VPr(e){return new z$({...ZPr,now:e})}var Hue="linkedin",Fpo=l.strictObject({accessToken:l.string().min(1),expiresAt:l.iso.datetime()});function SUe(e,t={}){let r=(n)=>new U$({...e,redirectUri:n},t.fetch),i=t.now??Date.now;return{id:Hue,authorizationUrl:({redirectUri:n,state:o})=>r(n).authorizationUrl(o),exchange:async({code:n,redirectUri:o})=>{let s=await r(o).exchange(n,i());return{accessToken:s.accessToken,expiresAt:s.expiresAt}}}}class kUe{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(WT.authorizations,{provider:Hue,brainState:e},"the connection");return new URL(KPr.parse(t).authorizationUrl)}async redeem(e){let t=YPr.parse(await this.post(WT.redeem,{provider:Hue,grant:e},"grant redemption"));if(t.provider!==Hue)throw Error("OAuth broker redeemed a grant for another provider");return Fpo.parse(t.credential)}async post(e,t,r){let{instanceId:i,secret:n}=this.config,o=await this.fetchFn(new URL(e,this.config.url),{method:"POST",headers:{Accept:"application/json",Authorization:`Basic ${Buffer.from(`${i}:${n}`).toString("base64")}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)throw Error(`OAuth broker refused ${r} (${o.status})`);return o.json()}}function Mpo(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function MB(e,t){return e.map((r)=>Mpo(r[t])).find(Boolean)}function JPr(e){let t=[MB(e,"First Name"),MB(e,"Last Name")].filter(Boolean).join(" ")||void 0,r=MB(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],i={name:t,headline:MB(e,"Headline"),industry:MB(e,"Industry"),location:MB(e,"Geo Location"),website:r,story:MB(e,"Summary")};return Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))}function QPr(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new br(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new br("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class BUe{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:r}=await this.previewFields(t);return QPr(await this.messaging.request($$,{fields:t,revision:r}))}async previewFields(e){return QPr(await this.messaging.request(q$,{fields:e}))}async imported(e){let t=new j$(e,this.fetchFn);return JPr(await t.fetchProfile())}}var CUe="/linkedin/oauth/start",H$="/linkedin/oauth/callback",W$="/linkedin/oauth/broker/return";function XPr(e){return e?.permissionLevel==="admin"&&e.isAnchor}function G$(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function tRr(e){let t=(c)=>{let u=e.workspaceUrl(),d=u.includes("?")?"&":"?";return G$(303,`${u}${d}connection=${c}`)},r=async(c,u)=>{let d=e.states.take(u),p=await e.resolveSession(c);return d&&XPr(p)&&p?.userId===d?d:null},i=async(c,u)=>{try{return await e.connections.save(c,await u()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${fe(d)}`),t("failed")}},n=async(c)=>{let u=await e.resolveSession(c);if(!u)return G$(401);if(!XPr(u))return G$(403);let d=e.states.issue(u.userId),{mode:p}=e;if(p.kind==="direct")return G$(302,p.oauth.authorizationUrl(d).toString());try{return G$(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${fe(m)}`),t("failed")}},o=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=await r(u,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 i(p,()=>c.exchange(m,e.now()))},s=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=await r(u,d.get("state")??""),m=eRr.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 i(p,()=>c.redeem(h))},{mode:a}=e;return[{path:CUe,method:"GET",public:!0,handler:n},a.kind==="direct"?{path:H$,method:"GET",public:!0,handler:o(a.oauth)}:{path:W$,method:"GET",public:!0,handler:s(a.broker)}]}var Opo=/^(?: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,Npo=[[/^$/,"<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>"],[Opo,"<month-year>"]];function nRr(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 rRr(e){if(typeof e!=="string")return`<${nRr(e)}>`;let t=e.trim();return Npo.find(([r])=>r.test(t))?.[1]??"<string>"}function Lpo(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(rRr))].sort();return rRr(e)}function iRr([e],[t]){return e.localeCompare(t)}function jpo(e){let t=e.flatMap((o)=>Object.entries(o)),i=[...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])=>nRr(a)))].sort(),presentCount:s.length}}),n=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(iRr).map(([a,c])=>[a,Lpo(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:i,recordShapes:[...n].sort(iRr).map(([,o])=>o)}}async function oRr(e){let t=await Promise.all(GPr.map(async(r)=>[r,jpo(await e.fetchDomain(r))]));return Object.fromEntries(t)}var dRr={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},zpo={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},Upo={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."}},sRr=200,_Ue=Vr({name:"import-profile",label:"Import from LinkedIn",permission:"admin",confirmation:{kind:"prepared"},input:l.object({}),output:l.object({filled:l.array(l.string()),kept:l.array(l.string())})}),Wue=Vr({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:l.object({}),output:l.object({disconnected:l.boolean()})}),PUe=Vr({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:l.object({}),output:l.object({shapes:l.string()})}),RUe=l.object({connection:l.enum(["connected","declined","failed"]).optional()}),qpo=l.object({field:l.enum(["name","headline","industry","location","website","story"]),current:l.string().nullable(),imported:l.string(),outcome:l.enum(["fill","preserve","unchanged"])}),DUe=RUe.shape.connection,$po=l.discriminatedUnion("status",[l.object({status:l.literal("disconnected"),expired:l.boolean(),startUrl:l.string(),connection:DUe}),l.object({status:l.literal("unavailable"),message:l.string(),startUrl:l.string(),connection:DUe}),l.object({status:l.literal("ready"),fields:l.array(qpo),connection:DUe})]);function aRr(e){if(e===null)return"\u2014";return e.length>sRr?`${e.slice(0,sRr-1)}\u2026`:e}function cRr(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function lRr(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function IUe(e){let t=e.connection?Upo[e.connection]:null;return t?[{type:"notice",...t}]:[]}var uRr=Po({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",section:"library",query:RUe,data:$po,actions:[_Ue,Wue,PUe],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:[...IUe(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],lRr(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...IUe(e),{type:"notice",tone:"warn",text:e.message},lRr(e.startUrl,"Connect LinkedIn again"),{type:"action",action:Wue,input:{}}]};let t=e.fields.some((r)=>r.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:_Ue,input:{}}}:{},blocks:[...IUe(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((r)=>({id:r.field,cells:{field:dRr[r.field],current:aRr(r.current),imported:aRr(r.imported),outcome:zpo[r.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:PUe,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:Wue,input:{}}]}}});function TUe(e){if(e?.permission!=="admin"||!e.isAnchor)throw new br("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function Gpo(e){if(e instanceof Gue&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${fe(e)}`}async function pRr(e,t){if(!e.isAvailable())return;let r=async(n)=>{let o=await t.connections.get(TUe(n));if(!o||wUe(o))throw new br("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},i=e.source({definition:uRr,bind:(n)=>uRr.bind(n,{load:async({caller:o,query:s})=>{let a=TUe(o),{connection:c}=s.get(RUe),u=await t.connections.get(a);if(!u||wUe(u))return{status:"disconnected",expired:u!==null,startUrl:t.startUrl,connection:c};try{return{status:"ready",fields:(await t.profileImport.preview(u.accessToken)).fields,connection:c}}catch(d){return{status:"unavailable",message:Gpo(d),startUrl:t.startUrl,connection:c}}},actions:[_Ue.bind(n,async({caller:o})=>t.profileImport.apply((await r(o)).accessToken),async({caller:o})=>{let s=await t.profileImport.preview((await r(o)).accessToken),a=(d)=>s.fields.filter((p)=>p.outcome===d).map((p)=>dRr[p.field].toLowerCase()),c=a("fill"),u=a("preserve");if(c.length===0)throw new br("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${cRr(c)} from LinkedIn?${u.length>0?` Your ${cRr(u)} stay as you wrote them.`:""}`,revision:s.revision}}),PUe.bind(n,async({caller:o})=>{let s=await oRr(t.clientFor((await r(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),Wue.bind(n,async({caller:o})=>(await t.connections.forget(TUe(o)),{disconnected:!0}))]})});return e.register({...i,accessHandler:async(n)=>n.isAnchor&&await i.accessHandler(n)})}var mRr={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.823",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 Wpo="/studio",Zpo=l.object({clientId:l.string().trim().min(1).describe("LinkedIn app client ID"),clientSecret:l.string().trim().min(1).describe("LinkedIn app client secret"),redirectUri:l.url({protocol:/^https?$/}).describe(`This brain's callback URL ending at ${H$}, registered with the LinkedIn app`)}),Vpo=l.object({url:l.url({protocol:/^https$/}).describe("The managed broker's origin"),instanceId:l.string().trim().min(1).describe("This brain's broker instance"),secret:l.string().min(32).describe("This brain's broker instance secret"),returnUri:l.url({protocol:/^https?$/}).describe(`This brain's return URL ending at ${W$}, registered with the broker`)}),hRr=l.object({oauth:Zpo.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:Vpo.optional().describe("The managed broker holding the shared LinkedIn app")});function Kpo(e,t){let{oauth:r,broker:i}=e;if(r&&i)throw Error("linkedin-import: configure either oauth (direct) or broker, not both");if(r&&new URL(r.redirectUri).pathname!==H$)throw Error(`linkedin-import: oauth.redirectUri must end at ${H$}`);if(i&&new URL(i.returnUri).pathname!==W$)throw Error(`linkedin-import: broker.returnUri must end at ${W$}`);if(r)return{kind:"direct",oauth:new U$(r,t.fetch)};if(i)return{kind:"broker",broker:new kUe(i,t.fetch)};return null}function fRr(e={}){let t=zt({id:"linkedin-import",config:hRr,setup:(r)=>{let{config:i}=r,n=Kpo(i,e),o=i.oauth?.redirectUri??i.broker?.returnUri;if(!n||!o)return{routes:[]};let s=bt(r),a=new AUe(s.accountSettings,{pluginId:s.pluginId,packageName:mRr.name}),c=Wpo;return s.registered(async()=>{let u=await pRr(s.studio,{profileImport:new BUe(s.messaging,e.fetch),clientFor:(d)=>new j$(d,e.fetch),connections:a,startUrl:new URL(CUe,o).toString()});if(u)c=u}),{routes:tRr({mode:n,states:VPr(),connections:a,resolveSession:async(u)=>s.auth()?.resolveSession(u),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return ko(t,({state:r})=>r.routes)}var FUe=fRr();import{createHash as Ypo,timingSafeEqual as Jpo}from"crypto";function xRr(e){return Ypo("sha256").update(e).digest()}function Qpo(e){if(!e?.startsWith("Basic "))return null;let t=Buffer.from(e.slice(6),"base64").toString("utf8"),r=t.indexOf(":");if(r<=0||r===t.length-1)return null;return{id:t.slice(0,r),secret:t.slice(r+1)}}class MUe{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:xRr(t.secret)}]))}authenticate(e){let t=Qpo(e.headers.get("authorization")),r=t?this.instances.get(t.id):void 0;if(!t||!r)return null;return Jpo(xRr(t.secret),r.secretHash)?{id:r.id,returnUris:r.returnUris}:null}}var Xpo=10,emo=600000,NUe={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function C8(e,t=200){return Response.json(e,{status:t,headers:NUe})}function gRr(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...NUe,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function yRr(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function Zue(e,t){let r=new URL(e.returnUri);return r.searchParams.set("provider",e.provider),r.searchParams.set("state",e.brainState),Object.entries(t).forEach(([i,n])=>r.searchParams.set(i,n)),new Response(null,{status:303,headers:{...NUe,Location:r.toString()}})}function vRr(e){let t=new Map(e.providers.map((c)=>[c.id,c])),r=new Map,i=(c)=>{let u=e.now(),d=(r.get(c)??[]).filter((m)=>m>u-emo),p=d.length<Xpo;return r.set(c,p?[...d,u]:d),p},n=(c)=>new URL(OUe(c),e.publicUrl).toString(),o=async(c)=>{let u=e.instances.authenticate(c);if(!u)return gRr();let d=bRr.safeParse(await yRr(c));if(!d.success)return C8({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=u.returnUris[d.data.provider];if(!p||!m)return C8({error:"Provider is unavailable for this instance"},400);if(!i(u.id))return C8({error:"Too many connections started; try later"},429);let h=e.authorizations.issue({provider:p.id,instanceId:u.id,returnUri:m,brainState:d.data.brainState}),f=p.authorizationUrl({redirectUri:n(p.id),state:h}).toString();return C8({authorizationUrl:f})},s=async(c)=>{let u=e.instances.authenticate(c);if(!u)return gRr();let d=ERr.safeParse(await yRr(c));if(!d.success)return C8({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,m=e.grants.take(d.data.grant,(h)=>h.provider===p&&h.instanceId===u.id);if(!m)return C8({error:"Invalid or expired grant"},400);return C8({provider:p,credential:m.credential})},a=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=e.authorizations.take(d.get("state")??"",(h)=>h.provider===c.id);if(!p)return C8({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return Zue(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return Zue(p,{error:"authorization_incomplete"});try{let h=await c.exchange({code:m,redirectUri:n(c.id)}),f=e.grants.issue({provider:c.id,instanceId:p.instanceId,credential:h});return Zue(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${fe(h)}`),Zue(p,{error:"credential_exchange_failed"})}};return[{path:WT.authorizations,method:"POST",public:!0,handler:o},{path:WT.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:OUe(c.id),method:"GET",public:!0,handler:a(c)}))]}var tmo=600000,rmo=120000,ARr=1000,imo=l.object({clientId:l.string().trim().min(1),clientSecret:l.string().trim().min(1)}),nmo=l.object({id:l.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/),secret:l.string().min(32).describe("Revocable instance secret"),returnUris:l.record(LUe,l.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),wRr=l.object({publicUrl:l.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:l.record(LUe,imo).default({}).describe("Per provider, the shared app the broker holds"),instances:l.array(nmo).default([])});function omo(e,t){return Object.entries(e.providers).map(([r,i])=>{let n=t.providers[r];if(!n)throw Error(`oauth-broker: no adapter for provider "${r}"`);let o=n(i);if(o.id!==r)throw Error(`oauth-broker: adapter for "${r}" reports provider "${o.id}"`);return o})}function jUe(e){let t=zt({id:"oauth-broker",config:wRr,setup:(r)=>{let{config:i}=r,n=omo(i,e);if(i.instances.length===0||n.length===0)return{routes:[]};return{routes:vRr({publicUrl:i.publicUrl,providers:n,instances:new MUe(i.instances),authorizations:new z$({ttlMs:tmo,maxPending:ARr,now:e.now}),grants:new z$({ttlMs:rmo,maxPending:ARr,now:e.now}),now:e.now??Date.now,logger:bt(r).logger})}}});return ko(t,({state:r})=>r.routes)}var smo=2592000000,Z$=(e,t)=>Ht(`${e}
|
|
9604
9608
|
${t}`);function SRr(e,t){let r=(i)=>i!==void 0&&t()-i.usedAt<smo;return{get:async(i,n)=>{let o=await e.get(Z$(i,n));return r(o)?{hash:o.hash,...o.conflictEdit!==void 0&&{conflictEdit:o.conflictEdit},...o.conflictId!==void 0&&{conflictId:o.conflictId}}:void 0},held:async(i,n,o)=>{await e.set(Z$(i,n),{hash:o,usedAt:t()})},conflictKept:async(i,n,o,s)=>{let a=await e.get(Z$(i,n));if(!r(a))return;await e.set(Z$(i,n),{hash:a.hash,conflictEdit:o,...s!==void 0&&{conflictId:s},usedAt:t()})},forget:async(i,n)=>{await e.delete(Z$(i,n))},sweep:async()=>{let i=(await e.keys()).filter(({value:n})=>!r(n));await Promise.all(i.map(({key:n})=>e.delete(n)))}}}function kRr(e=Date.now){let t=new Map;return SRr({get:async(r)=>t.get(r),set:async(r,i)=>{t.set(r,i)},delete:async(r)=>{t.delete(r)},keys:async()=>[...t].map(([r,i])=>({key:r,value:i}))},e)}var amo="webdav.mount-base",cmo=l.object({hash:l.string().min(1),conflictEdit:l.string().min(1).optional(),conflictId:l.string().min(1).optional(),usedAt:l.number()});function BRr(e,t=Date.now){let r=e.scoped({namespace:amo,schema:cmo});return SRr({get:async(i)=>await r.get(i)??void 0,set:async(i,n)=>{await r.set(i,n)},delete:async(i)=>{await r.delete(i)},keys:()=>r.list()},t)}var lmo=new Set([".obsidian"]),CRr=33554432;function OB(e){let[t]=e;return t!==void 0&&lmo.has(t)}function DRr(){let e=new Map,t=(r)=>{let i=e.get(r)??new Map;return e.set(r,i),i};return{load:async(r)=>[...t(r).values()],put:async(r,i)=>{t(r).set(i.path,i)},remove:async(r,i)=>{i.forEach((n)=>t(r).delete(n))}}}var umo="webdav.kept",dmo=l.object({path:l.string().min(1),bytes:l.string().optional(),modified:l.number()});function IRr(e){let t=e.scoped({namespace:umo,schema:dmo}),r=(n)=>`${Ht(n)}/`,i=(n,o)=>`${r(n)}${Ht(o)}`;return{load:async(n)=>(await t.list({keyPrefix:r(n)})).map(({value:o})=>({path:o.path,modified:o.modified,...o.bytes!==void 0&&{bytes:new Uint8Array(Buffer.from(o.bytes,"base64"))}})),put:async(n,o)=>{await t.set(i(n,o.path),{path:o.path,modified:o.modified,...o.bytes!==void 0&&{bytes:Buffer.from(o.bytes).toString("base64")}})},remove:async(n,o)=>{await Promise.all(o.map((s)=>t.delete(i(n,s))))}}}import{randomUUID as pmo}from"crypto";var mmo=500;class zUe{run=pmo().slice(0,8);keep;sequence=0;recent=[];waiting=new Set;closed=!1;constructor(e={}){this.keep=e.keep??mmo}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 r of t)r()}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,r]=e.split(":"),i=Number(r),n=this.recent[0]?.sequence??this.sequence+1;if(t!==this.run||!Number.isInteger(i)||i>this.sequence||i<n-1)return{cursor:this.cursor(),reset:!0};return{cursor:this.cursor(),types:[...new Set(this.recent.filter((o)=>o.sequence>i).map((o)=>o.type))]}}async wait(e,t,r){let i=this.since(e);if("reset"in i||i.types.length>0||e===null)return i;if(t<=0||this.closed)return i;return await new Promise((n)=>{let o=()=>{clearTimeout(s),this.waiting.delete(o),r?.removeEventListener("abort",o),n()},s=setTimeout(o,t);this.waiting.add(o),r?.addEventListener("abort",o,{once:!0})}),this.since(e)}}var _Rr="obsidian",PRr="Obsidian",hmo=1024,fmo="Your brain could not answer this.",xmo=l.object({question:l.string().min(1).max(8000),conversation:l.string().min(1).max(Vue).optional(),path:l.string().min(1).max(hmo).optional()}),gmo=l.object({conversation:l.string().min(1).max(Vue),approval:l.string().min(1).max(Vue),confirmed:l.boolean()});function RRr(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 ymo(e,t){let r=await e.entityAt(t.split("/"));if(!r)return;let i=await r.file.open();if(typeof i!=="string")return;let n=r.entity.metadata.title;return{entityType:r.entity.entityType,id:r.entity.id,title:typeof n==="string"&&n!==""?n:r.entity.id,content:i.slice(0,TRr)}}async function FRr(e,t,r){let i=(r.cards??[]).flatMap((a)=>a.kind==="sources"?a.sources:[]),n=await Promise.all(i.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=(r.pendingConfirmations??[]).map(({id:a,summary:c,preview:u})=>({id:a,summary:c,...u!==void 0&&{preview:u}})),s={conversation:t,text:r.text,...r.error!==void 0&&{error:fmo},sources:n,confirmations:o};return new Response(JSON.stringify(s),{status:200,headers:{"Content-Type":"application/json; charset=utf-8"}})}var MRr=()=>new Response("Nothing answers questions here right now.",{status:503});async function ORr(e,t){let r=xmo.safeParse(t);if(!r.success)return new Response('Ask with { "question": "\u2026" }',{status:400});let{question:i,conversation:n,path:o}=r.data,s=o===void 0?void 0:await ymo(e.tree,o),a=await e.ask?.({asker:RRr(e.grant),interfaceType:_Rr,channelName:PRr,question:i,...n!==void 0&&{conversationId:n},...s!==void 0&&{entry:s}});if(!a)return MRr();if("message"in a)return new Response(a.message,{status:409});return FRr(e.tree,a.conversationId,a.response)}async function NRr(e,t){let r=gmo.safeParse(t);if(!r.success)return new Response('Answer with { "conversation": "\u2026", "approval": "\u2026", "confirmed": true }',{status:400});let{conversation:i,approval:n,confirmed:o}=r.data,s=await e.confirmAsk?.({asker:RRr(e.grant),interfaceType:_Rr,channelName:PRr,conversationId:i,approvalId:n,confirmed:o});if(!s)return MRr();if("message"in s)return new Response(s.message,{status:409});return FRr(e.tree,i,s.response)}import{createHash as wmo}from"crypto";import{posix as Smo}from"path";var bmo="conflict",V$="note",Emo=100,jRr=new Set(["image","document"]);function qUe(e){return jRr.has(e)}var vmo={".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"};class $Ue{reader;scope;containment;everyType;constructor(e,t,r={}){this.reader=e,this.scope=t,this.containment=Dy(e),this.everyType=r.everyType??!1}async resolve(e){if(e.length===0)return{kind:"folder",segments:e};if(!e.every(UUe))return;let t=await this.entityAt(e);if(t)return t.file;let[r]=e;if(this.everyType&&e.length===1&&r!==void 0&&this.isFolderType(r))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:r}=e.length===0?await this.rootChildren():await this.typeFolderChildren(e);return[...[...new Set(t)].sort(LRr).map((i)=>({kind:"folder",segments:[...e,i]})),...r.sort((i,n)=>LRr(i.segments.join("/"),n.segments.join("/")))]}async rootChildren(){let e=new Map((await this.reader.getEntityCounts(this.scope)).map((i)=>[i.entityType,i.count])),t=this.reader.getEntityTypes().filter((i)=>this.isFolderType(i)&&(this.everyType||[i,this.containedIn(i)].some((n)=>n!==void 0&&(e.get(n)??0)>0))),r=this.reader.getEntityTypes().includes(V$)?(await this.hierarchy(V$,[])).entities:[];return{folders:t,files:await this.filesIn([],r)}}async typeFolderChildren(e){let[t,...r]=e;if(t===void 0||!this.isFolderType(t))return{folders:[],files:[]};let i=await Promise.all([t,this.containedIn(t)].filter((n)=>n!==void 0).map((n)=>this.hierarchy(n,r)));return{folders:i.flatMap((n)=>n.folders),files:await this.filesIn(e,i.flatMap((n)=>n.entities))}}async hierarchy(e,t,r=0){let[i,...n]=t,o=await this.reader.queryEntityHierarchy({entityType:e,prefix:i===void 0?null:[i,...n],visibilityScope:this.scope,limit:Emo,offset:r,source:!0}),s=o.entities.map((u)=>u.entity),a=r+s.length,c=s.length>0&&a<o.totalEntities?(await this.hierarchy(e,t,a)).entities:[];return{folders:o.folders.map((u)=>u.name),entities:[...s,...c]}}async filesIn(e,t){return(await Promise.all(t.map((i)=>this.fileOf(i)))).filter((i)=>i!==void 0).filter((i)=>i.segments.length===e.length+1&&e.every((n,o)=>i.segments[o]===n))}async related(e,t){let r=await this.entityAt(e);if(!r)return;let i=await this.nearestTo(r.entity,t);if(i==="unindexed")return i;return(await Promise.all(i.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((r)=>!qUe(r)&&r!==bmo),limit:t,visibilityScope:this.scope})}catch(r){if(r instanceof U9)return"unindexed";throw r}}async pathOf(e,t){if(!this.reader.getEntityTypes().includes(e))return;let r=await this.reader.getEntityRaw({entityType:e,id:t,visibilityScope:this.scope,source:!0});return(r?await this.fileOf(r):void 0)?.segments.join("/")}async entityAt(e){if(e.length===0||!e.every(UUe))return;let{entityType:t,id:r}=V6(e.join("/"),this.containment);if(!this.reader.getEntityTypes().includes(t))return;let i=await this.reader.getEntityRaw({entityType:t,id:r,visibilityScope:this.scope,source:!0}),n=i?await this.fileOf(i):void 0;return i&&n?.segments.join("/")===e.join("/")?{entity:i,file:n}:void 0}textExtension(e){return this.reader.fileExtension(e)}placementAt(e,t){if(e.length===0||!e.every(UUe))return;let r=e.join("/"),{entityType:i,id:n}=V6(r,this.containment);if(!this.reader.getEntityTypes().includes(i))return;let o=Iy(i,n,t,this.containment);return o.writable&&o.relativePath===r?{entityType:i,id:n}:void 0}async fileOf(e){let t=t8(e,this.reader.fileExtension(e.entityType));if(!Iy(e.entityType,e.id,t,this.containment).writable)return;let i={kind:"file",segments:I7(e.id,e.entityType,t,this.containment).split("/"),contentType:vmo[t]??"application/octet-stream",etag:`"${e.contentHash}"`,modified:new Date(e.updated)};if(!jRr.has(e.entityType)||t===".md"){let a=t===".yaml"?EP(e.content):e.content;return{...i,size:Buffer.byteLength(a),open:async()=>a}}if(e.content==="")return;let n=cp.safeParse(e.content);if(n.success){let a=await this.reader.statAsset(n.data);if(!a)return;return{...i,size:a.sizeBytes,open:async()=>Amo(await this.reader.openAsset(n.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{...i,size:s.byteLength,open:async()=>s}}isFolderType(e){return e!==V$&&!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 LRr(e,t){return e<t?-1:e>t?1:0}function UUe(e){return e.length>0&&e!=="."&&e!==".."&&!/[/\\\0]/.test(e)}function Amo(e){let t=e[Symbol.asyncIterator]();return new ReadableStream({async pull(r){let i=await t.next();if(i.done)r.close();else r.enqueue(i.value)},async cancel(){await t.return?.()}})}var GRr="image",kmo="document",Bmo=".pdf",zRr="note",GUe="webdav";async function HUe(e,t){let r=Smo.extname(t.segments[t.segments.length-1]??"").toLowerCase();if(Zu.includes(r))return qRr(e,t,r,_mo);if(r===Bmo)return qRr(e,t,r,Pmo);let i=r===".yaml"?Cmo(e,t):t;if(i===void 0)return await Kue(e,t)?D8("No entry can be stored at this path"):Yue();if(r!==".md"&&r!==".yaml")return await Kue(e,i)?D8("The drive stores notes, entries, images and PDFs"):Yue();if(i.bytes.byteLength>e.writes.maxFileBytes)return KRr();let n=await e.tree.entityAt(i.segments),o=n?.entity.entityType??e.tree.placementAt(i.segments,r)?.entityType;if(o!==void 0&&qUe(o))return D8(o===GRr?"An image is stored as its image file":"A document is stored as its PDF file");return n?Dmo(e,i,n):Tmo(e,i,r)}function Cmo(e,t){let r=e.tree.placementAt(t.segments,".yaml")?.entityType;if(r===void 0||e.tree.textExtension(r)!==".yaml")return;let i=JRr(t.bytes);if(i===void 0)return t;return{...t,bytes:new Uint8Array(Buffer.from(vP(i),"utf8"))}}async function Dmo(e,t,{entity:r,file:i}){let{writes:n}=e,o=t.onlyIfAbsent===!0||!WUe(t.ifMatch,i.etag);if(o&&!t.keepAsConflict)return t.onlyIfAbsent?Jue():I8();let s=ZRr(n,t.bytes,r.entityType);if("status"in s)return s;if(Imo(n,s.parsed,r))return await e.mount.held(r.contentHash),{status:204,etag:await VRr(e,t,s.text)};let{visibility:a,...c}=s.parsed.metadata??r.metadata,u={...r,...s.parsed,id:r.id,entityType:r.entityType,content:s.text,metadata:c,visibility:s.parsed.visibility??r.visibility},d=await K$(e,t.grant,"update",u,p5(r.entityType,r,u,e.reader));if(d)return d;if(o)return URr(e,t,{existing:r,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!==r.contentHash)return URr(e,t,{existing:r,base:h,text:s.text,declared:s.parsed.visibility})}let p=await Que(()=>n.updateEntity({entity:u,options:{expectedContentHash:r.contentHash,eventContext:Y$(t.grant)}}));if(!p.ok)return YRr(p.error);if(p.value.skipReason==="content-conflict")return I8();if(!p.value.skipped)await NB(n,t.grant,"update","allowed",u);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 Imo(e,t,r){let i=VUe(()=>e.deserializeEntity(r.content,r.entityType));return i.ok&&(t.visibility??r.visibility)===r.visibility&&Bun.deepEquals(t,i.value)}async function URr(e,t,r){let{existing:i,base:n,text:o,declared:s}=r,a=Ht(o);if(n?.conflictEdit===a)return{status:204,conflictId:n.conflictId};let c=await e.recordConflict({entityType:i.entityType,entityId:i.id,origin:"drive",actor:t.grant.principal.userId,...n!==void 0&&{base:n.hash},current:i.contentHash,text:o,targetVisibility:i.visibility,...s!==void 0&&s!==i.visibility&&{declaredVisibility:s}});if(c===void 0)return I8();return await e.mount.conflictKept(a,c),{status:204,conflictId:c}}async function Tmo(e,t,r){let{writes:i,tree:n}=e,{segments:o}=t;if(!await Kue(e,t))return Yue();let s=n.placementAt(o,r);if(!s)return D8("No entry can be stored at this path");let a=ZRr(i,t.bytes,s.entityType);if("status"in a)return a;let{visibility:c,...u}=a.parsed.metadata??{},d=a.parsed.visibility??"public",p={...a.parsed,id:s.id,entityType:s.entityType,content:a.text,metadata:u,visibility:d},m=Ufe(s.entityType,void 0,u.status,e.reader)!=="non-publish",h=await K$(e,t.grant,"create",p,m?["create","publish"]:["create"]);if(h)return h;let f=await Que(()=>i.createEntity({entity:p,options:{conditionalWrite:{expectedRevision:null},eventContext:Y$(t.grant)}}));if(!f.ok)return ZUe(f.error);return await NB(i,t.grant,"create","allowed",p),{status:201,etag:await VRr(e,t,a.text)}}var _mo={entityType:GRr,noun:"image",wrongFolder:"An image can only be stored in the image folder",describe:async({bytes:e,digest:t,extension:r,existing:i})=>{let n=await F7($Rr(e));if(!n)return{status:422,message:"The file is not a PNG, JPEG, GIF or WebP image"};let o=D7(n.format);if(o!==r)return{status:422,message:`These bytes are stored as ${o}; save the image under that extension`};let s=i?.status;if(typeof s==="string"&&M7(t,s))return{status:422,message:"These bytes are the old pending placeholder, not this image's bytes"};return{metadata:{...i,...n}}}},Pmo={entityType:kmo,noun:"document",wrongFolder:"A PDF can only be stored in the document folder",describe:async({bytes:e,digest:t,name:r,existing:i})=>{if(!zae(e))return{status:422,message:"The file is not a PDF"};if(Kse(t))return{status:422,message:"These bytes are the old pending placeholder, not a document's bytes"};let{pageCount:n,status:o,processingJobId:s,processingError:a,...c}=i??{},u=Oae(e);return{metadata:{...i?c:{filename:r,attachmentType:"uploaded"},mimeType:"application/pdf",...u>0&&{pageCount:u}}}}};async function qRr(e,t,r,i){let{writes:n,tree:o}=e,{segments:s,bytes:a,grant:c}=t,u=await o.entityAt(s);if(!u&&!await Kue(e,t))return Yue();let d=u?{entityType:u.entity.entityType,id:u.entity.id}:o.placementAt(s,r);if(d?.entityType!==i.entityType)return D8(i.wrongFolder);if(a.byteLength>n.maxAssetBytes)return KRr();if(u&&t.onlyIfAbsent)return Jue();if(u&&!WUe(t.ifMatch,u.file.etag))return I8();let p=await i.describe({bytes:a,digest:wmo("sha256").update(a).digest("hex"),extension:r,name:s[s.length-1]??"",existing:u?.entity.metadata});if("status"in p)return p;let m=u?"update":"create",h={id:d.id,entityType:i.entityType,visibility:u?.entity.visibility??"public"},f=await K$(e,c,m,h,[m]);if(f)return f;if(u&&t.ifMatch===null){let R=await e.mount.base();if(R!==void 0&&R.hash!==u.entity.contentHash)return{status:409,message:`The ${i.noun} changed since this drive last read it`}}let g=await n.stageAsset(a,{maxBytes:n.maxAssetBytes,expectedSize:a.byteLength}),y={content:g.ref,metadata:{...p.metadata,sizeBytes:g.sizeBytes}},b={eventContext:Y$(c)},A=await Que(async()=>{if(u)return(await n.updateEntity({entity:{...u.entity,...y},stagedAsset:g,options:{...b,expectedContentHash:u.entity.contentHash}})).skipReason==="content-conflict"?I8():void 0;await n.createEntity({entity:{...h,...y},stagedAsset:g,options:{...b,conditionalWrite:{expectedRevision:null}}});return}),w=A.ok?A.value:ZUe(A.error);if(w)return await n.discardStagedAsset(g),w;await NB(n,c,m,"allowed",h);let B=await o.entityAt(s);if(B)await e.mount.held(B.entity.contentHash);return{status:u?204:201,etag:B?.file.etag}}async function HRr(e,t){let{writes:r,tree:i}=e,n=await i.entityAt(t.from);if(!n)return{status:404,message:"Not found"};let{entity:o}=n,s=i.placementAt(t.to,".md");if(o.entityType!==zRr||s?.entityType!==zRr)return D8("The drive renames notes only, to another note's name");if(await i.entityAt(t.to))return Jue();let a=await K$(e,t.grant,"rename",o,["update"]);if(a)return a;let c=await Que(()=>r.renameEntity({entityType:o.entityType,id:o.id,newId:s.id,options:{expectedContentHash:o.contentHash,eventContext:Y$(t.grant)}}));if(!c.ok)return ZUe(c.error);if(!c.value.renamed)return I8();return await NB(r,t.grant,"rename","allowed",o),{status:201}}async function WRr(e,t){let r=await e.tree.entityAt(t.segments);if(!r)return{status:404,message:"Not found"};let{entity:i,file:n}=r;if(!WUe(t.ifMatch,n.etag))return I8();let o=await K$(e,t.grant,"delete",i,["delete"]);if(o)return o;if(t.ifMatch===null){let a=await e.mount.base();if(a!==void 0&&a.hash!==i.contentHash)return{status:409,message:"The file changed since this drive last read it"}}if(!await e.writes.deleteEntity({entityType:i.entityType,id:i.id,options:{expectedContentHash:i.contentHash,eventContext:Y$(t.grant)}}))return I8();return await e.mount.forget(),await NB(e.writes,t.grant,"delete","allowed",i),{status:204}}function ZRr(e,t,r){let i=JRr(t);if(i===void 0)return{status:422,message:"The file is not UTF-8 text"};let n=VUe(()=>e.deserializeEntity(i,r));return n.ok?{text:i,parsed:n.value}:{status:422,message:fe(n.error,"The file cannot be read")}}async function K$(e,t,r,i,n){let o=t.principal.permissionLevel,s=VUe(()=>n.forEach((a)=>e.writes.permissions.assertEntityActionAllowed(i.entityType,a,{userPermissionLevel:o})));if(!s.ok)return await NB(e.writes,t,r,"denied",i,"entity-action-policy"),D8(fe(s.error,"Not allowed"));if(r!=="delete"&&!xm(o,i.visibility))return await NB(e.writes,t,r,"denied",i,"visibility-policy"),D8(`Cannot set visibility to "${i.visibility}" at ${o} permission`);return}function NB(e,t,r,i,n,o){return e.recordAudit({actorUserId:t.principal.userId,action:`${GUe}.entity.${r}.${i}`,targetType:"entity",targetId:n.id,metadata:{entityType:n.entityType,interfaceType:GUe,outcome:i,...o?{reason:o}:{}}})}async function VRr(e,t,r){let i=await e.tree.entityAt(t.segments);return i?.entity.content===r?i.file.etag:void 0}function Y$(e){return{actor:{kind:"user",userId:e.principal.userId},interfaceType:GUe}}function WUe(e,t){return e===null||e==="*"||e===t}function Kue(e,t){return e.folderExists(t.segments.slice(0,-1))}function Yue(){return{status:409,message:"The folder does not exist"}}function KRr(){return{status:413,message:"The file is larger than the drive accepts"}}function Jue(){return{status:412,message:"An entry already exists at this path"}}function ZUe(e){return e instanceof Error&&e.name==="EntityWriteConflictError"?Jue():YRr(e)}function D8(e){return{status:403,message:e}}function I8(){return{status:412,message:"The file changed since it was opened"}}function YRr(e){if(l5(e))return{status:422,message:fe(e,"The file cannot be saved")};throw e}function JRr(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}}function VUe(e){try{return{ok:!0,value:e()}}catch(t){return{ok:!1,error:t}}}async function Que(e){try{return{ok:!0,value:await e()}}catch(t){return{ok:!1,error:t}}}import{posix as Rmo}from"path";var Fmo=new Set([".md",".yaml",...Zu,...e8]),Mmo=600000,Omo=16777216,QRr=(e,t,r)=>!OB(e.split("/"))&&r-t>=Mmo;function XRr(e){return e.startsWith(".")||!Fmo.has(Rmo.extname(e).toLowerCase())}class KUe{files=new Map;folders=new Map;now;kept;opened=new Map;pending=Promise.resolve();constructor(e=Date.now,t=DRr()){this.now=e,this.kept=t}open(e){let t=this.opened.get(e)??this.kept.load(e).then((r)=>{r.forEach(({path:i,bytes:n,modified:o})=>{let s=i.split("/");if(n===void 0)this.foldersOf(e).set(i,o);else this.filesOf(e).set(i,{segments:s,bytes:n,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 r=this.live(e).get(t.join("/"));if(r)r.touched=this.now();return r}list(e,t){return[...this.live(e).values()].filter((r)=>r.segments.length===t.length+1&&t.every((i,n)=>r.segments[n]===i)).sort((r,i)=>r.segments.join("/")<i.segments.join("/")?-1:1)}put(e,t,r){let i=this.live(e),n=t.join("/"),o=i.get(n),s=OB(t);if([...i.values()].filter((u)=>OB(u.segments)===s).reduce((u,d)=>u+d.bytes.byteLength,0)-(o?.bytes.byteLength??0)+r.byteLength>(s?CRr:Omo))return"full";let c=this.now();if(i.set(n,{segments:t,bytes:r,modified:new Date(c),touched:c}),this.files.set(e,i),s)t.slice(0,-1).forEach((u,d)=>this.makeFolder(e,t.slice(0,d+1))),this.persist(()=>this.kept.put(e,{path:n,bytes:r,modified:c}));return o?"replaced":"created"}delete(e,t){let r=t.join("/"),i=this.live(e).delete(r);if(i&&OB(t))this.persist(()=>this.kept.remove(e,[r]));return i}hasFolder(e,t){let r=this.liveFolders(e),i=t.join("/");if(!r.has(i))return!1;return r.set(i,this.now()),!0}listFolders(e,t){let r=t.length>0?`${t.join("/")}/`:"";return[...this.liveFolders(e).keys()].filter((i)=>i.startsWith(r)&&!i.slice(r.length).includes("/")).map((i)=>i.slice(r.length)).sort()}makeFolder(e,t){let r=this.liveFolders(e),i=t.join("/"),n=r.has(i),o=this.now();if(r.set(i,o),this.folders.set(e,r),!n&&OB(t))this.persist(()=>this.kept.put(e,{path:i,modified:o}))}removeFolder(e,t){let r=t.join("/"),i=(a)=>a===r||a.startsWith(`${r}/`),n=this.liveFolders(e);if(!n.has(r))return!1;let o=this.live(e),s=[...n.keys(),...o.keys()].filter(i);if(s.forEach((a)=>{n.delete(a),o.delete(a)}),OB(t))this.persist(()=>this.kept.remove(e,s));return!0}forgetFolders(e,t){let r=this.liveFolders(e);t.forEach((i,n)=>r.delete(t.slice(0,n+1).join("/")))}rename(e,t,r){let i=this.get(e,t);if(!i)return"missing";let n=this.put(e,r,i.bytes);if(n==="full")return"missing";return this.delete(e,t),n}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,r=this.now();if([...t].forEach(([i,n])=>{if(QRr(i,n,r))t.delete(i)}),t.size===0)this.folders.delete(e);return t}live(e){let t=this.files.get(e)??new Map,r=this.now();if([...t].forEach(([i,n])=>{if(QRr(i,n.touched,r))t.delete(i)}),t.size===0)this.files.delete(e);return t}}class YUe{expected=new Map;now;constructor(e=Date.now){this.now=e}expect(e,t){let r=this.now();for(let[i,n]of this.expected)if(n<=r)this.expected.delete(i);this.expected.set(eFr(e,t),r+30000)}take(e,t){let r=eFr(e,t),i=this.expected.get(r);if(i===void 0)return!1;return this.expected.delete(r),i>this.now()}}function eFr(e,t){return`${e}
|
|
9605
9609
|
${t.join("/")}`}import{createHash as Nmo}from"crypto";var Lmo=600000,jmo=16777216;class JUe{held=new Map;now;capBytes;constructor(e=Date.now,t=jmo){this.now=e,this.capBytes=t}hold(e,t,r){let i=this.live(e),n=t.join("/");i.delete(n);let o=this.now();i.set(n,{...r,savedAt:new Date(o),etag:`"held-${Nmo("sha256").update(r.bytes).digest("hex")}"`,until:o+Lmo});let s={bytes:0,full:!1,dropped:[]},{dropped:a}=[...i].reverse().reduce((c,[u,d],p)=>{let m=c.bytes+d.bytes.byteLength;return p>0&&(c.full||m>this.capBytes)?{...c,full:!0,dropped:[...c.dropped,u]}:{...c,bytes:m}},s);a.forEach((c)=>i.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(),r=this.held.get(e)??new Map;return[...r].forEach(([i,n])=>{if(n.until<=t)r.delete(i)}),this.held.set(e,r),r}}import{randomUUID as zmo}from"crypto";var tFr=600;class QUe{locks=new Map;now;constructor(e=Date.now){this.now=e}acquire(e,t,r){if(this.live(e))return;let i={token:`opaquelocktoken:${zmo()}`,userId:t,seconds:r,expires:this.now()+r*1000};return this.locks.set(e.join("/"),i),i}refresh(e,t,r,i){let n=this.live(e);if(!n||!rFr(n,t,r))return;return n.seconds=i,n.expires=this.now()+i*1000,n}release(e,t,r){let i=this.live(e);if(i?.userId!==t||i.token!==r)return!1;return this.locks.delete(e.join("/"))}permits(e,t,r){let i=this.live(e);return!i||rFr(i,t,r??"")}live(e){let t=e.join("/"),r=this.locks.get(t);if(r&&r.expires<=this.now()){this.locks.delete(t);return}return r}}function rFr(e,t,r){return e.userId===t&&r.includes(`<${e.token}>`)}function iFr(e){let t=/Second-(\d+)/i.exec(e??"")?.[1];return Math.min(t?Number(t):tFr,tFr)}function Umo(e){let t=Ane(e);if(t==="enum"){let r=Sne(e);return r?{type:"enum",enumValues:r}:{type:"enum"}}if(t==="literal")return{type:"string",defaultValue:kne(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 qmo(e){let t=[];for(let[r,i]of Object.entries(e.shape)){if(S6(i)?.studioWidget==="hidden")continue;let{inner:n,required:o,defaultValue:s}=wne(i),a=Umo(n),c={name:r,type:a.type,required:o},u=s!==void 0?s:a.defaultValue;if(u!==void 0)c.defaultValue=u;if(a.enumValues)c.enumValues=a.enumValues;t.push(c)}return t}function XUe(e){return e.types().flatMap((t)=>{if(e.fileExtension(t)===".yaml")return[];let r=e.frontmatterSchema(t);if(!r)return[];return[{entityType:t,singleton:e.isSingleton(t),bodyTemplate:e.bodyTemplate(t),fields:qmo(r)}]})}var $mo={"&":"&","<":"<",">":">"};function LB(e){return e.replace(/[&<>]/g,(t)=>$mo[t]??t)}var nFr="<D:lockscope><D:exclusive/></D:lockscope><D:locktype><D:write/></D:locktype>";function Gmo(e){return[`<D:supportedlock><D:lockentry>${nFr}</D:lockentry></D:supportedlock>`,`<D:displayname>${LB(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>${LB(e.contentType)}</D:getcontenttype>`:"",e.etag?`<D:getetag>${LB(e.etag)}</D:getetag>`:"",e.lastModified?`<D:getlastmodified>${e.lastModified.toUTCString()}</D:getlastmodified>`:""].join("")}function oFr(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:">${e.map((r)=>`<D:response><D:href>${LB(r.href)}</D:href><D:propstat><D:prop>${Gmo(r)}</D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>`).join("")}</D:multistatus>`}function sFr(e){return`<?xml version="1.0" encoding="utf-8"?><D:error xmlns:D="DAV:"><D:${e}/></D:error>`}function aFr(e){return`<?xml version="1.0" encoding="utf-8"?><D:prop xmlns:D="DAV:"><D:lockdiscovery><D:activelock>${nFr}<D:depth>0</D:depth><D:timeout>Second-${e.seconds}</D:timeout><D:locktoken><D:href>${LB(e.token)}</D:href></D:locktoken><D:lockroot><D:href>${LB(e.href)}</D:href></D:lockroot></D:activelock></D:lockdiscovery></D:prop>`}function cFr(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"><D:response><D:href>${LB(e)}</D:href><D:status>HTTP/1.1 200 OK</D:status></D:response></D:multistatus>`}var Hmo=[".brain","changes"],Wmo=50,lFr=25,uFr=[".brain","conflicts"],Zmo=".brain",Vmo=65536,Kmo=1024,Ymo=[".brain","publish"],Jmo=l.object({path:l.string().min(1).max(Kmo)}),dFr=".brain/ask",pFr=".brain/ask/confirm",Qmo=[".brain","related"],mFr=10,Xmo=25,eho=[".brain","vault-shapes.json"],tho=["OPTIONS","GET","HEAD","PROPFIND"],bFr=["POST","PUT","DELETE","MOVE","COPY","PROPPATCH","MKCOL","LOCK","UNLOCK"],EFr=[...tho,...bFr],rho=EFr.filter((e)=>e!=="POST").join(", "),tde='application/xml; charset="utf-8"',iho={"X-Content-Type-Options":"nosniff","Content-Security-Policy":"sandbox","Cache-Control":"no-store"};function vFr(e){let t={options:e,mounts:e.mounts??kRr(e.now),scratch:new KUe(e.now,e.kept),locks:new QUe(e.now),cleanups:new YUe(e.now),holds:new JUe(e.now)},r={GET:(i,n)=>xFr(i,n,!0),HEAD:(i,n)=>xFr(i,n,!1),PROPFIND:sho,POST:mho,PUT:aho,DELETE:gho,MOVE:Eho,COPY:async()=>VT("The drive does not copy files"),PROPPATCH:yho,MKCOL:bho,LOCK:who,UNLOCK:Sho};return EFr.map((i)=>({path:e.basePath,match:"prefix",method:i,public:!0,handler:async(n)=>{if(i==="OPTIONS")return J$(Cho());let o=await e.resolveAppPassword(n);if(!o)return J$(Dho(e.realm));if(hFr(i)&&o.access!=="write")return J$(VT("This app password is read-only"));let s=n.headers.get("x-brain-sync")?.trim()==="1",a={request:n,grant:o,tree:new $Ue(e.reader,ai(o.principal.permissionLevel),{everyType:s}),path:TFr(e.basePath,new URL(n.url).pathname),sync:s};if(hFr(i)&&i!=="LOCK"&&i!=="UNLOCK"&&a.path&&!AFr(t,a,a.path.segments))return J$(oqe());await t.scratch.open(o.principal.userId);let c=await r[i](t,a);return await t.scratch.settle(),J$(c)}}))}function AFr(e,t,r){return e.locks.permits(r,t.grant.principal.userId,t.request.headers.get("if"))}function hFr(e){return bFr.some((t)=>t===e)}function rde(e,t){let{path:r}=t;return r&&!r.asFolder&&ZT(r.segments)?e.scratch.get(t.grant.principal.userId,r.segments):void 0}function ZT(e){let t=e[e.length-1];return t!==void 0&&(wFr(e)||XRr(t))}function wFr(e){return e.some((t)=>t.startsWith("."))}async function ide(e,t){if(!t.path)return;let r=await t.tree.resolve(t.path.segments);if(r)return r.kind==="file"&&t.path.asFolder?void 0:r;return e.scratch.hasFolder(t.grant.principal.userId,t.path.segments)?{kind:"folder",segments:t.path.segments}:void 0}async function iqe(e,t,r){return r.length===0||e.scratch.hasFolder(t.grant.principal.userId,r)||(await t.tree.resolve(r))?.kind==="folder"}async function nqe(e,t,r){if(r.kind!=="file"||t.sync)return;let i=t.grant.appPasswordId,n=e.holds.get(i,r.segments);if(!n)return;let{conflictPending:o}=e.options;if((n.conflictId===void 0||o===void 0||await o(n.conflictId))&&r.etag===`"${n.storedHash}"`)return n;e.holds.release(i,r.segments);return}async function SFr(e,t,r){let i=t.request.headers.get("if-match");if(i===null)return null;if(t.sync)return i;if(!e.holds.get(t.grant.appPasswordId,r))return i;let n=await t.tree.resolve(r);return(n?await nqe(e,t,n):void 0)?.etag===i?null:i}async function nho(e,t){let r=new URL(t.request.url).searchParams,i=Number(r.get("wait")??lFr),n=Number.isFinite(i)?Math.min(Math.max(i,0),Wmo):lFr,o=await e.wait(r.get("since"),n*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 oho(e){let t=new URL(e.request.url).searchParams,r=t.get("path")??"";if(r==="")return new Response("Name the file with ?path=",{status:400});let i=Number(t.get("limit")??mFr),n=Number.isInteger(i)&&i>0?Math.min(i,Xmo):mFr,o=await e.tree.related(r.split("/"),n)??[];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 fFr(e,t,r){let i=tqe(r,e.options.basePath),n=await nqe(e,t,r);return n?{...i,contentLength:n.bytes.byteLength,etag:n.etag,lastModified:n.savedAt}:i}function kFr(e,t){let r=t.grant.appPasswordId,i=(t.path?.segments??[]).join("/");return{base:()=>e.mounts.get(r,i),held:(n)=>e.mounts.held(r,i,n),conflictKept:(n,o)=>e.mounts.conflictKept(r,i,n,o),forget:()=>e.mounts.forget(r,i)}}function nde(e,t){return{tree:t.tree,reader:e.options.reader,writes:e.options.writes,mount:kFr(e,t),recordConflict:async(r)=>e.options.recordConflict?.(r),folderExists:(r)=>iqe(e,t,r)}}async function xFr(e,t,r){let{shapes:i,changes:n}=e.options;if(t.sync&&t.path?.segments.join("/")===Qmo.join("/"))return oho(t);if(t.sync&&n!==void 0&&t.path?.segments.join("/")===Hmo.join("/"))return nho(n,t);if(t.sync&&i!==void 0&&t.path?.segments.join("/")===eho.join("/")){let c=JSON.stringify({shapes:XUe(i).filter((u)=>u.entityType===V$||t.tree.isFolderType(u.entityType))});return new Response(r?c:null,{status:200,headers:{"Content-Type":"application/json; charset=utf-8",ETag:`"${Ht(c)}"`}})}let o=rde(e,t);if(o)return new Response(r?o.bytes:null,{status:200,headers:{"Content-Type":"application/octet-stream","Content-Disposition":"attachment","Content-Length":String(o.bytes.byteLength),ETag:IFr(o),"Last-Modified":o.modified.toUTCString()}});let s=await ide(e,t);if(!s)return Ah();if(s.kind==="folder")return rqe();let a=await nqe(e,t,s);if(a)return new Response(r?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 kFr(e,t).held(s.etag.replace(/^"|"$/g,"")),new Response(r?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 sho(e,t){let r=t.request.headers.get("depth");if(r!=="0"&&r!=="1")return new Response(sFr("propfind-finite-depth"),{status:403,headers:{"Content-Type":tde}});let{basePath:i}=e.options,n=rde(e,t);if(n)return eqe([yFr(n,i)]);let o=await ide(e,t);if(!o)return Ah();if(o.kind==="file"||r==="0")return eqe([await fFr(e,t,o)]);let s=t.grant.principal.userId,a=await t.tree.children(o.segments),c=new Set(a.filter((u)=>u.kind==="folder").map((u)=>u.segments[u.segments.length-1]));return eqe([tqe(o,i),...await Promise.all(a.map((u)=>fFr(e,t,u))),...e.scratch.listFolders(s,o.segments).filter((u)=>!c.has(u)).map((u)=>tqe({kind:"folder",segments:[...o.segments,u]},i)),...e.scratch.list(s,o.segments).map((u)=>yFr(u,i))])}async function aho(e,t){let{path:r}=t;if(!r)return Ah();if(r.asFolder||r.segments.length===0)return rqe();let{maxFileBytes:i,maxAssetBytes:n}=e.options.writes,o=await DFr(t.request,Math.max(i,n)),s=t.grant.principal.userId,a=ZT(r.segments);if(!o){if(!a)e.cleanups.expect(s,r.segments);return new Response("The file is larger than the drive accepts",{status:413})}if(a){if(await iqe(e,t,r.segments))return rqe();return CFr(e.scratch.put(s,r.segments,o))}let c=await HUe(nde(e,t),{segments:r.segments,bytes:o,ifMatch:await SFr(e,t,r.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 cho(e,t,r.segments,o,c);if("message"in c||c.etag===void 0)e.cleanups.expect(s,r.segments);return await uho(e,t,r.segments,o,c),X$(e,t,r.segments,c)}async function cho(e,t,r,i,n){if("message"in n)return X$(e,t,r,n);e.holds.release(t.grant.appPasswordId,r);let o=await t.tree.entityAt(r),s={};if(o)s.ETag=o.file.etag,s["X-Brain-Stored"]=n.conflictId!==void 0?"conflict":await lho(o.file,i)?"as-sent":"other-form";if(n.conflictId!==void 0)s["X-Brain-Conflict"]=n.conflictId;if(n.status===201)e.scratch.forgetFolders(t.grant.principal.userId,r.slice(0,-1));return new Response(null,{status:n.status,headers:s})}async function lho(e,t){if(e.size!==t.byteLength)return!1;let r=new Uint8Array(await new Response(await e.open()).arrayBuffer());return Buffer.from(r).equals(Buffer.from(t))}async function uho(e,t,r,i,n){if("message"in n)return;let o=t.grant.appPasswordId;if(n.etag!==void 0){e.holds.release(o,r);return}let s=await t.tree.entityAt(r);if(!s)return;e.holds.hold(o,r,{bytes:i,storedHash:s.entity.contentHash,conflictId:n.conflictId})}async function dho(e){let t=await DFr(e,Vmo);if(!t)return BFr;try{return JSON.parse(new TextDecoder().decode(t))}catch{return}}var BFr=Symbol("too large");function pho(){return new Response("The request is too large",{status:413})}async function mho(e,t){let r=t.sync?t.path?.segments.join("/"):void 0,i=()=>({tree:t.tree,grant:t.grant,ask:e.options.ask,confirmAsk:e.options.confirmAsk}),n=[dFr,pFr,Ymo.join("/")];if(r===void 0||!n.includes(r))return new Response("The drive takes no POST here",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}});let o=await dho(t.request);if(o===BFr)return pho();if(r===dFr)return ORr(i(),o);if(r===pFr)return NRr(i(),o);return hho(e,t,o)}async function hho(e,t,r){let i=Jmo.safeParse(r);if(!i.success)return new Response('Name the file: { "path": "\u2026" }',{status:400});let n=await t.tree.entityAt(i.data.path.split("/"));if(!n)return new Response("There is no entry at this path.",{status:409});let o=await e.options.publish?.({entityType:n.entity.entityType,id:n.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 fho(e){let[t,r,i,...n]=e;return t===uFr[0]&&r===uFr[1]&&i!==void 0&&n.length===0?i:void 0}async function xho(e,t,r){return await e.options.resolveConflict?.({conflictId:r,action:"keep-current",userId:t.grant.principal.userId,permissionLevel:t.grant.principal.permissionLevel})?Xue():new Response("Conflicts cannot be settled here right now.",{status:503})}async function gho(e,t){let{path:r}=t;if(!r)return Ah();let i=t.sync&&!r.asFolder?fho(r.segments):void 0;if(i!==void 0)return xho(e,t,i);let n=t.grant.principal.userId;if(e.scratch.removeFolder(n,r.segments))return Xue();if(!r.asFolder&&ZT(r.segments)){if(e.scratch.delete(n,r.segments))return Xue()}if(r.segments.length===0||(await t.tree.resolve(r.segments))?.kind==="folder")return VT("The drive does not delete folders");if(r.asFolder)return Ah();if(t.request.headers.get("if-match")===null&&e.cleanups.take(n,r.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 WRr(nde(e,t),{segments:r.segments,ifMatch:await SFr(e,t,r.segments),grant:t.grant});if(!("message"in o))e.holds.release(t.grant.appPasswordId,r.segments);return X$(e,t,r.segments,o)}async function yho(e,t){let r=rde(e,t)??await ide(e,t);if(!r||!t.path)return Ah();let i="kind"in r&&r.kind==="folder",n=Q$(t.path.segments);return new Response(cFr(`${e.options.basePath}/${n}${i&&n?"/":""}`),{status:207,headers:{"Content-Type":tde}})}async function bho(e,t){let{path:r}=t;if(!r)return Ah();if((await t.request.arrayBuffer()).byteLength>0)return new Response("MKCOL takes no body",{status:415});let{segments:i}=r,n=t.grant.principal.userId;if(i.length===0||await t.tree.resolve(i)||e.scratch.hasFolder(n,i)||e.scratch.get(n,i))return new Response("Already exists",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}});if(!await iqe(e,t,i.slice(0,-1)))return new Response("The parent folder does not exist",{status:409});let[o]=i;if(!wFr(i)&&(o===void 0||!t.tree.isFolderType(o)))return VT("Only an entity type can be a folder here");return e.scratch.makeFolder(n,i),new Response(null,{status:201})}async function Eho(e,t){let r=t.request.headers.get("destination");if(!r)return new Response("Destination required",{status:400});let i=kho(e.options.basePath,t.request,r);if(!i)return new Response("Destination is not on this drive",{status:502});let{path:n}=t;if(!n)return Ah();if(!AFr(e,t,i.segments))return oqe();let o=t.request.headers.get("overwrite")?.toUpperCase()!=="F";if(n.asFolder)return VT("The drive does not rename files");if(!ZT(n.segments))return ZT(i.segments)?Aho(e,t,n.segments,i.segments,o):vho(e,t,n.segments,i.segments);let s=t.grant.principal.userId,a=e.scratch.get(s,n.segments);if(!a)return Ah();if(ZT(i.segments)){if(!o&&e.scratch.get(s,i.segments))return ede("The destination exists");let u=e.scratch.rename(s,n.segments,i.segments);return u==="missing"?Ah():new Response(null,{status:u==="created"?201:204})}if(!o&&await t.tree.entityAt(i.segments))return ede("The destination exists");let c=await HUe(nde(e,t),{segments:i.segments,bytes:a.bytes,ifMatch:null,grant:t.grant});if(c.status<300)e.scratch.delete(s,n.segments),e.holds.release(t.grant.appPasswordId,i.segments);return X$(e,t,i.segments,c)}async function vho(e,t,r,i){let n=await HRr(nde(e,t),{from:r,to:i,grant:t.grant});if(n.status<300){let o=t.grant.appPasswordId,s=await e.mounts.get(o,r.join("/"));if(await e.mounts.forget(o,r.join("/")),s)await e.mounts.held(o,i.join("/"),s.hash);e.holds.release(o,r)}return X$(e,t,i,n)}async function Aho(e,t,r,i,n){let o=await t.tree.entityAt(r);if(!o)return Ah();let s=t.grant.principal.userId;if(!n&&e.scratch.get(s,i))return ede("The destination exists");let a=new Uint8Array(await new Response(await o.file.open()).arrayBuffer());return CFr(e.scratch.put(s,i,a))}async function who(e,t){let{path:r}=t;if(!r||r.segments.length===0)return Ah();if(r.segments[0]===Zmo)return VT("There is nothing to lock here");let i=t.grant.principal.userId,n=iFr(t.request.headers.get("timeout")),o=t.request.headers.get("if"),s=(await t.request.arrayBuffer()).byteLength>0;if(o&&!s){let u=e.locks.refresh(r.segments,i,o,n);return u?gFr(e,r.segments,u,200):ede("No such lock to refresh")}let a=e.locks.acquire(r.segments,i,n);if(!a)return oqe();let c=rde(e,t)!==void 0||await ide(e,t)!==void 0;return gFr(e,r.segments,a,c?200:201)}function gFr(e,t,r,i){return new Response(aFr({...r,href:`${e.options.basePath}/${Q$(t)}`}),{status:i,headers:{"Content-Type":tde,"Lock-Token":`<${r.token}>`}})}async function Sho(e,t){let{path:r}=t;if(!r)return Ah();let i=/<([^>]+)>/.exec(t.request.headers.get("lock-token")??"")?.[1];if(!i)return new Response("Lock-Token required",{status:400});return e.locks.release(r.segments,t.grant.principal.userId,i)?Xue():new Response("No such lock",{status:409})}function X$(e,t,r,i){if("message"in i)return new Response(i.message,{status:i.status});if(i.status===201)e.scratch.forgetFolders(t.grant.principal.userId,r.slice(0,-1));return new Response(null,{status:i.status,headers:i.etag?{ETag:i.etag}:{}})}function CFr(e){return e==="full"?new Response("Too many temporary files",{status:507}):new Response(null,{status:e==="created"?201:204})}async function DFr(e,t){if(Number(e.headers.get("content-length")??0)>t)return;let r=new Uint8Array(await e.arrayBuffer());return r.byteLength>t?void 0:r}function tqe(e,t){let r=e.segments[e.segments.length-1]??"";if(e.kind==="folder"){let i=Q$(e.segments);return{href:i?`${t}/${i}/`:`${t}/`,displayName:r,collection:!0}}return{href:`${t}/${Q$(e.segments)}`,displayName:r,collection:!1,contentLength:e.size,contentType:e.contentType,etag:e.etag,lastModified:e.modified}}function yFr(e,t){return{href:`${t}/${Q$(e.segments)}`,displayName:e.segments[e.segments.length-1]??"",collection:!1,contentLength:e.bytes.byteLength,contentType:"application/octet-stream",etag:IFr(e),lastModified:e.modified}}function IFr(e){return`"scratch-${e.modified.getTime()}-${e.bytes.byteLength}"`}function Q$(e){return e.map(encodeURIComponent).join("/")}function TFr(e,t){if(t!==e&&!t.startsWith(`${e}/`))return;let r=t.slice(e.length+1);if(r==="")return{segments:[],asFolder:!0};let i=r.endsWith("/"),o=(i?r.slice(0,-1):r).split("/").map(Bho);return o.every((s)=>s!==void 0&&s!==""&&!/[/\\\0]/.test(s))?{segments:o.filter((s)=>s!==void 0),asFolder:i}:void 0}function kho(e,t,r){let i=new URL(t.url),n=URL.canParse(r,i)?new URL(r,i):void 0;if(n?.host!==i.host)return;let o=TFr(e,n.pathname);return o&&!o.asFolder&&o.segments.length>0?o:void 0}function Bho(e){try{return decodeURIComponent(e)}catch{return}}function eqe(e){return new Response(oFr(e),{status:207,headers:{"Content-Type":tde}})}function Cho(){return new Response(null,{status:200,headers:{DAV:"1, 2",Allow:rho,"MS-Author-Via":"DAV"}})}function Dho(e){return new Response("Authentication required",{status:401,headers:{"WWW-Authenticate":`Basic realm="${e.replace(/["\\]/g,"")}", charset="UTF-8"`}})}function rqe(){return new Response("A folder has no content",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}})}function Xue(){return new Response(null,{status:204})}function Ah(){return new Response("Not found",{status:404})}function VT(e){return new Response(e,{status:403})}function oqe(){return new Response("The file is locked",{status:423})}function ede(e){return new Response(e,{status:412})}function J$(e){let t=new Headers(e.headers);return Object.entries(iho).forEach(([r,i])=>t.set(r,i)),new Response(e.body,{status:e.status,headers:t})}var sqe="/dav",Iho=5242880,_Fr=l.strictObject({maxFileBytes:l.number().int().positive().describe("Maximum bytes of a file a client may save").default(Iho)}),Tho=zt({id:"webdav",config:_Fr,setup:(e)=>{let t=bt(e);if(t.executionOnly)return{routes:[]};t.registered(()=>{if(t.entityReads.getEntityTypes().includes(us))return;throw Error(`webdav needs the "${us}" entity type to keep saves that lose to a newer version. Add "conflict" to this brain, which the core bundle includes.`)});let r=new zUe;for(let n of[ma,fs,lp,Sb])t.listen(n,({payload:o})=>r.record(o.entityType),{mode:"observe"});t.listen(uo.shuttingDown,()=>r.close(),{mode:"observe"});let i=BRr(t.classRuntimeState);return t.ready(()=>i.sweep()),t.interaction({id:Wne,label:"Drive",description:"Mount the brain as a network drive over WebDAV.",href:`${sqe}/`,kind:"protocol",priority:40,visibility:"trusted"}),{routes:vFr({basePath:sqe,realm:t.identity.get().name,reader:t.entityReads,shapes:t.entityShapes,changes:r,writes:{maxFileBytes:e.config.maxFileBytes,maxAssetBytes:k7,stageAsset:(n,o)=>t.entityWrites.stageAsset(n,o),discardStagedAsset:(n)=>t.entityWrites.discardStagedAsset(n),deserializeEntity:(n,o)=>t.entityReads.deserializeEntity(n,o),createEntity:(n)=>t.entityWrites.createEntity(n),updateEntity:(n)=>t.entityWrites.updateEntity(n),deleteEntity:(n)=>t.entityWrites.deleteEntity(n),renameEntity:(n)=>t.entityWrites.renameEntity(n),permissions:t.permissions,recordAudit:async(n)=>{await t.auth()?.recordAuditEvent(n)}},resolveAppPassword:async(n)=>t.auth()?.resolveAppPassword(n),mounts:i,kept:IRr(t.classRuntimeState),recordConflict:async(n)=>{let o=await t.messaging.request(LS,n);return o.status==="answered"?o.data.conflictId:void 0},ask:async(n)=>{let o=await t.messaging.request(ode,n);if(o.status==="answered")return o.data;return o.status==="failed"?{message:o.error.message}:void 0},confirmAsk:async(n)=>{let o=await t.messaging.request(sde,n);if(o.status==="answered")return o.data;return o.status==="failed"?{message:o.error.message}:void 0},publish:async(n)=>{let o=await t.messaging.request(ooe,n);if(o.status==="answered")return o.data;return o.status==="failed"?{message:o.error.message}:void 0},resolveConflict:async(n)=>{let o=await t.messaging.request(qI,n);if(o.status==="answered")return{resolved:!0};return o.status==="failed"?{message:o.error.message}:void 0},conflictPending:async(n)=>await t.entityReads.getEntityRaw({entityType:us,id:n,visibilityScope:ot("ask only whether a conflict is still waiting to be resolved")})!==null})}}}),aqe=ko(Tho,({state:e})=>e.routes);var PFr=aqe;var _ho=l.object({errcode:l.string()}),Pho=l.object({session:l.string()});async function cqe(e){let t=e.fetch??fetch,r=`${e.homeserverUrl.replace(/\/+$/,"")}/_matrix/client/v3`,i=e.userId.slice(1).split(":")[0]??"",n=(p,m)=>t(`${r}${p}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(m)}),o=await n("/login",{type:"m.login.password",identifier:{type:"m.id.user",user:i},password:e.password,device_id:"brain-bootstrap"});if(o.ok)return"exists";let s=await RFr(o);if(s!=="M_FORBIDDEN")throw Error(`Matrix bot login failed: ${s??o.status}`);let a={username:i,password:e.password,inhibit_login:!0},c=await n("/register",a),u=Pho.safeParse(await c.json().catch(()=>{return}));if(!u.success)throw Error(`Matrix bot registration did not start: ${c.status}`);let d=await n("/register",{...a,auth:{type:"m.login.registration_token",token:e.registrationToken,session:u.data.session}});if(!d.ok)throw Error(`Matrix bot registration failed: ${await RFr(d)??d.status}`);return"registered"}async function RFr(e){let t=_ho.safeParse(await e.json().catch(()=>{return}));return t.success?t.data.errcode:void 0}var lqe="matrix-homeserver";function ade(e){return`${e.replace(/\/+$/,"")}/_matrix/client/unstable/login/sso/callback/matrix-homeserver`}function Jy(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`}function uqe(e){let t=e.publicBaseUrl.replace(/\/+$/,"");return`[global]
|
|
9606
9610
|
server_name = ${Jy(e.serverName)}
|
|
@@ -11190,5 +11194,5 @@ ${Xpe}</style><link rel="stylesheet" href="${Dwo}"></head><body class="guest-pag
|
|
|
11190
11194
|
`);return{kind:"text",filename:"inbox-source.txt",mediaType:"text/plain",content:u,sizeBytes:new TextEncoder().encode(u).byteLength}}catch{return vWe()}}async readEntryContext(e,t){let r=R$r(e);if(!r)return null;let i=await this.runtime.request(Vne,{...r,visibilityScope:ai(t)}).catch(()=>null);return i?.status==="answered"?i.data:null}async handleContextSessionRequest(e){let t=Ea(e);if(t)return t;return _qr(e,{conversations:this.runtime.conversations,resolveAccess:(r)=>this.resolveConversationAccess(r),interfaceType:om,authorizeSource:async({sourceId:r,itemId:i,permissionLevel:n,signal:o})=>{if(r===AWe)return await this.readEntryContext(i,n)!==null;let s=this.runtime.inbox.getSource(r);if(!s?.resolveDetail)return!1;return await s.resolveDetail(i,{permissionLevel:n},o),!0}})}async handleSessionsRequest(e){return Uqr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:om})}async handleDeleteSessionRequest(e){return qqr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:om})}async handleRenameSessionRequest(e){return $qr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:om})}async handleArchiveSessionRequest(e){return Gqr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:om})}async handleDocumentAttachmentRequest(e){return UUr(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleImageAttachmentRequest(e){return qUr(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleJobStatusRequest(e){return Fqr(e,{resolveAuthSession:this.resolveAuthSession,createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),jobs:this.runtime.jobs})}async handleMessagesRequest(e){return Zqr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:om})}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,om,t)}ensureWebChatConversation(e,t){return this.ensureBrowserConversation(e,om,"Web Chat",t)}async requireExistingBrowserConversation(e,t,r){let i=await this.runtime.conversations.get(e);return ob(i,r,t)?void 0:new Response("Conversation not found",{status:404})}async ensureBrowserConversation(e,t,r,i){let n=await this.runtime.conversations.get(e);if(n)return ob(n,i,t)?void 0:new Response("Conversation not found",{status:404});if(i.permissionLevel==="trusted"&&!i.personId)return new Response("Forbidden",{status:403});await this.runtime.conversations.start({sessionId:e,interfaceType:t,channelId:e,...i.personId?{personId:i.personId}:{},metadata:{channelName:r,interfaceType:t,channelId:e}});let o=await this.runtime.conversations.get(e);return ob(o,i,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 i=t.status==="active"&&(t.permissionLevel==="admin"||t.permissionLevel==="trusted");return{principal:t,permissionLevel:i?t.permissionLevel:"public",hasChatAccess:i}}if(this.resolveCallerPermissionLevel){let i=await this.resolveCallerPermissionLevel(e);return{permissionLevel:i,hasChatAccess:i==="admin"||i==="trusted"}}let r=this.resolveAuthSessionOverride?await this.resolveAuthSessionOverride(e):!1;return{permissionLevel:r?"admin":"public",hasChatAccess:r}}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,r){return Ype(e,t,r,(i)=>this.createId(i))}createId(e){return`${e}-${crypto.randomUUID()}`}}function vWe(){return new Response("Inbox context is unavailable",{status:409})}function wWe(e={}){let t=_h({id:om,config:aWe,setup:async(n)=>{let o=Jo(n),s=new O$r(n.config,e,o,n.runtimeState(J7));return await s.register(),o.ready(()=>s.onReady()),s}}),r=ko(t,({state:n})=>n.webRoutes()),i=Kx(r,({state:n})=>{let o=n.maintenanceDaemon();return{id:"guest-maintenance",start:()=>o.start(),stop:()=>o.stop(),healthCheck:()=>o.healthCheck()}});return Ene(i,({state:n})=>n.transport())}var d1o=wWe(),N$r=d1o;var SWe='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 L$r={critical:0,high:1,medium:2,low:3};function j$r(e){return[...e].sort((t,r)=>{let i=r.metadata.requested-t.metadata.requested;if(i!==0)return i;return L$r[t.metadata.priority]-L$r[r.metadata.priority]})}var YG=l.enum(["new","planned","in-progress","done","declined"]),JG=l.enum(["low","medium","high","critical"]),dme=l.object({title:l.string(),status:YG,priority:JG.default("medium"),requested:l.number().int().default(1).meta({studioWidget:"provenance"}),declinedReason:l.string().optional()}),kWe=l.object({title:l.string(),status:YG,priority:JG,requested:l.number().int().meta({studioWidget:"provenance"}),slug:l.string().optional().meta({studioWidget:"hidden"}),declinedReason:l.string().optional()});var p1o=l.object({items:l.array(l.object({id:l.string(),name:l.string(),count:l.number().int().nonnegative(),priority:JG,status:YG}))});function m1o(e){if(e==="critical")return"error";if(e==="high")return"warn";return"neutral"}var BWe=ro({id:"top-wishes",title:"Top Wishes",group:"knowledge",placement:"secondary",priority:30,permission:"public",data:p1o,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:m1o(t.priority)},{label:t.status,tone:t.status==="done"?"good":"neutral"}]}))}]})});function h1o(e){return BWe.bind(e,async({entities:t,signal:r})=>(r.throwIfAborted(),{items:j$r(await t.list(ab,{limit:10})).map((n)=>({id:n.id,name:n.metadata.title,count:n.metadata.requested,priority:n.metadata.priority,status:n.metadata.status}))}))}var ab=Vi(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:kWe,markdown:{decode:({content:e,frontmatter:t})=>{let r=dme.parse(t);return{content:e,metadata:{title:r.title,status:r.status,priority:r.priority,requested:r.requested,slug:Lt(r.title),...r.declinedReason!==void 0&&{declinedReason:r.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:SWe,dashboardWidgets:(e)=>[h1o(e)]}),dme);var z$r=0.3,f1o="Do these two wishes ask for the same thing?",x1o=l.object({same:l.boolean().describe("True only when delivering one would fulfil the other.")});async function g1o(e,t,r){let{same:i}=await e.generateObject([f1o,"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:",r].join(`
|
|
11191
11195
|
`),x1o);return i}function pme(e,t,r){return{nearest:(i,n)=>e.nearest(ab,i,{maxDistance:n}),getEntity:(i)=>t.get(ab,i),maxDistance:r,ai:e}}async function mme(e,t){let r=(await e.nearest(t.content,e.maxDistance)).flatMap(({entity:s})=>s.visibility==="public"?[s]:[]),i=async(s)=>{let a=r[s];if(!a)return;return await g1o(e.ai,t.content,y1o(a))?a:i(s+1)},n=await i(0);if(n)return n;let o=await e.getEntity(Lt(t.title));return o?.visibility==="public"?o:null}function y1o(e){let{title:t,status:r,priority:i,requested:n,declinedReason:o}=e.metadata;return QG({title:t,status:r,priority:i,requested:n,declinedReason:o},e.content)}function QG(e,t){let r=Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0&&i!==null));return Object.keys(r).length>0?fi(r,t):t}var U$r=l.object({title:l.string(),description:l.string()}),b1o=l.object({stored:U$r,incoming:U$r}),CWe="eval-stored-wish";function q$r(e){return QG({title:e.title,status:"new",priority:"medium",requested:1},e.description)}function $$r(e){return{sameWish:async(t,r)=>{let{stored:i,incoming:n}=b1o.parse(t),{fixtures:o}=r;await o.reset(),await o.seed({id:CWe,entityType:"wish",content:q$r(i),metadata:{title:i.title,status:"new",priority:"medium",requested:1,slug:Lt(i.title)}}),await o.settleEmbeddings();let s=$t(r),a=q$r(n),c=(await s.nearest(ab,a,{maxDistance:2})).find(({entity:d})=>d.id===CWe)?.distance;if(c===void 0)throw Error("The stored wish was not embedded");let u=await mme(pme(s,r.entities,e),{title:n.title,content:a});return{distance:c,shortlisted:c<=e,sameWish:u?.id===CWe}}}}async function E1o(e,t){let{input:r}=e;if(r.visibility!==void 0&&r.visibility!=="public")return{refuse:"Wish creation currently supports public visibility only; use a note for shared or restricted capture."};let i=r.title??r.prompt??"Untitled wish",n=r.content??r.prompt??"",o={title:i,status:"new",priority:"medium",requested:1},s=await mme(pme($t(e),e.entities,t),{title:i,content:QG(o,n)});if(s)return{update:{id:s.id,content:s.content.trim(),metadata:{...s.metadata,requested:s.metadata.requested+1}}};let a=Lt(i);return{create:{id:a,content:n,metadata:{...o,slug:a}}}}function G$r(e){let t={resolve:(r)=>E1o(r,e)};return{fromPrompt:t,fromContent:t,fromUpload:t}}var DWe=l.object({sameWishDistance:l.number().min(0).max(1).default(z$r)});var v1o=Pi({id:"wishlist",config:DWe,entities:[ab],configure:({config:e})=>({entities:[{entity:ab,create:G$r(e.sameWishDistance),evals:$$r(e.sameWishDistance)}]})}),H$r=v1o;var W$r="gpt-6-luna";var OA={create:"trusted",update:"trusted",delete:"admin",extract:"admin",publish:"admin"},Z$r=[{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}}],V$r=["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.'],K$r=[{member:"topics",value:{extractableStatuses:["published","draft"]}},{member:"conversation-memory",value:{memoryVisibility:"shared"}},{member:"action-board",value:{cardVisibility:"shared"}}],Y$r=["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 j8="capability-bundles-v1",IWe="core",TWe="media",_We="automation",XG="web",PWe="chat",RWe="site",FWe="publishing",MWe="federation",OWe="team",A1o="matrix",hme=pm({id:IWe,members:["profile","prompt","conflict","style-guide","directory-sync","note","refined-note","link","topics","unified-inbox","mcp","a2a","agents"],evalDisable:["mcp"]}),fme=pm({id:TWe,members:["document","image"]}),xme=pm({id:_We,members:["playbooks","onboarding"]}),gme=pm({id:XG,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"]}),yme=pm({id:PWe,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"]}),bme=pm({id:RWe,members:["site-info","site-content","site-builder","form","analytics"],config:[{member:"dashboard",value:{routePath:"/dashboard"},overrides:XG}]}),Eme=pm({id:FWe,members:["blog","series","portfolio","decks","content-pipeline","social-media","newsletter","stock-photo"],config:Z$r,agentInstructions:V$r}),vme=pm({id:MWe,members:["atproto","references"],evalDisable:["atproto"]}),Ame=pm({id:OWe,members:[],config:K$r,permissions:[{member:"note",config:{entityActions:{note:OA}}},{member:"refined-note",config:{entityActions:{"refined-note":OA}}},{member:"link",config:{entityActions:{link:OA}}},{member:"image",config:{entityActions:{image:OA}}},{member:"docs",config:{entityActions:{doc:OA}}},{member:"conversation-memory",config:{entityActions:{decision:OA,insight:OA,"action-item":OA}}},{member:"mcp",config:{rules:[{pattern:"mcp:http",level:"admin"}]},overrides:XG}],agentInstructions:Y$r}),w1o=pm({id:A1o,members:["matrix-server"],http:!0,permissions:[{member:"chat",config:{rules:[{pattern:"matrix:*",level:"public"}]}}]}),J$r=[hme,fme,xme,gme,yme,bme,Eme,vme,w1o,Ame];function tH(e,t,r){let i={name:e,version:z8.version};return(n)=>mm(t,n,i,r)}function S1o(e){let{entity:t,provider:r}=wPr(e),i={name:"@brains/newsletter",version:z8.version};return[...mm(t.definition,t.config,i,{pluginId:"newsletter"}),...r?mm(r.definition,r.config,i,{pluginId:r.kind}):[]]}function $r(e,t,r,i={},n=void 0){return[e,tH(t,r,i),n]}function eH(e,t,r,i,n={}){return[e,tH(t,r,n),i]}var Q$r=Kme({name:"brain",version:z8.version,bundleContract:j8,model:W$r,reasoningEffort:"low",capabilities:[$r("prompt","@brains/prompt",COr,{pluginId:"prompt"}),$r("conflict","@brains/conflict",kOr,{pluginId:"conflicts"}),$r("profile","@brains/profile",s$e,{pluginId:"profile"}),$r("style-guide","@brains/style-guide",Djr,{pluginId:"style-guide"}),$r("ask-content","@brains/ask-content",Tjr,{pluginId:"ask-content"}),["image",(e)=>[...tH("@brains/image-plugin",f_r,{pluginId:"image"})(e),...tH("@brains/image-plugin",h_r,{})({})],void 0],$r("document","@brains/document-plugin",FSr,{pluginId:"document"}),$r("note","@brains/note",jPr,{pluginId:"note"}),$r("refined-note","@brains/refined-note",TOr,{pluginId:"refined-note"}),$r("link","@brains/link",__r,{pluginId:"link"}),$r("references","@brains/reference",V_r,{pluginId:"references",ownedTypePluginId:"reference"}),$r("wishlist","@brains/wishlist",H$r,{pluginId:"wishlist"}),["topics",(e)=>[...mm(Dzr,e,{name:"@brains/topics",version:z8.version},{pluginId:"topics"}),...mm(BHe,{},{name:"@brains/knowledge-map",version:z8.version},{pluginId:"knowledge-map"})],void 0],$r("decks","@brains/decks",VEr,{pluginId:"decks"}),$r("directory-sync","@brains/directory-sync",Dwr,{pluginId:"directory-sync"},{seedContent:!0,seedContentPath:"./seed-content",initialSync:!0}),$r("atproto-registry","@brains/atproto-registry",$ye,{pluginId:"atproto-registry"}),["agents",(e)=>{let{enableSkillDerivation:t,notifyOnNewAgents:r,askAllApproved:i}=wrt.parse(e),n={name:"@brains/agent-discovery",version:z8.version};return[...mm(Gge,{},n,{pluginId:"agent-discovery",ownedTypePluginId:"agent-entity"}),...mm(Hge,{notifyOnNewAgents:r,askAllApproved:i},n,{pluginId:"agent"}),...mm(t?Wge:Vge,{},n,{pluginId:"skill",ownedTypePluginId:"skill-entity"}),...mm(Zge,{},n,{pluginId:"shared-copies",ownedTypePluginId:"shared-copy"})]},void 0],["assessment",(e)=>mm(vye.parse(e).enableSwotDerivation?Aye:wye,{},{name:"@brains/assessment",version:z8.version},{pluginId:"swot"}),void 0],$r("auth-service","@brains/auth-service",VAe,{pluginId:"auth-service"}),$r("notifications","@brains/notifications",qPr,{pluginId:"notifications"}),$r("contact","@brains/contact",vgr,{pluginId:"contact",dependencies:Egr}),$r("quiz","@brains/quiz",Fgr,{pluginId:"quiz",dependencies:Rgr}),$r("playbooks","@brains/playbooks",Pqe,{pluginId:"playbooks"}),$r("onboarding","@brains/onboarding",FOr,{pluginId:"onboarding",dependencies:["playbook","playbooks"]}),$r("studio","@brains/studio",kxr,{pluginId:"studio"}),$r("dashboard","@brains/dashboard",EEr,{pluginId:"dashboard"}),$r("admin","@brains/admin",Ffe,{pluginId:"admin"}),$r("site-info","@brains/site-info",NGe,{pluginId:"site-metadata"}),$r("site-content","@brains/site-content",ojr,{pluginId:"site-content",ownedTypePluginId:"site-content-entity"}),$r("site-builder","@brains/site-builder-plugin",rjr,{pluginId:"site-builder"}),$r("form","@brains/form",wgr,{pluginId:"form"}),$r("analytics","@brains/analytics",Yrt,{pluginId:"analytics"}),$r("blog","@brains/blog",Eyt,{pluginId:"blog"}),$r("series","@brains/series",zNr,{pluginId:"series"}),$r("portfolio","@brains/portfolio",HMr,{pluginId:"portfolio"}),$r("content-pipeline","@brains/content-pipeline",tgr,{pluginId:"content-pipeline"}),$r("social-media","@brains/social-media",Ajr,{pluginId:"social-media"}),["newsletter",S1o,void 0],$r("stock-photo","@brains/stock-photo",Bjr,{pluginId:"stock-photo"}),["atproto",tH("@brains/atproto",Fit,{pluginId:"atproto"}),(e)=>({...e.ATPROTO_APP_PASSWORD?{appPassword:e.ATPROTO_APP_PASSWORD}:{}})],$r("conversation-memory","@brains/conversation-memory",iPe,{pluginId:"conversation-memory"}),$r("action-board","@brains/action-board",rWe,{pluginId:"action-board"}),$r("faq","@brains/faq",zbr,{pluginId:"faq",ownedTypePluginId:"faq-entity"}),$r("docs","@brains/doc",Ywr,{pluginId:"docs"}),$r("guides","@brains/guide",E1r,{pluginId:"guides"}),$r("book","@brains/book",wSr,{pluginId:"book",ownedTypePluginId:"book-entity"}),$r("seminar","@brains/seminar",BNr,{pluginId:"seminar",ownedTypePluginId:"seminar-entity"}),$r("email-workflows","@brains/email-workflows",WTr,{pluginId:"email-workflows"}),$r("unified-inbox","@brains/unified-inbox",GHe,{pluginId:"unified-inbox"}),$r("linkedin-import","@brains/linkedin-import",FUe,{pluginId:"linkedin-import"}),$r("oauth-broker","@brains/oauth-broker",jUe({providers:{linkedin:SUe}}),{pluginId:"oauth-broker"}),$r("webdav","@brains/webdav",PFr,{pluginId:"webdav"}),$r("matrix-server","@brains/matrix-server",YFr,{pluginId:"matrix-server"},(e)=>hqe(e))],interfaces:[eH("mcp","@brains/mcp",iPr,(e)=>({...e.MCP_AUTH_TOKEN?{authToken:e.MCP_AUTH_TOKEN}:{}}),{pluginId:"mcp"}),eH("email","@brains/email",TTr,()=>({}),{pluginId:"email"}),eH("web-chat","@brains/web-chat",N$r,()=>({}),{pluginId:"web-chat"}),eH("chat","@brains/chat",Hfr,(e)=>j7e(e,{captureUrls:!0}),{pluginId:"chat"}),eH("a2a","@brains/a2a",sVe,()=>({}),{pluginId:"a2a"})],bundles:J$r,permissions:{rules:[{pattern:"cli:*",level:"admin"},{pattern:"mcp:stdio",level:"admin"}]},deployment:{cdn:{enabled:!0,provider:"bunny"},dns:{enabled:!0,provider:"bunny"}}});var k1o=["headless","personal","professional","team"];var B1o={headless:{bundleContract:j8,bundles:["core"]},personal:{bundleContract:j8,anchor:"person",kind:"professional",bundles:["core","media","web","chat"],plugins:{"directory-sync":{seedContentPath:"./seed-content"}}},professional:{bundleContract:j8,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:j8,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 C1o(e){return structuredClone(e)}function D1o(e){return C1o(B1o[e])}var I1o=Q$r,hpc=hme,fpc=fme,xpc=xme,gpc=gme,ypc=yme,bpc=bme,Epc=Eme,vpc=vme,Apc=Ame,Spc=I1o;export{_We as AUTOMATION_BUNDLE_ID,k1o as BRAIN_RECIPE_NAMES,j8 as CANONICAL_BUNDLE_CONTRACT,PWe as CHAT_BUNDLE_ID,IWe as CORE_BUNDLE_ID,MWe as FEDERATION_BUNDLE_ID,TWe as MEDIA_BUNDLE_ID,FWe as PUBLISHING_BUNDLE_ID,RWe as SITE_BUNDLE_ID,OWe as TEAM_BUNDLE_ID,XG as WEB_BUNDLE_ID,xpc as automationBundle,I1o as canonicalBrain,ypc as chatBundle,hpc as coreBundle,Spc as default,D1o as expandBrainRecipe,vpc as federationBundle,fpc as mediaBundle,Epc as publishingBundle,bpc as siteBundle,Apc as teamBundle,gpc as webBundle};
|
|
11192
11196
|
|
|
11193
|
-
//# debugId=
|
|
11197
|
+
//# debugId=10781046BE15CAD864756E2164756E21
|
|
11194
11198
|
//# sourceMappingURL=model.js.map
|