@rizom/brain 0.2.0-alpha.778 → 0.2.0-alpha.779
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 +4 -4
- package/dist/chunks/{app-q0dbdfnk.js → app-8pphv30e.js} +2 -2
- package/dist/chunks/{index-01kswdac.js → index-502w71jz.js} +3 -3
- package/dist/chunks/{index-01kswdac.js.map → index-502w71jz.js.map} +1 -1
- package/dist/chunks/{index-hxmx2bjt.js → index-z7gkbgw5.js} +2 -2
- package/dist/chunks/{package-6nhxfs2p.js → package-t4pk40zn.js} +3 -3
- package/dist/chunks/{package-6nhxfs2p.js.map → package-t4pk40zn.js.map} +1 -1
- package/dist/model.js +4 -4
- package/dist/model.js.map +1 -1
- package/dist/testing.js +1 -1
- package/package.json +1 -1
- /package/dist/chunks/{app-q0dbdfnk.js.map → app-8pphv30e.js.map} +0 -0
- /package/dist/chunks/{index-hxmx2bjt.js.map → index-z7gkbgw5.js.map} +0 -0
package/dist/model.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunks/index-hxmx2bjt.js";import{$ as xo,$a as zxn,$b as Agn,$c as Kgn,Aa as q0,Ab as Aj,Ad as Eyn,Ba as Fcr,Bb as ugn,Bd as Fk,C as Zg,Ca as Mcr,Cb as dgn,Cc as Cpr,Cd as vyn,D as M0n,Da as Exn,Db as nv,Dd as Ayn,E as wcr,Ea as vxn,Eb as Lcr,Ed as wyn,F as Pcr,Fa as Tre,Fb as yj,Fd as Kg,G as W0n,Ga as Axn,Gb as pgn,Gd as vj,H as Z0n,Hb as mgn,Hd as Syn,I as V0n,Ia as I3e,Ib as hgn,Id as kyn,J as K0n,Ja as wxn,Jb as fgn,Jd as Byn,K as Y0n,Ka as Sxn,Kd as Cyn,La as kxn,Lb as jcr,Ld as Dyn,M as Fre,Ma as Bxn,Mb as zcr,Md as Iyn,Na as Cxn,Nb as Ucr,Nd as _yn,Oa as Dxn,Ob as qcr,Od as Tyn,P as Ok,Pa as Ixn,Pb as $cr,Pd as Pyn,Q as fcr,Qa as Ocr,Qb as Gcr,Qd as Ore,R as Mk,Ra as _xn,Rb as Hcr,Rc as Jcr,Rd as L3e,S as Wg,Sa as Txn,Sb as Wcr,Sc as Ugn,Sd as Ryn,Ta as Pxn,Tb as Zcr,Tc as qgn,Td as _3e,U as O3e,Ua as Rxn,Ub as Vcr,Uc as $gn,Ud as Fyn,V as J0n,Va as Fxn,Vb as xgn,Vc as Ggn,Vd as qm,W as Vt,Wa as Mxn,Wb as ggn,Wc as Rk,Wd as ure,Xa as Oxn,Xb as ygn,Xc as Hgn,Xd as Myn,Y as Rcr,Ya as Nxn,Yb as bgn,Yc as Wgn,Z as Q0n,Za as Lxn,Zb as Egn,Zc as Zgn,_ as s8,_a as jxn,_b as vgn,_c as Vgn,aa as l8,ab as Uxn,ac as wgn,ad as Ygn,ba as Jc,bb as qxn,bc as Sgn,bd as Jgn,ca as X0n,cb as $xn,cc as kgn,cd as Qgn,da as exn,db as a8,dc as Bgn,dd as Xgn,ea as txn,eb as Gxn,ec as Cgn,ed as eyn,fa as rxn,fb as k3e,fc as Dgn,fd as tyn,ga as ixn,gb as Hxn,gc as Ign,gd as ryn,ha as nxn,hb as Wxn,hc as _gn,hd as iyn,ia as oxn,ib as Zxn,ic as Tgn,id as nyn,ja as sxn,jb as Vxn,jc as B3e,jd as oyn,ka as axn,kb as Kxn,kc as Ej,kd as syn,la as cxn,lb as Yxn,lc as Pgn,ld as ayn,ma as lxn,mb as Jxn,mc as Rgn,md as cyn,na as uxn,nb as Qxn,nc as Fgn,nd as lyn,oa as dxn,ob as Xxn,oc as Mgn,od as uyn,pa as pxn,pb as egn,pc as Ogn,qa as mxn,qb as tgn,qc as Ngn,qd as dyn,ra as hxn,rb as rgn,rc as Lgn,rd as pyn,sa as fxn,sb as ign,sc as Kcr,sd as myn,ta as FCe,tb as ngn,tc as Ycr,td as bcr,ua as xxn,ub as ogn,uc as hcr,ud as hyn,va as gxn,vb as sgn,vc as jgn,vd as fyn,wa as yxn,wb as Ncr,wc as zgn,wd as xyn,xa as bxn,xb as agn,xc as N3e,xd as gyn,ya as S3e,yb as cgn,yd as yyn,za as Bj,zb as lgn,zd as byn}from"./chunks/index-v13gwxf7.js";import{$d as Dbr,Yd as XI,Zd as aEr,be as TTe}from"./chunks/index-tcaxjgy7.js";import{de as a0e}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 bS}from"./chunks/index-01kswdac.js";import{Ce as SHe,De as b7r,Ee as QPr,Fe as bg,Ge as eJ,He as lU,Ie as mbr,Je as xy,Ke as $Dr,Le as YI,Me as w_r,Ne as lbr,Oe as hbr,Pe as YDr,Qe as zDr,Re as Wft,Se as $Rr,Te as _Ue,Ue as TUe,Ve as PUe,We as Tyr,Xe as UI,Ye as UDr,Ze as hf,_e as JI,gf as NG,ke as fGe,le as jG,ne as So,oe as h5,pe as tge,qe as oge,re as qb,se as JW,te as QW,ue as XW,ve as iXe,we as eZ,xe as n4,ye as Wet,ze as fs}from"./chunks/index-14pxgebm.js";import{jf as wme,kf as ojr}from"./chunks/index-bskj3xx3.js";import"./chunks/index-s8p4985c.js";import{$f as dtt,$g as RA,$h as FA,$i as Ect,$k as mme,$l as fme,$n as axt,Af as MZ,Ag as ca,Ah as g3,Ai as LA,Aj as JLr,Ak as $S,Al as hhe,Am as N0t,Ao as vme,Bf as vl,Bg as ds,Bh as BJ,Bi as AI,Bj as QLr,Bk as GS,Bl as fhe,Bm as gJ,Bo as CA,Cf as drt,Cg as Qd,Ch as bxt,Ci as CUe,Cj as Yz,Ck as mH,Cl as WS,Cm as Pde,Cn as emr,Co as fh,Df as IR,Dg as cb,Dh as S2,Di as yGe,Dj as _f,Dl as UT,Dm as Rde,Dn as tmr,Do as Ame,Ef as _R,Eg as Vpe,Eh as Tl,Ei as SFr,Ej as MB,Ek as HS,El as ZS,En as yJ,Eo as TT,Ff as gr,Fh as a1,Fi as sJ,Fj as sLr,Fl as la,Fn as K0t,Fo as $Ir,Gf as g4,Gh as bO,Gi as vne,Gj as aLr,Gl as Zo,Gm as HNr,Gn as Y0t,Hf as OZ,Hg as nhe,Hh as s1,Hi as vue,Hj as Sde,Hl as qT,Hn as fLr,If as mR,Ig as un,Ih as I0,Ii as Ane,Ij as XLr,Ik as sme,Il as Wi,In as xLr,Jg as wo,Jh as C1e,Ji as yle,Jj as ejr,Jk as IA,Jl as xhe,Jn as J0t,Kf as aw,Kg as Yft,Kh as Ixt,Ki as nJ,Kj as CNr,Kk as db,Kl as ghe,Kn as Q0t,Ko as TA,Lf as lge,Lg as ohe,Lh as Dxt,Li as dS,Lj as DNr,Lk as MS,Ll as im,Ln as Ywe,Lo as Wb,Mf as NZ,Mh as Nte,Mi as BI,Mj as INr,Mk as CT,Ml as $t,Mn as L0t,Mo as gh,Nf as hs,Ng as RT,Nh as Mxt,Ni as CI,Nj as _Nr,Nk as ame,Nl as fb,Nn as $0t,No as Fx,Of as nr,Og as qS,Oh as lxt,Oi as cwe,Oj as TNr,Ok as iH,Ol as Qn,Om as N6,On as fO,Oo as ihr,Pf as Ye,Pg as rH,Ph as uxt,Pi as Rbr,Pj as tjr,Pk as cme,Pl as ps,Pm as mAr,Pn as X0t,Po as ma,Qf as Po,Qg as FT,Qi as pc,Qj as KNr,Qk as lme,Ql as p4,Qm as y7r,Qn as xO,Rf as Ws,Rg as MT,Rh as kJ,Ri as det,Rj as YNr,Rk as ume,Rl as IT,Rm as gAr,Rn as bNr,Sf as _h,Sg as she,Sh as Oxt,Si as lhe,Sj as eLr,Sk as h9,Sl as zn,Sm as dbr,Sn as BIe,Tf as age,Tg as mb,Th as P1e,Ti as l7,Tj as cLr,Tk as dme,Tl as yt,Tm as yAr,Tn as G0t,Ug as OT,Ui as xT,Uj as lLr,Um as hAr,Un as H0t,Vf as ctt,Vg as NT,Vh as i7r,Vi as kUe,Vj as uLr,Vk as pme,Vl as IIr,Vm as bAr,Vn as lz,Wf as ltt,Wg as LT,Wi as pS,Wj as wde,Wm as vAr,Wn as W0t,Xg as jT,Xh as $s,Xi as N_e,Xj as njr,Xk as so,Xl as Pi,Xn as AJ,Yg as zT,Yj as iLr,Yl as M7r,Yn as Z0t,Zf as utt,Zg as ahe,Zi as iw,Zj as fNr,Zl as Vq,Zn as ONr,_g as x9,_h as lb,_i as bGe,_k as OS,_l as R7r,_n as ext,ah as vh,aj as vct,am as Zr,ao as NNr,bh as hb,bi as ac,bk as gA,bn as Kle,bo as MNr,ch as NA,ci as zt,ck as FS,cn as B0,co as j0t,dh as $w,di as _ne,dk as Kpe,do as bie,eh as _Dr,ei as g9,ek as Mx,el as DT,em as pb,eo as iz,fh as Irt,fi as om,fl as hme,fm as Ct,fo as zpr,gh as nye,gi as sc,gm as Ox,go as nm,hi as r1,hm as pl,ho as VS,ii as ao,im as dct,in as gNr,io as xb,jg as yFr,jh as Cie,ji as af,jj as ub,jk as kT,jl as xNr,jm as Yu,jn as yNr,jo as gb,kh as Die,ki as tgr,kk as Ype,km as _T,kn as wJ,ko as yb,lg as bFr,lh as Iie,li as hmr,lk as Jpe,lm as xme,ln as txt,lo as Ju,mg as pEr,mh as _ie,mi as NI,mk as Qpe,mm as gme,mn as rxt,mo as bme,nf as rhe,nh as pmr,ni as ex,nk as BT,nl as hfr,nm as qt,nn as ixt,no as LS,of as ihe,oh as mmr,oi as D0t,ok as Xpe,ol as fne,om as Rx,on as x3,oo as nH,pf as Wpe,ph as nIe,pi as A9,pj as fFr,pk as eme,pl as lmr,pm as wie,pn as gO,qf as Jd,qh as oz,qi as zl,qk as tme,ql as LG,qm as Sie,rf as RS,ri as EI,rk as rme,rm as Ao,rn as rge,ro as jS,sf as Zpe,sh as uo,si as ct,sk as ime,sm as Jn,so as zS,tf as m9,th as Fxt,ti as bu,tk as nme,tl as Xp,tm as qIr,tn as xh,uf as st,ug as Ql,uh as Ie,ui as M$e,uk as ome,um as us,vf as kr,vg as AT,vh as D0,vi as che,vl as Qu,wg as _i,wh as Fn,wj as xA,wl as uhe,xf as he,xg as rm,xh as CJ,xj as GNr,xl as dhe,xo as _A,yf as cw,yg as Uf,yh as Pxt,yi as wT,yj as ELr,yl as phe,yo as Eme,zf as ht,zg as Vr,zh as A2,zi as DA,zj as z$e,zk as Hf,zl as mhe,zm as pO,zn as yme,zo as KGe}from"./chunks/index-evas4byh.js";import{$o as Oue,$p as M_,$q as _Z,$r as Fhr,Ap as nNr,Aq as VP,Ar as hz,As as MK,Bp as SPe,Bs as Rie,Cp as kPe,Cq as rue,Cs as uct,Dp as kU,Dq as wxr,Ep as BPe,Eq as os,Es as Xxr,Fp as fvr,Fq as $Pr,Fs as nwe,Gp as CPe,Gq as Lgr,Gr as mse,Hp as xvr,Hq as E8,Hr as vse,Hs as Ov,Ip as gvr,Iq as Gmr,Ir as Oie,Is as tIr,Jp as lse,Jq as Lie,Jr as zie,Js as Xce,Kp as use,Kq as Gne,Kr as Bi,Ks as lB,Lp as yvr,Lq as UTr,Lr as gFr,Ls as n6,Mp as dse,Mq as qTr,Mr as NFr,Ms as Ape,Np as Er,Nq as RK,Nr as uZ,Ns as Aie,Op as f5,Or as Bf,Os as aa,Pp as Ht,Pq as lrt,Ps as gyr,Qo as Avr,Qp as V0,Qq as urt,Qr as Q7,Qs as jp,Ro as Nue,Rp as iZ,Rq as Ett,Rr as yse,Rs as Xu,Sp as Op,Sq as vtt,Sr as m$,Ss as Xl,To as wn,Tp as oy,Tq as lct,Tr as iue,Ts as et,Uo as uf,Up as Yn,Uq as bn,Ur as Wze,Vo as Qie,Vp as Ede,Vq as id,Vr as Yq,Wq as eS,Wr as Jq,Ws as ST,Xo as Sr,Xp as TLr,Xq as Tce,Xr as _$,Xs as Nf,Yo as mi,Yp as PLr,Yq as pDr,Yr as tOr,Ys as wpe,Zo as xI,Zq as Pce,Zr as T$,_o as DB,_q as uge,_r as tne,_s as Bpe,ap as EB,as as Ohr,bp as Fq,br as i1,bs as qhr,cp as hJ,cr as fe,cs as Nhr,dp as xc,dq as vT,ds as Lhr,ep as Rv,eq as NTr,er as Do,es as n1,fp as vB,fs as fmr,gp as zLe,hq as YLr,hs as Cle,ip as pse,ir as Lr,is as D7r,jp as Pv,jq as WTr,jr as oZ,js as I7r,kp as nse,kq as Ret,kr as zLr,ks as UC,kt as Xd,lp as ose,lr as p9,ls as tde,lt as em,mp as tNr,mq as Gpe,mr as jie,ms as rde,mt as tm,np as doe,nq as VG,nr as iJ,ns as Ble,op as SU,oq as KG,or as c3,os as s_,pp as KP,pq as YG,ps as Oje,pt as NS,qp as cse,qq as eH,qs as Lje,rp as F6,rq as tH,rr as Kne,rs as a_r,sp as ase,sq as PS,sr as N0r,ss as N7r,tp as L8,tq as SGe,tr as Zpr,ts as c_r,up as lvr,uq as fHe,ur as vie,us as L7r,vp as uvr,vq as Px,vr as Eie,vs as q7r,wp as rNr,wq as xHe,ws as Zie,xp as xde,xq as qG,xs as qC,yp as iNr,yq as JG,yr as JIr,ys as Uie,zp as hvr,zq as QG,zr as sw,zs as FK}from"./chunks/index-mqyxs389.js";import{rt as nje,tt as UG}from"./chunks/index-epdh4ns2.js";import{$x as qs,Ax as C4,Mx as nc,Wy as SJ,_A as Xe,fB as cxt,iv as Bwe,mB as hh,nB as B4,pB as Ic,rB as Lp,sB as Jfr,tB as Vi,uB as rjr,yx as Jl}from"./chunks/index-qgnvptqj.js";import{MC as u}from"./chunks/index-a17g7wcg.js";import"./chunks/index-3d6m6emw.js";import{QC as eo,RC as fVr,SC as E,TC as zx,UC as ms,VC as ce}from"./chunks/index-6kydq3sj.js";function pZe(e){return e===0||e>=55296&&e<=57343||e>1114111}function mZe(e){if(pZe(e))return 65533;if(e>=128&&e<=159)return K$r[e-128]||e;return e}function hZe(e){return pZe(e)?65533:e}var K$r;var fZe=ms(()=>{K$r=[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 xZe(e,t,r,i,n,o){let a=e.length,c=o*90,l=0,d=()=>{let L=Zf[e.charCodeAt(l++)];return L<o?L:L*91-c+Zf[e.charCodeAt(l++)]},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,G){let V=0,ee=G,q=G+L;while(ee<q){let S=Zf[e.charCodeAt(l++)];if(S<89)V+=S,h[ee++]=V;else if(S===89){let I=Zf[e.charCodeAt(l++)]+2;while(I--)h[ee++]=++V}else{let I=Zf[e.charCodeAt(l++)];V+=89+(I<90?I*91+Zf[e.charCodeAt(l++)]:Zf[e.charCodeAt(l++)]*8281+Zf[e.charCodeAt(l++)]*91+Zf[e.charCodeAt(l++)]),h[ee++]=V}}}y(i,0),y(p,o);let b=new Int32Array(n*2),A=0,w=0;function C(L,G){for(let V=0;V<L;V++){let ee=G+V,q=d(),S=d();b[w*2]=q,b[w*2+1]=S,w+=1,f[ee]=A;let I=(h[q]<0?g[q]:1)+(h[S]<0?g[S]:1);g[ee]=I,A+=I}}C(n-o+i,o+p),C(o-i,i);let F=new Uint16Array(A),M=0;for(let L=0;L<w;L++)for(let G=0;G<2;G++){let V=b[L*2+G],ee=h[V];if(ee<0){let q=f[V],S=q+g[V];while(q<S)F[M++]=F[q++]}else F[M++]=ee}let k=new Uint16Array(t),N=0;while(l<a){let L=Zf[e.charCodeAt(l++)];if(L>=o)L=L*91-c+Zf[e.charCodeAt(l++)];let G=h[L];if(G<0){let V=f[L],ee=V+g[L];while(V<ee)k[N++]=F[V++]}else k[N++]=G}return k}var Zf;var gZe=ms(()=>{Zf=(()=>{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 Khe;var yZe=ms(()=>{gZe();Khe=xZe("!}.&u%}'&}*'~!6*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;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 tP;var Yhe=ms(()=>{tP=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 Pc;var bZe=ms(()=>{(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"})(Pc||(Pc={}))});function EZe(e){return e-tu.ZERO>>>0<=9}function Y$r(e){return(e|BH)-tu.LOWER_A>>>0<=5}function J$r(e){return(e|BH)-tu.LOWER_A>>>0<=25}function Q$r(e){return e===tu.EQUALS||J$r(e)||EZe(e)}class Jhe{decodeTree;emitCodePoint;errors;state=eu.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=Vf.Strict;runConsumed=0;constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r}startEntity(e){this.decodeMode=e,this.state=eu.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case eu.EntityStart:{if(e.charCodeAt(t)===tu.NUM)return this.state=eu.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=eu.NamedEntity,this.stateNamedEntity(e,t)}case eu.NumericStart:return this.stateNumericStart(e,t);case eu.NumericDecimal:return this.stateNumericDecimal(e,t);case eu.NumericHex:return this.stateNumericHex(e,t);default:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){if(t>=e.length)return-1;if((e.charCodeAt(t)|BH)===tu.LOWER_X)return this.state=eu.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=eu.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){let r=e.length,{result:i}=this,{consumed:n}=this;while(t<r){let o=e.charCodeAt(t);if(EZe(o)||Y$r(o)){let s=o<=tu.NINE?o-tu.ZERO:(o|BH)-tu.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)-tu.ZERO;if(o>>>0>9)return this.result=i,this.consumed=n,this.emitNumericEntity(o+tu.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===tu.SEMI)this.consumed+=1;else if(this.decodeMode===Vf.Strict)return 0;if(this.emitCodePoint((this.decodeTree===tP?hZe:mZe)(this.result),this.consumed),this.errors){if(e!==tu.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===Vf.Attribute&&(i===0||t>1||Q$r(r))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:r}=this,i=e.length,n=this.decodeMode===Vf.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=r[o];while(t<i){while((c&(Pc.VALUE_LENGTH|Pc.FLAG13))===0&&(c&Pc.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&Pc.JUMP_TABLE,f=(c&Pc.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&(Pc.VALUE_LENGTH|Pc.FLAG13))===Pc.FLAG13){let m=(c&Pc.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&Pc.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 l=c>>>14,d=e.charCodeAt(t);if(l!==0){if(!n&&(c&Pc.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===tu.SEMI)return this.emitNamedEntityData(o,l,a+s);if(l===1)return this.flushAndEmitLegacyOrReject(a,s,d,l)}let p=X$r(r,c,o+(l||1),d);if(p<0)return this.flushAndEmitLegacyOrReject(a,s,d,l);o=p,c=r[o],t+=1,s+=1}if(!n&&c>>>14!==0&&(c&Pc.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]&Pc.VALUE_MASK:i[e+1],r),t===3)this.emitCodePoint(i[e+2],r);return r}end(){switch(this.state){case eu.NamedEntity:return this.result!==0&&(this.decodeMode!==Vf.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case eu.NumericDecimal:return this.emitNumericEntity(0,2);case eu.NumericHex:return this.emitNumericEntity(0,3);case eu.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function X$r(e,t,r,i){let n=(t&Pc.BRANCH_LENGTH)>>7,o=t&Pc.JUMP_TABLE;if(o){if(n===0)return i===o?r:-1;let c=i-o;if(c>>>0>=n)return-1;let l=e[r+c];return l===0?-1:r+n+l-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 tu,BH=32,eu,Vf;var vZe=ms(()=>{fZe();Yhe();bZe();yZe();Yhe();(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"})(tu||(tu={}));(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(eu||(eu={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(Vf||(Vf={}))});function JS(e){return e===br.Space||e===br.NewLine||e===br.Tab||e===br.FormFeed||e===br.CarriageReturn}function B9(e){return e===br.Slash||e===br.Gt||JS(e)}function eGr(e){return e>=br.LowerA&&e<=br.LowerZ||e>=br.UpperA&&e<=br.UpperZ}class C9{cbs;state=We.Text;buffer="";sectionStart=0;index=0;entityStart=0;baseState=We.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 Jhe(e?tP:Khe,(n,o)=>this.emitCodePoint(n,o))}reset(){this.state=We.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=We.Text,this.isSpecial=!1,this.currentSequence=oi.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===br.Lt||!this.decodeEntities&&this.fastForwardTo(br.Lt)){if(this.index>this.sectionStart)this.cbs.ontext(this.sectionStart,this.index);this.state=We.BeforeTagName,this.sectionStart=this.index}else if(this.decodeEntities&&e===br.Amp)this.startEntity()}currentSequence=oi.Empty;sequenceIndex=0;enterTagBody(){if(this.currentSequence===oi.Plaintext)this.currentSequence=oi.Empty,this.state=We.InPlainText;else if(this.isSpecial)this.state=We.InSpecialTag,this.sequenceIndex=0;else this.state=We.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===oi.ScriptEnd&&t===oi.StyleEnd[3]){this.currentSequence=oi.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===oi.TitleEnd&&t===oi.TextareaEnd[3]){this.currentSequence=oi.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===oi.NoembedEnd&&t===oi.NoframesEnd[4]){this.currentSequence=oi.NoframesEnd,this.sequenceIndex=5;return}}else if(B9(e)){this.sequenceIndex=0,this.state=We.InTagName,this.stateInTagName(e);return}this.isSpecial=!1,this.currentSequence=oi.Empty,this.sequenceIndex=0,this.state=We.InTagName,this.stateInTagName(e)}stateCDATASequence(e){if(e===oi.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===oi.Cdata.length)this.state=We.InCommentLike,this.currentSequence=oi.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1}else if(this.sequenceIndex=0,this.xmlMode)this.state=We.InDeclaration,this.stateInDeclaration(e);else this.state=We.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=We.Text}stateInCommentLike(e){if(!this.xmlMode&&this.currentSequence===oi.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&e===br.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===oi.CommentEnd&&this.sequenceIndex===2&&e===br.Gt)this.emitComment(2);else if(this.currentSequence===oi.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&e!==br.Gt)this.sequenceIndex=Number(e===br.Dash);else if(e===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===oi.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=We.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?!B9(e):eGr(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(B9(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===oi.TitleEnd||this.currentSequence===oi.TextareaEnd){if(this.decodeEntities&&e===br.Amp)this.startEntity()}else if(this.fastForwardTo(br.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(e===br.Lt)}stateBeforeTagName(e){if(e===br.ExclamationMark)this.state=We.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===br.Questionmark)if(this.xmlMode)this.state=We.InProcessingInstruction,this.sequenceIndex=0,this.sectionStart=this.index+1;else this.state=We.InSpecialComment,this.sectionStart=this.index;else if(this.isTagStartChar(e)){this.sectionStart=this.index;let t=this.xmlMode||this.cbs.isInForeignContext?.()?void 0:tGr.get(e|32);if(t===void 0)this.state=We.InTagName;else this.isSpecial=!0,this.currentSequence=t,this.sequenceIndex=3,this.state=We.SpecialStartSequence}else if(e===br.Slash)this.state=We.BeforeClosingTagName;else this.state=We.Text,this.stateText(e)}stateInTagName(e){if(B9(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(JS(e))if(this.xmlMode);else this.state=We.InSpecialComment,this.sectionStart=this.index;else if(e===br.Gt){if(this.state=We.Text,!this.xmlMode)this.sectionStart=this.index+1}else this.state=this.isTagStartChar(e)?We.InClosingTagName:We.InSpecialComment,this.sectionStart=this.index}stateInClosingTagName(e){if(B9(e))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=We.AfterClosingTagName,this.stateAfterClosingTagName(e)}stateAfterClosingTagName(e){if(e===br.Gt||this.fastForwardTo(br.Gt))this.state=We.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(e){if(e===br.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(e===br.Slash)this.state=We.InSelfClosingTag;else if(!JS(e))this.state=We.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(e){if(e===br.Gt){if(this.cbs.onselfclosingtag(this.index),this.sectionStart=this.index+1,!this.recognizeSelfClosing){this.enterTagBody();return}this.state=We.Text,this.isSpecial=!1,this.currentSequence=oi.Empty}else if(!JS(e))this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===br.Eq||B9(e))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=We.AfterAttributeName,this.stateAfterAttributeName(e)}stateAfterAttributeName(e){if(e===br.Eq)this.state=We.BeforeAttributeValue;else if(e===br.Slash||e===br.Gt)this.cbs.onattribend(sm.NoValue,this.sectionStart),this.sectionStart=-1,this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!JS(e))this.cbs.onattribend(sm.NoValue,this.sectionStart),this.state=We.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(e){if(e===br.DoubleQuote)this.state=We.InAttributeValueDq,this.sectionStart=this.index+1;else if(e===br.SingleQuote)this.state=We.InAttributeValueSq,this.sectionStart=this.index+1;else if(!JS(e))this.sectionStart=this.index,this.state=We.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===br.DoubleQuote?sm.Double:sm.Single,this.index+1),this.state=We.BeforeAttributeName;else if(this.decodeEntities&&e===br.Amp)this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,br.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,br.SingleQuote)}stateInAttributeValueNoQuotes(e){if(JS(e)||e===br.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(sm.Unquoted,this.index),this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(this.decodeEntities&&e===br.Amp)this.startEntity()}stateBeforeDeclaration(e){if(e===br.OpeningSquareBracket)this.state=We.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=e===br.Dash?We.BeforeComment:We.InDeclaration;else if((e|32)===oi.Doctype[0])this.state=We.DeclarationSequence,this.currentSequence=oi.Doctype,this.sequenceIndex=1;else if(e===br.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=We.Text,this.sectionStart=this.index+1;else if(e===br.Dash)this.state=We.BeforeComment;else this.state=We.InSpecialComment}stateDeclarationSequence(e){if(this.sequenceIndex===this.currentSequence.length)this.state=We.InDeclaration,this.stateInDeclaration(e);else if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(e===br.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=We.Text,this.sectionStart=this.index+1;else this.state=We.InSpecialComment}stateInDeclaration(e){if(e===br.Gt||this.fastForwardTo(br.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=We.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(e){if(e===br.Questionmark)this.sequenceIndex=1;else if(e===br.Gt&&this.sequenceIndex===1)this.cbs.onprocessinginstruction(this.sectionStart,this.index-1),this.sequenceIndex=0,this.state=We.Text,this.sectionStart=this.index+1;else this.sequenceIndex=Number(this.fastForwardTo(br.Questionmark))}stateBeforeComment(e){if(e===br.Dash)this.state=We.InCommentLike,this.currentSequence=oi.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=We.InDeclaration;else if(e===br.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=We.Text,this.sectionStart=this.index+1;else this.state=We.InSpecialComment}stateInSpecialComment(e){if(e===br.Gt||this.fastForwardTo(br.Gt))this.cbs.oncomment(this.sectionStart,this.index,0),this.state=We.Text,this.sectionStart=this.index+1}startEntity(){this.baseState=this.state,this.state=We.InEntity,this.entityStart=this.index,this.entityDecoder.startEntity(this.xmlMode?Vf.Strict:this.baseState===We.Text||this.baseState===We.InSpecialTag?Vf.Legacy:Vf.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)===br.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===We.Text||this.state===We.InPlainText||this.state===We.InSpecialTag&&this.sequenceIndex===0)this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index;else if(this.state===We.InAttributeValueDq||this.state===We.InAttributeValueSq||this.state===We.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 We.Text:{this.stateText(e);break}case We.InPlainText:{this.index=this.buffer.length+this.offset-1;break}case We.SpecialStartSequence:{this.stateSpecialStartSequence(e);break}case We.InSpecialTag:{this.stateInSpecialTag(e);break}case We.CDATASequence:{this.stateCDATASequence(e);break}case We.DeclarationSequence:{this.stateDeclarationSequence(e);break}case We.InAttributeValueDq:{this.stateInAttributeValueDoubleQuotes(e);break}case We.InAttributeName:{this.stateInAttributeName(e);break}case We.InCommentLike:{this.stateInCommentLike(e);break}case We.InSpecialComment:{this.stateInSpecialComment(e);break}case We.BeforeAttributeName:{this.stateBeforeAttributeName(e);break}case We.InTagName:{this.stateInTagName(e);break}case We.InClosingTagName:{this.stateInClosingTagName(e);break}case We.BeforeTagName:{this.stateBeforeTagName(e);break}case We.AfterAttributeName:{this.stateAfterAttributeName(e);break}case We.InAttributeValueSq:{this.stateInAttributeValueSingleQuotes(e);break}case We.BeforeAttributeValue:{this.stateBeforeAttributeValue(e);break}case We.BeforeClosingTagName:{this.stateBeforeClosingTagName(e);break}case We.AfterClosingTagName:{this.stateAfterClosingTagName(e);break}case We.InAttributeValueNq:{this.stateInAttributeValueNoQuotes(e);break}case We.InSelfClosingTag:{this.stateInSelfClosingTag(e);break}case We.InDeclaration:{this.stateInDeclaration(e);break}case We.BeforeDeclaration:{this.stateBeforeDeclaration(e);break}case We.BeforeComment:{this.stateBeforeComment(e);break}case We.InProcessingInstruction:{this.stateInProcessingInstruction(e);break}case We.InEntity:{this.stateInEntity();break}}this.index++}this.cleanup()}finish(){if(this.state===We.InEntity)this.entityDecoder.end(),this.state=this.baseState;this.handleTrailingData(),this.cbs.onend()}handleTrailingCommentLikeData(e){if(this.state!==We.InCommentLike)return!1;if(this.currentSequence===oi.CdataEnd)if(this.xmlMode){if(this.sectionStart<e)this.cbs.oncdata(this.sectionStart,e,0)}else{let t=this.sectionStart-oi.Cdata.length-1;this.cbs.oncomment(t,e,0)}else{let t=this.xmlMode?0:Math.min(this.sequenceIndex,oi.CommentEnd.length-1);this.cbs.oncomment(this.sectionStart,e,t)}return!0}handleTrailingMarkupDeclaration(e){if(this.xmlMode)switch(this.state){case We.InSpecialComment:case We.BeforeComment:case We.CDATASequence:case We.DeclarationSequence:case We.InDeclaration:return this.cbs.ontext(this.sectionStart,e),!0;default:return!1}switch(this.state){case We.BeforeDeclaration:case We.InSpecialComment:case We.BeforeComment:case We.CDATASequence:return this.cbs.oncomment(this.sectionStart,e,0),!0;case We.DeclarationSequence:{if(this.sequenceIndex!==oi.Doctype.length)this.cbs.oncomment(this.sectionStart,e,0);return!0}case We.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 We.InTagName:case We.BeforeAttributeName:case We.BeforeAttributeValue:case We.AfterAttributeName:case We.InAttributeName:case We.InAttributeValueSq:case We.InAttributeValueDq:case We.InAttributeValueNq:case We.InClosingTagName:break;default:this.cbs.ontext(this.sectionStart,e)}}emitCodePoint(e,t){if(this.baseState!==We.Text&&this.baseState!==We.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 br,We,sm,oi,tGr;var Qhe=ms(()=>{vZe();(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"})(br||(br={}));(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"})(We||(We={}));(function(e){e[e.NoValue=0]="NoValue",e[e.Unquoted=1]="Unquoted",e[e.Single=2]="Single",e[e.Double=3]="Double"})(sm||(sm={}));oi={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])},tGr=new Map([[oi.IframeEnd[2],oi.IframeEnd],[oi.NoembedEnd[2],oi.NoembedEnd],[oi.Plaintext[2],oi.Plaintext],[oi.ScriptEnd[2],oi.ScriptEnd],[oi.TitleEnd[2],oi.TitleEnd],[oi.XmpEnd[2],oi.XmpEnd]])});class _9{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??C9)(this.options,this),this.foreignContext=[Ab.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?.(AZe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==Ab.None}isVoidElement(e){return this.htmlMode&&iGr.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]===Ab.Svg)return DZe.get(r)??r;if(this.foreignContext.length>1){let i=DZe.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&&rGr.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(Ab.Svg);else if(e==="math")this.foreignContext.unshift(Ab.MathML);else if(CZe.has(e))this.foreignContext.unshift(Ab.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&&(nGr.has(t)||CZe.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+=AZe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===sm.Double?'"':e===sm.Single?"'":e===sm.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(oGr),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?BZe:r.slice(0,BZe.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(Ab.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 AZe,D9,Gs,I9,wZe,SZe,kZe,rGr,BZe="doctype",iGr,nGr,CZe,DZe,Ab,oGr;var Xhe=ms(()=>{Qhe();({fromCodePoint:AZe}=String),D9=new Set(["input","option","optgroup","select","button","datalist","textarea"]),Gs=new Set(["p"]),I9=new Set(["h1","h2","h3","h4","h5","h6","p"]),wZe=new Set(["thead","tbody"]),SZe=new Set(["dd","dt"]),kZe=new Set(["rt","rp"]),rGr=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",Gs],["h1",I9],["h2",I9],["h3",I9],["h4",I9],["h5",I9],["h6",I9],["select",D9],["input",D9],["output",D9],["button",D9],["datalist",D9],["textarea",D9],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",SZe],["dt",SZe],["address",Gs],["article",Gs],["aside",Gs],["blockquote",Gs],["details",Gs],["div",Gs],["dl",Gs],["fieldset",Gs],["figcaption",Gs],["figure",Gs],["footer",Gs],["form",Gs],["header",Gs],["hr",Gs],["main",Gs],["nav",Gs],["ol",Gs],["pre",Gs],["section",Gs],["table",Gs],["ul",Gs],["rt",kZe],["rp",kZe],["tbody",wZe],["tfoot",wZe]]),iGr=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),nGr=new Set(["math","svg"]),CZe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),DZe=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"})(Ab||(Ab={}));oGr=/\s|\//});var CH={};zx(CH,{CDATA:()=>cfe,Comment:()=>nfe,Directive:()=>ife,Doctype:()=>sGr,ElementType:()=>dn,Root:()=>tfe,Script:()=>ofe,Style:()=>sfe,Tag:()=>afe,Text:()=>rfe,isTag:()=>efe});function efe(e){return e.type===dn.Tag||e.type===dn.Script||e.type===dn.Style}var dn,tfe,rfe,ife,nfe,ofe,sfe,afe,cfe,sGr;var T9=ms(()=>{(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"})(dn||(dn={}));tfe=dn.Root,rfe=dn.Text,ife=dn.Directive,nfe=dn.Comment,ofe=dn.Script,sfe=dn.Style,afe=dn.Tag,cfe=dn.CDATA,sGr=dn.Doctype});class ufe{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 IZe(this,e)}}function ru(e){return efe(e)}function FH(e){return e.type===dn.CDATA}function qA(e){return e.type===dn.Text}function dfe(e){return e.type===dn.Comment}function aGr(e){return e.type===dn.Directive}function cGr(e){return e.type===dn.Root}function ep(e){return Object.hasOwn(e,"children")}function IZe(e,t=!1){let r;if(qA(e))r=new rP(e.data);else if(dfe(e))r=new IH(e.data);else if(ru(e)){let i=t?lfe(e.children):[],n=new RH(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(FH(e)){let i=t?lfe(e.children):[],n=new PH(i);for(let o of i)o.parent=n;r=n}else if(cGr(e)){let i=t?lfe(e.children):[],n=new iP(i);for(let o of i)o.parent=n;if(e["x-mode"])n["x-mode"]=e["x-mode"];r=n}else if(aGr(e)){let i=new _H(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 lfe(e){let t=e.map((r)=>IZe(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 DH,rP,IH,_H,TH,PH,iP,RH;var pfe=ms(()=>{T9();DH=class DH extends ufe{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};rP=class rP extends DH{type=dn.Text;get nodeType(){return 3}};IH=class IH extends DH{type=dn.Comment;get nodeType(){return 8}};_H=class _H extends DH{type=dn.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};TH=class TH extends ufe{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}};PH=class PH extends TH{type=dn.CDATA;get nodeType(){return 4}};iP=class iP extends TH{type=dn.Root;get nodeType(){return 9}};RH=class RH extends TH{name;attribs;type;constructor(e,t,r=[],i=e==="script"?dn.Script:e==="style"?dn.Style:dn.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 QS{dom=[];root=new iP(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=_Ze;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??_Ze,this.elementCB=r??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new iP(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?dn.Tag:void 0,i=new RH(e,t,void 0,r);this.addNode(i),this.tagStack.push(i)}ontext(e){let{lastNode:t}=this;if(t&&t.type===dn.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let r=new rP(e);this.addNode(r),this.lastNode=r}}oncomment(e){if(this.lastNode&&this.lastNode.type===dn.Comment){this.lastNode.data+=e;return}let t=new IH(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new rP(""),t=new PH([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let r=new _H(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 _Ze;var $A=ms(()=>{T9();pfe();pfe();_Ze={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function P9(e,t,r=!0,i=Number.POSITIVE_INFINITY){return TZe(e,Array.isArray(t)?t:[t],r,i)}function TZe(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&&ep(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function MH(e,t,r=!0){let i=Array.isArray(t)?t:[t];for(let n of i){if(ru(n)&&e(n))return n;if(r&&ep(n)&&n.children.length>0){let o=MH(e,n.children,!0);if(o)return o}}return null}function PZe(e,t){return(Array.isArray(t)?t:[t]).some((r)=>ru(r)&&e(r)||ep(r)&&PZe(e,r.children))}function lGr(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(ru(o)&&e(o))r.push(o);if(ep(o)&&o.children.length>0)n.unshift(0),i.unshift(o.children)}}var mfe=ms(()=>{$A()});function hfe(e,t){if(typeof t==="function")return(r)=>ru(r)&&t(r.attribs[e]);return(r)=>ru(r)&&r.attribs[e]===t}function uGr(e,t){return(r)=>e(r)||t(r)}function RZe(e){let t=Object.keys(e).map((r)=>{let i=e[r];return Object.hasOwn(OH,r)?OH[r](i):hfe(r,i)});return t.length===0?null:t.reduce(uGr)}function dGr(e,t){let r=RZe(e);return r?r(t):!0}function pGr(e,t,r,i=Number.POSITIVE_INFINITY){let n=RZe(e);return n?P9(n,t,r,i):[]}function mGr(e,t,r=!0){if(!Array.isArray(t))t=[t];return MH(hfe("id",e),t,r)}function XS(e,t,r=!0,i=Number.POSITIVE_INFINITY){return P9(OH.tag_name(e),t,r,i)}function hGr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return P9(hfe("class",e),t,r,i)}function fGr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return P9(OH.tag_type(e),t,r,i)}var OH;var ffe=ms(()=>{$A();mfe();OH={tag_name(e){if(typeof e==="function")return(t)=>ru(t)&&e(t.name);if(e==="*")return ru;return(t)=>ru(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)=>qA(t)&&e(t.data);return(t)=>qA(t)&&t.data===e}}});function MZe(e){return e===34?""":e===38?"&":e===39?"'":e===60?"<":e===62?">":" "}function FZe(e){return e>=128||e>=32&&e<64&&(xGr>>>e&1)===1}function NH(e){let{length:t}=e,r,i=0,n=0;while(n<t){let o=e.charCodeAt(n);if(!FZe(o)){let a=Math.min(n+32,t),c=n+1;while(c<a&&!FZe(e.charCodeAt(c)))c++;if(c<a){n=c;continue}if(c>=t)break;if(xfe.lastIndex=c,!xfe.test(e))break;n=xfe.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+=MZe(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 OZe(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+=MZe(o),i=n+1}while(e.test(t));return r+t.substring(i)}function gfe(e){return OZe(gGr,e)}function yfe(e){return OZe(yGr,e)}var xGr=1342177476,xfe,gGr,yGr;var NZe=ms(()=>{xfe=/["&'<>\u0080-\uFFFF]/g;gGr=/["&\u{A0}]/gu;yGr=/[&<>\u{A0}]/gu});var LZe,jZe;var zZe=ms(()=>{NZe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(LZe||(LZe={}));(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"})(jZe||(jZe={}))});var UZe,qZe;var $Ze=ms(()=>{UZe=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])),qZe=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 wGr(e,t={}){let r="length"in e?e:[e],i=t.xmlMode??!1,n="";for(let o=0;o<r.length;o++)n+=HZe(r[o],t,i);return n}function GZe(e,t,r){let i="";for(let n=0;n<e.length;n++)i+=HZe(e[n],t,r);return i}function HZe(e,t,r){switch(e.type){case tfe:return GZe(e.children,t,r);case ife:return`<${e.data}>`;case nfe:return`<!--${e.data}-->`;case cfe:return`<![CDATA[${e.children[0].data}]]>`;case ofe:case sfe:case afe:return SGr(e,t,r);case rfe:{let i=e,n=i.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!r&&i.parent&&bGr.has(i.parent.name)))return r||t.encodeEntities!=="utf8"?NH(n):yfe(n);return n}}}function SGr(e,t,r){if(r==="foreign"){if(e.name=UZe.get(e.name)??e.name,e.parent&&AGr.has(e.parent.name))r=!1}if(!r&&vGr.has(e.name))r="foreign";let{name:i,children:n}=e,o=!r&&EGr.has(i),s=`<${i}${BGr(e.attribs,t,r)}`;if(n.length===0&&(r?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=r?"/>":" />";else{if(s+=">",n.length>0)s+=GZe(n,t,r);if(!o)s+=`</${i}>`}return s}function kGr(e){return e.replaceAll('"',""")}function BGr(e,t,r){if(!e)return"";let i=(t.encodeEntities??t.decodeEntities)===!1?kGr:r||t.encodeEntities!=="utf8"?NH:gfe,n=r==="foreign",o=!!(t.emptyAttrs??r),s="";for(let a in e){if(!Object.hasOwn(e,a))continue;let c=e[a],l=n?qZe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${l}`:` ${l}="${i(c==null?"":String(c))}"`}return s}var bGr,EGr,vGr,AGr,WZe;var ZZe=ms(()=>{T9();zZe();$Ze();bGr=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),EGr=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),vGr=new Set(["svg","math"]),AGr=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));WZe=wGr});function VZe(e,t){return WZe(e,t)}function CGr(e,t){return ep(e)?e.children.map((r)=>VZe(r,t)).join(""):""}function LH(e){if(Array.isArray(e))return e.map(LH).join("");if(ru(e))return e.name==="br"?`
|
|
2
|
+
import"./chunks/index-z7gkbgw5.js";import{$ as xo,$a as zxn,$b as Agn,$c as Kgn,Aa as q0,Ab as Aj,Ad as Eyn,Ba as Fcr,Bb as ugn,Bd as Fk,C as Zg,Ca as Mcr,Cb as dgn,Cc as Cpr,Cd as vyn,D as M0n,Da as Exn,Db as nv,Dd as Ayn,E as wcr,Ea as vxn,Eb as Lcr,Ed as wyn,F as Pcr,Fa as Tre,Fb as yj,Fd as Kg,G as W0n,Ga as Axn,Gb as pgn,Gd as vj,H as Z0n,Hb as mgn,Hd as Syn,I as V0n,Ia as I3e,Ib as hgn,Id as kyn,J as K0n,Ja as wxn,Jb as fgn,Jd as Byn,K as Y0n,Ka as Sxn,Kd as Cyn,La as kxn,Lb as jcr,Ld as Dyn,M as Fre,Ma as Bxn,Mb as zcr,Md as Iyn,Na as Cxn,Nb as Ucr,Nd as _yn,Oa as Dxn,Ob as qcr,Od as Tyn,P as Ok,Pa as Ixn,Pb as $cr,Pd as Pyn,Q as fcr,Qa as Ocr,Qb as Gcr,Qd as Ore,R as Mk,Ra as _xn,Rb as Hcr,Rc as Jcr,Rd as L3e,S as Wg,Sa as Txn,Sb as Wcr,Sc as Ugn,Sd as Ryn,Ta as Pxn,Tb as Zcr,Tc as qgn,Td as _3e,U as O3e,Ua as Rxn,Ub as Vcr,Uc as $gn,Ud as Fyn,V as J0n,Va as Fxn,Vb as xgn,Vc as Ggn,Vd as qm,W as Vt,Wa as Mxn,Wb as ggn,Wc as Rk,Wd as ure,Xa as Oxn,Xb as ygn,Xc as Hgn,Xd as Myn,Y as Rcr,Ya as Nxn,Yb as bgn,Yc as Wgn,Z as Q0n,Za as Lxn,Zb as Egn,Zc as Zgn,_ as s8,_a as jxn,_b as vgn,_c as Vgn,aa as l8,ab as Uxn,ac as wgn,ad as Ygn,ba as Jc,bb as qxn,bc as Sgn,bd as Jgn,ca as X0n,cb as $xn,cc as kgn,cd as Qgn,da as exn,db as a8,dc as Bgn,dd as Xgn,ea as txn,eb as Gxn,ec as Cgn,ed as eyn,fa as rxn,fb as k3e,fc as Dgn,fd as tyn,ga as ixn,gb as Hxn,gc as Ign,gd as ryn,ha as nxn,hb as Wxn,hc as _gn,hd as iyn,ia as oxn,ib as Zxn,ic as Tgn,id as nyn,ja as sxn,jb as Vxn,jc as B3e,jd as oyn,ka as axn,kb as Kxn,kc as Ej,kd as syn,la as cxn,lb as Yxn,lc as Pgn,ld as ayn,ma as lxn,mb as Jxn,mc as Rgn,md as cyn,na as uxn,nb as Qxn,nc as Fgn,nd as lyn,oa as dxn,ob as Xxn,oc as Mgn,od as uyn,pa as pxn,pb as egn,pc as Ogn,qa as mxn,qb as tgn,qc as Ngn,qd as dyn,ra as hxn,rb as rgn,rc as Lgn,rd as pyn,sa as fxn,sb as ign,sc as Kcr,sd as myn,ta as FCe,tb as ngn,tc as Ycr,td as bcr,ua as xxn,ub as ogn,uc as hcr,ud as hyn,va as gxn,vb as sgn,vc as jgn,vd as fyn,wa as yxn,wb as Ncr,wc as zgn,wd as xyn,xa as bxn,xb as agn,xc as N3e,xd as gyn,ya as S3e,yb as cgn,yd as yyn,za as Bj,zb as lgn,zd as byn}from"./chunks/index-v13gwxf7.js";import{$d as Dbr,Yd as XI,Zd as aEr,be as TTe}from"./chunks/index-tcaxjgy7.js";import{de as a0e}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 bS}from"./chunks/index-502w71jz.js";import{Ce as SHe,De as b7r,Ee as QPr,Fe as bg,Ge as eJ,He as lU,Ie as mbr,Je as xy,Ke as $Dr,Le as YI,Me as w_r,Ne as lbr,Oe as hbr,Pe as YDr,Qe as zDr,Re as Wft,Se as $Rr,Te as _Ue,Ue as TUe,Ve as PUe,We as Tyr,Xe as UI,Ye as UDr,Ze as hf,_e as JI,gf as NG,ke as fGe,le as jG,ne as So,oe as h5,pe as tge,qe as oge,re as qb,se as JW,te as QW,ue as XW,ve as iXe,we as eZ,xe as n4,ye as Wet,ze as fs}from"./chunks/index-14pxgebm.js";import{jf as wme,kf as ojr}from"./chunks/index-bskj3xx3.js";import"./chunks/index-s8p4985c.js";import{$f as dtt,$g as RA,$h as FA,$i as Ect,$k as mme,$l as fme,$n as axt,Af as MZ,Ag as ca,Ah as g3,Ai as LA,Aj as JLr,Ak as $S,Al as hhe,Am as N0t,Ao as vme,Bf as vl,Bg as ds,Bh as BJ,Bi as AI,Bj as QLr,Bk as GS,Bl as fhe,Bm as gJ,Bo as CA,Cf as drt,Cg as Qd,Ch as bxt,Ci as CUe,Cj as Yz,Ck as mH,Cl as WS,Cm as Pde,Cn as emr,Co as fh,Df as IR,Dg as cb,Dh as S2,Di as yGe,Dj as _f,Dl as UT,Dm as Rde,Dn as tmr,Do as Ame,Ef as _R,Eg as Vpe,Eh as Tl,Ei as SFr,Ej as MB,Ek as HS,El as ZS,En as yJ,Eo as TT,Ff as gr,Fh as a1,Fi as sJ,Fj as sLr,Fl as la,Fn as K0t,Fo as $Ir,Gf as g4,Gh as bO,Gi as vne,Gj as aLr,Gl as Zo,Gm as HNr,Gn as Y0t,Hf as OZ,Hg as nhe,Hh as s1,Hi as vue,Hj as Sde,Hl as qT,Hn as fLr,If as mR,Ig as un,Ih as I0,Ii as Ane,Ij as XLr,Ik as sme,Il as Wi,In as xLr,Jg as wo,Jh as C1e,Ji as yle,Jj as ejr,Jk as IA,Jl as xhe,Jn as J0t,Kf as aw,Kg as Yft,Kh as Ixt,Ki as nJ,Kj as CNr,Kk as db,Kl as ghe,Kn as Q0t,Ko as TA,Lf as lge,Lg as ohe,Lh as Dxt,Li as dS,Lj as DNr,Lk as MS,Ll as im,Ln as Ywe,Lo as Wb,Mf as NZ,Mh as Nte,Mi as BI,Mj as INr,Mk as CT,Ml as $t,Mn as L0t,Mo as gh,Nf as hs,Ng as RT,Nh as Mxt,Ni as CI,Nj as _Nr,Nk as ame,Nl as fb,Nn as $0t,No as Fx,Of as nr,Og as qS,Oh as lxt,Oi as cwe,Oj as TNr,Ok as iH,Ol as Qn,Om as N6,On as fO,Oo as ihr,Pf as Ye,Pg as rH,Ph as uxt,Pi as Rbr,Pj as tjr,Pk as cme,Pl as ps,Pm as mAr,Pn as X0t,Po as ma,Qf as Po,Qg as FT,Qi as pc,Qj as KNr,Qk as lme,Ql as p4,Qm as y7r,Qn as xO,Rf as Ws,Rg as MT,Rh as kJ,Ri as det,Rj as YNr,Rk as ume,Rl as IT,Rm as gAr,Rn as bNr,Sf as _h,Sg as she,Sh as Oxt,Si as lhe,Sj as eLr,Sk as h9,Sl as zn,Sm as dbr,Sn as BIe,Tf as age,Tg as mb,Th as P1e,Ti as l7,Tj as cLr,Tk as dme,Tl as yt,Tm as yAr,Tn as G0t,Ug as OT,Ui as xT,Uj as lLr,Um as hAr,Un as H0t,Vf as ctt,Vg as NT,Vh as i7r,Vi as kUe,Vj as uLr,Vk as pme,Vl as IIr,Vm as bAr,Vn as lz,Wf as ltt,Wg as LT,Wi as pS,Wj as wde,Wm as vAr,Wn as W0t,Xg as jT,Xh as $s,Xi as N_e,Xj as njr,Xk as so,Xl as Pi,Xn as AJ,Yg as zT,Yj as iLr,Yl as M7r,Yn as Z0t,Zf as utt,Zg as ahe,Zi as iw,Zj as fNr,Zl as Vq,Zn as ONr,_g as x9,_h as lb,_i as bGe,_k as OS,_l as R7r,_n as ext,ah as vh,aj as vct,am as Zr,ao as NNr,bh as hb,bi as ac,bk as gA,bn as Kle,bo as MNr,ch as NA,ci as zt,ck as FS,cn as B0,co as j0t,dh as $w,di as _ne,dk as Kpe,do as bie,eh as _Dr,ei as g9,ek as Mx,el as DT,em as pb,eo as iz,fh as Irt,fi as om,fl as hme,fm as Ct,fo as zpr,gh as nye,gi as sc,gm as Ox,go as nm,hi as r1,hm as pl,ho as VS,ii as ao,im as dct,in as gNr,io as xb,jg as yFr,jh as Cie,ji as af,jj as ub,jk as kT,jl as xNr,jm as Yu,jn as yNr,jo as gb,kh as Die,ki as tgr,kk as Ype,km as _T,kn as wJ,ko as yb,lg as bFr,lh as Iie,li as hmr,lk as Jpe,lm as xme,ln as txt,lo as Ju,mg as pEr,mh as _ie,mi as NI,mk as Qpe,mm as gme,mn as rxt,mo as bme,nf as rhe,nh as pmr,ni as ex,nk as BT,nl as hfr,nm as qt,nn as ixt,no as LS,of as ihe,oh as mmr,oi as D0t,ok as Xpe,ol as fne,om as Rx,on as x3,oo as nH,pf as Wpe,ph as nIe,pi as A9,pj as fFr,pk as eme,pl as lmr,pm as wie,pn as gO,qf as Jd,qh as oz,qi as zl,qk as tme,ql as LG,qm as Sie,rf as RS,ri as EI,rk as rme,rm as Ao,rn as rge,ro as jS,sf as Zpe,sh as uo,si as ct,sk as ime,sm as Jn,so as zS,tf as m9,th as Fxt,ti as bu,tk as nme,tl as Xp,tm as qIr,tn as xh,uf as st,ug as Ql,uh as Ie,ui as M$e,uk as ome,um as us,vf as kr,vg as AT,vh as D0,vi as che,vl as Qu,wg as _i,wh as Fn,wj as xA,wl as uhe,xf as he,xg as rm,xh as CJ,xj as GNr,xl as dhe,xo as _A,yf as cw,yg as Uf,yh as Pxt,yi as wT,yj as ELr,yl as phe,yo as Eme,zf as ht,zg as Vr,zh as A2,zi as DA,zj as z$e,zk as Hf,zl as mhe,zm as pO,zn as yme,zo as KGe}from"./chunks/index-evas4byh.js";import{$o as Oue,$p as M_,$q as _Z,$r as Fhr,Ap as nNr,Aq as VP,Ar as hz,As as MK,Bp as SPe,Bs as Rie,Cp as kPe,Cq as rue,Cs as uct,Dp as kU,Dq as wxr,Ep as BPe,Eq as os,Es as Xxr,Fp as fvr,Fq as $Pr,Fs as nwe,Gp as CPe,Gq as Lgr,Gr as mse,Hp as xvr,Hq as E8,Hr as vse,Hs as Ov,Ip as gvr,Iq as Gmr,Ir as Oie,Is as tIr,Jp as lse,Jq as Lie,Jr as zie,Js as Xce,Kp as use,Kq as Gne,Kr as Bi,Ks as lB,Lp as yvr,Lq as UTr,Lr as gFr,Ls as n6,Mp as dse,Mq as qTr,Mr as NFr,Ms as Ape,Np as Er,Nq as RK,Nr as uZ,Ns as Aie,Op as f5,Or as Bf,Os as aa,Pp as Ht,Pq as lrt,Ps as gyr,Qo as Avr,Qp as V0,Qq as urt,Qr as Q7,Qs as jp,Ro as Nue,Rp as iZ,Rq as Ett,Rr as yse,Rs as Xu,Sp as Op,Sq as vtt,Sr as m$,Ss as Xl,To as wn,Tp as oy,Tq as lct,Tr as iue,Ts as et,Uo as uf,Up as Yn,Uq as bn,Ur as Wze,Vo as Qie,Vp as Ede,Vq as id,Vr as Yq,Wq as eS,Wr as Jq,Ws as ST,Xo as Sr,Xp as TLr,Xq as Tce,Xr as _$,Xs as Nf,Yo as mi,Yp as PLr,Yq as pDr,Yr as tOr,Ys as wpe,Zo as xI,Zq as Pce,Zr as T$,_o as DB,_q as uge,_r as tne,_s as Bpe,ap as EB,as as Ohr,bp as Fq,br as i1,bs as qhr,cp as hJ,cr as fe,cs as Nhr,dp as xc,dq as vT,ds as Lhr,ep as Rv,eq as NTr,er as Do,es as n1,fp as vB,fs as fmr,gp as zLe,hq as YLr,hs as Cle,ip as pse,ir as Lr,is as D7r,jp as Pv,jq as WTr,jr as oZ,js as I7r,kp as nse,kq as Ret,kr as zLr,ks as UC,kt as Xd,lp as ose,lr as p9,ls as tde,lt as em,mp as tNr,mq as Gpe,mr as jie,ms as rde,mt as tm,np as doe,nq as VG,nr as iJ,ns as Ble,op as SU,oq as KG,or as c3,os as s_,pp as KP,pq as YG,ps as Oje,pt as NS,qp as cse,qq as eH,qs as Lje,rp as F6,rq as tH,rr as Kne,rs as a_r,sp as ase,sq as PS,sr as N0r,ss as N7r,tp as L8,tq as SGe,tr as Zpr,ts as c_r,up as lvr,uq as fHe,ur as vie,us as L7r,vp as uvr,vq as Px,vr as Eie,vs as q7r,wp as rNr,wq as xHe,ws as Zie,xp as xde,xq as qG,xs as qC,yp as iNr,yq as JG,yr as JIr,ys as Uie,zp as hvr,zq as QG,zr as sw,zs as FK}from"./chunks/index-mqyxs389.js";import{rt as nje,tt as UG}from"./chunks/index-epdh4ns2.js";import{$x as qs,Ax as C4,Mx as nc,Wy as SJ,_A as Xe,fB as cxt,iv as Bwe,mB as hh,nB as B4,pB as Ic,rB as Lp,sB as Jfr,tB as Vi,uB as rjr,yx as Jl}from"./chunks/index-qgnvptqj.js";import{MC as u}from"./chunks/index-a17g7wcg.js";import"./chunks/index-3d6m6emw.js";import{QC as eo,RC as fVr,SC as E,TC as zx,UC as ms,VC as ce}from"./chunks/index-6kydq3sj.js";function pZe(e){return e===0||e>=55296&&e<=57343||e>1114111}function mZe(e){if(pZe(e))return 65533;if(e>=128&&e<=159)return K$r[e-128]||e;return e}function hZe(e){return pZe(e)?65533:e}var K$r;var fZe=ms(()=>{K$r=[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 xZe(e,t,r,i,n,o){let a=e.length,c=o*90,l=0,d=()=>{let L=Zf[e.charCodeAt(l++)];return L<o?L:L*91-c+Zf[e.charCodeAt(l++)]},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,G){let V=0,ee=G,q=G+L;while(ee<q){let S=Zf[e.charCodeAt(l++)];if(S<89)V+=S,h[ee++]=V;else if(S===89){let I=Zf[e.charCodeAt(l++)]+2;while(I--)h[ee++]=++V}else{let I=Zf[e.charCodeAt(l++)];V+=89+(I<90?I*91+Zf[e.charCodeAt(l++)]:Zf[e.charCodeAt(l++)]*8281+Zf[e.charCodeAt(l++)]*91+Zf[e.charCodeAt(l++)]),h[ee++]=V}}}y(i,0),y(p,o);let b=new Int32Array(n*2),A=0,w=0;function C(L,G){for(let V=0;V<L;V++){let ee=G+V,q=d(),S=d();b[w*2]=q,b[w*2+1]=S,w+=1,f[ee]=A;let I=(h[q]<0?g[q]:1)+(h[S]<0?g[S]:1);g[ee]=I,A+=I}}C(n-o+i,o+p),C(o-i,i);let F=new Uint16Array(A),M=0;for(let L=0;L<w;L++)for(let G=0;G<2;G++){let V=b[L*2+G],ee=h[V];if(ee<0){let q=f[V],S=q+g[V];while(q<S)F[M++]=F[q++]}else F[M++]=ee}let k=new Uint16Array(t),N=0;while(l<a){let L=Zf[e.charCodeAt(l++)];if(L>=o)L=L*91-c+Zf[e.charCodeAt(l++)];let G=h[L];if(G<0){let V=f[L],ee=V+g[L];while(V<ee)k[N++]=F[V++]}else k[N++]=G}return k}var Zf;var gZe=ms(()=>{Zf=(()=>{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 Khe;var yZe=ms(()=>{gZe();Khe=xZe("!}.&u%}'&}*'~!6*)%&,~!J~!J~%L~y<~!R,~~%Lu~~#GD~~#|)1#%}^%}2%+#.##%##%}&%##%'#%##&%#%#'%#&#%#&#'#%%#&#%##%#)%''%&%#%#'%#%%#%%}%%%#%#&(23#%%#&-%0%('1#(##%#'##+%'*.:1}#%#6-+(%'%%#%%%}#L'2351&('%}&/N'(0(/*-%(%%}#'+&T%7.2}#&%&#%#36/5##%&%%#&#%%#))2%%##%&&'0~!#*+&'%1~!%).'3q?&%'1~!.##%6(~!+%%%(Gw'rT~!E#<nA%#jZ~!H%(~!42##~!*31&~!G%U~#)5~#`3~!J~!Z~%]~%Y~%C~!q~!u~#kz~%#~!6'~!D~!U~!?~#T~!c%~!G#'~%7|~!G~!J~!G&~#pb~(Df}#%}*&}#%##%##%##&#-}&'#'&%#.++}%mI,#,@&(}*%}*'%&##&#%##%}&0}#.},U},%}+%}&%}#%##&}B%(}(%}+%)})%##%#&}&%##%&}<%}>%#%&}*%}(%}9%}/%})%}*%}*%}?&}&%}3%}&*#%})%#%#)}#&#-#+*%E%%'%'#%}#*V##&##I}#&&##%&%#&&Qf%%))w/0+&%#(#.%-''''++++7}>%4'',##1,#%#&%##&#'##&#*#9)%&%}#*}%,#+P(%A&%#'&##wSD',9E00#y#@}(+}&%&>~!#~!X}#*}(&&}(&}(,%}%&#+&}#&}I%#%}%)#(},'%#*}4%%#%}(''}#/##(##),%-##%%)#&}(.}&%#&}%%}*&#%},&&}&%}#%*'#%})%}D&}&%}-&}6&#&}-,%}#%})-(~+`~,=?~I9'9%~!,#%})%})%}@%}?%}(~!?~#<~#pP~#BG~#=1#%K+~#?#~%;)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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 tP;var Yhe=ms(()=>{tP=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 Pc;var bZe=ms(()=>{(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"})(Pc||(Pc={}))});function EZe(e){return e-tu.ZERO>>>0<=9}function Y$r(e){return(e|BH)-tu.LOWER_A>>>0<=5}function J$r(e){return(e|BH)-tu.LOWER_A>>>0<=25}function Q$r(e){return e===tu.EQUALS||J$r(e)||EZe(e)}class Jhe{decodeTree;emitCodePoint;errors;state=eu.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=Vf.Strict;runConsumed=0;constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r}startEntity(e){this.decodeMode=e,this.state=eu.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case eu.EntityStart:{if(e.charCodeAt(t)===tu.NUM)return this.state=eu.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=eu.NamedEntity,this.stateNamedEntity(e,t)}case eu.NumericStart:return this.stateNumericStart(e,t);case eu.NumericDecimal:return this.stateNumericDecimal(e,t);case eu.NumericHex:return this.stateNumericHex(e,t);default:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){if(t>=e.length)return-1;if((e.charCodeAt(t)|BH)===tu.LOWER_X)return this.state=eu.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=eu.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){let r=e.length,{result:i}=this,{consumed:n}=this;while(t<r){let o=e.charCodeAt(t);if(EZe(o)||Y$r(o)){let s=o<=tu.NINE?o-tu.ZERO:(o|BH)-tu.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)-tu.ZERO;if(o>>>0>9)return this.result=i,this.consumed=n,this.emitNumericEntity(o+tu.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===tu.SEMI)this.consumed+=1;else if(this.decodeMode===Vf.Strict)return 0;if(this.emitCodePoint((this.decodeTree===tP?hZe:mZe)(this.result),this.consumed),this.errors){if(e!==tu.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===Vf.Attribute&&(i===0||t>1||Q$r(r))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:r}=this,i=e.length,n=this.decodeMode===Vf.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=r[o];while(t<i){while((c&(Pc.VALUE_LENGTH|Pc.FLAG13))===0&&(c&Pc.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&Pc.JUMP_TABLE,f=(c&Pc.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&(Pc.VALUE_LENGTH|Pc.FLAG13))===Pc.FLAG13){let m=(c&Pc.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&Pc.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 l=c>>>14,d=e.charCodeAt(t);if(l!==0){if(!n&&(c&Pc.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===tu.SEMI)return this.emitNamedEntityData(o,l,a+s);if(l===1)return this.flushAndEmitLegacyOrReject(a,s,d,l)}let p=X$r(r,c,o+(l||1),d);if(p<0)return this.flushAndEmitLegacyOrReject(a,s,d,l);o=p,c=r[o],t+=1,s+=1}if(!n&&c>>>14!==0&&(c&Pc.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]&Pc.VALUE_MASK:i[e+1],r),t===3)this.emitCodePoint(i[e+2],r);return r}end(){switch(this.state){case eu.NamedEntity:return this.result!==0&&(this.decodeMode!==Vf.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case eu.NumericDecimal:return this.emitNumericEntity(0,2);case eu.NumericHex:return this.emitNumericEntity(0,3);case eu.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function X$r(e,t,r,i){let n=(t&Pc.BRANCH_LENGTH)>>7,o=t&Pc.JUMP_TABLE;if(o){if(n===0)return i===o?r:-1;let c=i-o;if(c>>>0>=n)return-1;let l=e[r+c];return l===0?-1:r+n+l-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 tu,BH=32,eu,Vf;var vZe=ms(()=>{fZe();Yhe();bZe();yZe();Yhe();(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"})(tu||(tu={}));(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(eu||(eu={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(Vf||(Vf={}))});function JS(e){return e===br.Space||e===br.NewLine||e===br.Tab||e===br.FormFeed||e===br.CarriageReturn}function B9(e){return e===br.Slash||e===br.Gt||JS(e)}function eGr(e){return e>=br.LowerA&&e<=br.LowerZ||e>=br.UpperA&&e<=br.UpperZ}class C9{cbs;state=We.Text;buffer="";sectionStart=0;index=0;entityStart=0;baseState=We.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 Jhe(e?tP:Khe,(n,o)=>this.emitCodePoint(n,o))}reset(){this.state=We.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=We.Text,this.isSpecial=!1,this.currentSequence=oi.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===br.Lt||!this.decodeEntities&&this.fastForwardTo(br.Lt)){if(this.index>this.sectionStart)this.cbs.ontext(this.sectionStart,this.index);this.state=We.BeforeTagName,this.sectionStart=this.index}else if(this.decodeEntities&&e===br.Amp)this.startEntity()}currentSequence=oi.Empty;sequenceIndex=0;enterTagBody(){if(this.currentSequence===oi.Plaintext)this.currentSequence=oi.Empty,this.state=We.InPlainText;else if(this.isSpecial)this.state=We.InSpecialTag,this.sequenceIndex=0;else this.state=We.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===oi.ScriptEnd&&t===oi.StyleEnd[3]){this.currentSequence=oi.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===oi.TitleEnd&&t===oi.TextareaEnd[3]){this.currentSequence=oi.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===oi.NoembedEnd&&t===oi.NoframesEnd[4]){this.currentSequence=oi.NoframesEnd,this.sequenceIndex=5;return}}else if(B9(e)){this.sequenceIndex=0,this.state=We.InTagName,this.stateInTagName(e);return}this.isSpecial=!1,this.currentSequence=oi.Empty,this.sequenceIndex=0,this.state=We.InTagName,this.stateInTagName(e)}stateCDATASequence(e){if(e===oi.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===oi.Cdata.length)this.state=We.InCommentLike,this.currentSequence=oi.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1}else if(this.sequenceIndex=0,this.xmlMode)this.state=We.InDeclaration,this.stateInDeclaration(e);else this.state=We.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=We.Text}stateInCommentLike(e){if(!this.xmlMode&&this.currentSequence===oi.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&e===br.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===oi.CommentEnd&&this.sequenceIndex===2&&e===br.Gt)this.emitComment(2);else if(this.currentSequence===oi.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&e!==br.Gt)this.sequenceIndex=Number(e===br.Dash);else if(e===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===oi.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=We.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?!B9(e):eGr(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(B9(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===oi.TitleEnd||this.currentSequence===oi.TextareaEnd){if(this.decodeEntities&&e===br.Amp)this.startEntity()}else if(this.fastForwardTo(br.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(e===br.Lt)}stateBeforeTagName(e){if(e===br.ExclamationMark)this.state=We.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===br.Questionmark)if(this.xmlMode)this.state=We.InProcessingInstruction,this.sequenceIndex=0,this.sectionStart=this.index+1;else this.state=We.InSpecialComment,this.sectionStart=this.index;else if(this.isTagStartChar(e)){this.sectionStart=this.index;let t=this.xmlMode||this.cbs.isInForeignContext?.()?void 0:tGr.get(e|32);if(t===void 0)this.state=We.InTagName;else this.isSpecial=!0,this.currentSequence=t,this.sequenceIndex=3,this.state=We.SpecialStartSequence}else if(e===br.Slash)this.state=We.BeforeClosingTagName;else this.state=We.Text,this.stateText(e)}stateInTagName(e){if(B9(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(JS(e))if(this.xmlMode);else this.state=We.InSpecialComment,this.sectionStart=this.index;else if(e===br.Gt){if(this.state=We.Text,!this.xmlMode)this.sectionStart=this.index+1}else this.state=this.isTagStartChar(e)?We.InClosingTagName:We.InSpecialComment,this.sectionStart=this.index}stateInClosingTagName(e){if(B9(e))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=We.AfterClosingTagName,this.stateAfterClosingTagName(e)}stateAfterClosingTagName(e){if(e===br.Gt||this.fastForwardTo(br.Gt))this.state=We.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(e){if(e===br.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(e===br.Slash)this.state=We.InSelfClosingTag;else if(!JS(e))this.state=We.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(e){if(e===br.Gt){if(this.cbs.onselfclosingtag(this.index),this.sectionStart=this.index+1,!this.recognizeSelfClosing){this.enterTagBody();return}this.state=We.Text,this.isSpecial=!1,this.currentSequence=oi.Empty}else if(!JS(e))this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===br.Eq||B9(e))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=We.AfterAttributeName,this.stateAfterAttributeName(e)}stateAfterAttributeName(e){if(e===br.Eq)this.state=We.BeforeAttributeValue;else if(e===br.Slash||e===br.Gt)this.cbs.onattribend(sm.NoValue,this.sectionStart),this.sectionStart=-1,this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!JS(e))this.cbs.onattribend(sm.NoValue,this.sectionStart),this.state=We.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(e){if(e===br.DoubleQuote)this.state=We.InAttributeValueDq,this.sectionStart=this.index+1;else if(e===br.SingleQuote)this.state=We.InAttributeValueSq,this.sectionStart=this.index+1;else if(!JS(e))this.sectionStart=this.index,this.state=We.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===br.DoubleQuote?sm.Double:sm.Single,this.index+1),this.state=We.BeforeAttributeName;else if(this.decodeEntities&&e===br.Amp)this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,br.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,br.SingleQuote)}stateInAttributeValueNoQuotes(e){if(JS(e)||e===br.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(sm.Unquoted,this.index),this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(this.decodeEntities&&e===br.Amp)this.startEntity()}stateBeforeDeclaration(e){if(e===br.OpeningSquareBracket)this.state=We.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=e===br.Dash?We.BeforeComment:We.InDeclaration;else if((e|32)===oi.Doctype[0])this.state=We.DeclarationSequence,this.currentSequence=oi.Doctype,this.sequenceIndex=1;else if(e===br.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=We.Text,this.sectionStart=this.index+1;else if(e===br.Dash)this.state=We.BeforeComment;else this.state=We.InSpecialComment}stateDeclarationSequence(e){if(this.sequenceIndex===this.currentSequence.length)this.state=We.InDeclaration,this.stateInDeclaration(e);else if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(e===br.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=We.Text,this.sectionStart=this.index+1;else this.state=We.InSpecialComment}stateInDeclaration(e){if(e===br.Gt||this.fastForwardTo(br.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=We.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(e){if(e===br.Questionmark)this.sequenceIndex=1;else if(e===br.Gt&&this.sequenceIndex===1)this.cbs.onprocessinginstruction(this.sectionStart,this.index-1),this.sequenceIndex=0,this.state=We.Text,this.sectionStart=this.index+1;else this.sequenceIndex=Number(this.fastForwardTo(br.Questionmark))}stateBeforeComment(e){if(e===br.Dash)this.state=We.InCommentLike,this.currentSequence=oi.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=We.InDeclaration;else if(e===br.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=We.Text,this.sectionStart=this.index+1;else this.state=We.InSpecialComment}stateInSpecialComment(e){if(e===br.Gt||this.fastForwardTo(br.Gt))this.cbs.oncomment(this.sectionStart,this.index,0),this.state=We.Text,this.sectionStart=this.index+1}startEntity(){this.baseState=this.state,this.state=We.InEntity,this.entityStart=this.index,this.entityDecoder.startEntity(this.xmlMode?Vf.Strict:this.baseState===We.Text||this.baseState===We.InSpecialTag?Vf.Legacy:Vf.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)===br.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===We.Text||this.state===We.InPlainText||this.state===We.InSpecialTag&&this.sequenceIndex===0)this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index;else if(this.state===We.InAttributeValueDq||this.state===We.InAttributeValueSq||this.state===We.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 We.Text:{this.stateText(e);break}case We.InPlainText:{this.index=this.buffer.length+this.offset-1;break}case We.SpecialStartSequence:{this.stateSpecialStartSequence(e);break}case We.InSpecialTag:{this.stateInSpecialTag(e);break}case We.CDATASequence:{this.stateCDATASequence(e);break}case We.DeclarationSequence:{this.stateDeclarationSequence(e);break}case We.InAttributeValueDq:{this.stateInAttributeValueDoubleQuotes(e);break}case We.InAttributeName:{this.stateInAttributeName(e);break}case We.InCommentLike:{this.stateInCommentLike(e);break}case We.InSpecialComment:{this.stateInSpecialComment(e);break}case We.BeforeAttributeName:{this.stateBeforeAttributeName(e);break}case We.InTagName:{this.stateInTagName(e);break}case We.InClosingTagName:{this.stateInClosingTagName(e);break}case We.BeforeTagName:{this.stateBeforeTagName(e);break}case We.AfterAttributeName:{this.stateAfterAttributeName(e);break}case We.InAttributeValueSq:{this.stateInAttributeValueSingleQuotes(e);break}case We.BeforeAttributeValue:{this.stateBeforeAttributeValue(e);break}case We.BeforeClosingTagName:{this.stateBeforeClosingTagName(e);break}case We.AfterClosingTagName:{this.stateAfterClosingTagName(e);break}case We.InAttributeValueNq:{this.stateInAttributeValueNoQuotes(e);break}case We.InSelfClosingTag:{this.stateInSelfClosingTag(e);break}case We.InDeclaration:{this.stateInDeclaration(e);break}case We.BeforeDeclaration:{this.stateBeforeDeclaration(e);break}case We.BeforeComment:{this.stateBeforeComment(e);break}case We.InProcessingInstruction:{this.stateInProcessingInstruction(e);break}case We.InEntity:{this.stateInEntity();break}}this.index++}this.cleanup()}finish(){if(this.state===We.InEntity)this.entityDecoder.end(),this.state=this.baseState;this.handleTrailingData(),this.cbs.onend()}handleTrailingCommentLikeData(e){if(this.state!==We.InCommentLike)return!1;if(this.currentSequence===oi.CdataEnd)if(this.xmlMode){if(this.sectionStart<e)this.cbs.oncdata(this.sectionStart,e,0)}else{let t=this.sectionStart-oi.Cdata.length-1;this.cbs.oncomment(t,e,0)}else{let t=this.xmlMode?0:Math.min(this.sequenceIndex,oi.CommentEnd.length-1);this.cbs.oncomment(this.sectionStart,e,t)}return!0}handleTrailingMarkupDeclaration(e){if(this.xmlMode)switch(this.state){case We.InSpecialComment:case We.BeforeComment:case We.CDATASequence:case We.DeclarationSequence:case We.InDeclaration:return this.cbs.ontext(this.sectionStart,e),!0;default:return!1}switch(this.state){case We.BeforeDeclaration:case We.InSpecialComment:case We.BeforeComment:case We.CDATASequence:return this.cbs.oncomment(this.sectionStart,e,0),!0;case We.DeclarationSequence:{if(this.sequenceIndex!==oi.Doctype.length)this.cbs.oncomment(this.sectionStart,e,0);return!0}case We.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 We.InTagName:case We.BeforeAttributeName:case We.BeforeAttributeValue:case We.AfterAttributeName:case We.InAttributeName:case We.InAttributeValueSq:case We.InAttributeValueDq:case We.InAttributeValueNq:case We.InClosingTagName:break;default:this.cbs.ontext(this.sectionStart,e)}}emitCodePoint(e,t){if(this.baseState!==We.Text&&this.baseState!==We.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 br,We,sm,oi,tGr;var Qhe=ms(()=>{vZe();(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"})(br||(br={}));(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"})(We||(We={}));(function(e){e[e.NoValue=0]="NoValue",e[e.Unquoted=1]="Unquoted",e[e.Single=2]="Single",e[e.Double=3]="Double"})(sm||(sm={}));oi={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])},tGr=new Map([[oi.IframeEnd[2],oi.IframeEnd],[oi.NoembedEnd[2],oi.NoembedEnd],[oi.Plaintext[2],oi.Plaintext],[oi.ScriptEnd[2],oi.ScriptEnd],[oi.TitleEnd[2],oi.TitleEnd],[oi.XmpEnd[2],oi.XmpEnd]])});class _9{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??C9)(this.options,this),this.foreignContext=[Ab.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?.(AZe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==Ab.None}isVoidElement(e){return this.htmlMode&&iGr.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]===Ab.Svg)return DZe.get(r)??r;if(this.foreignContext.length>1){let i=DZe.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&&rGr.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(Ab.Svg);else if(e==="math")this.foreignContext.unshift(Ab.MathML);else if(CZe.has(e))this.foreignContext.unshift(Ab.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&&(nGr.has(t)||CZe.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+=AZe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===sm.Double?'"':e===sm.Single?"'":e===sm.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(oGr),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?BZe:r.slice(0,BZe.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(Ab.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 AZe,D9,Gs,I9,wZe,SZe,kZe,rGr,BZe="doctype",iGr,nGr,CZe,DZe,Ab,oGr;var Xhe=ms(()=>{Qhe();({fromCodePoint:AZe}=String),D9=new Set(["input","option","optgroup","select","button","datalist","textarea"]),Gs=new Set(["p"]),I9=new Set(["h1","h2","h3","h4","h5","h6","p"]),wZe=new Set(["thead","tbody"]),SZe=new Set(["dd","dt"]),kZe=new Set(["rt","rp"]),rGr=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",Gs],["h1",I9],["h2",I9],["h3",I9],["h4",I9],["h5",I9],["h6",I9],["select",D9],["input",D9],["output",D9],["button",D9],["datalist",D9],["textarea",D9],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",SZe],["dt",SZe],["address",Gs],["article",Gs],["aside",Gs],["blockquote",Gs],["details",Gs],["div",Gs],["dl",Gs],["fieldset",Gs],["figcaption",Gs],["figure",Gs],["footer",Gs],["form",Gs],["header",Gs],["hr",Gs],["main",Gs],["nav",Gs],["ol",Gs],["pre",Gs],["section",Gs],["table",Gs],["ul",Gs],["rt",kZe],["rp",kZe],["tbody",wZe],["tfoot",wZe]]),iGr=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),nGr=new Set(["math","svg"]),CZe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),DZe=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"})(Ab||(Ab={}));oGr=/\s|\//});var CH={};zx(CH,{CDATA:()=>cfe,Comment:()=>nfe,Directive:()=>ife,Doctype:()=>sGr,ElementType:()=>dn,Root:()=>tfe,Script:()=>ofe,Style:()=>sfe,Tag:()=>afe,Text:()=>rfe,isTag:()=>efe});function efe(e){return e.type===dn.Tag||e.type===dn.Script||e.type===dn.Style}var dn,tfe,rfe,ife,nfe,ofe,sfe,afe,cfe,sGr;var T9=ms(()=>{(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"})(dn||(dn={}));tfe=dn.Root,rfe=dn.Text,ife=dn.Directive,nfe=dn.Comment,ofe=dn.Script,sfe=dn.Style,afe=dn.Tag,cfe=dn.CDATA,sGr=dn.Doctype});class ufe{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 IZe(this,e)}}function ru(e){return efe(e)}function FH(e){return e.type===dn.CDATA}function qA(e){return e.type===dn.Text}function dfe(e){return e.type===dn.Comment}function aGr(e){return e.type===dn.Directive}function cGr(e){return e.type===dn.Root}function ep(e){return Object.hasOwn(e,"children")}function IZe(e,t=!1){let r;if(qA(e))r=new rP(e.data);else if(dfe(e))r=new IH(e.data);else if(ru(e)){let i=t?lfe(e.children):[],n=new RH(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(FH(e)){let i=t?lfe(e.children):[],n=new PH(i);for(let o of i)o.parent=n;r=n}else if(cGr(e)){let i=t?lfe(e.children):[],n=new iP(i);for(let o of i)o.parent=n;if(e["x-mode"])n["x-mode"]=e["x-mode"];r=n}else if(aGr(e)){let i=new _H(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 lfe(e){let t=e.map((r)=>IZe(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 DH,rP,IH,_H,TH,PH,iP,RH;var pfe=ms(()=>{T9();DH=class DH extends ufe{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};rP=class rP extends DH{type=dn.Text;get nodeType(){return 3}};IH=class IH extends DH{type=dn.Comment;get nodeType(){return 8}};_H=class _H extends DH{type=dn.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};TH=class TH extends ufe{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}};PH=class PH extends TH{type=dn.CDATA;get nodeType(){return 4}};iP=class iP extends TH{type=dn.Root;get nodeType(){return 9}};RH=class RH extends TH{name;attribs;type;constructor(e,t,r=[],i=e==="script"?dn.Script:e==="style"?dn.Style:dn.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 QS{dom=[];root=new iP(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=_Ze;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??_Ze,this.elementCB=r??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new iP(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?dn.Tag:void 0,i=new RH(e,t,void 0,r);this.addNode(i),this.tagStack.push(i)}ontext(e){let{lastNode:t}=this;if(t&&t.type===dn.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let r=new rP(e);this.addNode(r),this.lastNode=r}}oncomment(e){if(this.lastNode&&this.lastNode.type===dn.Comment){this.lastNode.data+=e;return}let t=new IH(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new rP(""),t=new PH([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let r=new _H(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 _Ze;var $A=ms(()=>{T9();pfe();pfe();_Ze={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function P9(e,t,r=!0,i=Number.POSITIVE_INFINITY){return TZe(e,Array.isArray(t)?t:[t],r,i)}function TZe(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&&ep(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function MH(e,t,r=!0){let i=Array.isArray(t)?t:[t];for(let n of i){if(ru(n)&&e(n))return n;if(r&&ep(n)&&n.children.length>0){let o=MH(e,n.children,!0);if(o)return o}}return null}function PZe(e,t){return(Array.isArray(t)?t:[t]).some((r)=>ru(r)&&e(r)||ep(r)&&PZe(e,r.children))}function lGr(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(ru(o)&&e(o))r.push(o);if(ep(o)&&o.children.length>0)n.unshift(0),i.unshift(o.children)}}var mfe=ms(()=>{$A()});function hfe(e,t){if(typeof t==="function")return(r)=>ru(r)&&t(r.attribs[e]);return(r)=>ru(r)&&r.attribs[e]===t}function uGr(e,t){return(r)=>e(r)||t(r)}function RZe(e){let t=Object.keys(e).map((r)=>{let i=e[r];return Object.hasOwn(OH,r)?OH[r](i):hfe(r,i)});return t.length===0?null:t.reduce(uGr)}function dGr(e,t){let r=RZe(e);return r?r(t):!0}function pGr(e,t,r,i=Number.POSITIVE_INFINITY){let n=RZe(e);return n?P9(n,t,r,i):[]}function mGr(e,t,r=!0){if(!Array.isArray(t))t=[t];return MH(hfe("id",e),t,r)}function XS(e,t,r=!0,i=Number.POSITIVE_INFINITY){return P9(OH.tag_name(e),t,r,i)}function hGr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return P9(hfe("class",e),t,r,i)}function fGr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return P9(OH.tag_type(e),t,r,i)}var OH;var ffe=ms(()=>{$A();mfe();OH={tag_name(e){if(typeof e==="function")return(t)=>ru(t)&&e(t.name);if(e==="*")return ru;return(t)=>ru(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)=>qA(t)&&e(t.data);return(t)=>qA(t)&&t.data===e}}});function MZe(e){return e===34?""":e===38?"&":e===39?"'":e===60?"<":e===62?">":" "}function FZe(e){return e>=128||e>=32&&e<64&&(xGr>>>e&1)===1}function NH(e){let{length:t}=e,r,i=0,n=0;while(n<t){let o=e.charCodeAt(n);if(!FZe(o)){let a=Math.min(n+32,t),c=n+1;while(c<a&&!FZe(e.charCodeAt(c)))c++;if(c<a){n=c;continue}if(c>=t)break;if(xfe.lastIndex=c,!xfe.test(e))break;n=xfe.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+=MZe(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 OZe(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+=MZe(o),i=n+1}while(e.test(t));return r+t.substring(i)}function gfe(e){return OZe(gGr,e)}function yfe(e){return OZe(yGr,e)}var xGr=1342177476,xfe,gGr,yGr;var NZe=ms(()=>{xfe=/["&'<>\u0080-\uFFFF]/g;gGr=/["&\u{A0}]/gu;yGr=/[&<>\u{A0}]/gu});var LZe,jZe;var zZe=ms(()=>{NZe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(LZe||(LZe={}));(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"})(jZe||(jZe={}))});var UZe,qZe;var $Ze=ms(()=>{UZe=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])),qZe=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 wGr(e,t={}){let r="length"in e?e:[e],i=t.xmlMode??!1,n="";for(let o=0;o<r.length;o++)n+=HZe(r[o],t,i);return n}function GZe(e,t,r){let i="";for(let n=0;n<e.length;n++)i+=HZe(e[n],t,r);return i}function HZe(e,t,r){switch(e.type){case tfe:return GZe(e.children,t,r);case ife:return`<${e.data}>`;case nfe:return`<!--${e.data}-->`;case cfe:return`<![CDATA[${e.children[0].data}]]>`;case ofe:case sfe:case afe:return SGr(e,t,r);case rfe:{let i=e,n=i.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!r&&i.parent&&bGr.has(i.parent.name)))return r||t.encodeEntities!=="utf8"?NH(n):yfe(n);return n}}}function SGr(e,t,r){if(r==="foreign"){if(e.name=UZe.get(e.name)??e.name,e.parent&&AGr.has(e.parent.name))r=!1}if(!r&&vGr.has(e.name))r="foreign";let{name:i,children:n}=e,o=!r&&EGr.has(i),s=`<${i}${BGr(e.attribs,t,r)}`;if(n.length===0&&(r?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=r?"/>":" />";else{if(s+=">",n.length>0)s+=GZe(n,t,r);if(!o)s+=`</${i}>`}return s}function kGr(e){return e.replaceAll('"',""")}function BGr(e,t,r){if(!e)return"";let i=(t.encodeEntities??t.decodeEntities)===!1?kGr:r||t.encodeEntities!=="utf8"?NH:gfe,n=r==="foreign",o=!!(t.emptyAttrs??r),s="";for(let a in e){if(!Object.hasOwn(e,a))continue;let c=e[a],l=n?qZe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${l}`:` ${l}="${i(c==null?"":String(c))}"`}return s}var bGr,EGr,vGr,AGr,WZe;var ZZe=ms(()=>{T9();zZe();$Ze();bGr=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),EGr=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),vGr=new Set(["svg","math"]),AGr=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));WZe=wGr});function VZe(e,t){return WZe(e,t)}function CGr(e,t){return ep(e)?e.children.map((r)=>VZe(r,t)).join(""):""}function LH(e){if(Array.isArray(e))return e.map(LH).join("");if(ru(e))return e.name==="br"?`
|
|
3
3
|
`:LH(e.children);if(FH(e))return LH(e.children);if(qA(e))return e.data;return""}function nP(e){if(Array.isArray(e))return e.map(nP).join("");if(ep(e)&&!dfe(e))return nP(e.children);if(qA(e))return e.data;return""}function bfe(e){if(Array.isArray(e))return e.map(bfe).join("");if(ep(e)&&(e.type===dn.Tag||FH(e)))return bfe(e.children);if(qA(e))return e.data;return""}var Efe=ms(()=>{ZZe();T9();$A()});function oP(e){let t=jH(PGr,e);return t?t.name==="feed"?DGr(t):IGr(t):null}function DGr(e){let t=e.children,r={type:"atom",items:XS("entry",t).map((o)=>{let{children:s}=o,a={media:KZe(s)};tp(a,"id","id",s),tp(a,"title","title",s);let c=jH("link",s)?.attribs.href;if(c)a.link=c;let l=GA("summary",s)||GA("content",s);if(l)a.description=l;let d=GA("updated",s);if(d)a.pubDate=new Date(d);return a})};tp(r,"id","id",t),tp(r,"title","title",t);let i=jH("link",t)?.attribs.href;if(i)r.link=i;tp(r,"description","subtitle",t);let n=GA("updated",t);if(n)r.updated=new Date(n);return tp(r,"author","email",t,!0),r}function IGr(e){let t=jH("channel",e.children)?.children??[],r={type:e.name.substr(0,3),id:"",items:XS("item",e.children).map((n)=>{let{children:o}=n,s={media:KZe(o)};tp(s,"id","guid",o),tp(s,"title","title",o),tp(s,"link","link",o),tp(s,"description","description",o);let a=GA("pubDate",o)||GA("dc:date",o);if(a)s.pubDate=new Date(a);return s})};tp(r,"title","title",t),tp(r,"link","link",t),tp(r,"description","description",t);let i=GA("lastBuildDate",t);if(i)r.updated=new Date(i);return tp(r,"author","managingEditor",t,!0),r}function KZe(e){return XS("media:content",e).map((t)=>{let{attribs:r}=t,i={medium:r.medium,isDefault:!!r.isDefault};for(let n of _Gr)if(r[n])i[n]=r[n];for(let n of TGr)if(r[n])i[n]=Number.parseInt(r[n],10);if(r.expression)i.expression=r.expression;return i})}function jH(e,t){return XS(e,t,!0,1)[0]}function GA(e,t,r=!1){return nP(XS(e,t,r,1)).trim()}function tp(e,t,r,i,n=!1){let o=GA(r,i,n);if(o)e[t]=o}function PGr(e){return e==="rss"||e==="feed"||e==="rdf:RDF"}var _Gr,TGr;var YZe=ms(()=>{ffe();Efe();_Gr=["url","type","lang"],TGr=["fileSize","bitrate","framerate","samplingrate","channels","duration","height","width"]});function RGr(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 JZe(e,t){let r=[],i=[];if(e===t)return 0;let n=ep(e)?e:e.parent;while(n)r.unshift(n),n=n.parent;n=ep(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 Ah.DISCONNECTED;let a=r[s-1],c=a.children,l=r[s],d=i[s];if(c.indexOf(l)>c.indexOf(d)){if(a===t)return Ah.FOLLOWING|Ah.CONTAINED_BY;return Ah.FOLLOWING}if(a===e)return Ah.PRECEDING|Ah.CONTAINS;return Ah.PRECEDING}function FGr(e){return e=e.filter((t,r,i)=>!i.includes(t,r+1)),e.sort((t,r)=>{let i=JZe(t,r);if(i&Ah.PRECEDING)return-1;if(i&Ah.FOLLOWING)return 1;return 0}),e}var Ah;var QZe=ms(()=>{$A();(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"})(Ah||(Ah={}))});function sP(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 MGr(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 OGr(e,t){if(sP(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 NGr(e,t){sP(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 LGr(e,t){if(sP(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 jGr(e,t){sP(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 XZe=()=>{};function eVe(e){return ep(e)?e.children:[]}function tVe(e){return e.parent||null}function zGr(e){let t=tVe(e);if(t!=null)return eVe(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 UGr(e,t){let{attribs:r}=e;return r?.[t]}function qGr(e,t){let{attribs:r}=e;return r!=null&&Object.hasOwn(r,t)&&r[t]!=null}function $Gr(e){return e.name}function GGr(e){let{next:t}=e;while(t!==null&&!ru(t))({next:t}=t);return t}function HGr(e){let{prev:t}=e;while(t!==null&&!ru(t))({prev:t}=t);return t}var rVe=ms(()=>{$A()});var vfe={};zx(vfe,{DocumentPosition:()=>Ah,append:()=>NGr,appendChild:()=>OGr,compareDocumentPosition:()=>JZe,existsOne:()=>PZe,filter:()=>P9,find:()=>TZe,findAll:()=>lGr,findOne:()=>MH,getAttributeValue:()=>UGr,getChildren:()=>eVe,getElementById:()=>mGr,getElements:()=>pGr,getElementsByClassName:()=>hGr,getElementsByTagName:()=>XS,getElementsByTagType:()=>fGr,getFeed:()=>oP,getInnerHTML:()=>CGr,getName:()=>$Gr,getOuterHTML:()=>VZe,getParent:()=>tVe,getSiblings:()=>zGr,getText:()=>LH,hasAttrib:()=>qGr,innerText:()=>bfe,nextElementSibling:()=>GGr,prepend:()=>jGr,prependChild:()=>LGr,prevElementSibling:()=>HGr,removeElement:()=>sP,removeSubsets:()=>RGr,replaceElement:()=>MGr,testElement:()=>dGr,textContent:()=>nP,uniqueSort:()=>FGr});var zH=ms(()=>{YZe();QZe();ffe();XZe();mfe();Efe();rVe()});var nVe={};zx(nVe,{DefaultHandler:()=>QS,DomHandler:()=>QS,DomUtils:()=>vfe,ElementType:()=>CH,Parser:()=>_9,QuoteType:()=>sm,Tokenizer:()=>C9,createDocumentStream:()=>WGr,getFeed:()=>oP,parseDocument:()=>iVe,parseFeed:()=>VGr});function iVe(e,t){let r=new QS(void 0,t);return new _9(r,t).end(e),r.root}function WGr(e,t,r){let i=new QS((n)=>e(n,i.root),t,r);return new _9(i,t)}function VGr(e,t=ZGr){return oP(iVe(e,t).children)}var ZGr;var oVe=ms(()=>{Xhe();Xhe();$A();$A();T9();Qhe();zH();zH();zH();ZGr={xmlMode:!0}});var aVe=E(function(X2o,sVe){sVe.exports=(e)=>{if(typeof e!=="string")throw TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}});var lVe=E(function(YGr){/*!
|
|
4
4
|
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
|
|
5
5
|
*
|
|
@@ -1035,7 +1035,7 @@ ${Qv(e.cont)}`}}function hXn(e,t){return t.map((r,i,{length:n})=>fXn(e,r,i===n-1
|
|
|
1035
1035
|
`).find((b)=>b.startsWith("data: "));if(!d)continue;let p;try{let b=Gzr.safeParse(JSON.parse(d.slice(6)));if(!b.success)continue;p=b.data}catch{return await Upe(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 Upe(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:qzr(a)}}}s=await pHe(i,t,r)}return{success:!1,error:"Stream ended without a terminal event"}}class $pe extends Error{timeoutMs;constructor(e){super(`request timed out after ${e}ms`);this.timeoutMs=e,this.name="A2ARequestTimeoutError"}}class ET extends Error{timeoutMs;constructor(e){super(`A2A stream stalled waiting for final event after ${e}ms`);this.timeoutMs=e,this.name="A2AStreamIdleTimeoutError"}}async function Qzr(e,t,r,i,n){return jpe((o)=>e(t,{...r,signal:o}),{timeoutMs:i,onTimeout:()=>new $pe(i),signal:n})}async function pHe(e,t,r){try{return await jpe(()=>e.read(),{timeoutMs:t,onTimeout:()=>new ET(t),signal:r})}catch(i){if(i instanceof ET||r?.aborted)await Upe(e,i);throw i}}async function Upe(e,t){try{await e.cancel(t)}catch{}}function Xzr(e){if(e instanceof $pe||e instanceof ET)return!1;return e instanceof Error}function zpe(e,t){let r=t>1?` after ${t} attempts`:"";if(e instanceof ET)return`${e.message}${r}`;let i=fe(e,"Unknown network error");return`Failed to reach remote agent${r}: ${i}`}async function ZG(e,t={},r={}){let i=t.fetch??globalThis.fetch,n=r.signal;n?.throwIfAborted();let o={requestTimeoutMs:t.requestTimeoutMs??Hzr,streamIdleTimeoutMs:t.streamIdleTimeoutMs??Wzr,maxNetworkAttempts:t.maxNetworkAttempts??Zzr},s=Yzr(e.agent),a=_i(r.userPermissionLevel);if(!s.ok){let p=t.entityService?await lHe(t.entityService,e.agent,a):void 0;if(typeof p==="string")return{success:!1,error:p};if(!p)return{success:!1,error:s.error}}if(!t.entityService)return{success:!1,error:"Agent directory is unavailable. Add the agent first, then try again."};let c=s.ok?s.agentId:e.agent.trim(),l=s.ok?await t.entityService.getEntity({entityType:"agent",id:c,visibilityScope:a}):null;if(n?.throwIfAborted(),!l&&!uHe(c)){let p=await lHe(t.entityService,e.agent,a);if(n?.throwIfAborted(),typeof p==="string")return{success:!1,error:p};if(p)l=p,c=p.id}if(!l){if(r.requireSaved)return{success:!1,error:`Agent ${c} is not saved or approved.`,code:"agent_not_saved"};if(!uHe(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 fh(c,{fetch:i,timeoutMs:o.requestTimeoutMs,signal:n});if(!p.ok){if(CA(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 dHe(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(l.metadata.status==="archived")return{success:!1,error:`Agent ${c} is archived and cannot be contacted until it is restored and approved.`,code:"agent_archived"};if(!await t.isContactApproved?.(c))return{success:!1,error:`Agent ${c} is discovered but not approved yet. Approve it first.`,code:"agent_not_approved"};let d=await fh(c,{fetch:i,timeoutMs:o.requestTimeoutMs,signal:n});if(!d.ok){if(CA(d.reason))return{success:!1,error:d.error};return{success:!1,error:`Could not fetch Agent Card from https://${c}`}}return dHe(d.card.url,e.message,i,t.requestSigner,o,n)}function hHe(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:Vzr,visibility:"trusted",sideEffects:"external",handler:async(t,r)=>{let i=Kzr.safeParse(t);if(!i.success)return{success:!1,error:`Invalid input: ${i.error.message}`};return ZG(i.data,e,{userPermissionLevel:r.userPermissionLevel,...r.signal?{signal:r.signal}:{}})}}}var eUr=30000,tUr=u.looseObject({result:u.looseObject({parts:u.array(u.looseObject({kind:u.string(),data:u.unknown()}))})});function jf(e,t){return{status:"refused",code:e,error:t}}async function gHe(e,t,r){let i=e.trim().toLowerCase(),n=await r.entityService?.getEntity({entityType:"agent",id:i,visibilityScope:_i("admin")});if(!n)return jf("agent_not_saved",`Agent ${i} is not saved.`);if(n.metadata.status==="archived")return jf("agent_archived",`Agent ${i} is archived.`);if(!await r.isContactApproved?.(i))return jf("agent_not_approved",`Agent ${i} is not approved yet. Approve it first.`);let{requestSigner:o}=r;if(!o)return jf("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??eUr,c=await fh(i,{fetch:s,timeoutMs:a});if(!c.ok)return jf("agent_card_unavailable",c.error);if(!c.card.extensions.includes(PS))return jf("not_offered",`${i} does not offer shared entities.`);let l={"Content-Type":"application/json","X-A2A-Extensions":PS},d=JSON.stringify({jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/send",params:{message:{kind:"message",messageId:crypto.randomUUID(),role:"user",parts:[{kind:"data",data:t}]}}});await o({method:"POST",url:c.card.url,headers:l,body:d});let p;try{p=await s(c.card.url,{method:"POST",headers:l,body:d,signal:AbortSignal.timeout(a)})}catch(h){return jf("peer_failed",fe(h,`${i} did not answer`))}if(p.status===404)return{status:"not-found"};if(!p.ok)return jf("peer_failed",`${i} answered HTTP ${p.status}`);let m=tUr.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 yHe(e,t){let r=await gHe(e.agent,{op:"list"},t);if(r.status!=="answered")return r;let i=r.data.map((n)=>fHe.safeParse(n)).find((n)=>n.success)?.data;return i?{status:"found",entities:i.entities}:jf("unreadable_answer",`${r.agentId} did not answer with a list.`)}async function bHe(e,t){let r=await gHe(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)=>xHe.safeParse(c)).find((c)=>c.success)?.data;if(s?.entityType!==e.entityType||s.id!==e.id)return jf("unreadable_answer",`${i} did not answer with the entity asked for.`);let a=jf("unverified",`${i} did not sign what it served, so it was not taken.`);if(s.contentHash!==Ht(s.markdown))return a;try{if((await LGe(qG(s),s.attestation.signature,s.attestation.keyId,new gT({fetch:(l)=>n(l,{signal:AbortSignal.timeout(o)})}))).domain!==i)return a}catch{return a}return{status:"found",entity:s}}var rUr=new Set(["agent_not_saved","agent_not_approved","agent_archived"]);function EHe(e,t){let r="code"in e&&rUr.has(e.code??"")?"permission_denied":"handler_failed",i="error"in e?e.error:t;return new Lr(r,{publicMessage:p9(i)})}function iUr(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
|
`)}function vHe(e,t,r={networkAskTimeoutMs:30000}){e.answer(VG,async({request:{agent:i,question:n}})=>{let o=r.networkAskTimeoutMs,s=AbortSignal.timeout(o),a=(d)=>new Lr("deadline_exceeded",{publicMessage:`${i} did not answer within ${o} ms`,cause:d}),c;try{c=await ZG({agent:i,message:iUr(n)},{...t,maxNetworkAttempts:1},{requireSaved:!0,signal:s})}catch(d){if(s.aborted)throw a(d);throw new Lr("handler_failed",{message:fe(d,`${i} did not answer`),publicMessage:`${i} did not answer`,cause:d})}if(s.aborted)throw a();if(!("success"in c)||c.success!==!0)throw EHe(c,`${i} did not answer`);let l=Gpe.safeParse(c.data);if(!l.success)throw new Lr("handler_failed",{publicMessage:`${i} gave no readable answer`});if(l.data.state!=="completed")throw new Lr("handler_failed",{publicMessage:p9(`${i} did not answer: ${l.data.response}`)});return l.data}),e.answer(JG,({request:i})=>bHe(i,t)),e.answer(QG,({request:i})=>yHe(i,t)),e.answer(KG,async({request:{agent:i,instruction:n,selection:o,userPermissionLevel:s}})=>{let a=await ZG({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 EHe(a,"Agent call failed");let c=Gpe.safeParse(a.data);if(!c.success)throw new Lr("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(YG,async({request:{userPermissionLevel:i}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:_i(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 AHe={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.778",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 XG(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 oUr={"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"},Ku=(e)=>XG(e,oUr);function sUr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(gh(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();await MGe(i,n.privateJwk,n.keyId)}}function aUr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(gh(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();return{keyId:n.keyId,signature:NGe(i,n.privateJwk)}}}function wHe(e,t,r){let i=sUr(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:eH,schema:tH}).has(n.trim().toLowerCase()))}}async function cUr(e,t,r){if(!r.cardReady)return;return YGe({character:e.identity.get(),profile:e.identity.getProfile(),version:AHe.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 lUr(e,t,r,i){let n=new URL(r.url),o=new URL(`${n.pathname}${n.search}`,Fx(r)),s=await OGe({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 uUr(e,t,r){let i=new SHe,n=e.agent;return i.get("/.well-known/agent-card.json",async(o)=>{let s=await cUr(e,t,r);if(!s)return Ku(o.json({error:"Agent Card not ready"},503));return Ku(o.json(s))}),i.get("/.well-known/agent-directory.json",async(o)=>{let s=await JGe(e.entityReads);return Ku(o.json(s))}),i.get("/a2a",(o)=>Ku(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),i.options("/a2a",()=>Ku(new Response(null,{status:204}))),i.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return Ku(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await lUr(e,r,o.req.raw,s)}catch{return Ku(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return Ku(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let l=eHe.safeParse(c);if(!l.success)return Ku(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(kGe(o.req.raw.headers)){let p=l.data.method==="message/send"?BGe(l.data.params):void 0,m=p?.op==="list"?await IGe(e.entityReads,a.permissionLevel):await DGe(e.entityReads,a.permissionLevel,p,aUr(e));if(!m)return Ku(o.json({error:"Not found"},404));return Ku(o.json({jsonrpc:"2.0",id:l.data.id,result:{kind:"message",messageId:crypto.randomUUID(),role:"agent",parts:[{kind:"data",data:m}]}}))}if(l.data.method==="message/stream"){let p=sHe.safeParse(l.data.params??{});if(!p.success)return Ku(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:l.data.id}));let m=aHe(l.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 Ku(o.json(m));return Ku(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await iHe(l.data,{taskManager:r.taskManager,turnSupervisor:r.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:r.publicAsks});return Ku(o.json(d))}),i}function Hpe(e={}){let t=xh({id:"a2a",config:VGe,setup:(n)=>{let{config:o}=n,s=us(n),{servesHttp:a}=s,c=wHe(s,o,e),l={cardReady:!1,servesHttp:a,taskManager:new Npe,turnSupervisor:new Lpe,jwksResolver:new gT(e.fetch?{fetch:e.fetch}:{}),clientDeps:c,publicAsks:new Ope(o.publicAsks,s.classRuntimeState)};if(vHe(s,c,{networkAskTimeoutMs:o.networkAskTimeoutMs}),a)s.endpoint({label:"A2A",url:"/a2a",priority:25}),s.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),s.logger.info("A2A interface registered",{domain:s.domain});else s.logger.info("A2A interface registered in tool-only mode",{domain:s.domain});return s.ready(()=>{l.cardReady=!0}),l}}),r=Ao(t,(n)=>{let{config:o,state:s}=n;if(!s.servesHttp)return[];let a=us(n),c=uUr(a,o,s),l=(p)=>Promise.resolve(c.fetch(p)),d=(p,m)=>({path:p,method:m,public:!0,handler:l});return[d("/.well-known/agent-card.json","GET"),d("/.well-known/agent-directory.json","GET"),d("/a2a","GET"),d("/a2a","POST"),d("/a2a","OPTIONS")]}),i=Rx(r,(n)=>{let{state:o}=n,{logger:s}=us(n);return{id:"a2a",start:async()=>{if(o.servesHttp)s.info("A2A mounted on shared webserver host");else s.info("A2A running without webserver routes")},stop:async()=>{await o.turnSupervisor.close(),s.info("A2A server stopped")}}});return Jn(i,(n)=>{let{config:o}=n,s=us(n),a=()=>hHe(wHe(s,o,e));return[{...a(),handler:(c,l)=>a().handler(c,l)}]})}var dUr=Hpe(),kHe=dUr;function yh(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function PA(e,t){return{registration:e,actionIds:t.map((r)=>r.name)}}var pUr=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function bh(e){return pUr.format(new Date(e))}function Eh(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function _c(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function oH(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function US(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 mUr={"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 kme(e){let t=mUr[e];if(t)return t;let r=e.replaceAll(/[._-]+/g," ").trim();return r.length===0?e:ao(r)}var Bme=u.strictObject({actorUserId:u.string().trim().min(1).max(120).optional(),action:u.string().trim().min(1).max(200).optional(),selected:u.string().trim().min(1).max(120).optional(),offset:u.preprocess(yh,u.number().int().min(0).max(1e5)).default(0),limit:u.preprocess(yh,u.number().int().min(1).max(100)).default(25)}),BHe=u.strictObject({id:u.string().min(1),actorUserId:u.string().min(1).optional(),action:u.string().min(1),targetType:u.string().min(1).optional(),targetId:u.string().min(1).optional(),targetUserId:u.string().min(1).optional(),createdAt:u.number().int().nonnegative()}),hUr=u.strictObject({userId:u.string().min(1),displayName:u.string().min(1)}),fUr=u.strictObject({query:Bme,events:u.array(BHe),selectedEvent:BHe.optional(),users:u.array(hUr),actions:u.array(u.strictObject({value:u.string().min(1),label:u.string().min(1),count:u.number().int().nonnegative()})),total:u.number().int().nonnegative()});function CHe(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 DHe(e,t){return e?t.get(e)??"Former Admin":"System"}function IHe(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 Sme=ps({id:"audit",label:"Audit",priority:90,permission:"admin",query:Bme,data:fUr,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:kme(r.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:DHe(r.actorUserId,t)},{label:"Action",value:r.action},{label:"Target",value:IHe(r,t)},{label:"Occurred",value:bh(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:kme(o.action),description:`${DHe(o.actorUserId,t)} \u2192 ${IHe(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 _He(e){let t=e.studio.source({definition:Sme,bind:(r)=>Sme.bind(r,{load:async({query:i})=>{let n=Eh(e),o=i.get(Bme),[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(CHe),...s.selectedEvent?{selectedEvent:CHe(s.selectedEvent)}:{},users:oH(a),actions:s.actions.map(({action:c,count:l})=>({value:c,label:kme(c),count:l})).sort((c,l)=>c.label.localeCompare(l.label)),total:s.total}},actions:[]})});return PA(t,Sme.actions)}var zf=u.strictObject({status:u.string()}),sH=u.strictObject({status:u.string(),setupUrl:u.url(),expiresAt:u.string()});function f9(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var aH=u.strictObject({type:u.string(),displayName:u.string(),subjectLabel:u.string(),deliveryModes:u.array(u.enum(["automatic","manual"]))});function cH(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function lH(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function uH(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 xUr}from"crypto";var THe=new Set(["claimed","expired","cancelled"]),gUr=new Set(["claimed","cancelled"]),Tme=u.strictObject({state:u.enum(["pending","history"]).optional().default("pending"),selected:u.string().trim().min(1).max(200).optional(),offset:u.preprocess(yh,u.number().int().min(0)).optional().default(0),limit:u.preprocess(yh,u.number().int().min(1).max(100)).optional().default(25)}),MHe=u.strictObject({status:u.string(),setupUrl:u.url().nullable(),expiresAt:u.string().nullable()}),yUr=u.strictObject({idempotencyKey:u.string().min(1),displayName:u.string().trim().min(1).max(200),role:u.enum(["admin","trusted"]),deliveryType:u.string().trim().min(1).max(100),deliverySubject:u.string().trim().min(1).max(500),deliveryLabel:u.string().trim().max(200).optional(),deliveryMode:u.enum(["automatic","manual"])}),OHe=u.strictObject({invitationId:u.string().min(1)}),bUr=u.strictObject({invitationId:u.string().min(1),deliveryAttemptId:u.string().min(1)}),NHe=u.strictObject({invitationId:u.string(),state:u.string()}),Ime=Zr({name:"create-invitation",label:"Add a person",permission:"admin",input:yUr,output:MHe}),Pme=Zr({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:OHe,output:MHe}),Rme=Zr({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:OHe,output:NHe}),Fme=Zr({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:bUr,output:NHe}),PHe=u.strictObject({id:u.string(),displayName:u.string(),role:u.string(),state:u.string(),destination:u.string(),updatedAt:u.number(),deliveryAttemptId:u.string().optional()}),EUr=u.strictObject({query:Tme,idempotencyKey:u.string(),channels:u.array(aH),invitations:u.array(PHe),selectedInvitation:PHe.optional(),selectedTotal:u.number().int().nonnegative(),pendingCount:u.number().int().nonnegative(),historyCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()});function _me(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 Cme(e,t){let r=_me(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 LHe(e,t){let r=_me(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")?[Cme(e,"create-invitation-unavailable")]:[],n=_me(e,"invitations");if(n.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=Cme(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,Cme(e,"invitation-filters"),n,{...o,presentation:"disclosure",blocks:[...o.blocks,r,...s]}]}}var jHe=f9("Invitation setup");function vUr(e){if(gUr.has(e.state))return[];return[...e.deliveryAttemptId?[{action:Fme,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:Pme,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:jHe}]:[],...e.state!=="expired"?[{action:Rme,input:{invitationId:e.id}}]:[]]}function RHe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return ao(e.state)}var Dme=ps({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:Tme,data:EUr,actions:[Ime,Pme,Rme,Fme],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=cH(e.channels),i;if(e.channels.length>0&&r.length>0)i={action:Ime,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:lH("Role"),...uH(e.channels,r)}},result:jHe};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:`${ao(o.role)} \xB7 ${RHe(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:ao(n.role)},{label:"Delivery",value:RHe(n)},{label:"Destination",value:n.destination},{label:"Updated",value:bh(n.updatedAt)}]},{type:"actions",id:"invitation-actions",items:vUr(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(ao).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 FHe(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 zHe(e){let t=Eh(e),r=new Map,i=e.studio.source({definition:Dme,bind:(n)=>{let o=Ime.bind(n,async({input:l,caller:d})=>{let p=await t.createInvitation({idempotencyKey:l.idempotencyKey,displayName:l.displayName,role:l.role,delivery:{type:l.deliveryType,subject:l.deliverySubject,...l.deliveryLabel?{label:l.deliveryLabel}:{},mode:l.deliveryMode}},_c(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return FHe(p)}),s=Pme.bind(n,async({input:l,caller:d})=>{let p=await t.resendInvitation(l.invitationId,_c(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return FHe(p)}),a=Rme.bind(n,async({input:l,caller:d})=>{let p=await t.cancelInvitation(l.invitationId,_c(d));return r.delete(l.invitationId),{invitationId:p.id,state:p.state}},({input:l})=>({summary:"Cancel this invitation and revoke its pending setup link?",revision:l.invitationId})),c=Fme.bind(n,async({input:l,caller:d})=>{let p=await t.confirmManualInvitationDelivery(l.invitationId,l.deliveryAttemptId,_c(d));return r.delete(l.invitationId),{invitationId:p.id,state:p.state}});return Dme.bind(n,{actions:[o,s,a,c],load:async({query:l})=>{let d=l.get(Tme),[p,m]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),h=m.filter((F)=>F.deliveryModes.length>0),f=p.filter((F)=>F.invitation!==void 0),g=f.filter((F)=>F.invitation&&!THe.has(F.invitation.state)),y=f.filter((F)=>F.invitation&&THe.has(F.invitation.state)),b=d.state==="pending"?g:y,A=f.flatMap((F)=>{let M=F.invitation;if(!M)return[];let k=F.identities.find((L)=>L.type!=="passkey")?.label??F.externalPeers[0]?.peerId??"Not recorded",N=r.get(M.id);return[{id:M.id,displayName:F.displayName,role:F.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((F)=>[F.id,F])),C=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:xUr(),channels:h.map((F)=>({type:F.type,displayName:F.displayName,subjectLabel:F.subjectLabel,deliveryModes:F.deliveryModes})),invitations:b.slice(d.offset,d.offset+d.limit).flatMap((F)=>{let M=F.invitation?w.get(F.invitation.id):void 0;return M?[M]:[]}),...C?{selectedInvitation:C}:{},selectedTotal:b.length,pendingCount:g.length,historyCount:y.length,failureCount:g.filter((F)=>F.invitation?.state==="failed").length}}})}});return PA(i,Dme.actions)}var Lme=u.strictObject({peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional()}),AUr=u.strictObject({peerId:u.string().trim().min(1).max(2000),displayName:u.string().trim().min(1).max(200),role:u.enum(["admin","trusted"]),deliveryType:u.string().trim().min(1).max(64),deliverySubject:u.string().trim().min(1).max(1000),deliveryLabel:u.string().trim().min(1).max(200).optional(),deliveryMode:u.enum(["automatic","manual"])}),wUr=u.strictObject({peerId:u.string().trim().min(1).max(2000),userId:u.string().min(1)}),Ome=Zr({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:AUr,output:sH}),Nme=Zr({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:wUr,output:zf}),SUr=u.strictObject({query:Lme,peers:u.array(u.strictObject({peerId:u.string(),displayName:u.string(),role:u.enum(["admin","trusted","public"]),verificationStatus:u.enum(["unverified","verified"]),createdAt:u.number()})),people:u.array(u.strictObject({userId:u.string(),displayName:u.string()})),channels:u.array(aH)});function dH(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 jme(e){let t=e.some((r)=>r.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[dH(e,"peers"),dH(e,"link-peer"),dH(e,t)],invitations:[dH(e,t)]}}var kUr=f9("Peer invitation setup"),Mme=ps({id:"peers",label:"Peers",priority:12,permission:"admin",query:Lme,data:SUr,actions:[Ome,Nme],view:({data:e})=>{let t=cH(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:Ome,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:lH("Local role"),...uH(e.channels,t)}},result:kUr}]});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:Nme,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:US(i.peerId),person:i.displayName,role:i.role,verification:i.verificationStatus,linked:bh(i.createdAt)},compact:{title:US(i.peerId),metadata:[i.displayName,ao(i.role),bh(i.createdAt)],badges:[{label:ao(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 UHe(e){let t=Eh(e),r=e.studio.source({definition:Mme,bind:(i)=>{let n=Ome.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}},_c(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=Nme.bind(i,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},_c(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((l)=>l.userId===s.userId)?.displayName??"person";return{summary:`Link ${s.peerId} to ${c}? Local access does not change.`,revision:`${s.peerId}:${s.userId}`}});return Mme.bind(i,{actions:[n,o],load:async({query:s})=>{let a=s.get(Lme),[c,l]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),d=c.filter((p)=>p.status!=="invited");return{query:a,peers:c.flatMap((p)=>p.externalPeers.map((m)=>({peerId:m.peerId,displayName:p.displayName,role:p.role,verificationStatus:m.verificationStatus,createdAt:m.createdAt}))),people:oH(d),channels:l.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return PA(r,Mme.actions)}function zme(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 qHe(e,t,r){let i=zme(e,"people-summary");if(i.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let n=zme(e,"people");if(n.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=zme(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 Yme=u.strictObject({selected:u.string().trim().min(1).max(200).optional()}),Jme=u.strictObject({userId:u.string().min(1)}),BUr=u.strictObject({userId:u.string().min(1),role:u.enum(["admin","trusted","public"])}),CUr=u.strictObject({userId:u.string().min(1),status:u.enum(["active","suspended"])});function DUr(e){return e.revokedAt===void 0&&e.type!=="passkey"}function IUr(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var _Ur=u.strictObject({userId:u.string().min(1),credentialId:u.string().min(1)}),TUr=u.strictObject({userId:u.string().min(1),type:u.string().trim().min(1).max(64),subject:u.string().trim().min(1).max(2000),issuer:u.string().trim().min(1).max(2000).optional(),label:u.string().trim().min(1).max(200).optional()}),PUr=u.strictObject({userId:u.string().min(1),identityId:u.string().min(1)}),RUr=u.strictObject({userId:u.string().min(1),peerId:u.string().trim().min(1).max(2000)}),$me=Zr({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:BUr,output:zf}),Gme=Zr({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:CUr,output:zf}),Hme=Zr({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:Jme,output:zf}),Wme=Zr({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:_Ur,output:zf}),Qme=Zr({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:Jme,output:sH}),Zme=Zr({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:Jme,output:zf}),Xme=Zr({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:TUr,output:zf}),Vme=Zr({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:PUr,output:zf}),Kme=Zr({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:RUr,output:zf}),FUr=u.strictObject({userId:u.string(),displayName:u.string(),role:u.enum(["admin","trusted","public"]),status:u.enum(["active","suspended"]),isAnchor:u.boolean(),isSelf:u.boolean(),profileEntityId:u.string().optional(),passkeys:u.array(u.strictObject({id:u.string(),kind:u.string(),createdAt:u.number()})),identities:u.array(u.strictObject({id:u.string(),type:u.string(),displayName:u.string(),label:u.string(),verified:u.boolean()})),peers:u.array(u.strictObject({peerId:u.string(),verificationStatus:u.enum(["unverified","verified"])}))}),MUr=u.strictObject({query:Yme,anchor:u.strictObject({kind:u.enum(["person","collective"]),configuredKind:u.enum(["person","team","organization"]),displayName:u.string(),administeredBy:u.number().int().nonnegative()}),people:u.array(FUr),activeCount:u.number().int().nonnegative(),activeAdminCount:u.number().int().nonnegative(),suspendedCount:u.number().int().nonnegative(),channelTypes:u.array(u.strictObject({type:u.string(),displayName:u.string()}))}),OUr=f9("Passkey setup");function NUr(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function Ume(e){return{type:"notice",tone:"warn",text:e}}function LUr(e){return{type:"action",action:Qme,input:{userId:e},result:OUr}}function jUr(e,t){return{type:"action",action:Xme,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 zUr(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var qme=ps({id:"people",label:"People",priority:10,permission:"admin",query:Yme,data:MUr,actions:[$me,Gme,Hme,Wme,Qme,Zme,Xme,Vme,Kme],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:ao(t.role)},{label:"Status",value:ao(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:$me,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:Gme,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:Zme,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:Hme,input:{userId:t.userId}}]:[]]},...t.isSelf?[NUr()]:[],...s&&t.status==="active"?[Ume(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:bh(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${bh(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:Wme,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[LUr(t.userId)]:[Ume("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:Vme,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[jUr(t.userId,e.channelTypes)]:[Ume("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:US(a.peerId),description:`Vouched in by ${US(a.peerId)} \xB7 ${a.peerId}`,metadata:[ao(a.verificationStatus)],actions:[{action:Kme,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:[ao(n.role),ao(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 ${US(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 pH(e,t){return e.find((r)=>r.userId===t)?.displayName??"person"}async function UUr(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function $He(e){let t=Eh(e),r=e.studio.source({definition:qme,bind:(i)=>{let n=$me.bind(i,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,_c(f)),{status:`Role changed to ${ao(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${pH(f,h.userId)}\u2019s role to ${ao(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=Gme.bind(i,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,_c(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${pH(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=Hme.bind(i,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,_c(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${pH(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=Wme.bind(i,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,_c(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=Qme.bind(i,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,_c(f));return{status:`Bound to ${g.delivery.label}. Deliver only through that confirmed private channel.`,setupUrl:g.setupUrl,expiresAt:new Date(g.expiresAt*1000).toISOString()}}),l=Zme.bind(i,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,_c(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${pH(f,h.userId)} out everywhere?`,revision:h.userId}}),d=Xme.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"}},_c(f)),{status:"Verified channel attached."})),p=Vme.bind(i,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,_c(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=Kme.bind(i,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,_c(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 qme.bind(i,{actions:[n,o,s,a,c,l,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(Yme),[y,b,A]=await Promise.all([UUr(t),t.listAdminUsers(),t.listInvitationChannels()]),w=b.filter((N)=>N.status!=="invited"),C=w.find((N)=>N.isAnchor)??w.find((N)=>N.role==="admin"&&N.status==="active"),F=y??zUr(C?.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:F.kind,configuredKind:F.configuredKind,displayName:F.displayName,administeredBy:F.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:IUr(L),createdAt:L.createdAt})),identities:N.identities.filter(DUr).map((L)=>({id:L.id,type:L.type,displayName:k.get(L.type)??ao(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 PA(r,qme.actions)}var qUr=u.strictObject({tab:u.enum(["people","invitations","audit"]).default("people"),selected:u.string().trim().min(1).max(200).optional(),state:u.enum(["pending","history"]).optional(),offset:u.preprocess(yh,u.number().int().min(0).max(1e5)).optional(),limit:u.preprocess(yh,u.number().int().min(1).max(100)).optional(),peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional(),actorUserId:u.string().trim().min(1).max(120).optional(),action:u.string().trim().min(1).max(200).optional()});function $Ur(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function GUr(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 HUr(e,t){if(!GUr(e))throw Error(`${t} tab returned invalid workspace data`);return e}function GHe(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 ehe(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function PT(e,t,r,i){return HUr(await e.dataProvider(t,r,i),e.label)}async function WUr(e,t,r,i){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,r,i)}function ZUr(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 VUr(e){let t=e.filter((i)=>i.status==="suspended").length,r=e.filter((i)=>i.invitation!==void 0&&!["claimed","expired","cancelled"].includes(i.invitation.state)).length;return t+r}async function HHe(e){if(!e.studio.isAvailable())return;let t=$He(e),r=zHe(e),i=UHe(e),n=_He(e),o=ZUr([t,r,i,n]),s=t.registration,a=r.registration,c=i.registration,l=n.registration;return e.studio.register({id:"admin:administration",label:"Administration",rendererName:kT,priority:10,permission:"admin",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=qUr.parse(p??{}),f,g=ehe("People"),y=ehe("Invitations"),b=ehe("Audit");if(h.tab==="people"){let[A,w]=await Promise.all([PT(s,d,{...h.selected?{selected:h.selected}:{}},m),PT(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),C=jme(w.view.blocks);g=[...qHe(GHe(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."},C.people).blocks]}else if(h.tab==="invitations"){let[A,w]=await Promise.all([PT(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...Yn({offset:h.offset,limit:h.limit})},m),PT(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),C=jme(w.view.blocks),F=LHe(A.view.blocks,C.invitations);f=A.view.primaryAction,y=[...F.blocks]}else{let A=await PT(l,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...Yn({offset:h.offset,limit:h.limit})},m);b=GHe(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=$Ur(d);if(!h)throw new Lr("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new Lr("not_found",{publicMessage:`Unknown Administration action: ${h}`});return WUr(f,d,p,m)},badgeProvider:async()=>VUr(await Eh(e).listAdminUsers())})}var KUr=259200000,YUr=u.strictObject({id:u.string(),displayName:u.string(),state:u.string(),reason:u.enum(["expiring","delivery-failed"]),expiresAt:u.number().optional()}),JUr=u.strictObject({invitations:u.array(YUr),expiringCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()}),WHe=Qn({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:JUr,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 ${bh(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function QUr(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+KUr)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 ZHe(e,t){t.throwIfAborted();let r=await Eh(e).listAdminUsers();return t.throwIfAborted(),QUr(r,Date.now())}var XUr=u.strictObject({}),eqr=qt({id:"admin",config:XUr},{subscriptions:(e)=>{let t=Ct(e);return t.registered(async()=>{await HHe(t)}),[]},dashboardWidgets:(e)=>{let t=Ct(e);return[WHe.bind(e,({signal:r})=>ZHe(t,r))]}}),the=eqr;var Zi="agent",VHe="agent-network",KHe="agent-proximity",yhe="agent-discovery:entities",YHe="agent-discovery:proximity-map",bhe="proximity-map",Ehe="agent-list",vhe="agent-detail",Tc="skill",JHe=30,QHe=120;var hH="skill-derivation",XHe="skill-derivation",Ahe="skill:skill-derivation",eWe="skills";var tqr=u.string().trim().min(1).max(QHe),whe=u.array(tqr).max(JHe),MA=u.object({name:u.string(),description:u.string(),tags:whe,examples:u.array(u.string())}),$T=MA,OA=Uf.extend({entityType:u.literal(Tc),metadata:$T});var fH=u.object({name:u.string(),description:u.string(),tags:whe}),bb=u.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),rqr=jS,qf=u.object({name:u.string(),kind:rqr,organization:u.string().optional(),brainName:u.string().describe("Name of the brain instance"),url:u.string().url().describe("Brain endpoint URL"),repoDid:u.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:u.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:u.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:u.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:u.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:u.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:u.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:u.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:bb,discoveredAt:u.string().datetime().meta({description:"When this agent was first discovered",studioWidget:"provenance"}),introducedBy:u.array(u.string()).optional().meta({description:"Agent ids of the peers whose directories reported this agent",studioWidget:"provenance"}),hops:u.number().int().min(2).optional().meta({description:"Discovery order: 2 = sighted through a first-order peer",studioWidget:"provenance"})}),GT=u.object({name:u.string(),url:u.string().url(),status:bb,discoveredAt:u.string().datetime().optional(),slug:u.string(),repoDid:u.string().optional(),brainDid:u.string().optional(),cardUri:u.string().optional(),cardCid:u.string().optional(),cardLastError:u.string().optional(),cardFailureCount:u.number().int().nonnegative().optional(),cardUnavailableAt:u.string().datetime().optional(),cardStaleAfter:u.string().datetime().optional()}),Tn=Uf.extend({entityType:u.literal(Zi),metadata:GT}),iqr=Vr.extend({entityType:u.literal(Zi),metadata:GT}),HT=iqr.extend({frontmatter:qf,about:u.string(),skills:u.array(fH),notes:u.string()}),nqr=HT.extend({url:u.string().optional(),typeLabel:u.string().optional()}),oqr=HT.extend({url:u.string(),typeLabel:u.string()});var sqr=u.record(u.string(),u.unknown());function aqr(e){try{return wo(e,sqr).content}catch{return e}}function She(e){return{name:e.name,url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:g9(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 tWe(e){return $s(Zi,e,qf)}function WT(e){return{content:e,metadata:She(tWe(e))}}function y9(e){let t={name:e.name,kind:e.kind,...e.organization&&{organization:e.organization},brainName:e.brainName,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:bb.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},r=Ame({about:e.about,skills:e.skills,notes:e.notes});return un(r,t)}function $f(e,t={}){return y9({...e.frontmatter,...e.body,...t})}function ZT(e){return TT(aqr(e))}function oc(e){return{frontmatter:tWe(e.content),body:ZT(e.content)}}function khe(e){return un("",e)}function lqr(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function rWe(e,t,r={}){let i=r.minCount??1,n=r.topN??12,o=new Map,s=(a)=>{for(let c of sc(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=ZT(a.content);s(c.skills.flatMap((l)=>l.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=i).sort(lqr).slice(0,n)}function iWe(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 EHe(a,"Agent call failed");let c=Gpe.safeParse(a.data);if(!c.success)throw new Lr("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(YG,async({request:{userPermissionLevel:i}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:_i(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 AHe={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.779",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 XG(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 oUr={"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"},Ku=(e)=>XG(e,oUr);function sUr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(gh(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();await MGe(i,n.privateJwk,n.keyId)}}function aUr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(gh(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();return{keyId:n.keyId,signature:NGe(i,n.privateJwk)}}}function wHe(e,t,r){let i=sUr(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:eH,schema:tH}).has(n.trim().toLowerCase()))}}async function cUr(e,t,r){if(!r.cardReady)return;return YGe({character:e.identity.get(),profile:e.identity.getProfile(),version:AHe.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 lUr(e,t,r,i){let n=new URL(r.url),o=new URL(`${n.pathname}${n.search}`,Fx(r)),s=await OGe({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 uUr(e,t,r){let i=new SHe,n=e.agent;return i.get("/.well-known/agent-card.json",async(o)=>{let s=await cUr(e,t,r);if(!s)return Ku(o.json({error:"Agent Card not ready"},503));return Ku(o.json(s))}),i.get("/.well-known/agent-directory.json",async(o)=>{let s=await JGe(e.entityReads);return Ku(o.json(s))}),i.get("/a2a",(o)=>Ku(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),i.options("/a2a",()=>Ku(new Response(null,{status:204}))),i.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return Ku(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await lUr(e,r,o.req.raw,s)}catch{return Ku(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return Ku(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let l=eHe.safeParse(c);if(!l.success)return Ku(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(kGe(o.req.raw.headers)){let p=l.data.method==="message/send"?BGe(l.data.params):void 0,m=p?.op==="list"?await IGe(e.entityReads,a.permissionLevel):await DGe(e.entityReads,a.permissionLevel,p,aUr(e));if(!m)return Ku(o.json({error:"Not found"},404));return Ku(o.json({jsonrpc:"2.0",id:l.data.id,result:{kind:"message",messageId:crypto.randomUUID(),role:"agent",parts:[{kind:"data",data:m}]}}))}if(l.data.method==="message/stream"){let p=sHe.safeParse(l.data.params??{});if(!p.success)return Ku(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:l.data.id}));let m=aHe(l.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 Ku(o.json(m));return Ku(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await iHe(l.data,{taskManager:r.taskManager,turnSupervisor:r.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:r.publicAsks});return Ku(o.json(d))}),i}function Hpe(e={}){let t=xh({id:"a2a",config:VGe,setup:(n)=>{let{config:o}=n,s=us(n),{servesHttp:a}=s,c=wHe(s,o,e),l={cardReady:!1,servesHttp:a,taskManager:new Npe,turnSupervisor:new Lpe,jwksResolver:new gT(e.fetch?{fetch:e.fetch}:{}),clientDeps:c,publicAsks:new Ope(o.publicAsks,s.classRuntimeState)};if(vHe(s,c,{networkAskTimeoutMs:o.networkAskTimeoutMs}),a)s.endpoint({label:"A2A",url:"/a2a",priority:25}),s.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),s.logger.info("A2A interface registered",{domain:s.domain});else s.logger.info("A2A interface registered in tool-only mode",{domain:s.domain});return s.ready(()=>{l.cardReady=!0}),l}}),r=Ao(t,(n)=>{let{config:o,state:s}=n;if(!s.servesHttp)return[];let a=us(n),c=uUr(a,o,s),l=(p)=>Promise.resolve(c.fetch(p)),d=(p,m)=>({path:p,method:m,public:!0,handler:l});return[d("/.well-known/agent-card.json","GET"),d("/.well-known/agent-directory.json","GET"),d("/a2a","GET"),d("/a2a","POST"),d("/a2a","OPTIONS")]}),i=Rx(r,(n)=>{let{state:o}=n,{logger:s}=us(n);return{id:"a2a",start:async()=>{if(o.servesHttp)s.info("A2A mounted on shared webserver host");else s.info("A2A running without webserver routes")},stop:async()=>{await o.turnSupervisor.close(),s.info("A2A server stopped")}}});return Jn(i,(n)=>{let{config:o}=n,s=us(n),a=()=>hHe(wHe(s,o,e));return[{...a(),handler:(c,l)=>a().handler(c,l)}]})}var dUr=Hpe(),kHe=dUr;function yh(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function PA(e,t){return{registration:e,actionIds:t.map((r)=>r.name)}}var pUr=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function bh(e){return pUr.format(new Date(e))}function Eh(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function _c(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function oH(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function US(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 mUr={"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 kme(e){let t=mUr[e];if(t)return t;let r=e.replaceAll(/[._-]+/g," ").trim();return r.length===0?e:ao(r)}var Bme=u.strictObject({actorUserId:u.string().trim().min(1).max(120).optional(),action:u.string().trim().min(1).max(200).optional(),selected:u.string().trim().min(1).max(120).optional(),offset:u.preprocess(yh,u.number().int().min(0).max(1e5)).default(0),limit:u.preprocess(yh,u.number().int().min(1).max(100)).default(25)}),BHe=u.strictObject({id:u.string().min(1),actorUserId:u.string().min(1).optional(),action:u.string().min(1),targetType:u.string().min(1).optional(),targetId:u.string().min(1).optional(),targetUserId:u.string().min(1).optional(),createdAt:u.number().int().nonnegative()}),hUr=u.strictObject({userId:u.string().min(1),displayName:u.string().min(1)}),fUr=u.strictObject({query:Bme,events:u.array(BHe),selectedEvent:BHe.optional(),users:u.array(hUr),actions:u.array(u.strictObject({value:u.string().min(1),label:u.string().min(1),count:u.number().int().nonnegative()})),total:u.number().int().nonnegative()});function CHe(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 DHe(e,t){return e?t.get(e)??"Former Admin":"System"}function IHe(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 Sme=ps({id:"audit",label:"Audit",priority:90,permission:"admin",query:Bme,data:fUr,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:kme(r.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:DHe(r.actorUserId,t)},{label:"Action",value:r.action},{label:"Target",value:IHe(r,t)},{label:"Occurred",value:bh(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:kme(o.action),description:`${DHe(o.actorUserId,t)} \u2192 ${IHe(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 _He(e){let t=e.studio.source({definition:Sme,bind:(r)=>Sme.bind(r,{load:async({query:i})=>{let n=Eh(e),o=i.get(Bme),[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(CHe),...s.selectedEvent?{selectedEvent:CHe(s.selectedEvent)}:{},users:oH(a),actions:s.actions.map(({action:c,count:l})=>({value:c,label:kme(c),count:l})).sort((c,l)=>c.label.localeCompare(l.label)),total:s.total}},actions:[]})});return PA(t,Sme.actions)}var zf=u.strictObject({status:u.string()}),sH=u.strictObject({status:u.string(),setupUrl:u.url(),expiresAt:u.string()});function f9(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var aH=u.strictObject({type:u.string(),displayName:u.string(),subjectLabel:u.string(),deliveryModes:u.array(u.enum(["automatic","manual"]))});function cH(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function lH(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function uH(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 xUr}from"crypto";var THe=new Set(["claimed","expired","cancelled"]),gUr=new Set(["claimed","cancelled"]),Tme=u.strictObject({state:u.enum(["pending","history"]).optional().default("pending"),selected:u.string().trim().min(1).max(200).optional(),offset:u.preprocess(yh,u.number().int().min(0)).optional().default(0),limit:u.preprocess(yh,u.number().int().min(1).max(100)).optional().default(25)}),MHe=u.strictObject({status:u.string(),setupUrl:u.url().nullable(),expiresAt:u.string().nullable()}),yUr=u.strictObject({idempotencyKey:u.string().min(1),displayName:u.string().trim().min(1).max(200),role:u.enum(["admin","trusted"]),deliveryType:u.string().trim().min(1).max(100),deliverySubject:u.string().trim().min(1).max(500),deliveryLabel:u.string().trim().max(200).optional(),deliveryMode:u.enum(["automatic","manual"])}),OHe=u.strictObject({invitationId:u.string().min(1)}),bUr=u.strictObject({invitationId:u.string().min(1),deliveryAttemptId:u.string().min(1)}),NHe=u.strictObject({invitationId:u.string(),state:u.string()}),Ime=Zr({name:"create-invitation",label:"Add a person",permission:"admin",input:yUr,output:MHe}),Pme=Zr({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:OHe,output:MHe}),Rme=Zr({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:OHe,output:NHe}),Fme=Zr({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:bUr,output:NHe}),PHe=u.strictObject({id:u.string(),displayName:u.string(),role:u.string(),state:u.string(),destination:u.string(),updatedAt:u.number(),deliveryAttemptId:u.string().optional()}),EUr=u.strictObject({query:Tme,idempotencyKey:u.string(),channels:u.array(aH),invitations:u.array(PHe),selectedInvitation:PHe.optional(),selectedTotal:u.number().int().nonnegative(),pendingCount:u.number().int().nonnegative(),historyCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()});function _me(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 Cme(e,t){let r=_me(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 LHe(e,t){let r=_me(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")?[Cme(e,"create-invitation-unavailable")]:[],n=_me(e,"invitations");if(n.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=Cme(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,Cme(e,"invitation-filters"),n,{...o,presentation:"disclosure",blocks:[...o.blocks,r,...s]}]}}var jHe=f9("Invitation setup");function vUr(e){if(gUr.has(e.state))return[];return[...e.deliveryAttemptId?[{action:Fme,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:Pme,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:jHe}]:[],...e.state!=="expired"?[{action:Rme,input:{invitationId:e.id}}]:[]]}function RHe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return ao(e.state)}var Dme=ps({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:Tme,data:EUr,actions:[Ime,Pme,Rme,Fme],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=cH(e.channels),i;if(e.channels.length>0&&r.length>0)i={action:Ime,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:lH("Role"),...uH(e.channels,r)}},result:jHe};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:`${ao(o.role)} \xB7 ${RHe(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:ao(n.role)},{label:"Delivery",value:RHe(n)},{label:"Destination",value:n.destination},{label:"Updated",value:bh(n.updatedAt)}]},{type:"actions",id:"invitation-actions",items:vUr(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(ao).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 FHe(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 zHe(e){let t=Eh(e),r=new Map,i=e.studio.source({definition:Dme,bind:(n)=>{let o=Ime.bind(n,async({input:l,caller:d})=>{let p=await t.createInvitation({idempotencyKey:l.idempotencyKey,displayName:l.displayName,role:l.role,delivery:{type:l.deliveryType,subject:l.deliverySubject,...l.deliveryLabel?{label:l.deliveryLabel}:{},mode:l.deliveryMode}},_c(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return FHe(p)}),s=Pme.bind(n,async({input:l,caller:d})=>{let p=await t.resendInvitation(l.invitationId,_c(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return FHe(p)}),a=Rme.bind(n,async({input:l,caller:d})=>{let p=await t.cancelInvitation(l.invitationId,_c(d));return r.delete(l.invitationId),{invitationId:p.id,state:p.state}},({input:l})=>({summary:"Cancel this invitation and revoke its pending setup link?",revision:l.invitationId})),c=Fme.bind(n,async({input:l,caller:d})=>{let p=await t.confirmManualInvitationDelivery(l.invitationId,l.deliveryAttemptId,_c(d));return r.delete(l.invitationId),{invitationId:p.id,state:p.state}});return Dme.bind(n,{actions:[o,s,a,c],load:async({query:l})=>{let d=l.get(Tme),[p,m]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),h=m.filter((F)=>F.deliveryModes.length>0),f=p.filter((F)=>F.invitation!==void 0),g=f.filter((F)=>F.invitation&&!THe.has(F.invitation.state)),y=f.filter((F)=>F.invitation&&THe.has(F.invitation.state)),b=d.state==="pending"?g:y,A=f.flatMap((F)=>{let M=F.invitation;if(!M)return[];let k=F.identities.find((L)=>L.type!=="passkey")?.label??F.externalPeers[0]?.peerId??"Not recorded",N=r.get(M.id);return[{id:M.id,displayName:F.displayName,role:F.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((F)=>[F.id,F])),C=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:xUr(),channels:h.map((F)=>({type:F.type,displayName:F.displayName,subjectLabel:F.subjectLabel,deliveryModes:F.deliveryModes})),invitations:b.slice(d.offset,d.offset+d.limit).flatMap((F)=>{let M=F.invitation?w.get(F.invitation.id):void 0;return M?[M]:[]}),...C?{selectedInvitation:C}:{},selectedTotal:b.length,pendingCount:g.length,historyCount:y.length,failureCount:g.filter((F)=>F.invitation?.state==="failed").length}}})}});return PA(i,Dme.actions)}var Lme=u.strictObject({peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional()}),AUr=u.strictObject({peerId:u.string().trim().min(1).max(2000),displayName:u.string().trim().min(1).max(200),role:u.enum(["admin","trusted"]),deliveryType:u.string().trim().min(1).max(64),deliverySubject:u.string().trim().min(1).max(1000),deliveryLabel:u.string().trim().min(1).max(200).optional(),deliveryMode:u.enum(["automatic","manual"])}),wUr=u.strictObject({peerId:u.string().trim().min(1).max(2000),userId:u.string().min(1)}),Ome=Zr({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:AUr,output:sH}),Nme=Zr({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:wUr,output:zf}),SUr=u.strictObject({query:Lme,peers:u.array(u.strictObject({peerId:u.string(),displayName:u.string(),role:u.enum(["admin","trusted","public"]),verificationStatus:u.enum(["unverified","verified"]),createdAt:u.number()})),people:u.array(u.strictObject({userId:u.string(),displayName:u.string()})),channels:u.array(aH)});function dH(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 jme(e){let t=e.some((r)=>r.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[dH(e,"peers"),dH(e,"link-peer"),dH(e,t)],invitations:[dH(e,t)]}}var kUr=f9("Peer invitation setup"),Mme=ps({id:"peers",label:"Peers",priority:12,permission:"admin",query:Lme,data:SUr,actions:[Ome,Nme],view:({data:e})=>{let t=cH(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:Ome,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:lH("Local role"),...uH(e.channels,t)}},result:kUr}]});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:Nme,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:US(i.peerId),person:i.displayName,role:i.role,verification:i.verificationStatus,linked:bh(i.createdAt)},compact:{title:US(i.peerId),metadata:[i.displayName,ao(i.role),bh(i.createdAt)],badges:[{label:ao(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 UHe(e){let t=Eh(e),r=e.studio.source({definition:Mme,bind:(i)=>{let n=Ome.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}},_c(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=Nme.bind(i,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},_c(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((l)=>l.userId===s.userId)?.displayName??"person";return{summary:`Link ${s.peerId} to ${c}? Local access does not change.`,revision:`${s.peerId}:${s.userId}`}});return Mme.bind(i,{actions:[n,o],load:async({query:s})=>{let a=s.get(Lme),[c,l]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),d=c.filter((p)=>p.status!=="invited");return{query:a,peers:c.flatMap((p)=>p.externalPeers.map((m)=>({peerId:m.peerId,displayName:p.displayName,role:p.role,verificationStatus:m.verificationStatus,createdAt:m.createdAt}))),people:oH(d),channels:l.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return PA(r,Mme.actions)}function zme(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 qHe(e,t,r){let i=zme(e,"people-summary");if(i.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let n=zme(e,"people");if(n.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=zme(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 Yme=u.strictObject({selected:u.string().trim().min(1).max(200).optional()}),Jme=u.strictObject({userId:u.string().min(1)}),BUr=u.strictObject({userId:u.string().min(1),role:u.enum(["admin","trusted","public"])}),CUr=u.strictObject({userId:u.string().min(1),status:u.enum(["active","suspended"])});function DUr(e){return e.revokedAt===void 0&&e.type!=="passkey"}function IUr(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var _Ur=u.strictObject({userId:u.string().min(1),credentialId:u.string().min(1)}),TUr=u.strictObject({userId:u.string().min(1),type:u.string().trim().min(1).max(64),subject:u.string().trim().min(1).max(2000),issuer:u.string().trim().min(1).max(2000).optional(),label:u.string().trim().min(1).max(200).optional()}),PUr=u.strictObject({userId:u.string().min(1),identityId:u.string().min(1)}),RUr=u.strictObject({userId:u.string().min(1),peerId:u.string().trim().min(1).max(2000)}),$me=Zr({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:BUr,output:zf}),Gme=Zr({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:CUr,output:zf}),Hme=Zr({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:Jme,output:zf}),Wme=Zr({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:_Ur,output:zf}),Qme=Zr({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:Jme,output:sH}),Zme=Zr({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:Jme,output:zf}),Xme=Zr({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:TUr,output:zf}),Vme=Zr({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:PUr,output:zf}),Kme=Zr({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:RUr,output:zf}),FUr=u.strictObject({userId:u.string(),displayName:u.string(),role:u.enum(["admin","trusted","public"]),status:u.enum(["active","suspended"]),isAnchor:u.boolean(),isSelf:u.boolean(),profileEntityId:u.string().optional(),passkeys:u.array(u.strictObject({id:u.string(),kind:u.string(),createdAt:u.number()})),identities:u.array(u.strictObject({id:u.string(),type:u.string(),displayName:u.string(),label:u.string(),verified:u.boolean()})),peers:u.array(u.strictObject({peerId:u.string(),verificationStatus:u.enum(["unverified","verified"])}))}),MUr=u.strictObject({query:Yme,anchor:u.strictObject({kind:u.enum(["person","collective"]),configuredKind:u.enum(["person","team","organization"]),displayName:u.string(),administeredBy:u.number().int().nonnegative()}),people:u.array(FUr),activeCount:u.number().int().nonnegative(),activeAdminCount:u.number().int().nonnegative(),suspendedCount:u.number().int().nonnegative(),channelTypes:u.array(u.strictObject({type:u.string(),displayName:u.string()}))}),OUr=f9("Passkey setup");function NUr(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function Ume(e){return{type:"notice",tone:"warn",text:e}}function LUr(e){return{type:"action",action:Qme,input:{userId:e},result:OUr}}function jUr(e,t){return{type:"action",action:Xme,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 zUr(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var qme=ps({id:"people",label:"People",priority:10,permission:"admin",query:Yme,data:MUr,actions:[$me,Gme,Hme,Wme,Qme,Zme,Xme,Vme,Kme],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:ao(t.role)},{label:"Status",value:ao(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:$me,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:Gme,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:Zme,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:Hme,input:{userId:t.userId}}]:[]]},...t.isSelf?[NUr()]:[],...s&&t.status==="active"?[Ume(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:bh(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${bh(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:Wme,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[LUr(t.userId)]:[Ume("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:Vme,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[jUr(t.userId,e.channelTypes)]:[Ume("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:US(a.peerId),description:`Vouched in by ${US(a.peerId)} \xB7 ${a.peerId}`,metadata:[ao(a.verificationStatus)],actions:[{action:Kme,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:[ao(n.role),ao(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 ${US(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 pH(e,t){return e.find((r)=>r.userId===t)?.displayName??"person"}async function UUr(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function $He(e){let t=Eh(e),r=e.studio.source({definition:qme,bind:(i)=>{let n=$me.bind(i,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,_c(f)),{status:`Role changed to ${ao(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${pH(f,h.userId)}\u2019s role to ${ao(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=Gme.bind(i,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,_c(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${pH(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=Hme.bind(i,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,_c(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${pH(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=Wme.bind(i,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,_c(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=Qme.bind(i,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,_c(f));return{status:`Bound to ${g.delivery.label}. Deliver only through that confirmed private channel.`,setupUrl:g.setupUrl,expiresAt:new Date(g.expiresAt*1000).toISOString()}}),l=Zme.bind(i,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,_c(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${pH(f,h.userId)} out everywhere?`,revision:h.userId}}),d=Xme.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"}},_c(f)),{status:"Verified channel attached."})),p=Vme.bind(i,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,_c(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=Kme.bind(i,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,_c(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 qme.bind(i,{actions:[n,o,s,a,c,l,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(Yme),[y,b,A]=await Promise.all([UUr(t),t.listAdminUsers(),t.listInvitationChannels()]),w=b.filter((N)=>N.status!=="invited"),C=w.find((N)=>N.isAnchor)??w.find((N)=>N.role==="admin"&&N.status==="active"),F=y??zUr(C?.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:F.kind,configuredKind:F.configuredKind,displayName:F.displayName,administeredBy:F.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:IUr(L),createdAt:L.createdAt})),identities:N.identities.filter(DUr).map((L)=>({id:L.id,type:L.type,displayName:k.get(L.type)??ao(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 PA(r,qme.actions)}var qUr=u.strictObject({tab:u.enum(["people","invitations","audit"]).default("people"),selected:u.string().trim().min(1).max(200).optional(),state:u.enum(["pending","history"]).optional(),offset:u.preprocess(yh,u.number().int().min(0).max(1e5)).optional(),limit:u.preprocess(yh,u.number().int().min(1).max(100)).optional(),peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional(),actorUserId:u.string().trim().min(1).max(120).optional(),action:u.string().trim().min(1).max(200).optional()});function $Ur(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function GUr(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 HUr(e,t){if(!GUr(e))throw Error(`${t} tab returned invalid workspace data`);return e}function GHe(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 ehe(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function PT(e,t,r,i){return HUr(await e.dataProvider(t,r,i),e.label)}async function WUr(e,t,r,i){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,r,i)}function ZUr(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 VUr(e){let t=e.filter((i)=>i.status==="suspended").length,r=e.filter((i)=>i.invitation!==void 0&&!["claimed","expired","cancelled"].includes(i.invitation.state)).length;return t+r}async function HHe(e){if(!e.studio.isAvailable())return;let t=$He(e),r=zHe(e),i=UHe(e),n=_He(e),o=ZUr([t,r,i,n]),s=t.registration,a=r.registration,c=i.registration,l=n.registration;return e.studio.register({id:"admin:administration",label:"Administration",rendererName:kT,priority:10,permission:"admin",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=qUr.parse(p??{}),f,g=ehe("People"),y=ehe("Invitations"),b=ehe("Audit");if(h.tab==="people"){let[A,w]=await Promise.all([PT(s,d,{...h.selected?{selected:h.selected}:{}},m),PT(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),C=jme(w.view.blocks);g=[...qHe(GHe(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."},C.people).blocks]}else if(h.tab==="invitations"){let[A,w]=await Promise.all([PT(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...Yn({offset:h.offset,limit:h.limit})},m),PT(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),C=jme(w.view.blocks),F=LHe(A.view.blocks,C.invitations);f=A.view.primaryAction,y=[...F.blocks]}else{let A=await PT(l,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...Yn({offset:h.offset,limit:h.limit})},m);b=GHe(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=$Ur(d);if(!h)throw new Lr("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new Lr("not_found",{publicMessage:`Unknown Administration action: ${h}`});return WUr(f,d,p,m)},badgeProvider:async()=>VUr(await Eh(e).listAdminUsers())})}var KUr=259200000,YUr=u.strictObject({id:u.string(),displayName:u.string(),state:u.string(),reason:u.enum(["expiring","delivery-failed"]),expiresAt:u.number().optional()}),JUr=u.strictObject({invitations:u.array(YUr),expiringCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()}),WHe=Qn({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:JUr,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 ${bh(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function QUr(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+KUr)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 ZHe(e,t){t.throwIfAborted();let r=await Eh(e).listAdminUsers();return t.throwIfAborted(),QUr(r,Date.now())}var XUr=u.strictObject({}),eqr=qt({id:"admin",config:XUr},{subscriptions:(e)=>{let t=Ct(e);return t.registered(async()=>{await HHe(t)}),[]},dashboardWidgets:(e)=>{let t=Ct(e);return[WHe.bind(e,({signal:r})=>ZHe(t,r))]}}),the=eqr;var Zi="agent",VHe="agent-network",KHe="agent-proximity",yhe="agent-discovery:entities",YHe="agent-discovery:proximity-map",bhe="proximity-map",Ehe="agent-list",vhe="agent-detail",Tc="skill",JHe=30,QHe=120;var hH="skill-derivation",XHe="skill-derivation",Ahe="skill:skill-derivation",eWe="skills";var tqr=u.string().trim().min(1).max(QHe),whe=u.array(tqr).max(JHe),MA=u.object({name:u.string(),description:u.string(),tags:whe,examples:u.array(u.string())}),$T=MA,OA=Uf.extend({entityType:u.literal(Tc),metadata:$T});var fH=u.object({name:u.string(),description:u.string(),tags:whe}),bb=u.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),rqr=jS,qf=u.object({name:u.string(),kind:rqr,organization:u.string().optional(),brainName:u.string().describe("Name of the brain instance"),url:u.string().url().describe("Brain endpoint URL"),repoDid:u.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:u.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:u.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:u.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:u.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:u.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:u.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:u.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:bb,discoveredAt:u.string().datetime().meta({description:"When this agent was first discovered",studioWidget:"provenance"}),introducedBy:u.array(u.string()).optional().meta({description:"Agent ids of the peers whose directories reported this agent",studioWidget:"provenance"}),hops:u.number().int().min(2).optional().meta({description:"Discovery order: 2 = sighted through a first-order peer",studioWidget:"provenance"})}),GT=u.object({name:u.string(),url:u.string().url(),status:bb,discoveredAt:u.string().datetime().optional(),slug:u.string(),repoDid:u.string().optional(),brainDid:u.string().optional(),cardUri:u.string().optional(),cardCid:u.string().optional(),cardLastError:u.string().optional(),cardFailureCount:u.number().int().nonnegative().optional(),cardUnavailableAt:u.string().datetime().optional(),cardStaleAfter:u.string().datetime().optional()}),Tn=Uf.extend({entityType:u.literal(Zi),metadata:GT}),iqr=Vr.extend({entityType:u.literal(Zi),metadata:GT}),HT=iqr.extend({frontmatter:qf,about:u.string(),skills:u.array(fH),notes:u.string()}),nqr=HT.extend({url:u.string().optional(),typeLabel:u.string().optional()}),oqr=HT.extend({url:u.string(),typeLabel:u.string()});var sqr=u.record(u.string(),u.unknown());function aqr(e){try{return wo(e,sqr).content}catch{return e}}function She(e){return{name:e.name,url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:g9(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 tWe(e){return $s(Zi,e,qf)}function WT(e){return{content:e,metadata:She(tWe(e))}}function y9(e){let t={name:e.name,kind:e.kind,...e.organization&&{organization:e.organization},brainName:e.brainName,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:bb.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},r=Ame({about:e.about,skills:e.skills,notes:e.notes});return un(r,t)}function $f(e,t={}){return y9({...e.frontmatter,...e.body,...t})}function ZT(e){return TT(aqr(e))}function oc(e){return{frontmatter:tWe(e.content),body:ZT(e.content)}}function khe(e){return un("",e)}function lqr(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function rWe(e,t,r={}){let i=r.minCount??1,n=r.topN??12,o=new Map,s=(a)=>{for(let c of sc(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=ZT(a.content);s(c.skills.flatMap((l)=>l.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=i).sort(lqr).slice(0,n)}function iWe(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 b9(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:y9({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:sc(c.tags)})),notes:""}),metadata:{name:r,url:e.url,status:o,discoveredAt:s,slug:g9(e.url)},anchorName:r}}function Nx(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 uqr=u.object({prompt:u.string().optional(),url:u.string().optional(),content:u.string().optional(),skipAi:u.boolean().optional(),status:u.enum(["discovered","approved","archived"]).optional()});function nWe(e){return{input:uqr,generate:async({input:t})=>{let r=Nx(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 fh(r,{fetch:e??globalThis.fetch});if(!i.ok)return{success:!1,error:CA(i.reason)?i.error:`Could not fetch Agent Card from ${r}. Make sure the agent is running and accessible.`};let{content:n,metadata:o}=b9(i.card,{...t.status!==void 0?{status:t.status}:{}});return{success:!0,id:r,content:n,metadata:o}}}}var dqr=100,oWe=50000,Che="connect",sWe="dismiss";function Bhe(e){let t=Tn.parse(e),r=pqr(t);return r?{entity:t,parsed:r}:void 0}function aWe(e){return{sourceId:"agent-sightings",displayName:"Agent sightings",list:async({records:r})=>(await r.list()).flatMap((i)=>{let n=Bhe(i);return n?[n]:[]}).sort((i,n)=>n.parsed.frontmatter.discoveredAt.localeCompare(i.parsed.frontmatter.discoveredAt)).slice(0,dqr).map(({entity:i,parsed:n})=>mqr(i,n)),resolveDetail:async(r,{records:i,signal:n})=>{n.throwIfAborted();let o=Bhe(await i.get(r));if(n.throwIfAborted(),!o)throw Error("Agent sighting not found");let s=fqr(o.entity,o.parsed);return{kind:"plain",text:s.slice(0,oWe),truncated:s.length>oWe}},act:async(r,i,{records:n,edits:o})=>{if(i!==Che&&i!==sWe)throw Error("Invalid agent sighting Inbox action");let s=await n.get(r),a=s?Bhe(s):void 0;if(!s||!a)throw Error("Agent sighting not found");let c=i===Che?"approved":"archived";if(c==="approved")await e.approve(s.id);else await e.revoke(s.id);await o.update(s,{content:$f(a.parsed,{status:c,...c==="approved"?{introducedBy:void 0,hops:void 0}:{}}),metadata:{...s.metadata,status:c}})}}}function pqr(e){let t=oc(e);return t.frontmatter.status==="discovered"&&(t.frontmatter.introducedBy?.length??0)>0?t:void 0}function mqr(e,t){let r=Gf(t.frontmatter.name),i=Gf(e.id),n=cWe(r===i?r:`${r} \xB7 ${i}`,160);return{id:e.id,title:n,summary:hqr(t),receivedAt:t.frontmatter.discoveredAt,urgency:"normal",entityRef:{entityType:Zi,entityId:e.id},actions:[{id:Che,label:"Connect",confirm:!0},{id:sWe,label:"Dismiss",confirm:!0}]}}function hqr(e){let t=e.frontmatter.introducedBy??[],r=`Introduced by ${Dhe(t.map(Gf))}.`,i=Gf(e.body.about),n=e.body.skills.map((s)=>Gf(s.name)).filter(Boolean).slice(0,4),o=n.length>0?` Declared skills: ${Dhe(n)}.`:"";return cWe(`${r}${i?` ${i}`:""}${o}`,1000)}function fqr(e,t){let r=[`Agent: ${Gf(t.frontmatter.name)}`,`Domain: ${Gf(e.id)}`,`Introduced by: ${Dhe((t.frontmatter.introducedBy??[]).map(Gf))}`],i=Gf(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=Gf(n.description);return`- ${Gf(n.name)}${o?`: ${o}`:""}`}));return r.join(`
|
|
@@ -9525,7 +9525,7 @@ Guidelines:
|
|
|
9525
9525
|
3. Depth: Provide enough detail to be useful as a reference, but stay focused on the topic.
|
|
9526
9526
|
4. Style: Informative and educational. Write as if explaining to yourself for future reference.
|
|
9527
9527
|
5. Length: Adjust based on topic complexity - concise for simple topics, more detailed for complex ones.
|
|
9528
|
-
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var Yso="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.",o_=Wi(dhe(yt({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:wle,markdown:Sle,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:Yso,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:gje(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:vje},generation:yje,create:{fromUpload:k7r},jobs:{"upload-import":S7r(()=>o_)},evals:{generateNote:async(e,{ai:t})=>t.generate({template:"generation",prompt:u.object({prompt:u.string()}).parse(e).prompt,representedIdentity:"none"},u.object({title:u.string(),body:u.string()}))},atproto:xje}),[uhe(Ble,async({request:e,entities:t})=>{let{id:r,title:i,body:n}=e;if(await t.get(o_,r))return{noteId:r,created:!1};return await t.create(o_,{id:r,content:n,metadata:{title:i,titleStated:!0},visibility:"restricted"}),{noteId:r,created:!0}})]),n_);var Jso=Pi({id:"note",config:fje,entities:[o_]}),C7r=Jso;var Qso=u.object({type:u.literal("email"),address:u.string().max(0).optional()}).transform(()=>{return}),Xso=u.looseObject({defaultRecipient:Qso.or(D7r).optional()}),eao=qt({id:"notifications",config:Xso},{subscriptions:(e)=>{let{config:t}=e,r=Ct(e),{logger:i}=r;return r.answer(UC,async({request:n})=>{let o=n.recipient??t.defaultRecipient;if(!o)return i.warn(Cle.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=r.deliveryProvider(o.type);if(!s||!await s.isAvailable())return i.warn(Cle.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(Cle.deliveryFailed,{transportCode:a.failureCode});let c=I7r.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}),[]}}),_7r=eao;var P7r=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],tao=u.looseObject({elements:u.array(u.looseObject({snapshotDomain:u.string(),snapshotData:u.array(u.record(u.string(),u.unknown()))})),paging:u.looseObject({links:u.array(u.looseObject({rel:u.string().optional(),href:u.string().optional()})).optional()}).optional()}),rao="https://api.linkedin.com/rest",iao="202312",T7r=1000,nao=1000;function oao(e){return e.toLowerCase().includes("no data found for this memberid")}function sao(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 Zq{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===T7r)throw Error(`LinkedIn snapshot exceeded ${T7r} 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,sao(i,t),r+1)]}async fetchPage(e,t){let r=new URL(`${rao}/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":iao}});if(i.ok)return tao.parse(await i.json());let n=await i.text();if(i.status<500&&oao(n))return null;throw new Dle(i.status,n.slice(0,nao))}}class Dle extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var aao=R7r({title:"LinkedIn",description:"The LinkedIn connection the LinkedIn import reads your profile with. Connect from the LinkedIn workspace, or paste a member token with the r_dma_portability_3rd_party scope.",schema:u.object({accessToken:u.string().trim().min(1),expiresAt:u.iso.datetime().optional()}),fields:{accessToken:{label:"Access token",secret:!0},expiresAt:{label:"Expires (ISO date and time)"}}});class Aje{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:aao})}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 wje(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var cao="https://www.linkedin.com/oauth/v2/authorization",lao="https://www.linkedin.com/oauth/v2/accessToken",F7r="r_dma_portability_3rd_party",uao=500,dao=u.looseObject({access_token:u.string().min(1),expires_in:u.number().int().positive(),scope:u.string().optional()}),pao=u.looseObject({error:u.string().optional(),error_description:u.string().optional()});async function mao(e){try{return await e.json()}catch{return null}}class Kq{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(cao);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",F7r),t}async exchange(e,t){let r=await this.fetchFn(lao,{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 mao(r);if(!r.ok){let o=pao.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,uao)}`:""}`)}let n=dao.parse(i);if(n.scope!==void 0&&n.scope!==F7r)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 O7r(e){return new Vq({...M7r,now:e})}var Ile="linkedin",hao=u.strictObject({accessToken:u.string().min(1),expiresAt:u.iso.datetime()});function Sje(e,t={}){let r=(n)=>new Kq({...e,redirectUri:n},t.fetch),i=t.now??Date.now;return{id:Ile,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 kje{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(s_.authorizations,{provider:Ile,brainState:e},"the connection");return new URL(N7r.parse(t).authorizationUrl)}async redeem(e){let t=L7r.parse(await this.post(s_.redeem,{provider:Ile,grant:e},"grant redemption"));if(t.provider!==Ile)throw Error("OAuth broker redeemed a grant for another provider");return hao.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 fao(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function dB(e,t){return e.map((r)=>fao(r[t])).find(Boolean)}function j7r(e){let t=[dB(e,"First Name"),dB(e,"Last Name")].filter(Boolean).join(" ")||void 0,r=dB(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],i={name:t,headline:dB(e,"Headline"),industry:dB(e,"Industry"),location:dB(e,"Geo Location"),website:r,story:dB(e,"Summary")};return Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))}function z7r(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new Lr(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new Lr("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class Bje{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 z7r(await this.messaging.request(Jq,{fields:t,revision:r}))}async previewFields(e){return z7r(await this.messaging.request(Yq,{fields:e}))}async imported(e){let t=new Zq(e,this.fetchFn);return j7r(await t.fetchProfile())}}var Cje="/linkedin/oauth/start",Xq="/linkedin/oauth/callback",e$="/linkedin/oauth/broker/return";function U7r(e){return e?.permissionLevel==="admin"&&e.isAnchor}function Qq(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function $7r(e){let t=(c)=>{let l=e.workspaceUrl(),d=l.includes("?")?"&":"?";return Qq(303,`${l}${d}connection=${c}`)},r=async(c,l)=>{let d=e.states.take(l),p=await e.resolveSession(c);return d&&U7r(p)&&p?.userId===d?d:null},i=async(c,l)=>{try{return await e.connections.save(c,await l()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${fe(d)}`),t("failed")}},n=async(c)=>{let l=await e.resolveSession(c);if(!l)return Qq(401);if(!U7r(l))return Qq(403);let d=e.states.issue(l.userId),{mode:p}=e;if(p.kind==="direct")return Qq(302,p.oauth.authorizationUrl(d).toString());try{return Qq(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${fe(m)}`),t("failed")}},o=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await r(l,d.get("state")??"");if(!p)return t("failed");if(d.has("error"))return t("declined");let m=d.get("code");if(!m)return t("failed");return i(p,()=>c.exchange(m,e.now()))},s=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await r(l,d.get("state")??""),m=q7r.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:Cje,method:"GET",public:!0,handler:n},a.kind==="direct"?{path:Xq,method:"GET",public:!0,handler:o(a.oauth)}:{path:e$,method:"GET",public:!0,handler:s(a.broker)}]}var xao=/^(?: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,gao=[[/^$/,"<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>"],[xao,"<month-year>"]];function W7r(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 G7r(e){if(typeof e!=="string")return`<${W7r(e)}>`;let t=e.trim();return gao.find(([r])=>r.test(t))?.[1]??"<string>"}function yao(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(G7r))].sort();return G7r(e)}function H7r([e],[t]){return e.localeCompare(t)}function bao(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])=>W7r(a)))].sort(),presentCount:s.length}}),n=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(H7r).map(([a,c])=>[a,yao(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:i,recordShapes:[...n].sort(H7r).map(([,o])=>o)}}async function Z7r(e){let t=await Promise.all(P7r.map(async(r)=>[r,bao(await e.fetchDomain(r))]));return Object.fromEntries(t)}var X7r={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},Eao={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},vao={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."}},V7r=200,Tje=Zr({name:"import-profile",label:"Import from LinkedIn",permission:"admin",confirmation:{kind:"prepared"},input:u.object({}),output:u.object({filled:u.array(u.string()),kept:u.array(u.string())})}),_le=Zr({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:u.object({}),output:u.object({disconnected:u.boolean()})}),Pje=Zr({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:u.object({}),output:u.object({shapes:u.string()})}),Rje=u.object({connection:u.enum(["connected","declined","failed"]).optional()}),Aao=u.object({field:u.enum(["name","headline","industry","location","website","story"]),current:u.string().nullable(),imported:u.string(),outcome:u.enum(["fill","preserve","unchanged"])}),Dje=Rje.shape.connection,wao=u.discriminatedUnion("status",[u.object({status:u.literal("disconnected"),expired:u.boolean(),startUrl:u.string(),connection:Dje}),u.object({status:u.literal("unavailable"),message:u.string(),startUrl:u.string(),connection:Dje}),u.object({status:u.literal("ready"),fields:u.array(Aao),connection:Dje})]);function K7r(e){if(e===null)return"\u2014";return e.length>V7r?`${e.slice(0,V7r-1)}\u2026`:e}function Y7r(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function J7r(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function Ije(e){let t=e.connection?vao[e.connection]:null;return t?[{type:"notice",...t}]:[]}var Q7r=ps({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",query:Rje,data:wao,actions:[Tje,_le,Pje],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:[...Ije(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],J7r(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...Ije(e),{type:"notice",tone:"warn",text:e.message},J7r(e.startUrl,"Connect LinkedIn again"),{type:"action",action:_le,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:Tje,input:{}}}:{},blocks:[...Ije(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:X7r[r.field],current:K7r(r.current),imported:K7r(r.imported),outcome:Eao[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:Pje,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:_le,input:{}}]}}});function _je(e){if(e?.permission!=="admin"||!e.isAnchor)throw new Lr("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function Sao(e){if(e instanceof Dle&&[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 e_r(e,t){if(!e.isAvailable())return;let r=async(n)=>{let o=await t.connections.get(_je(n));if(!o||wje(o))throw new Lr("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},i=e.source({definition:Q7r,bind:(n)=>Q7r.bind(n,{load:async({caller:o,query:s})=>{let a=_je(o),{connection:c}=s.get(Rje),l=await t.connections.get(a);if(!l||wje(l))return{status:"disconnected",expired:l!==null,startUrl:t.startUrl,connection:c};try{return{status:"ready",fields:(await t.profileImport.preview(l.accessToken)).fields,connection:c}}catch(d){return{status:"unavailable",message:Sao(d),startUrl:t.startUrl,connection:c}}},actions:[Tje.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)=>X7r[p.field].toLowerCase()),c=a("fill"),l=a("preserve");if(c.length===0)throw new Lr("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${Y7r(c)} from LinkedIn?${l.length>0?` Your ${Y7r(l)} stay as you wrote them.`:""}`,revision:s.revision}}),Pje.bind(n,async({caller:o})=>{let s=await Z7r(t.clientFor((await r(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),_le.bind(n,async({caller:o})=>(await t.connections.forget(_je(o)),{disconnected:!0}))]})});return e.register({...i,accessHandler:async(n)=>n.isAnchor&&await i.accessHandler(n)})}var t_r={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.778",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 Bao="/studio",Cao=u.object({clientId:u.string().trim().min(1).describe("LinkedIn app client ID"),clientSecret:u.string().trim().min(1).describe("LinkedIn app client secret"),redirectUri:u.url({protocol:/^https?$/}).describe(`This brain's callback URL ending at ${Xq}, registered with the LinkedIn app`)}),Dao=u.object({url:u.url({protocol:/^https$/}).describe("The managed broker's origin"),instanceId:u.string().trim().min(1).describe("This brain's broker instance"),secret:u.string().min(32).describe("This brain's broker instance secret"),returnUri:u.url({protocol:/^https?$/}).describe(`This brain's return URL ending at ${e$}, registered with the broker`)}),r_r=u.object({oauth:Cao.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:Dao.optional().describe("The managed broker holding the shared LinkedIn app")});function Iao(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!==Xq)throw Error(`linkedin-import: oauth.redirectUri must end at ${Xq}`);if(i&&new URL(i.returnUri).pathname!==e$)throw Error(`linkedin-import: broker.returnUri must end at ${e$}`);if(r)return{kind:"direct",oauth:new Kq(r,t.fetch)};if(i)return{kind:"broker",broker:new kje(i,t.fetch)};return null}function i_r(e={}){let t=qt({id:"linkedin-import",config:r_r,setup:(r)=>{let{config:i}=r,n=Iao(i,e),o=i.oauth?.redirectUri??i.broker?.returnUri;if(!n||!o)return{routes:[]};let s=Ct(r),a=new Aje(s.accountSettings,{pluginId:s.pluginId,packageName:t_r.name}),c=Bao;return s.registered(async()=>{let l=await e_r(s.studio,{profileImport:new Bje(s.messaging,e.fetch),clientFor:(d)=>new Zq(d,e.fetch),connections:a,startUrl:new URL(Cje,o).toString()});if(l)c=l}),{routes:$7r({mode:n,states:O7r(),connections:a,resolveSession:async(l)=>s.auth()?.resolveSession(l),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return Ao(t,({state:r})=>r.routes)}var Fje=i_r();import{createHash as _ao,timingSafeEqual as Tao}from"crypto";function n_r(e){return _ao("sha256").update(e).digest()}function Pao(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 Mje{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:n_r(t.secret)}]))}authenticate(e){let t=Pao(e.headers.get("authorization")),r=t?this.instances.get(t.id):void 0;if(!t||!r)return null;return Tao(n_r(t.secret),r.secretHash)?{id:r.id,returnUris:r.returnUris}:null}}var Rao=10,Fao=600000,Nje={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function sS(e,t=200){return Response.json(e,{status:t,headers:Nje})}function o_r(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...Nje,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function s_r(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function Tle(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:{...Nje,Location:r.toString()}})}function l_r(e){let t=new Map(e.providers.map((c)=>[c.id,c])),r=new Map,i=(c)=>{let l=e.now(),d=(r.get(c)??[]).filter((m)=>m>l-Fao),p=d.length<Rao;return r.set(c,p?[...d,l]:d),p},n=(c)=>new URL(Oje(c),e.publicUrl).toString(),o=async(c)=>{let l=e.instances.authenticate(c);if(!l)return o_r();let d=a_r.safeParse(await s_r(c));if(!d.success)return sS({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=l.returnUris[d.data.provider];if(!p||!m)return sS({error:"Provider is unavailable for this instance"},400);if(!i(l.id))return sS({error:"Too many connections started; try later"},429);let h=e.authorizations.issue({provider:p.id,instanceId:l.id,returnUri:m,brainState:d.data.brainState}),f=p.authorizationUrl({redirectUri:n(p.id),state:h}).toString();return sS({authorizationUrl:f})},s=async(c)=>{let l=e.instances.authenticate(c);if(!l)return o_r();let d=c_r.safeParse(await s_r(c));if(!d.success)return sS({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,m=e.grants.take(d.data.grant,(h)=>h.provider===p&&h.instanceId===l.id);if(!m)return sS({error:"Invalid or expired grant"},400);return sS({provider:p,credential:m.credential})},a=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=e.authorizations.take(d.get("state")??"",(h)=>h.provider===c.id);if(!p)return sS({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return Tle(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return Tle(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 Tle(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${fe(h)}`),Tle(p,{error:"credential_exchange_failed"})}};return[{path:s_.authorizations,method:"POST",public:!0,handler:o},{path:s_.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:Oje(c.id),method:"GET",public:!0,handler:a(c)}))]}var Mao=600000,Oao=120000,u_r=1000,Nao=u.object({clientId:u.string().trim().min(1),clientSecret:u.string().trim().min(1)}),Lao=u.object({id:u.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/),secret:u.string().min(32).describe("Revocable instance secret"),returnUris:u.record(Lje,u.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),d_r=u.object({publicUrl:u.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:u.record(Lje,Nao).default({}).describe("Per provider, the shared app the broker holds"),instances:u.array(Lao).default([])});function jao(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 jje(e){let t=qt({id:"oauth-broker",config:d_r,setup:(r)=>{let{config:i}=r,n=jao(i,e);if(i.instances.length===0||n.length===0)return{routes:[]};return{routes:l_r({publicUrl:i.publicUrl,providers:n,instances:new Mje(i.instances),authorizations:new Vq({ttlMs:Mao,maxPending:u_r,now:e.now}),grants:new Vq({ttlMs:Oao,maxPending:u_r,now:e.now}),now:e.now??Date.now,logger:Ct(r).logger})}}});return Ao(t,({state:r})=>r.routes)}var zao=2592000000,t$=(e,t)=>Ht(`${e}
|
|
9528
|
+
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var Yso="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.",o_=Wi(dhe(yt({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:wle,markdown:Sle,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:Yso,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:gje(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:vje},generation:yje,create:{fromUpload:k7r},jobs:{"upload-import":S7r(()=>o_)},evals:{generateNote:async(e,{ai:t})=>t.generate({template:"generation",prompt:u.object({prompt:u.string()}).parse(e).prompt,representedIdentity:"none"},u.object({title:u.string(),body:u.string()}))},atproto:xje}),[uhe(Ble,async({request:e,entities:t})=>{let{id:r,title:i,body:n}=e;if(await t.get(o_,r))return{noteId:r,created:!1};return await t.create(o_,{id:r,content:n,metadata:{title:i,titleStated:!0},visibility:"restricted"}),{noteId:r,created:!0}})]),n_);var Jso=Pi({id:"note",config:fje,entities:[o_]}),C7r=Jso;var Qso=u.object({type:u.literal("email"),address:u.string().max(0).optional()}).transform(()=>{return}),Xso=u.looseObject({defaultRecipient:Qso.or(D7r).optional()}),eao=qt({id:"notifications",config:Xso},{subscriptions:(e)=>{let{config:t}=e,r=Ct(e),{logger:i}=r;return r.answer(UC,async({request:n})=>{let o=n.recipient??t.defaultRecipient;if(!o)return i.warn(Cle.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=r.deliveryProvider(o.type);if(!s||!await s.isAvailable())return i.warn(Cle.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(Cle.deliveryFailed,{transportCode:a.failureCode});let c=I7r.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}),[]}}),_7r=eao;var P7r=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],tao=u.looseObject({elements:u.array(u.looseObject({snapshotDomain:u.string(),snapshotData:u.array(u.record(u.string(),u.unknown()))})),paging:u.looseObject({links:u.array(u.looseObject({rel:u.string().optional(),href:u.string().optional()})).optional()}).optional()}),rao="https://api.linkedin.com/rest",iao="202312",T7r=1000,nao=1000;function oao(e){return e.toLowerCase().includes("no data found for this memberid")}function sao(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 Zq{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===T7r)throw Error(`LinkedIn snapshot exceeded ${T7r} 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,sao(i,t),r+1)]}async fetchPage(e,t){let r=new URL(`${rao}/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":iao}});if(i.ok)return tao.parse(await i.json());let n=await i.text();if(i.status<500&&oao(n))return null;throw new Dle(i.status,n.slice(0,nao))}}class Dle extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var aao=R7r({title:"LinkedIn",description:"The LinkedIn connection the LinkedIn import reads your profile with. Connect from the LinkedIn workspace, or paste a member token with the r_dma_portability_3rd_party scope.",schema:u.object({accessToken:u.string().trim().min(1),expiresAt:u.iso.datetime().optional()}),fields:{accessToken:{label:"Access token",secret:!0},expiresAt:{label:"Expires (ISO date and time)"}}});class Aje{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:aao})}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 wje(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var cao="https://www.linkedin.com/oauth/v2/authorization",lao="https://www.linkedin.com/oauth/v2/accessToken",F7r="r_dma_portability_3rd_party",uao=500,dao=u.looseObject({access_token:u.string().min(1),expires_in:u.number().int().positive(),scope:u.string().optional()}),pao=u.looseObject({error:u.string().optional(),error_description:u.string().optional()});async function mao(e){try{return await e.json()}catch{return null}}class Kq{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(cao);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",F7r),t}async exchange(e,t){let r=await this.fetchFn(lao,{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 mao(r);if(!r.ok){let o=pao.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,uao)}`:""}`)}let n=dao.parse(i);if(n.scope!==void 0&&n.scope!==F7r)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 O7r(e){return new Vq({...M7r,now:e})}var Ile="linkedin",hao=u.strictObject({accessToken:u.string().min(1),expiresAt:u.iso.datetime()});function Sje(e,t={}){let r=(n)=>new Kq({...e,redirectUri:n},t.fetch),i=t.now??Date.now;return{id:Ile,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 kje{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(s_.authorizations,{provider:Ile,brainState:e},"the connection");return new URL(N7r.parse(t).authorizationUrl)}async redeem(e){let t=L7r.parse(await this.post(s_.redeem,{provider:Ile,grant:e},"grant redemption"));if(t.provider!==Ile)throw Error("OAuth broker redeemed a grant for another provider");return hao.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 fao(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function dB(e,t){return e.map((r)=>fao(r[t])).find(Boolean)}function j7r(e){let t=[dB(e,"First Name"),dB(e,"Last Name")].filter(Boolean).join(" ")||void 0,r=dB(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],i={name:t,headline:dB(e,"Headline"),industry:dB(e,"Industry"),location:dB(e,"Geo Location"),website:r,story:dB(e,"Summary")};return Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))}function z7r(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new Lr(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new Lr("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class Bje{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 z7r(await this.messaging.request(Jq,{fields:t,revision:r}))}async previewFields(e){return z7r(await this.messaging.request(Yq,{fields:e}))}async imported(e){let t=new Zq(e,this.fetchFn);return j7r(await t.fetchProfile())}}var Cje="/linkedin/oauth/start",Xq="/linkedin/oauth/callback",e$="/linkedin/oauth/broker/return";function U7r(e){return e?.permissionLevel==="admin"&&e.isAnchor}function Qq(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function $7r(e){let t=(c)=>{let l=e.workspaceUrl(),d=l.includes("?")?"&":"?";return Qq(303,`${l}${d}connection=${c}`)},r=async(c,l)=>{let d=e.states.take(l),p=await e.resolveSession(c);return d&&U7r(p)&&p?.userId===d?d:null},i=async(c,l)=>{try{return await e.connections.save(c,await l()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${fe(d)}`),t("failed")}},n=async(c)=>{let l=await e.resolveSession(c);if(!l)return Qq(401);if(!U7r(l))return Qq(403);let d=e.states.issue(l.userId),{mode:p}=e;if(p.kind==="direct")return Qq(302,p.oauth.authorizationUrl(d).toString());try{return Qq(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${fe(m)}`),t("failed")}},o=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await r(l,d.get("state")??"");if(!p)return t("failed");if(d.has("error"))return t("declined");let m=d.get("code");if(!m)return t("failed");return i(p,()=>c.exchange(m,e.now()))},s=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await r(l,d.get("state")??""),m=q7r.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:Cje,method:"GET",public:!0,handler:n},a.kind==="direct"?{path:Xq,method:"GET",public:!0,handler:o(a.oauth)}:{path:e$,method:"GET",public:!0,handler:s(a.broker)}]}var xao=/^(?: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,gao=[[/^$/,"<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>"],[xao,"<month-year>"]];function W7r(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 G7r(e){if(typeof e!=="string")return`<${W7r(e)}>`;let t=e.trim();return gao.find(([r])=>r.test(t))?.[1]??"<string>"}function yao(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(G7r))].sort();return G7r(e)}function H7r([e],[t]){return e.localeCompare(t)}function bao(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])=>W7r(a)))].sort(),presentCount:s.length}}),n=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(H7r).map(([a,c])=>[a,yao(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:i,recordShapes:[...n].sort(H7r).map(([,o])=>o)}}async function Z7r(e){let t=await Promise.all(P7r.map(async(r)=>[r,bao(await e.fetchDomain(r))]));return Object.fromEntries(t)}var X7r={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},Eao={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},vao={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."}},V7r=200,Tje=Zr({name:"import-profile",label:"Import from LinkedIn",permission:"admin",confirmation:{kind:"prepared"},input:u.object({}),output:u.object({filled:u.array(u.string()),kept:u.array(u.string())})}),_le=Zr({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:u.object({}),output:u.object({disconnected:u.boolean()})}),Pje=Zr({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:u.object({}),output:u.object({shapes:u.string()})}),Rje=u.object({connection:u.enum(["connected","declined","failed"]).optional()}),Aao=u.object({field:u.enum(["name","headline","industry","location","website","story"]),current:u.string().nullable(),imported:u.string(),outcome:u.enum(["fill","preserve","unchanged"])}),Dje=Rje.shape.connection,wao=u.discriminatedUnion("status",[u.object({status:u.literal("disconnected"),expired:u.boolean(),startUrl:u.string(),connection:Dje}),u.object({status:u.literal("unavailable"),message:u.string(),startUrl:u.string(),connection:Dje}),u.object({status:u.literal("ready"),fields:u.array(Aao),connection:Dje})]);function K7r(e){if(e===null)return"\u2014";return e.length>V7r?`${e.slice(0,V7r-1)}\u2026`:e}function Y7r(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function J7r(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function Ije(e){let t=e.connection?vao[e.connection]:null;return t?[{type:"notice",...t}]:[]}var Q7r=ps({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",query:Rje,data:wao,actions:[Tje,_le,Pje],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:[...Ije(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],J7r(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...Ije(e),{type:"notice",tone:"warn",text:e.message},J7r(e.startUrl,"Connect LinkedIn again"),{type:"action",action:_le,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:Tje,input:{}}}:{},blocks:[...Ije(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:X7r[r.field],current:K7r(r.current),imported:K7r(r.imported),outcome:Eao[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:Pje,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:_le,input:{}}]}}});function _je(e){if(e?.permission!=="admin"||!e.isAnchor)throw new Lr("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function Sao(e){if(e instanceof Dle&&[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 e_r(e,t){if(!e.isAvailable())return;let r=async(n)=>{let o=await t.connections.get(_je(n));if(!o||wje(o))throw new Lr("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},i=e.source({definition:Q7r,bind:(n)=>Q7r.bind(n,{load:async({caller:o,query:s})=>{let a=_je(o),{connection:c}=s.get(Rje),l=await t.connections.get(a);if(!l||wje(l))return{status:"disconnected",expired:l!==null,startUrl:t.startUrl,connection:c};try{return{status:"ready",fields:(await t.profileImport.preview(l.accessToken)).fields,connection:c}}catch(d){return{status:"unavailable",message:Sao(d),startUrl:t.startUrl,connection:c}}},actions:[Tje.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)=>X7r[p.field].toLowerCase()),c=a("fill"),l=a("preserve");if(c.length===0)throw new Lr("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${Y7r(c)} from LinkedIn?${l.length>0?` Your ${Y7r(l)} stay as you wrote them.`:""}`,revision:s.revision}}),Pje.bind(n,async({caller:o})=>{let s=await Z7r(t.clientFor((await r(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),_le.bind(n,async({caller:o})=>(await t.connections.forget(_je(o)),{disconnected:!0}))]})});return e.register({...i,accessHandler:async(n)=>n.isAnchor&&await i.accessHandler(n)})}var t_r={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.779",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 Bao="/studio",Cao=u.object({clientId:u.string().trim().min(1).describe("LinkedIn app client ID"),clientSecret:u.string().trim().min(1).describe("LinkedIn app client secret"),redirectUri:u.url({protocol:/^https?$/}).describe(`This brain's callback URL ending at ${Xq}, registered with the LinkedIn app`)}),Dao=u.object({url:u.url({protocol:/^https$/}).describe("The managed broker's origin"),instanceId:u.string().trim().min(1).describe("This brain's broker instance"),secret:u.string().min(32).describe("This brain's broker instance secret"),returnUri:u.url({protocol:/^https?$/}).describe(`This brain's return URL ending at ${e$}, registered with the broker`)}),r_r=u.object({oauth:Cao.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:Dao.optional().describe("The managed broker holding the shared LinkedIn app")});function Iao(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!==Xq)throw Error(`linkedin-import: oauth.redirectUri must end at ${Xq}`);if(i&&new URL(i.returnUri).pathname!==e$)throw Error(`linkedin-import: broker.returnUri must end at ${e$}`);if(r)return{kind:"direct",oauth:new Kq(r,t.fetch)};if(i)return{kind:"broker",broker:new kje(i,t.fetch)};return null}function i_r(e={}){let t=qt({id:"linkedin-import",config:r_r,setup:(r)=>{let{config:i}=r,n=Iao(i,e),o=i.oauth?.redirectUri??i.broker?.returnUri;if(!n||!o)return{routes:[]};let s=Ct(r),a=new Aje(s.accountSettings,{pluginId:s.pluginId,packageName:t_r.name}),c=Bao;return s.registered(async()=>{let l=await e_r(s.studio,{profileImport:new Bje(s.messaging,e.fetch),clientFor:(d)=>new Zq(d,e.fetch),connections:a,startUrl:new URL(Cje,o).toString()});if(l)c=l}),{routes:$7r({mode:n,states:O7r(),connections:a,resolveSession:async(l)=>s.auth()?.resolveSession(l),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return Ao(t,({state:r})=>r.routes)}var Fje=i_r();import{createHash as _ao,timingSafeEqual as Tao}from"crypto";function n_r(e){return _ao("sha256").update(e).digest()}function Pao(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 Mje{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:n_r(t.secret)}]))}authenticate(e){let t=Pao(e.headers.get("authorization")),r=t?this.instances.get(t.id):void 0;if(!t||!r)return null;return Tao(n_r(t.secret),r.secretHash)?{id:r.id,returnUris:r.returnUris}:null}}var Rao=10,Fao=600000,Nje={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function sS(e,t=200){return Response.json(e,{status:t,headers:Nje})}function o_r(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...Nje,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function s_r(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function Tle(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:{...Nje,Location:r.toString()}})}function l_r(e){let t=new Map(e.providers.map((c)=>[c.id,c])),r=new Map,i=(c)=>{let l=e.now(),d=(r.get(c)??[]).filter((m)=>m>l-Fao),p=d.length<Rao;return r.set(c,p?[...d,l]:d),p},n=(c)=>new URL(Oje(c),e.publicUrl).toString(),o=async(c)=>{let l=e.instances.authenticate(c);if(!l)return o_r();let d=a_r.safeParse(await s_r(c));if(!d.success)return sS({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=l.returnUris[d.data.provider];if(!p||!m)return sS({error:"Provider is unavailable for this instance"},400);if(!i(l.id))return sS({error:"Too many connections started; try later"},429);let h=e.authorizations.issue({provider:p.id,instanceId:l.id,returnUri:m,brainState:d.data.brainState}),f=p.authorizationUrl({redirectUri:n(p.id),state:h}).toString();return sS({authorizationUrl:f})},s=async(c)=>{let l=e.instances.authenticate(c);if(!l)return o_r();let d=c_r.safeParse(await s_r(c));if(!d.success)return sS({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,m=e.grants.take(d.data.grant,(h)=>h.provider===p&&h.instanceId===l.id);if(!m)return sS({error:"Invalid or expired grant"},400);return sS({provider:p,credential:m.credential})},a=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=e.authorizations.take(d.get("state")??"",(h)=>h.provider===c.id);if(!p)return sS({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return Tle(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return Tle(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 Tle(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${fe(h)}`),Tle(p,{error:"credential_exchange_failed"})}};return[{path:s_.authorizations,method:"POST",public:!0,handler:o},{path:s_.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:Oje(c.id),method:"GET",public:!0,handler:a(c)}))]}var Mao=600000,Oao=120000,u_r=1000,Nao=u.object({clientId:u.string().trim().min(1),clientSecret:u.string().trim().min(1)}),Lao=u.object({id:u.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/),secret:u.string().min(32).describe("Revocable instance secret"),returnUris:u.record(Lje,u.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),d_r=u.object({publicUrl:u.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:u.record(Lje,Nao).default({}).describe("Per provider, the shared app the broker holds"),instances:u.array(Lao).default([])});function jao(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 jje(e){let t=qt({id:"oauth-broker",config:d_r,setup:(r)=>{let{config:i}=r,n=jao(i,e);if(i.instances.length===0||n.length===0)return{routes:[]};return{routes:l_r({publicUrl:i.publicUrl,providers:n,instances:new Mje(i.instances),authorizations:new Vq({ttlMs:Mao,maxPending:u_r,now:e.now}),grants:new Vq({ttlMs:Oao,maxPending:u_r,now:e.now}),now:e.now??Date.now,logger:Ct(r).logger})}}});return Ao(t,({state:r})=>r.routes)}var zao=2592000000,t$=(e,t)=>Ht(`${e}
|
|
9529
9529
|
${t}`);function p_r(e,t){let r=(i)=>i!==void 0&&t()-i.usedAt<zao;return{get:async(i,n)=>{let o=await e.get(t$(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(t$(i,n),{hash:o,usedAt:t()})},conflictKept:async(i,n,o,s)=>{let a=await e.get(t$(i,n));if(!r(a))return;await e.set(t$(i,n),{hash:a.hash,conflictEdit:o,...s!==void 0&&{conflictId:s},usedAt:t()})},forget:async(i,n)=>{await e.delete(t$(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 m_r(e=Date.now){let t=new Map;return p_r({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 Uao="webdav.mount-base",qao=u.object({hash:u.string().min(1),conflictEdit:u.string().min(1).optional(),conflictId:u.string().min(1).optional(),usedAt:u.number()});function h_r(e,t=Date.now){let r=e.scoped({namespace:Uao,schema:qao});return p_r({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 $ao=new Set([".obsidian"]),f_r=33554432;function pB(e){let[t]=e;return t!==void 0&&$ao.has(t)}function x_r(){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 Gao="webdav.kept",Hao=u.object({path:u.string().min(1),bytes:u.string().optional(),modified:u.number()});function g_r(e){let t=e.scoped({namespace:Gao,schema:Hao}),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 Wao}from"crypto";var Zao=500;class zje{run=Wao().slice(0,8);keep;sequence=0;recent=[];waiting=new Set;closed=!1;constructor(e={}){this.keep=e.keep??Zao}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)}}import{createHash as Jao}from"crypto";import{posix as Qao}from"path";var r$="note",Vao=100,b_r=new Set(["image","document"]);function E_r(e){return b_r.has(e)}var Kao={".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 qje{reader;scope;containment;everyType;constructor(e,t,r={}){this.reader=e,this.scope=t,this.containment=hy(e),this.everyType=r.everyType??!1}async resolve(e){if(e.length===0)return{kind:"folder",segments:e};if(!e.every(Uje))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(y_r).map((i)=>({kind:"folder",segments:[...e,i]})),...r.sort((i,n)=>y_r(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(r$)?(await this.hierarchy(r$,[])).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:Vao,offset:r,source:!0}),s=o.entities.map((l)=>l.entity),a=r+s.length,c=s.length>0&&a<o.totalEntities?(await this.hierarchy(e,t,a)).entities:[];return{folders:o.folders.map((l)=>l.name),entities:[...s,...c]}}async filesIn(e,t){return(await Promise.all(t.map((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 entityAt(e){if(e.length===0||!e.every(Uje))return;let{entityType:t,id:r}=k6(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(Uje))return;let r=e.join("/"),{entityType:i,id:n}=k6(r,this.containment);if(!this.reader.getEntityTypes().includes(i))return;let o=fy(i,n,t,this.containment);return o.writable&&o.relativePath===r?{entityType:i,id:n}:void 0}async fileOf(e){let t=F8(e,this.reader.fileExtension(e.entityType));if(!fy(e.entityType,e.id,t,this.containment).writable)return;let i={kind:"file",segments:HI(e.id,e.entityType,t,this.containment).split("/"),contentType:Kao[t]??"application/octet-stream",etag:`"${e.contentHash}"`,modified:new Date(e.updated)};if(!b_r.has(e.entityType)||t===".md"){let a=t===".yaml"?FT(e.content):e.content;return{...i,size:Buffer.byteLength(a),open:async()=>a}}if(e.content==="")return;let n=Jd.safeParse(e.content);if(n.success){let a=await this.reader.statAsset(n.data);if(!a)return;return{...i,size:a.sizeBytes,open:async()=>Yao(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!==r$&&!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 y_r(e,t){return e<t?-1:e>t?1:0}function Uje(e){return e.length>0&&e!=="."&&e!==".."&&!/[/\\\0]/.test(e)}function Yao(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 $je="image",v_r="note",Gje="webdav";async function Hje(e,t){let r=Qao.extname(t.segments[t.segments.length-1]??"").toLowerCase();if(Lu.includes(r))return ico(e,t,r);let i=r===".yaml"?Xao(e,t):t;if(i===void 0)return await Ple(e,t)?aS("No entry can be stored at this path"):Rle();if(r!==".md"&&r!==".yaml")return await Ple(e,i)?aS("The drive cannot take documents"):Rle();if(i.bytes.byteLength>e.writes.maxFileBytes)return D_r();let n=await e.tree.entityAt(i.segments),o=n?.entity.entityType??e.tree.placementAt(i.segments,r)?.entityType;if(o!==void 0&&E_r(o))return aS(o===$je?"An image is stored as its image file":"The drive cannot take documents");return n?eco(e,i,n):rco(e,i,r)}function Xao(e,t){let r=e.tree.placementAt(t.segments,".yaml")?.entityType;if(r===void 0||e.tree.textExtension(r)!==".yaml")return;let i=__r(t.bytes);if(i===void 0)return t;return{...t,bytes:new Uint8Array(Buffer.from(MT(i),"utf8"))}}async function eco(e,t,{entity:r,file:i}){let{writes:n}=e,o=t.onlyIfAbsent===!0||!Wje(t.ifMatch,i.etag);if(o&&!t.keepAsConflict)return t.onlyIfAbsent?Fle():cS();let s=B_r(n,t.bytes,r.entityType);if("status"in s)return s;if(tco(n,s.parsed,r))return await e.mount.held(r.contentHash),{status:204,etag:await C_r(e,t,s.text)};let{visibility:a,...c}=s.parsed.metadata??r.metadata,l={...r,...s.parsed,id:r.id,entityType:r.entityType,content:s.text,metadata:c,visibility:s.parsed.visibility??r.visibility},d=FA(r.entityType,r.metadata.status,l.metadata.status,e.reader)!=="non-publish",p=await i$(e,t.grant,"update",l,[d?"publish":"update"]);if(p)return p;if(o)return A_r(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 f=await e.mount.base();if(f!==void 0&&f.hash!==r.contentHash)return A_r(e,t,{existing:r,base:f,text:s.text,declared:s.parsed.visibility})}let m=await Mle(()=>n.updateEntity({entity:l,options:{expectedContentHash:r.contentHash,eventContext:n$(t.grant)}}));if(!m.ok)return I_r(m.error);if(m.value.skipReason==="content-conflict")return cS();if(!m.value.skipped)await mB(n,t.grant,"update","allowed",l);let h=await e.tree.entityAt(t.segments);if(h)await e.mount.held(h.entity.contentHash);return{status:204,etag:h?.entity.content===s.text?h.file.etag:void 0}}function tco(e,t,r){let i=Vje(()=>e.deserializeEntity(r.content,r.entityType));return i.ok&&(t.visibility??r.visibility)===r.visibility&&Bun.deepEquals(t,i.value)}async function A_r(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 cS();return await e.mount.conflictKept(a,c),{status:204,conflictId:c}}async function rco(e,t,r){let{writes:i,tree:n}=e,{segments:o}=t;if(!await Ple(e,t))return Rle();let s=n.placementAt(o,r);if(!s)return aS("No entry can be stored at this path");let a=B_r(i,t.bytes,s.entityType);if("status"in a)return a;let{visibility:c,...l}=a.parsed.metadata??{},d=a.parsed.visibility??"public",p={...a.parsed,id:s.id,entityType:s.entityType,content:a.text,metadata:l,visibility:d},m=FA(s.entityType,void 0,l.status,e.reader)!=="non-publish",h=await i$(e,t.grant,"create",p,m?["create","publish"]:["create"]);if(h)return h;let f=await Mle(()=>i.createEntity({entity:p,options:{conditionalWrite:{expectedRevision:null},eventContext:n$(t.grant)}}));if(!f.ok)return Zje(f.error);return await mB(i,t.grant,"create","allowed",p),{status:201,etag:await C_r(e,t,a.text)}}async function ico(e,t,r){let{writes:i,tree:n}=e,{segments:o,bytes:s,grant:a}=t,c=await n.entityAt(o);if(!c&&!await Ple(e,t))return Rle();let l=c?{entityType:c.entity.entityType,id:c.entity.id}:n.placementAt(o,r);if(l?.entityType!==$je)return aS("An image can only be stored in the image folder");if(s.byteLength>i.maxAssetBytes)return D_r();if(c&&t.onlyIfAbsent)return Fle();if(c&&!Wje(t.ifMatch,c.file.etag))return cS();let d=await YI(w_r(s));if(!d)return{status:422,message:"The file is not a PNG, JPEG, GIF or WebP image"};let p=GI(d.format);if(p!==r)return{status:422,message:`These bytes are stored as ${p}; save the image under that extension`};let m=c?.entity.metadata.status;if(typeof m==="string"&&JI(Jao("sha256").update(s).digest("hex"),m))return{status:422,message:"These bytes are the old pending placeholder, not this image's bytes"};let h=c?"update":"create",f={id:l.id,entityType:$je,visibility:c?.entity.visibility??"public"},g=await i$(e,a,h,f,[h]);if(g)return g;if(c&&t.ifMatch===null){let M=await e.mount.base();if(M!==void 0&&M.hash!==c.entity.contentHash)return{status:409,message:"The image changed since this drive last read it"}}let y=await i.stageAsset(s,{maxBytes:i.maxAssetBytes,expectedSize:s.byteLength}),b={content:y.ref,metadata:{...c?.entity.metadata,...d,sizeBytes:y.sizeBytes}},A={eventContext:n$(a)},w=await Mle(async()=>{if(c)return(await i.updateEntity({entity:{...c.entity,...b},stagedAsset:y,options:{...A,expectedContentHash:c.entity.contentHash}})).skipReason==="content-conflict"?cS():void 0;await i.createEntity({entity:{...f,...b},stagedAsset:y,options:{...A,conditionalWrite:{expectedRevision:null}}});return}),C=w.ok?w.value:Zje(w.error);if(C)return await i.discardStagedAsset(y),C;await mB(i,a,h,"allowed",f);let F=await n.entityAt(o);if(F)await e.mount.held(F.entity.contentHash);return{status:c?204:201,etag:F?.file.etag}}async function S_r(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!==v_r||s?.entityType!==v_r)return aS("The drive renames notes only, to another note's name");if(await i.entityAt(t.to))return Fle();let a=await i$(e,t.grant,"rename",o,["update"]);if(a)return a;let c=await Mle(()=>r.renameEntity({entityType:o.entityType,id:o.id,newId:s.id,options:{expectedContentHash:o.contentHash,eventContext:n$(t.grant)}}));if(!c.ok)return Zje(c.error);if(!c.value.renamed)return cS();return await mB(r,t.grant,"rename","allowed",o),{status:201}}async function k_r(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(!Wje(t.ifMatch,n.etag))return cS();let o=await i$(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:n$(t.grant)}}))return cS();return await e.mount.forget(),await mB(e.writes,t.grant,"delete","allowed",i),{status:204}}function B_r(e,t,r){let i=__r(t);if(i===void 0)return{status:422,message:"The file is not UTF-8 text"};let n=Vje(()=>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 i$(e,t,r,i,n){let o=t.principal.permissionLevel,s=Vje(()=>n.forEach((a)=>e.writes.permissions.assertEntityActionAllowed(i.entityType,a,{userPermissionLevel:o})));if(!s.ok)return await mB(e.writes,t,r,"denied",i,"entity-action-policy"),aS(fe(s.error,"Not allowed"));if(r!=="delete"&&!rm(o,i.visibility))return await mB(e.writes,t,r,"denied",i,"visibility-policy"),aS(`Cannot set visibility to "${i.visibility}" at ${o} permission`);return}function mB(e,t,r,i,n,o){return e.recordAudit({actorUserId:t.principal.userId,action:`${Gje}.entity.${r}.${i}`,targetType:"entity",targetId:n.id,metadata:{entityType:n.entityType,interfaceType:Gje,outcome:i,...o?{reason:o}:{}}})}async function C_r(e,t,r){let i=await e.tree.entityAt(t.segments);return i?.entity.content===r?i.file.etag:void 0}function n$(e){return{actor:{kind:"user",userId:e.principal.userId},interfaceType:Gje}}function Wje(e,t){return e===null||e==="*"||e===t}function Ple(e,t){return e.folderExists(t.segments.slice(0,-1))}function Rle(){return{status:409,message:"The folder does not exist"}}function D_r(){return{status:413,message:"The file is larger than the drive accepts"}}function Fle(){return{status:412,message:"An entry already exists at this path"}}function Zje(e){return e instanceof Error&&e.name==="EntityWriteConflictError"?Fle():I_r(e)}function aS(e){return{status:403,message:e}}function cS(){return{status:412,message:"The file changed since it was opened"}}function I_r(e){if(qS(e))return{status:422,message:fe(e,"The file cannot be saved")};throw e}function __r(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}}function Vje(e){try{return{ok:!0,value:e()}}catch(t){return{ok:!1,error:t}}}async function Mle(e){try{return{ok:!0,value:await e()}}catch(t){return{ok:!1,error:t}}}import{posix as nco}from"path";var oco=new Set([".md",".yaml",...Lu,...R8]),sco=600000,aco=16777216,T_r=(e,t,r)=>!pB(e.split("/"))&&r-t>=sco;function P_r(e){return e.startsWith(".")||!oco.has(nco.extname(e).toLowerCase())}class Kje{files=new Map;folders=new Map;now;kept;opened=new Map;pending=Promise.resolve();constructor(e=Date.now,t=x_r()){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=pB(t);if([...i.values()].filter((l)=>pB(l.segments)===s).reduce((l,d)=>l+d.bytes.byteLength,0)-(o?.bytes.byteLength??0)+r.byteLength>(s?f_r:aco))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((l,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&&pB(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&&pB(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)}),pB(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(T_r(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(T_r(i,n.touched,r))t.delete(i)}),t.size===0)this.files.delete(e);return t}}class Yje{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(R_r(e,t),r+30000)}take(e,t){let r=R_r(e,t),i=this.expected.get(r);if(i===void 0)return!1;return this.expected.delete(r),i>this.now()}}function R_r(e,t){return`${e}
|
|
9530
9530
|
${t.join("/")}`}import{createHash as cco}from"crypto";var lco=600000,uco=16777216;class Jje{held=new Map;now;capBytes;constructor(e=Date.now,t=uco){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-${cco("sha256").update(r.bytes).digest("hex")}"`,until:o+lco});let s={bytes:0,full:!1,dropped:[]},{dropped:a}=[...i].reverse().reduce((c,[l,d],p)=>{let m=c.bytes+d.bytes.byteLength;return p>0&&(c.full||m>this.capBytes)?{...c,full:!0,dropped:[...c.dropped,l]}:{...c,bytes:m}},s);a.forEach((c)=>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 dco}from"crypto";var F_r=600;class Qje{locks=new Map;now;constructor(e=Date.now){this.now=e}acquire(e,t,r){if(this.live(e))return;let i={token:`opaquelocktoken:${dco()}`,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||!M_r(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||M_r(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 M_r(e,t,r){return e.userId===t&&r.includes(`<${e.token}>`)}function O_r(e){let t=/Second-(\d+)/i.exec(e??"")?.[1];return Math.min(t?Number(t):F_r,F_r)}function pco(e){let t=Cie(e);if(t==="enum"){let r=Iie(e);return r?{type:"enum",enumValues:r}:{type:"enum"}}if(t==="literal")return{type:"string",defaultValue:_ie(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 mco(e){let t=[];for(let[r,i]of Object.entries(e.shape)){if(oz(i)?.studioWidget==="hidden")continue;let{inner:n,required:o,defaultValue:s}=Die(i),a=pco(n),c={name:r,type:a.type,required:o},l=s!==void 0?s:a.defaultValue;if(l!==void 0)c.defaultValue=l;if(a.enumValues)c.enumValues=a.enumValues;t.push(c)}return t}function Xje(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:mco(r)}]})}var hco={"&":"&","<":"<",">":">"};function hB(e){return e.replace(/[&<>]/g,(t)=>hco[t]??t)}var N_r="<D:lockscope><D:exclusive/></D:lockscope><D:locktype><D:write/></D:locktype>";function fco(e){return[`<D:supportedlock><D:lockentry>${N_r}</D:lockentry></D:supportedlock>`,`<D:displayname>${hB(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>${hB(e.contentType)}</D:getcontenttype>`:"",e.etag?`<D:getetag>${hB(e.etag)}</D:getetag>`:"",e.lastModified?`<D:getlastmodified>${e.lastModified.toUTCString()}</D:getlastmodified>`:""].join("")}function L_r(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:">${e.map((r)=>`<D:response><D:href>${hB(r.href)}</D:href><D:propstat><D:prop>${fco(r)}</D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>`).join("")}</D:multistatus>`}function j_r(e){return`<?xml version="1.0" encoding="utf-8"?><D:error xmlns:D="DAV:"><D:${e}/></D:error>`}function z_r(e){return`<?xml version="1.0" encoding="utf-8"?><D:prop xmlns:D="DAV:"><D:lockdiscovery><D:activelock>${N_r}<D:depth>0</D:depth><D:timeout>Second-${e.seconds}</D:timeout><D:locktoken><D:href>${hB(e.token)}</D:href></D:locktoken><D:lockroot><D:href>${hB(e.href)}</D:href></D:lockroot></D:activelock></D:lockdiscovery></D:prop>`}function U_r(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"><D:response><D:href>${hB(e)}</D:href><D:status>HTTP/1.1 200 OK</D:status></D:response></D:multistatus>`}var xco=[".brain","changes"],gco=50,q_r=25,yco=[".brain","vault-shapes.json"],bco=["OPTIONS","GET","HEAD","PROPFIND"],V_r=["PUT","DELETE","MOVE","COPY","PROPPATCH","MKCOL","LOCK","UNLOCK"],K_r=[...bco,...V_r],Eco=K_r.join(", "),Nle='application/xml; charset="utf-8"',vco={"X-Content-Type-Options":"nosniff","Content-Security-Policy":"sandbox","Cache-Control":"no-store"};function Y_r(e){let t={options:e,mounts:e.mounts??m_r(e.now),scratch:new Kje(e.now,e.kept),locks:new Qje(e.now),cleanups:new Yje(e.now),holds:new Jje(e.now)},r={GET:(i,n)=>H_r(i,n,!0),HEAD:(i,n)=>H_r(i,n,!1),PROPFIND:wco,PUT:Sco,DELETE:Dco,MOVE:Tco,COPY:async()=>a$("The drive does not copy files"),PROPPATCH:Ico,MKCOL:_co,LOCK:Fco,UNLOCK:Mco};return K_r.map((i)=>({path:e.basePath,match:"prefix",method:i,public:!0,handler:async(n)=>{if(i==="OPTIONS")return o$(jco());let o=await e.resolveAppPassword(n);if(!o)return o$(zco(e.realm));if($_r(i)&&o.access!=="write")return o$(a$("This app password is read-only"));let s=n.headers.get("x-brain-sync")?.trim()==="1",a={request:n,grant:o,tree:new qje(e.reader,_i(o.principal.permissionLevel),{everyType:s}),path:iTr(e.basePath,new URL(n.url).pathname),sync:s};if($_r(i)&&i!=="LOCK"&&i!=="UNLOCK"&&a.path&&!J_r(t,a,a.path.segments))return o$(sze());await t.scratch.open(o.principal.userId);let c=await r[i](t,a);return await t.scratch.settle(),o$(c)}}))}function J_r(e,t,r){return e.locks.permits(r,t.grant.principal.userId,t.request.headers.get("if"))}function $_r(e){return V_r.some((t)=>t===e)}function Lle(e,t){let{path:r}=t;return r&&!r.asFolder&&a_(r.segments)?e.scratch.get(t.grant.principal.userId,r.segments):void 0}function a_(e){let t=e[e.length-1];return t!==void 0&&(Q_r(e)||P_r(t))}function Q_r(e){return e.some((t)=>t.startsWith("."))}async function jle(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 nze(e,t,r){return r.length===0||e.scratch.hasFolder(t.grant.principal.userId,r)||(await t.tree.resolve(r))?.kind==="folder"}async function oze(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 X_r(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 oze(e,t,n):void 0)?.etag===i?null:i}async function Aco(e,t){let r=new URL(t.request.url).searchParams,i=Number(r.get("wait")??q_r),n=Number.isFinite(i)?Math.min(Math.max(i,0),gco):q_r,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 G_r(e,t,r){let i=tze(r,e.options.basePath),n=await oze(e,t,r);return n?{...i,contentLength:n.bytes.byteLength,etag:n.etag,lastModified:n.savedAt}:i}function eTr(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 zle(e,t){return{tree:t.tree,reader:e.options.reader,writes:e.options.writes,mount:eTr(e,t),recordConflict:async(r)=>e.options.recordConflict?.(r),folderExists:(r)=>nze(e,t,r)}}async function H_r(e,t,r){let{shapes:i,changes:n}=e.options;if(t.sync&&n!==void 0&&t.path?.segments.join("/")===xco.join("/"))return Aco(n,t);if(t.sync&&i!==void 0&&t.path?.segments.join("/")===yco.join("/")){let c=JSON.stringify({shapes:Xje(i).filter((l)=>l.entityType===r$||t.tree.isFolderType(l.entityType))});return new Response(r?c:null,{status:200,headers:{"Content-Type":"application/json; charset=utf-8",ETag:`"${Ht(c)}"`}})}let o=Lle(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:rTr(o),"Last-Modified":o.modified.toUTCString()}});let s=await jle(e,t);if(!s)return ah();if(s.kind==="folder")return rze();let a=await oze(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 eTr(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 wco(e,t){let r=t.request.headers.get("depth");if(r!=="0"&&r!=="1")return new Response(j_r("propfind-finite-depth"),{status:403,headers:{"Content-Type":Nle}});let{basePath:i}=e.options,n=Lle(e,t);if(n)return eze([Z_r(n,i)]);let o=await jle(e,t);if(!o)return ah();if(o.kind==="file"||r==="0")return eze([await G_r(e,t,o)]);let s=t.grant.principal.userId,a=await t.tree.children(o.segments),c=new Set(a.filter((l)=>l.kind==="folder").map((l)=>l.segments[l.segments.length-1]));return eze([tze(o,i),...await Promise.all(a.map((l)=>G_r(e,t,l))),...e.scratch.listFolders(s,o.segments).filter((l)=>!c.has(l)).map((l)=>tze({kind:"folder",segments:[...o.segments,l]},i)),...e.scratch.list(s,o.segments).map((l)=>Z_r(l,i))])}async function Sco(e,t){let{path:r}=t;if(!r)return ah();if(r.asFolder||r.segments.length===0)return rze();let{maxFileBytes:i,maxAssetBytes:n}=e.options.writes,o=await Oco(t.request,Math.max(i,n)),s=t.grant.principal.userId,a=a_(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 nze(e,t,r.segments))return rze();return tTr(e.scratch.put(s,r.segments,o))}let c=await Hje(zle(e,t),{segments:r.segments,bytes:o,ifMatch:await X_r(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 kco(e,t,r.segments,o,c);if("message"in c||c.etag===void 0)e.cleanups.expect(s,r.segments);return await Cco(e,t,r.segments,o,c),c$(e,t,r.segments,c)}async function kco(e,t,r,i,n){if("message"in n)return c$(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 Bco(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 Bco(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 Cco(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 Dco(e,t){let{path:r}=t;if(!r)return ah();let i=t.grant.principal.userId;if(e.scratch.removeFolder(i,r.segments))return ize();if(!r.asFolder&&a_(r.segments)){if(e.scratch.delete(i,r.segments))return ize()}if(r.segments.length===0||(await t.tree.resolve(r.segments))?.kind==="folder")return a$("The drive does not delete folders");if(r.asFolder)return ah();if(t.request.headers.get("if-match")===null&&e.cleanups.take(i,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 n=await k_r(zle(e,t),{segments:r.segments,ifMatch:await X_r(e,t,r.segments),grant:t.grant});if(!("message"in n))e.holds.release(t.grant.appPasswordId,r.segments);return c$(e,t,r.segments,n)}async function Ico(e,t){let r=Lle(e,t)??await jle(e,t);if(!r||!t.path)return ah();let i="kind"in r&&r.kind==="folder",n=s$(t.path.segments);return new Response(U_r(`${e.options.basePath}/${n}${i&&n?"/":""}`),{status:207,headers:{"Content-Type":Nle}})}async function _co(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 nze(e,t,i.slice(0,-1)))return new Response("The parent folder does not exist",{status:409});let[o]=i;if(!Q_r(i)&&(o===void 0||!t.tree.isFolderType(o)))return a$("Only an entity type can be a folder here");return e.scratch.makeFolder(n,i),new Response(null,{status:201})}async function Tco(e,t){let r=t.request.headers.get("destination");if(!r)return new Response("Destination required",{status:400});let i=Nco(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(!J_r(e,t,i.segments))return sze();let o=t.request.headers.get("overwrite")?.toUpperCase()!=="F";if(n.asFolder)return a$("The drive does not rename files");if(!a_(n.segments))return a_(i.segments)?Rco(e,t,n.segments,i.segments,o):Pco(e,t,n.segments,i.segments);let s=t.grant.principal.userId,a=e.scratch.get(s,n.segments);if(!a)return ah();if(a_(i.segments)){if(!o&&e.scratch.get(s,i.segments))return Ole("The destination exists");let l=e.scratch.rename(s,n.segments,i.segments);return l==="missing"?ah():new Response(null,{status:l==="created"?201:204})}if(!o&&await t.tree.entityAt(i.segments))return Ole("The destination exists");let c=await Hje(zle(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 c$(e,t,i.segments,c)}async function Pco(e,t,r,i){let n=await S_r(zle(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 c$(e,t,i,n)}async function Rco(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 Ole("The destination exists");let a=new Uint8Array(await new Response(await o.file.open()).arrayBuffer());return tTr(e.scratch.put(s,i,a))}async function Fco(e,t){let{path:r}=t;if(!r||r.segments.length===0)return ah();let i=t.grant.principal.userId,n=O_r(t.request.headers.get("timeout")),o=t.request.headers.get("if"),s=(await t.request.arrayBuffer()).byteLength>0;if(o&&!s){let l=e.locks.refresh(r.segments,i,o,n);return l?W_r(e,r.segments,l,200):Ole("No such lock to refresh")}let a=e.locks.acquire(r.segments,i,n);if(!a)return sze();let c=Lle(e,t)!==void 0||await jle(e,t)!==void 0;return W_r(e,r.segments,a,c?200:201)}function W_r(e,t,r,i){return new Response(z_r({...r,href:`${e.options.basePath}/${s$(t)}`}),{status:i,headers:{"Content-Type":Nle,"Lock-Token":`<${r.token}>`}})}async function Mco(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)?ize():new Response("No such lock",{status:409})}function c$(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 tTr(e){return e==="full"?new Response("Too many temporary files",{status:507}):new Response(null,{status:e==="created"?201:204})}async function Oco(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 tze(e,t){let r=e.segments[e.segments.length-1]??"";if(e.kind==="folder"){let i=s$(e.segments);return{href:i?`${t}/${i}/`:`${t}/`,displayName:r,collection:!0}}return{href:`${t}/${s$(e.segments)}`,displayName:r,collection:!1,contentLength:e.size,contentType:e.contentType,etag:e.etag,lastModified:e.modified}}function Z_r(e,t){return{href:`${t}/${s$(e.segments)}`,displayName:e.segments[e.segments.length-1]??"",collection:!1,contentLength:e.bytes.byteLength,contentType:"application/octet-stream",etag:rTr(e),lastModified:e.modified}}function rTr(e){return`"scratch-${e.modified.getTime()}-${e.bytes.byteLength}"`}function s$(e){return e.map(encodeURIComponent).join("/")}function iTr(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(Lco);return o.every((s)=>s!==void 0&&s!==""&&!/[/\\\0]/.test(s))?{segments:o.filter((s)=>s!==void 0),asFolder:i}:void 0}function Nco(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=iTr(e,n.pathname);return o&&!o.asFolder&&o.segments.length>0?o:void 0}function Lco(e){try{return decodeURIComponent(e)}catch{return}}function eze(e){return new Response(L_r(e),{status:207,headers:{"Content-Type":Nle}})}function jco(){return new Response(null,{status:200,headers:{DAV:"1, 2",Allow:Eco,"MS-Author-Via":"DAV"}})}function zco(e){return new Response("Authentication required",{status:401,headers:{"WWW-Authenticate":`Basic realm="${e.replace(/["\\]/g,"")}", charset="UTF-8"`}})}function rze(){return new Response("A folder has no content",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}})}function ize(){return new Response(null,{status:204})}function ah(){return new Response("Not found",{status:404})}function a$(e){return new Response(e,{status:403})}function sze(){return new Response("The file is locked",{status:423})}function Ole(e){return new Response(e,{status:412})}function o$(e){let t=new Headers(e.headers);return Object.entries(vco).forEach(([r,i])=>t.set(r,i)),new Response(e.body,{status:e.status,headers:t})}var aze="/dav",Uco=5242880,nTr=u.strictObject({maxFileBytes:u.number().int().positive().describe("Maximum bytes of a file a client may save").default(Uco)}),qco=qt({id:"webdav",config:nTr,setup:(e)=>{let t=Ct(e);if(t.executionOnly)return{routes:[]};t.registered(()=>{if(t.entityReads.getEntityTypes().includes(os))return;throw Error(`webdav needs the "${os}" entity type to keep saves that lose to a newer version. Add "conflict" to this brain, which the core bundle includes.`)});let r=new zje;for(let n of[ca,ds,Qd,cb])t.listen(n,({payload:o})=>r.record(o.entityType),{mode:"observe"});t.listen(so.shuttingDown,()=>r.close(),{mode:"observe"});let i=h_r(t.classRuntimeState);return t.ready(()=>i.sweep()),t.interaction({id:Uie,label:"Drive",description:"Mount the brain as a network drive over WebDAV.",href:`${aze}/`,kind:"protocol",priority:40,visibility:"trusted"}),{routes:Y_r({basePath:aze,realm:t.identity.get().name,reader:t.entityReads,shapes:t.entityShapes,changes:r,writes:{maxFileBytes:e.config.maxFileBytes,maxAssetBytes:UI,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:g_r(t.classRuntimeState),recordConflict:async(n)=>{let o=await t.messaging.request(E8,n);return o.status==="answered"?o.data.conflictId:void 0},conflictPending:async(n)=>await t.entityReads.getEntityRaw({entityType:os,id:n,visibilityScope:st("ask only whether a conflict is still waiting to be resolved")})!==null})}}}),cze=Ao(qco,({state:e})=>e.routes);var oTr=cze;var $co=u.object({errcode:u.string()}),Gco=u.object({session:u.string()});async function lze(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 sTr(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),l=Gco.safeParse(await c.json().catch(()=>{return}));if(!l.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:l.data.session}});if(!d.ok)throw Error(`Matrix bot registration failed: ${await sTr(d)??d.status}`);return"registered"}async function sTr(e){let t=$co.safeParse(await e.json().catch(()=>{return}));return t.success?t.data.errcode:void 0}var uze="matrix-homeserver";function Ule(e){return`${e.replace(/\/+$/,"")}/_matrix/client/unstable/login/sso/callback/matrix-homeserver`}function Ny(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`}function dze(e){let t=e.publicBaseUrl.replace(/\/+$/,"");return`[global]
|
|
9531
9531
|
server_name = ${Ny(e.serverName)}
|
|
@@ -11091,5 +11091,5 @@ ${Ade}</style><link rel="stylesheet" href="${ago}"></head><body class="guest-pag
|
|
|
11091
11091
|
`);return{kind:"text",filename:"inbox-source.txt",mediaType:"text/plain",content:l,sizeBytes:new TextEncoder().encode(l).byteLength}}catch{return ijr()}}async handleContextSessionRequest(e){let t=ma(e);if(t)return t;return tLr(e,{conversations:this.runtime.conversations,resolveAccess:(r)=>this.resolveConversationAccess(r),interfaceType:Hp,authorizeSource:async({sourceId:r,itemId:i,permissionLevel:n,signal:o})=>{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 dLr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Hp})}async handleDeleteSessionRequest(e){return pLr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Hp})}async handleRenameSessionRequest(e){return mLr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Hp})}async handleArchiveSessionRequest(e){return hLr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Hp})}async handleDocumentAttachmentRequest(e){return dNr(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleImageAttachmentRequest(e){return pNr(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleJobStatusRequest(e){return nLr(e,{resolveAuthSession:this.resolveAuthSession,createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),jobs:this.runtime.jobs})}async handleMessagesRequest(e){return gLr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Hp})}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,Hp,t)}ensureWebChatConversation(e,t){return this.ensureBrowserConversation(e,Hp,"Web Chat",t)}async requireExistingBrowserConversation(e,t,r){let i=await this.runtime.conversations.get(e);return $y(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 $y(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 $y(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 bde(e,t,r,(i)=>this.createId(i))}createId(e){return`${e}-${crypto.randomUUID()}`}}function ijr(){return new Response("Inbox context is unavailable",{status:409})}function $$e(e={}){let t=xh({id:Hp,config:I$e,setup:async(n)=>{let o=us(n),s=new sjr(n.config,e,o,n.runtimeState(vse));return await s.register(),o.ready(()=>s.onReady()),s}}),r=Ao(t,({state:n})=>n.webRoutes()),i=Rx(r,({state:n})=>{let o=n.maintenanceDaemon();return{id:"guest-maintenance",start:()=>o.start(),stop:()=>o.stop(),healthCheck:()=>o.healthCheck()}});return wie(i,({state:n})=>n.transport())}var Ggo=$$e(),ajr=Ggo;var G$e='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 cjr={critical:0,high:1,medium:2,low:3};function ljr(e){return[...e].sort((t,r)=>{let i=r.metadata.requested-t.metadata.requested;if(i!==0)return i;return cjr[t.metadata.priority]-cjr[r.metadata.priority]})}var eG=u.enum(["new","planned","in-progress","done","declined"]),tG=u.enum(["low","medium","high","critical"]),Fde=u.object({title:u.string(),status:eG,priority:tG.default("medium"),requested:u.number().int().default(1).meta({studioWidget:"provenance"}),declinedReason:u.string().optional()}),H$e=u.object({title:u.string(),status:eG,priority:tG,requested:u.number().int().meta({studioWidget:"provenance"}),slug:u.string().optional().meta({studioWidget:"hidden"}),declinedReason:u.string().optional()});var Hgo=u.object({items:u.array(u.object({id:u.string(),name:u.string(),count:u.number().int().nonnegative(),priority:tG,status:eG}))});function Wgo(e){if(e==="critical")return"error";if(e==="high")return"warn";return"neutral"}var W$e=Qn({id:"top-wishes",title:"Top Wishes",group:"knowledge",placement:"secondary",priority:30,permission:"public",data:Hgo,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:Wgo(t.priority)},{label:t.status,tone:t.status==="done"?"good":"neutral"}]}))}]})});function Zgo(e){return W$e.bind(e,async({entities:t,signal:r})=>(r.throwIfAborted(),{items:ljr(await t.list(Hy,{limit:10})).map((n)=>({id:n.id,name:n.metadata.title,count:n.metadata.requested,priority:n.metadata.priority,status:n.metadata.status}))}))}var Hy=Wi(yt({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:H$e,markdown:{decode:({content:e,frontmatter:t})=>{let r=Fde.parse(t);return{content:e,metadata:{title:r.title,status:r.status,priority:r.priority,requested:r.requested,slug:zt(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:G$e,dashboardWidgets:(e)=>[Zgo(e)]}),Fde);var ujr=0.3,Vgo="Do these two wishes ask for the same thing?",Kgo=u.object({same:u.boolean().describe("True only when delivering one would fulfil the other.")});async function Ygo(e,t,r){let{same:i}=await e.generateObject([Vgo,"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(`
|
|
11092
11092
|
`),Kgo);return i}function Mde(e,t,r){return{nearest:(i,n)=>e.nearest(Hy,i,{maxDistance:n}),getEntity:(i)=>t.get(Hy,i),maxDistance:r,ai:e}}async function Ode(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 Ygo(e.ai,t.content,Jgo(a))?a:i(s+1)},n=await i(0);if(n)return n;let o=await e.getEntity(zt(t.title));return o?.visibility==="public"?o:null}function Jgo(e){let{title:t,status:r,priority:i,requested:n,declinedReason:o}=e.metadata;return rG({title:t,status:r,priority:i,requested:n,declinedReason:o},e.content)}function rG(e,t){let r=Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0&&i!==null));return Object.keys(r).length>0?mi(r,t):t}var djr=u.object({title:u.string(),description:u.string()}),Qgo=u.object({stored:djr,incoming:djr}),Z$e="eval-stored-wish";function pjr(e){return rG({title:e.title,status:"new",priority:"medium",requested:1},e.description)}function mjr(e){return{sameWish:async(t,r)=>{let{stored:i,incoming:n}=Qgo.parse(t),{fixtures:o}=r;await o.reset(),await o.seed({id:Z$e,entityType:"wish",content:pjr(i),metadata:{title:i.title,status:"new",priority:"medium",requested:1,slug:zt(i.title)}}),await o.settleEmbeddings();let s=$t(r),a=pjr(n),c=(await s.nearest(Hy,a,{maxDistance:2})).find(({entity:d})=>d.id===Z$e)?.distance;if(c===void 0)throw Error("The stored wish was not embedded");let l=await Ode(Mde(s,r.entities,e),{title:n.title,content:a});return{distance:c,shortlisted:c<=e,sameWish:l?.id===Z$e}}}}async function Xgo(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 Ode(Mde($t(e),e.entities,t),{title:i,content:rG(o,n)});if(s)return{update:{id:s.id,content:s.content.trim(),metadata:{...s.metadata,requested:s.metadata.requested+1}}};let a=zt(i);return{create:{id:a,content:n,metadata:{...o,slug:a}}}}function hjr(e){let t={resolve:(r)=>Xgo(r,e)};return{fromPrompt:t,fromContent:t,fromUpload:t}}var V$e=u.object({sameWishDistance:u.number().min(0).max(1).default(ujr)});var eyo=Pi({id:"wishlist",config:V$e,entities:[Hy],configure:({config:e})=>({entities:[{entity:Hy,create:hjr(e.sameWishDistance),evals:mjr(e.sameWishDistance)}]})}),fjr=eyo;var xjr="gpt-6-luna";var gS={create:"trusted",update:"trusted",delete:"admin",extract:"admin",publish:"admin"},gjr=[{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}}],yjr=["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.'],bjr=[{member:"topics",value:{extractableStatuses:["published","draft"]}},{member:"conversation-memory",value:{memoryVisibility:"shared"}},{member:"action-board",value:{cardVisibility:"shared"}}],Ejr=["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 yS="capability-bundles-v1",K$e="core",Y$e="media",J$e="automation",iG="web",Q$e="chat",X$e="site",eGe="publishing",tGe="federation",rGe="team",tyo="matrix",Nde=Qp({id:K$e,members:["profile","prompt","conflict","style-guide","directory-sync","note","refined-note","link","topics","unified-inbox","mcp","a2a","agents"],evalDisable:["mcp"]}),Lde=Qp({id:Y$e,members:["document","image"]}),jde=Qp({id:J$e,members:["playbooks","onboarding"]}),zde=Qp({id:iG,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"]}),Ude=Qp({id:Q$e,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"]}),qde=Qp({id:X$e,members:["site-info","site-content","site-builder","form","analytics"],config:[{member:"dashboard",value:{routePath:"/dashboard"},overrides:iG}]}),$de=Qp({id:eGe,members:["blog","series","portfolio","decks","content-pipeline","social-media","newsletter","stock-photo"],config:gjr,agentInstructions:yjr}),Gde=Qp({id:tGe,members:["atproto","references"],evalDisable:["atproto"]}),Hde=Qp({id:rGe,members:[],config:bjr,permissions:[{member:"note",config:{entityActions:{note:gS}}},{member:"refined-note",config:{entityActions:{"refined-note":gS}}},{member:"link",config:{entityActions:{link:gS}}},{member:"image",config:{entityActions:{image:gS}}},{member:"docs",config:{entityActions:{doc:gS}}},{member:"conversation-memory",config:{entityActions:{decision:gS,"action-item":gS}}},{member:"mcp",config:{rules:[{pattern:"mcp:http",level:"admin"}]},overrides:iG}],agentInstructions:Ejr}),ryo=Qp({id:tyo,members:["matrix-server"],http:!0,permissions:[{member:"chat",config:{rules:[{pattern:"matrix:*",level:"public"}]}}]}),vjr=[Nde,Lde,jde,zde,Ude,qde,$de,Gde,ryo,Hde];function oG(e,t,r){let i={name:e,version:bS.version};return(n)=>Xp(t,n,i,r)}function iyo(e){let{entity:t,provider:r}=d7r(e),i={name:"@brains/newsletter",version:bS.version};return[...Xp(t.definition,t.config,i,{pluginId:"newsletter"}),...r?Xp(r.definition,r.config,i,{pluginId:r.kind}):[]]}function Wr(e,t,r,i={},n=void 0){return[e,oG(t,r,i),n]}function nG(e,t,r,i,n={}){return[e,oG(t,r,n),i]}var Ajr=ype({name:"brain",version:bS.version,bundleContract:yS,model:xjr,reasoningEffort:"low",capabilities:[Wr("prompt","@brains/prompt",tRr,{pluginId:"prompt"}),Wr("conflict","@brains/conflict",XPr,{pluginId:"conflicts"}),Wr("profile","@brains/profile",aUe,{pluginId:"profile"}),Wr("style-guide","@brains/style-guide",uMr,{pluginId:"style-guide"}),Wr("ask-content","@brains/ask-content",pMr,{pluginId:"ask-content"}),["image",(e)=>[...oG("@brains/image-plugin",iIr,{pluginId:"image"})(e),...oG("@brains/image-plugin",rIr,{})({})],void 0],Wr("document","@brains/document-plugin",AAr,{pluginId:"document"}),Wr("note","@brains/note",C7r,{pluginId:"note"}),Wr("refined-note","@brains/refined-note",nRr,{pluginId:"refined-note"}),Wr("link","@brains/link",bIr,{pluginId:"link"}),Wr("references","@brains/reference",OIr,{pluginId:"references",ownedTypePluginId:"reference"}),Wr("wishlist","@brains/wishlist",fjr,{pluginId:"wishlist"}),["topics",(e)=>[...Xp(lOr,e,{name:"@brains/topics",version:bS.version},{pluginId:"topics"}),...Xp(Kqe,{},{name:"@brains/knowledge-map",version:bS.version},{pluginId:"knowledge-map"})],void 0],Wr("decks","@brains/decks",Rgr,{pluginId:"decks"}),Wr("directory-sync","@brains/directory-sync",hEr,{pluginId:"directory-sync"},{seedContent:!0,seedContentPath:"./seed-content",initialSync:!0}),Wr("atproto-registry","@brains/atproto-registry",sge,{pluginId:"atproto-registry"}),["agents",(e)=>{let{enableSkillDerivation:t,notifyOnNewAgents:r}=jXe.parse(e),i={name:"@brains/agent-discovery",version:bS.version};return[...Xp(lxe,{},i,{pluginId:"agent-discovery",ownedTypePluginId:"agent-entity"}),...Xp(uxe,{notifyOnNewAgents:r},i,{pluginId:"agent"}),...Xp(t?dxe:mxe,{},i,{pluginId:"skill",ownedTypePluginId:"skill-entity"}),...Xp(pxe,{},i,{pluginId:"shared-copies",ownedTypePluginId:"shared-copy"})]},void 0],["assessment",(e)=>Xp(Lxe.parse(e).enableSwotDerivation?jxe:zxe,{},{name:"@brains/assessment",version:bS.version},{pluginId:"swot"}),void 0],Wr("auth-service","@brains/auth-service",dve,{pluginId:"auth-service"}),Wr("notifications","@brains/notifications",_7r,{pluginId:"notifications"}),Wr("contact","@brains/contact",wfr,{pluginId:"contact",dependencies:Afr}),Wr("quiz","@brains/quiz",Ofr,{pluginId:"quiz",dependencies:Mfr}),Wr("playbooks","@brains/playbooks",Rze,{pluginId:"playbooks"}),Wr("onboarding","@brains/onboarding",cRr,{pluginId:"onboarding",dependencies:["playbook","playbooks"]}),Wr("studio","@brains/studio",Bhr,{pluginId:"studio"}),Wr("dashboard","@brains/dashboard",ogr,{pluginId:"dashboard"}),Wr("admin","@brains/admin",the,{pluginId:"admin"}),Wr("site-info","@brains/site-info",sqe,{pluginId:"site-metadata"}),Wr("site-content","@brains/site-content",UFr,{pluginId:"site-content",ownedTypePluginId:"site-content-entity"}),Wr("site-builder","@brains/site-builder-plugin",LFr,{pluginId:"site-builder"}),Wr("form","@brains/form",kfr,{pluginId:"form"}),Wr("analytics","@brains/analytics",cet,{pluginId:"analytics"}),Wr("blog","@brains/blog",P0t,{pluginId:"blog"}),Wr("series","@brains/series",kRr,{pluginId:"series"}),Wr("portfolio","@brains/portfolio",bPr,{pluginId:"portfolio"}),Wr("content-pipeline","@brains/content-pipeline",ifr,{pluginId:"content-pipeline"}),Wr("social-media","@brains/social-media",nMr,{pluginId:"social-media"}),["newsletter",iyo,void 0],Wr("stock-photo","@brains/stock-photo",cMr,{pluginId:"stock-photo"}),["atproto",oG("@brains/atproto",Vet,{pluginId:"atproto"}),(e)=>({...e.ATPROTO_APP_PASSWORD?{appPassword:e.ATPROTO_APP_PASSWORD}:{}})],Wr("conversation-memory","@brains/conversation-memory",r_e,{pluginId:"conversation-memory"}),Wr("action-board","@brains/action-board",S$e,{pluginId:"action-board"}),Wr("faq","@brains/faq",kxr,{pluginId:"faq",ownedTypePluginId:"faq-entity"}),Wr("docs","@brains/doc",OEr,{pluginId:"docs"}),Wr("guides","@brains/guide",svr,{pluginId:"guides"}),Wr("book","@brains/book",lAr,{pluginId:"book",ownedTypePluginId:"book-entity"}),Wr("email-workflows","@brains/email-workflows",FDr,{pluginId:"email-workflows"}),Wr("unified-inbox","@brains/unified-inbox",p$e,{pluginId:"unified-inbox"}),Wr("linkedin-import","@brains/linkedin-import",Fje,{pluginId:"linkedin-import"}),Wr("oauth-broker","@brains/oauth-broker",jje({providers:{linkedin:Sje}}),{pluginId:"oauth-broker"}),Wr("webdav","@brains/webdav",oTr,{pluginId:"webdav"}),Wr("matrix-server","@brains/matrix-server",STr,{pluginId:"matrix-server"},(e)=>fze(e))],interfaces:[nG("mcp","@brains/mcp",HIr,(e)=>({...e.MCP_AUTH_TOKEN?{authToken:e.MCP_AUTH_TOKEN}:{}}),{pluginId:"mcp"}),nG("email","@brains/email",yDr,()=>({}),{pluginId:"email"}),nG("web-chat","@brains/web-chat",ajr,()=>({}),{pluginId:"web-chat"}),nG("chat","@brains/chat",rmr,(e)=>rIe(e,{captureUrls:!0}),{pluginId:"chat"}),nG("a2a","@brains/a2a",kHe,()=>({}),{pluginId:"a2a"})],bundles:vjr,permissions:{rules:[{pattern:"cli:*",level:"admin"},{pattern:"mcp:stdio",level:"admin"}]},deployment:{cdn:{enabled:!0,provider:"bunny"},dns:{enabled:!0,provider:"bunny"}}});var nyo=["headless","personal","professional","team"];var oyo={headless:{bundleContract:yS,bundles:["core"]},personal:{bundleContract:yS,anchor:"person",kind:"professional",bundles:["core","media","web","chat"],plugins:{"directory-sync":{seedContentPath:"./seed-content"}}},professional:{bundleContract:yS,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:yS,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 syo(e){return structuredClone(e)}function ayo(e){return syo(oyo[e])}var cyo=Ajr,ctc=Nde,ltc=Lde,utc=jde,dtc=zde,ptc=Ude,mtc=qde,htc=$de,ftc=Gde,xtc=Hde,ytc=cyo;export{J$e as AUTOMATION_BUNDLE_ID,nyo as BRAIN_RECIPE_NAMES,yS as CANONICAL_BUNDLE_CONTRACT,Q$e as CHAT_BUNDLE_ID,K$e as CORE_BUNDLE_ID,tGe as FEDERATION_BUNDLE_ID,Y$e as MEDIA_BUNDLE_ID,eGe as PUBLISHING_BUNDLE_ID,X$e as SITE_BUNDLE_ID,rGe as TEAM_BUNDLE_ID,iG as WEB_BUNDLE_ID,utc as automationBundle,cyo as canonicalBrain,ptc as chatBundle,ctc as coreBundle,ytc as default,ayo as expandBrainRecipe,ftc as federationBundle,ltc as mediaBundle,htc as publishingBundle,mtc as siteBundle,xtc as teamBundle,dtc as webBundle};
|
|
11093
11093
|
|
|
11094
|
-
//# debugId=
|
|
11094
|
+
//# debugId=59B21F6D45A9FE0B64756E2164756E21
|
|
11095
11095
|
//# sourceMappingURL=model.js.map
|