@rizom/brain 0.2.0-alpha.790 → 0.2.0-alpha.791
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brain.js +5 -5
- package/dist/chunks/{app-jae0qpb3.js → app-h7sxa3mc.js} +2 -2
- package/dist/chunks/{index-wz64f6xz.js → index-1phtzjk2.js} +3 -3
- package/dist/chunks/{index-wz64f6xz.js.map → index-1phtzjk2.js.map} +1 -1
- package/dist/chunks/{index-eg87hv8p.js → index-83mk5vfd.js} +2 -2
- package/dist/chunks/{package-v3n18b6c.js → package-3t5qh3q0.js} +3 -3
- package/dist/chunks/{package-v3n18b6c.js.map → package-3t5qh3q0.js.map} +1 -1
- package/dist/model.js +5 -5
- package/dist/model.js.map +3 -3
- package/dist/testing.js +1 -1
- package/package.json +1 -1
- /package/dist/chunks/{app-jae0qpb3.js.map → app-h7sxa3mc.js.map} +0 -0
- /package/dist/chunks/{index-eg87hv8p.js.map → index-83mk5vfd.js.map} +0 -0
package/dist/model.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunks/index-eg87hv8p.js";import{$ as go,$a as Tyn,$b as mbn,$c as zbn,Aa as K0,Ab as jj,Ad as dEn,Ba as Ylr,Bb as tbn,Bd as Gk,C as ry,Ca as Jlr,Cb as rbn,Cc as $mr,Cd as pEn,D as Bgn,Da as dyn,Db as hv,Dd as mEn,E as jlr,Ea as pyn,Eb as eur,Ed as hEn,F as Vlr,Fa as Xre,Fb as Mj,Fd as ny,G as Ngn,Ga as myn,Gb as ibn,Gd as Lj,H as Lgn,Hb as nbn,Hd as fEn,I as jgn,Ia as uDe,Ib as obn,Id as xEn,J as zgn,Ja as hyn,Jb as sbn,Jd as gEn,K as Ugn,Ka as fyn,Kd as yEn,La as xyn,Lb as tur,Ld as bEn,M as rie,Ma as gyn,Mb as rur,Md as EEn,Na as yyn,Nb as iur,Nd as vEn,Oa as byn,Ob as nur,Od as AEn,P as Wk,Pa as Eyn,Pb as our,Pd as wEn,Q as Tlr,Qa as Qlr,Qb as sur,Qd as nie,R as Hk,Ra as vyn,Rb as aur,Rc as mur,Rd as bDe,S as ty,Sa as Ayn,Sb as cur,Sc as Pbn,Sd as SEn,Ta as wyn,Tb as lur,Tc as Rbn,Td as dDe,U as gDe,Ua as Syn,Ub as uur,Uc as Fbn,Ud as kEn,V as qgn,Va as kyn,Vb as abn,Vc as Mbn,Vd as Zm,W as Vt,Wa as Byn,Wb as cbn,Wc as $k,Wd as Pre,Xa as Cyn,Xb as lbn,Xc as Obn,Xd as BEn,Y as Klr,Ya as Dyn,Yb as ubn,Yc as Nbn,Z as $gn,Za as Iyn,Zb as dbn,Zc as Lbn,_ as f8,_a as _yn,_b as pbn,_c as jbn,aa as y8,ab as Pyn,ac as hbn,ad as Ubn,ba as el,bb as Ryn,bc as fbn,bd as qbn,ca as Ggn,cb as Fyn,cc as xbn,cd as $bn,da as Hgn,db as x8,dc as gbn,dd as Gbn,ea as Wgn,eb as Myn,ec as ybn,ed as Hbn,fa as Zgn,fb as sDe,fc as bbn,fd as Wbn,ga as Vgn,gb as Oyn,gc as Ebn,gd as Zbn,ha as Kgn,hb as Nyn,hc as vbn,hd as Vbn,ia as Ygn,ib as Lyn,ic as Abn,id as Kbn,ja as Jgn,jb as jyn,jc as aDe,jd as Ybn,ka as Qgn,kb as zyn,kc as Nj,kd as Jbn,la as Xgn,lb as Uyn,lc as wbn,ld as Qbn,ma as eyn,mb as qyn,mc as Sbn,md as Xbn,na as tyn,nb as $yn,nc as kbn,nd as eEn,oa as ryn,ob as Gyn,oc as Bbn,od as tEn,pa as iyn,pb as Hyn,pc as Cbn,qa as nyn,qb as Wyn,qc as Dbn,qd as rEn,ra as oyn,rb as Zyn,rc as Ibn,rd as iEn,sa as syn,sb as Vyn,sc as dur,sd as nEn,ta as f3e,tb as Kyn,tc as pur,td as Mlr,ua as ayn,ub as Yyn,uc as _lr,ud as oEn,va as cyn,vb as Jyn,vc as _bn,vd as sEn,wa as lyn,wb as Xlr,wc as Tbn,wd as aEn,xa as uyn,xb as Qyn,xc as yDe,xd as cEn,ya as oDe,yb as Xyn,yd as lEn,za as $j,zb as ebn,zd as uEn}from"./chunks/index-e86c8bvy.js";import{$d as HEr,Yd as f7,Zd as Svr,be as mPe}from"./chunks/index-jtzbfbxr.js";import{de as z0e}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 DS}from"./chunks/index-wz64f6xz.js";import{Ce as LWe,De as O_r,Ee as hFr,Fe as Dg,Ge as AJ,He as kU,Ie as _Er,Je as Sy,Ke as s7r,Le as p7,Me as zTr,Ne as BEr,Oe as TEr,Pe as m7r,Qe as i7r,Re as cxt,Se as MMr,Te as $qe,Ue as Gqe,Ve as Hqe,We as Vbr,Xe as i7,Ye as n7r,Ze as Ef,_e as m7,gf as nH,ke as DHe,le as sH,ne as ko,oe as S5,pe as Oge,qe as zge,re as Qb,se as EZ,te as vZ,ue as AZ,ve as yet,we as wZ,xe as y4,ye as srt,ze as ys}from"./chunks/index-e7drdbaa.js";import{jf as the,kf as Jzr}from"./chunks/index-7d748trp.js";import"./chunks/index-rkhex3pb.js";import{$f as krt,$g as qA,$h as zhe,$i as Lqe,$j as rzr,$k as Gme,$l as W7r,$m as Twr,$n as agt,Af as iV,Ag as da,Ah as R3,Ak as Nme,Am as o_r,An as Eh,Bf as Sl,Bg as ms,Bh as VJ,Bi as qT,Bl as td,Bm as Ko,Cf as kit,Cg as tp,Ch as Mgt,Ci as NA,Cj as kA,Cl as $he,Df as ZR,Dg as yb,Dh as F2,Di as WA,Dj as Ojr,Dl as Ghe,Ef as VR,Eg as Bme,Eh as Fl,Ei as LI,Ej as pzr,El as Hhe,Eo as jA,Ff as gr,Fh as x1,Fi as zqe,Fj as XGe,Fk as Qf,Fl as Whe,Fo as Qme,Gf as P4,Gh as OO,Gi as THe,Gj as $zr,Gk as XS,Gl as Zhe,Gm as IO,Gn as Yme,Go as cWe,Hf as nV,Hg as Ohe,Hh as f1,Hi as xOr,Hj as Gzr,Hk as e5,Hl as Vhe,Hm as Xxt,Ho as Xme,If as TR,Ig as dn,Ih as O0,Ii as DJ,Ij as pU,Ik as OH,Il as r5,Im as jJ,Io as OA,Jg as So,Jh as c8e,Ji as Gne,Jj as Nf,Jl as sP,Jm as lpe,Jn as xhr,Jo as bh,Kf as fw,Kg as pxt,Kh as Hgt,Ki as Que,Kj as KB,Kk as t5,Kl as i5,Km as upe,Kn as ghr,Ko as ehe,Lf as Gge,Lg as Nhe,Lh as Ggt,Li as Hne,Lj as Qjr,Ll as ma,Ln as zJ,Lo as YT,Mf as oV,Mh as ore,Mi as Ule,Mj as Xjr,Ml as Yo,Mn as dgt,Mo as s_r,Nf as gs,Ng as QT,Nh as Jgt,Ni as BJ,Nj as tpe,Nl as aP,Nm as Njr,Nn as pgt,Of as nr,Og as JS,Oh as kgt,Oi as ES,Oj as Hzr,Ok as Lme,Ol as Zi,On as azr,Pf as Je,Pg as kH,Ph as Bgt,Pi as qI,Pj as Wzr,Pk as LA,Pl as Khe,Pn as czr,Qf as Ro,Qg as XT,Qi as $I,Qj as bjr,Qk as vb,Ql as Yhe,Qn as mgt,Rf as Ks,Rg as eP,Rh as ZJ,Ri as $we,Rj as Ejr,Rk as GS,Rl as am,Rn as hgt,Ro as zA,Sf as Fh,Sg as Lhe,Sh as Qgt,Si as YEr,Sj as vjr,Sk as WT,Sl as $t,Sn as T1e,So as rE,Tf as qge,Tg as wb,Th as m8e,Ti as fa,Tj as Ajr,Tk as jme,Tl as kb,Tn as egt,To as vh,Ug as tP,Ui as Btt,Uj as wjr,Uk as BH,Ul as Xn,Un as ogt,Uo as $x,Vf as Art,Vg as rP,Vh as E_r,Vi as qhe,Vj as Zzr,Vk as zme,Vl as hs,Vm as Y6,Vn as PO,Vo as Afr,Wf as wrt,Wg as iP,Wi as k7,Wj as Ujr,Wk as Ume,Wl as C4,Wm as _wr,Wn as fgt,Wo as ya,Xg as nP,Xh as Ws,Xi as _6,Xj as qjr,Xk as qme,Xl as VT,Xm as M_r,Xn as RO,Yg as oP,Yi as woe,Yj as Wjr,Yk as D9,Yl as kn,Ym as Fwr,Yn as djr,Zf as Srt,Zg as jhe,Zi as Soe,Zj as ezr,Zk as $me,Zl as ht,Zm as DEr,Zn as c7e,_g as _9,_h as bb,_i as MT,_j as tzr,_m as Mwr,_n as sgt,ah as kh,aj as vS,ak as epe,an as Owr,ao as kz,bh as Sb,bi as QS,bj as bTe,bk as Yzr,bl as ao,bm as Pi,bn as Lwr,bo as cgt,ch as HA,ck as Kjr,cm as Q_r,co as GJ,dh as Jw,dj as dw,dk as ajr,dm as u$,do as lgt,eh as ZIr,ei as pc,ej as PHe,el as HS,em as Y_r,eo as Djr,fh as $it,fi as jt,fj as Olt,fl as Hme,fm as Zme,fo as xgt,gh as jye,gi as Xne,gj as Nlt,gm as Vr,go as wgt,hi as T9,hk as BA,ho as Ijr,ii as lm,ik as $S,in as yue,io as Cjr,jg as uOr,jh as Kie,ji as dc,jk as Cme,jn as R0,jo as tgt,kh as Yie,ki as d1,kk as Gx,kl as ZT,km as Ab,ko as Uie,lg as dOr,lh as Jie,li as co,ll as Wme,lm as bt,lo as Ez,mg as Ivr,mh as Qie,mi as pf,mm as Hx,mo as rhr,nf as Fhe,nh as Dhr,ni as yyr,nm as pa,no as cm,of as Mhe,oh as Ihr,oi as _hr,om as klt,oo as n5,pf as Sme,ph as jIe,pi as XI,pj as Eb,pk as GT,pl as cjr,pm as fl,pn as ljr,po as Bb,qf as ep,qh as d6,qi as cx,qk as Dme,qm as KT,qn as ujr,qo as Cb,rf as qS,ri as Gxt,rk as Ime,rm as Vme,rn as HJ,ro as Db,sf as kme,sh as po,si as O9,sk as _me,sm as Kme,sn as ggt,so as ed,tf as C9,th as Ygt,ti as $l,tk as HT,tl as R0r,tm as zt,tn as ygt,to as Jme,uf as st,ug as tu,uh as Ie,ui as OI,uk as Tme,ul as Lne,um as qx,un as bgt,uo as ZS,vf as kr,vg as UT,vh as M0,vi as ct,vj as aOr,vk as Pme,vl as khr,vm as Hie,vn as P3,vo as CH,wg as _i,wh as Nn,wi as Au,wk as Rme,wl as oH,wm as Wie,wn as FO,xf as fe,xg as sm,xh as KJ,xi as VGe,xk as Fme,xm as NWe,yf as xw,yg as Vf,yh as Vgt,yi as Uhe,yk as Mme,ym as wo,yn as Nge,yo as VS,zf as ft,zg as Ur,zh as P2,zk as Ome,zl as nm,zm as Rn,zo as KS}from"./chunks/index-gx72qzwf.js";import{$o as xf,$p as Qn,$q as wlt,$r as Bue,$s as rd,Ap as Z8,Aq as US,Ar as rgr,As as eTr,Bp as BAr,Bq as NHe,Br as lhr,Bs as kTr,Cp as CAr,Cq as DWe,Cr as $ie,Cs as tTr,Dp as VLr,Dq as Ux,Dr as qie,Ds as oTr,Ep as Zde,Eq as IWe,Es as xne,Fp as KLr,Fq as lH,Fs as i3,Gp as TAr,Gq as EH,Gr as h_r,Gs as une,Hp as YLr,Hq as vH,Hr as hw,Hs as rY,Ip as sRe,Iq as mR,Ir as _z,Is as iY,Jp as aRe,Js as tne,Kp as zU,Kq as kue,Ks as Slt,Lp as cRe,Lq as zgr,Mp as PAr,Mq as cs,Ms as xyr,Np as lRe,Nq as oFr,Ns as jwe,Op as RAr,Oq as tbr,Or as Nse,Pp as FAr,Pq as I8,Pr as I7,Ps as Hv,Qp as Rse,Qq as sfr,Qr as one,Qs as y7r,Rp as Fse,Rq as ane,Rr as lne,Rs as Ale,Sp as MAr,Sq as moe,Sr as Bi,Ss as AB,Tp as Mse,Tq as iRr,Tr as lOr,Ts as f6,Up as Er,Uq as nRr,Ur as IOr,Us as Xpe,Vp as k5,Vq as tY,Vr as PZ,Vs as Gie,Wp as Ht,Wr as Rf,Ws as wm,Xo as jAr,Xp as rx,Xq as wit,Xs as Qw,Yo as hde,Yp as BZ,Yq as Sit,Yr as x_,Ys as ua,Zp as jp,Zq as Frt,Zr as qse,Zs as Fbr,_o as Sn,_p as hy,_q as Mrt,_r as I$,_s as qp,ap as vne,aq as Jde,ar as En,as as DUe,at as ru,br as sd,bs as p$,bt as Ke,cp as Sr,cq as wzr,cr as lS,cs as m$,dp as mi,dq as Szr,dr as ele,ds as J$,ep as PI,er as IIr,es as ZNr,et as $T,fp as qB,fr as tle,fs as Q$,ft as Gf,gp as mde,gq as eT,gr as Hge,gs as Sne,gt as eme,hp as FB,hr as QZ,hs as Xfr,ip as Yq,is as t0r,it as ime,jp as OJ,jr as p1,js as a0r,kp as va,kq as zT,kr as he,ks as r0r,lp as qv,lq as XPr,ls as i0r,mp as MB,mr as Io,ms as m1,np as vje,ns as Thr,oq as qzr,pp as Ose,ps as Yle,qp as Uv,qq as cRr,qr as Rr,qs as H_r,rp as Ise,rq as Ztt,rr as A4,rs as W_r,sp as _se,sr as Pzr,ss as r3,tp as ZLr,tq as vme,tr as B9,ts as Pde,up as Ooe,uq as xH,ur as cne,us as Rde,ut as rp,vp as W6,vq as gH,vr as kJ,vs as Kle,vt as om,wp as qxe,wq as yH,wr as w3,ws as S_,wt as Xu,xp as Pse,xq as bH,xs as gze,yp as Z6,yq as wH,ys as bze,zp as Tse,zq as SH,zr as yoe,zs as STr,zt as WS}from"./chunks/index-wxxzncf6.js";import{Bt as jje,Dt as cH}from"./chunks/index-88nn119k.js";import{BB as Up,CB as xxr,DB as Ki,EB as Vzr,Ix as eu,Kx as q4,Wx as lc,ez as WJ,iB as et,jy as Hs,pB as Sgt,sv as a1e,wB as yh,xB as U4,zB as Pc}from"./chunks/index-ahk2enhj.js";import{WC as u}from"./chunks/index-gdatxzx2.js";import"./chunks/index-qefyds15.js";import{$C as aYr,_C as to,aD as E,bD as Kx,cD as fs,dD as ce}from"./chunks/index-3dxmcttv.js";function BVe(e){return e===0||e>=55296&&e<=57343||e>1114111}function CVe(e){if(BVe(e))return 65533;if(e>=128&&e<=159)return UHr[e-128]||e;return e}function DVe(e){return BVe(e)?65533:e}var UHr;var IVe=fs(()=>{UHr=[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 _Ve(e,t,r,i,n,o){let a=e.length,c=o*90,l=0,d=()=>{let L=e0[e.charCodeAt(l++)];return L<o?L:L*91-c+e0[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,H){let V=0,ee=H,q=H+L;while(ee<q){let S=e0[e.charCodeAt(l++)];if(S<89)V+=S,h[ee++]=V;else if(S===89){let I=e0[e.charCodeAt(l++)]+2;while(I--)h[ee++]=++V}else{let I=e0[e.charCodeAt(l++)];V+=89+(I<90?I*91+e0[e.charCodeAt(l++)]:e0[e.charCodeAt(l++)]*8281+e0[e.charCodeAt(l++)]*91+e0[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,H){for(let V=0;V<L;V++){let ee=H+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 H=0;H<2;H++){let V=b[L*2+H],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=e0[e.charCodeAt(l++)];if(L>=o)L=L*91-c+e0[e.charCodeAt(l++)];let H=h[L];if(H<0){let V=f[L],ee=V+g[L];while(V<ee)k[N++]=F[V++]}else k[N++]=H}return k}var e0;var TVe=fs(()=>{e0=(()=>{let e=new Uint8Array(127),t=0;for(let r=33;r<=126;r++)if(r!==34&&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!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 EP;var Ife=fs(()=>{EP=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 Mc;var RVe=fs(()=>{(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"})(Mc||(Mc={}))});function FVe(e){return e-nu.ZERO>>>0<=9}function qHr(e){return(e|KH)-nu.LOWER_A>>>0<=5}function $Hr(e){return(e|KH)-nu.LOWER_A>>>0<=25}function GHr(e){return e===nu.EQUALS||$Hr(e)||FVe(e)}class _fe{decodeTree;emitCodePoint;errors;state=iu.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=t0.Strict;runConsumed=0;constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r}startEntity(e){this.decodeMode=e,this.state=iu.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case iu.EntityStart:{if(e.charCodeAt(t)===nu.NUM)return this.state=iu.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=iu.NamedEntity,this.stateNamedEntity(e,t)}case iu.NumericStart:return this.stateNumericStart(e,t);case iu.NumericDecimal:return this.stateNumericDecimal(e,t);case iu.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)|KH)===nu.LOWER_X)return this.state=iu.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=iu.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(FVe(o)||qHr(o)){let s=o<=nu.NINE?o-nu.ZERO:(o|KH)-nu.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)-nu.ZERO;if(o>>>0>9)return this.result=i,this.consumed=n,this.emitNumericEntity(o+nu.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===nu.SEMI)this.consumed+=1;else if(this.decodeMode===t0.Strict)return 0;if(this.emitCodePoint((this.decodeTree===EP?DVe:CVe)(this.result),this.consumed),this.errors){if(e!==nu.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===t0.Attribute&&(i===0||t>1||GHr(r))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:r}=this,i=e.length,n=this.decodeMode===t0.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=r[o];while(t<i){while((c&(Mc.VALUE_LENGTH|Mc.FLAG13))===0&&(c&Mc.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&Mc.JUMP_TABLE,f=(c&Mc.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&(Mc.VALUE_LENGTH|Mc.FLAG13))===Mc.FLAG13){let m=(c&Mc.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&Mc.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&Mc.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===nu.SEMI)return this.emitNamedEntityData(o,l,a+s);if(l===1)return this.flushAndEmitLegacyOrReject(a,s,d,l)}let p=HHr(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&Mc.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]&Mc.VALUE_MASK:i[e+1],r),t===3)this.emitCodePoint(i[e+2],r);return r}end(){switch(this.state){case iu.NamedEntity:return this.result!==0&&(this.decodeMode!==t0.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case iu.NumericDecimal:return this.emitNumericEntity(0,2);case iu.NumericHex:return this.emitNumericEntity(0,3);case iu.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function HHr(e,t,r,i){let n=(t&Mc.BRANCH_LENGTH)>>7,o=t&Mc.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 nu,KH=32,iu,t0;var MVe=fs(()=>{IVe();Ife();RVe();PVe();Ife();(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"})(nu||(nu={}));(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"})(iu||(iu={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(t0||(t0={}))});function a5(e){return e===br.Space||e===br.NewLine||e===br.Tab||e===br.FormFeed||e===br.CarriageReturn}function z9(e){return e===br.Slash||e===br.Gt||a5(e)}function WHr(e){return e>=br.LowerA&&e<=br.LowerZ||e>=br.UpperA&&e<=br.UpperZ}class U9{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 _fe(e?EP:Dfe,(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(z9(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?!z9(e):WHr(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(z9(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:ZHr.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(z9(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(a5(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(z9(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(!a5(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(!a5(e))this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===br.Eq||z9(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(um.NoValue,this.sectionStart),this.sectionStart=-1,this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!a5(e))this.cbs.onattribend(um.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(!a5(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?um.Double:um.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(a5(e)||e===br.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(um.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?t0.Strict:this.baseState===We.Text||this.baseState===We.InSpecialTag?t0.Legacy:t0.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,um,oi,ZHr;var Tfe=fs(()=>{MVe();(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"})(um||(um={}));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])},ZHr=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 G9{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??U9)(this.options,this),this.foreignContext=[Pb.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?.(OVe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==Pb.None}isVoidElement(e){return this.htmlMode&&KHr.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]===Pb.Svg)return qVe.get(r)??r;if(this.foreignContext.length>1){let i=qVe.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&&VHr.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(Pb.Svg);else if(e==="math")this.foreignContext.unshift(Pb.MathML);else if(UVe.has(e))this.foreignContext.unshift(Pb.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&&(YHr.has(t)||UVe.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+=OVe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===um.Double?'"':e===um.Single?"'":e===um.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(JHr),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?zVe:r.slice(0,zVe.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(Pb.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 OVe,q9,Zs,$9,NVe,LVe,jVe,VHr,zVe="doctype",KHr,YHr,UVe,qVe,Pb,JHr;var Pfe=fs(()=>{Tfe();({fromCodePoint:OVe}=String),q9=new Set(["input","option","optgroup","select","button","datalist","textarea"]),Zs=new Set(["p"]),$9=new Set(["h1","h2","h3","h4","h5","h6","p"]),NVe=new Set(["thead","tbody"]),LVe=new Set(["dd","dt"]),jVe=new Set(["rt","rp"]),VHr=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",Zs],["h1",$9],["h2",$9],["h3",$9],["h4",$9],["h5",$9],["h6",$9],["select",q9],["input",q9],["output",q9],["button",q9],["datalist",q9],["textarea",q9],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",LVe],["dt",LVe],["address",Zs],["article",Zs],["aside",Zs],["blockquote",Zs],["details",Zs],["div",Zs],["dl",Zs],["fieldset",Zs],["figcaption",Zs],["figure",Zs],["footer",Zs],["form",Zs],["header",Zs],["hr",Zs],["main",Zs],["nav",Zs],["ol",Zs],["pre",Zs],["section",Zs],["table",Zs],["ul",Zs],["rt",jVe],["rp",jVe],["tbody",NVe],["tfoot",NVe]]),KHr=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),YHr=new Set(["math","svg"]),UVe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),qVe=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"})(Pb||(Pb={}));JHr=/\s|\//});var YH={};Kx(YH,{CDATA:()=>Ufe,Comment:()=>Nfe,Directive:()=>Ofe,Doctype:()=>QHr,ElementType:()=>pn,Root:()=>Ffe,Script:()=>Lfe,Style:()=>jfe,Tag:()=>zfe,Text:()=>Mfe,isTag:()=>Rfe});function Rfe(e){return e.type===pn.Tag||e.type===pn.Script||e.type===pn.Style}var pn,Ffe,Mfe,Ofe,Nfe,Lfe,jfe,zfe,Ufe,QHr;var H9=fs(()=>{(function(e){e.Root="root",e.Text="text",e.Directive="directive",e.Comment="comment",e.Script="script",e.Style="style",e.Tag="tag",e.CDATA="cdata",e.Doctype="doctype"})(pn||(pn={}));Ffe=pn.Root,Mfe=pn.Text,Ofe=pn.Directive,Nfe=pn.Comment,Lfe=pn.Script,jfe=pn.Style,zfe=pn.Tag,Ufe=pn.CDATA,QHr=pn.Doctype});class $fe{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 $Ve(this,e)}}function ou(e){return Rfe(e)}function iW(e){return e.type===pn.CDATA}function YA(e){return e.type===pn.Text}function Gfe(e){return e.type===pn.Comment}function XHr(e){return e.type===pn.Directive}function eWr(e){return e.type===pn.Root}function ip(e){return Object.hasOwn(e,"children")}function $Ve(e,t=!1){let r;if(YA(e))r=new vP(e.data);else if(Gfe(e))r=new QH(e.data);else if(ou(e)){let i=t?qfe(e.children):[],n=new rW(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(iW(e)){let i=t?qfe(e.children):[],n=new tW(i);for(let o of i)o.parent=n;r=n}else if(eWr(e)){let i=t?qfe(e.children):[],n=new AP(i);for(let o of i)o.parent=n;if(e["x-mode"])n["x-mode"]=e["x-mode"];r=n}else if(XHr(e)){let i=new XH(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 qfe(e){let t=e.map((r)=>$Ve(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 JH,vP,QH,XH,eW,tW,AP,rW;var Hfe=fs(()=>{H9();JH=class JH extends $fe{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};vP=class vP extends JH{type=pn.Text;get nodeType(){return 3}};QH=class QH extends JH{type=pn.Comment;get nodeType(){return 8}};XH=class XH extends JH{type=pn.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};eW=class eW extends $fe{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}};tW=class tW extends eW{type=pn.CDATA;get nodeType(){return 4}};AP=class AP extends eW{type=pn.Root;get nodeType(){return 9}};rW=class rW extends eW{name;attribs;type;constructor(e,t,r=[],i=e==="script"?pn.Script:e==="style"?pn.Style:pn.Tag){super(r);this.name=e,this.attribs=t,this.type=i}get nodeType(){return 1}get tagName(){return this.name}set tagName(e){this.name=e}get attributes(){return Object.keys(this.attribs).map((e)=>({name:e,value:this.attribs[e],namespace:this["x-attribsNamespace"]?.[e],prefix:this["x-attribsPrefix"]?.[e]}))}namespace;"x-attribsNamespace";"x-attribsPrefix"}});class c5{dom=[];root=new AP(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=GVe;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??GVe,this.elementCB=r??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new AP(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){if(this.done)return;this.done=!0,this.parser=null,this.handleCallback(null)}onerror(e){this.handleCallback(e)}onclosetag(){this.lastNode=null;let e=this.tagStack.pop();if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(this.elementCB)this.elementCB(e)}onopentag(e,t){let r=this.options.xmlMode?pn.Tag:void 0,i=new rW(e,t,void 0,r);this.addNode(i),this.tagStack.push(i)}ontext(e){let{lastNode:t}=this;if(t&&t.type===pn.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let r=new vP(e);this.addNode(r),this.lastNode=r}}oncomment(e){if(this.lastNode&&this.lastNode.type===pn.Comment){this.lastNode.data+=e;return}let t=new QH(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new vP(""),t=new tW([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let r=new XH(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 GVe;var JA=fs(()=>{H9();Hfe();Hfe();GVe={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function W9(e,t,r=!0,i=Number.POSITIVE_INFINITY){return HVe(e,Array.isArray(t)?t:[t],r,i)}function HVe(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&&ip(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function nW(e,t,r=!0){let i=Array.isArray(t)?t:[t];for(let n of i){if(ou(n)&&e(n))return n;if(r&&ip(n)&&n.children.length>0){let o=nW(e,n.children,!0);if(o)return o}}return null}function WVe(e,t){return(Array.isArray(t)?t:[t]).some((r)=>ou(r)&&e(r)||ip(r)&&WVe(e,r.children))}function tWr(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(ou(o)&&e(o))r.push(o);if(ip(o)&&o.children.length>0)n.unshift(0),i.unshift(o.children)}}var Wfe=fs(()=>{JA()});function Zfe(e,t){if(typeof t==="function")return(r)=>ou(r)&&t(r.attribs[e]);return(r)=>ou(r)&&r.attribs[e]===t}function rWr(e,t){return(r)=>e(r)||t(r)}function ZVe(e){let t=Object.keys(e).map((r)=>{let i=e[r];return Object.hasOwn(oW,r)?oW[r](i):Zfe(r,i)});return t.length===0?null:t.reduce(rWr)}function iWr(e,t){let r=ZVe(e);return r?r(t):!0}function nWr(e,t,r,i=Number.POSITIVE_INFINITY){let n=ZVe(e);return n?W9(n,t,r,i):[]}function oWr(e,t,r=!0){if(!Array.isArray(t))t=[t];return nW(Zfe("id",e),t,r)}function l5(e,t,r=!0,i=Number.POSITIVE_INFINITY){return W9(oW.tag_name(e),t,r,i)}function sWr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return W9(Zfe("class",e),t,r,i)}function aWr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return W9(oW.tag_type(e),t,r,i)}var oW;var Vfe=fs(()=>{JA();Wfe();oW={tag_name(e){if(typeof e==="function")return(t)=>ou(t)&&e(t.name);if(e==="*")return ou;return(t)=>ou(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)=>YA(t)&&e(t.data);return(t)=>YA(t)&&t.data===e}}});function KVe(e){return e===34?""":e===38?"&":e===39?"'":e===60?"<":e===62?">":" "}function VVe(e){return e>=128||e>=32&&e<64&&(cWr>>>e&1)===1}function sW(e){let{length:t}=e,r,i=0,n=0;while(n<t){let o=e.charCodeAt(n);if(!VVe(o)){let a=Math.min(n+32,t),c=n+1;while(c<a&&!VVe(e.charCodeAt(c)))c++;if(c<a){n=c;continue}if(c>=t)break;if(Kfe.lastIndex=c,!Kfe.test(e))break;n=Kfe.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+=KVe(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 YVe(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+=KVe(o),i=n+1}while(e.test(t));return r+t.substring(i)}function Yfe(e){return YVe(lWr,e)}function Jfe(e){return YVe(uWr,e)}var cWr=1342177476,Kfe,lWr,uWr;var JVe=fs(()=>{Kfe=/["&'<>\u0080-\uFFFF]/g;lWr=/["&\u{A0}]/gu;uWr=/[&<>\u{A0}]/gu});var QVe,XVe;var eKe=fs(()=>{JVe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(QVe||(QVe={}));(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"})(XVe||(XVe={}))});var tKe,rKe;var iKe=fs(()=>{tKe=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])),rKe=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 fWr(e,t={}){let r="length"in e?e:[e],i=t.xmlMode??!1,n="";for(let o=0;o<r.length;o++)n+=oKe(r[o],t,i);return n}function nKe(e,t,r){let i="";for(let n=0;n<e.length;n++)i+=oKe(e[n],t,r);return i}function oKe(e,t,r){switch(e.type){case Ffe:return nKe(e.children,t,r);case Ofe:return`<${e.data}>`;case Nfe:return`<!--${e.data}-->`;case Ufe:return`<![CDATA[${e.children[0].data}]]>`;case Lfe:case jfe:case zfe:return xWr(e,t,r);case Mfe:{let i=e,n=i.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!r&&i.parent&&dWr.has(i.parent.name)))return r||t.encodeEntities!=="utf8"?sW(n):Jfe(n);return n}}}function xWr(e,t,r){if(r==="foreign"){if(e.name=tKe.get(e.name)??e.name,e.parent&&hWr.has(e.parent.name))r=!1}if(!r&&mWr.has(e.name))r="foreign";let{name:i,children:n}=e,o=!r&&pWr.has(i),s=`<${i}${yWr(e.attribs,t,r)}`;if(n.length===0&&(r?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=r?"/>":" />";else{if(s+=">",n.length>0)s+=nKe(n,t,r);if(!o)s+=`</${i}>`}return s}function gWr(e){return e.replaceAll('"',""")}function yWr(e,t,r){if(!e)return"";let i=(t.encodeEntities??t.decodeEntities)===!1?gWr:r||t.encodeEntities!=="utf8"?sW:Yfe,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?rKe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${l}`:` ${l}="${i(c==null?"":String(c))}"`}return s}var dWr,pWr,mWr,hWr,sKe;var aKe=fs(()=>{H9();eKe();iKe();dWr=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),pWr=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),mWr=new Set(["svg","math"]),hWr=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));sKe=fWr});function cKe(e,t){return sKe(e,t)}function bWr(e,t){return ip(e)?e.children.map((r)=>cKe(r,t)).join(""):""}function aW(e){if(Array.isArray(e))return e.map(aW).join("");if(ou(e))return e.name==="br"?`
|
|
2
|
+
import"./chunks/index-83mk5vfd.js";import{$ as go,$a as Tyn,$b as mbn,$c as zbn,Aa as K0,Ab as jj,Ad as dEn,Ba as Ylr,Bb as tbn,Bd as Gk,C as ry,Ca as Jlr,Cb as rbn,Cc as $mr,Cd as pEn,D as Bgn,Da as dyn,Db as hv,Dd as mEn,E as jlr,Ea as pyn,Eb as eur,Ed as hEn,F as Vlr,Fa as Xre,Fb as Mj,Fd as ny,G as Ngn,Ga as myn,Gb as ibn,Gd as Lj,H as Lgn,Hb as nbn,Hd as fEn,I as jgn,Ia as uDe,Ib as obn,Id as xEn,J as zgn,Ja as hyn,Jb as sbn,Jd as gEn,K as Ugn,Ka as fyn,Kd as yEn,La as xyn,Lb as tur,Ld as bEn,M as rie,Ma as gyn,Mb as rur,Md as EEn,Na as yyn,Nb as iur,Nd as vEn,Oa as byn,Ob as nur,Od as AEn,P as Wk,Pa as Eyn,Pb as our,Pd as wEn,Q as Tlr,Qa as Qlr,Qb as sur,Qd as nie,R as Hk,Ra as vyn,Rb as aur,Rc as mur,Rd as bDe,S as ty,Sa as Ayn,Sb as cur,Sc as Pbn,Sd as SEn,Ta as wyn,Tb as lur,Tc as Rbn,Td as dDe,U as gDe,Ua as Syn,Ub as uur,Uc as Fbn,Ud as kEn,V as qgn,Va as kyn,Vb as abn,Vc as Mbn,Vd as Zm,W as Vt,Wa as Byn,Wb as cbn,Wc as $k,Wd as Pre,Xa as Cyn,Xb as lbn,Xc as Obn,Xd as BEn,Y as Klr,Ya as Dyn,Yb as ubn,Yc as Nbn,Z as $gn,Za as Iyn,Zb as dbn,Zc as Lbn,_ as f8,_a as _yn,_b as pbn,_c as jbn,aa as y8,ab as Pyn,ac as hbn,ad as Ubn,ba as el,bb as Ryn,bc as fbn,bd as qbn,ca as Ggn,cb as Fyn,cc as xbn,cd as $bn,da as Hgn,db as x8,dc as gbn,dd as Gbn,ea as Wgn,eb as Myn,ec as ybn,ed as Hbn,fa as Zgn,fb as sDe,fc as bbn,fd as Wbn,ga as Vgn,gb as Oyn,gc as Ebn,gd as Zbn,ha as Kgn,hb as Nyn,hc as vbn,hd as Vbn,ia as Ygn,ib as Lyn,ic as Abn,id as Kbn,ja as Jgn,jb as jyn,jc as aDe,jd as Ybn,ka as Qgn,kb as zyn,kc as Nj,kd as Jbn,la as Xgn,lb as Uyn,lc as wbn,ld as Qbn,ma as eyn,mb as qyn,mc as Sbn,md as Xbn,na as tyn,nb as $yn,nc as kbn,nd as eEn,oa as ryn,ob as Gyn,oc as Bbn,od as tEn,pa as iyn,pb as Hyn,pc as Cbn,qa as nyn,qb as Wyn,qc as Dbn,qd as rEn,ra as oyn,rb as Zyn,rc as Ibn,rd as iEn,sa as syn,sb as Vyn,sc as dur,sd as nEn,ta as f3e,tb as Kyn,tc as pur,td as Mlr,ua as ayn,ub as Yyn,uc as _lr,ud as oEn,va as cyn,vb as Jyn,vc as _bn,vd as sEn,wa as lyn,wb as Xlr,wc as Tbn,wd as aEn,xa as uyn,xb as Qyn,xc as yDe,xd as cEn,ya as oDe,yb as Xyn,yd as lEn,za as $j,zb as ebn,zd as uEn}from"./chunks/index-e86c8bvy.js";import{$d as HEr,Yd as f7,Zd as Svr,be as mPe}from"./chunks/index-jtzbfbxr.js";import{de as z0e}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 DS}from"./chunks/index-1phtzjk2.js";import{Ce as LWe,De as O_r,Ee as hFr,Fe as Dg,Ge as AJ,He as kU,Ie as _Er,Je as Sy,Ke as s7r,Le as p7,Me as zTr,Ne as BEr,Oe as TEr,Pe as m7r,Qe as i7r,Re as cxt,Se as MMr,Te as $qe,Ue as Gqe,Ve as Hqe,We as Vbr,Xe as i7,Ye as n7r,Ze as Ef,_e as m7,gf as nH,ke as DHe,le as sH,ne as ko,oe as S5,pe as Oge,qe as zge,re as Qb,se as EZ,te as vZ,ue as AZ,ve as yet,we as wZ,xe as y4,ye as srt,ze as ys}from"./chunks/index-e7drdbaa.js";import{jf as the,kf as Jzr}from"./chunks/index-7d748trp.js";import"./chunks/index-rkhex3pb.js";import{$f as krt,$g as qA,$h as zhe,$i as Lqe,$j as rzr,$k as Gme,$l as W7r,$m as Twr,$n as agt,Af as iV,Ag as da,Ah as R3,Ak as Nme,Am as o_r,An as Eh,Bf as Sl,Bg as ms,Bh as VJ,Bi as qT,Bl as td,Bm as Ko,Cf as kit,Cg as tp,Ch as Mgt,Ci as NA,Cj as kA,Cl as $he,Df as ZR,Dg as yb,Dh as F2,Di as WA,Dj as Ojr,Dl as Ghe,Ef as VR,Eg as Bme,Eh as Fl,Ei as LI,Ej as pzr,El as Hhe,Eo as jA,Ff as gr,Fh as x1,Fi as zqe,Fj as XGe,Fk as Qf,Fl as Whe,Fo as Qme,Gf as P4,Gh as OO,Gi as THe,Gj as $zr,Gk as XS,Gl as Zhe,Gm as IO,Gn as Yme,Go as cWe,Hf as nV,Hg as Ohe,Hh as f1,Hi as xOr,Hj as Gzr,Hk as e5,Hl as Vhe,Hm as Xxt,Ho as Xme,If as TR,Ig as dn,Ih as O0,Ii as DJ,Ij as pU,Ik as OH,Il as r5,Im as jJ,Io as OA,Jg as So,Jh as c8e,Ji as Gne,Jj as Nf,Jl as sP,Jm as lpe,Jn as xhr,Jo as bh,Kf as fw,Kg as pxt,Kh as Hgt,Ki as Que,Kj as KB,Kk as t5,Kl as i5,Km as upe,Kn as ghr,Ko as ehe,Lf as Gge,Lg as Nhe,Lh as Ggt,Li as Hne,Lj as Qjr,Ll as ma,Ln as zJ,Lo as YT,Mf as oV,Mh as ore,Mi as Ule,Mj as Xjr,Ml as Yo,Mn as dgt,Mo as s_r,Nf as gs,Ng as QT,Nh as Jgt,Ni as BJ,Nj as tpe,Nl as aP,Nm as Njr,Nn as pgt,Of as nr,Og as JS,Oh as kgt,Oi as ES,Oj as Hzr,Ok as Lme,Ol as Zi,On as azr,Pf as Je,Pg as kH,Ph as Bgt,Pi as qI,Pj as Wzr,Pk as LA,Pl as Khe,Pn as czr,Qf as Ro,Qg as XT,Qi as $I,Qj as bjr,Qk as vb,Ql as Yhe,Qn as mgt,Rf as Ks,Rg as eP,Rh as ZJ,Ri as $we,Rj as Ejr,Rk as GS,Rl as am,Rn as hgt,Ro as zA,Sf as Fh,Sg as Lhe,Sh as Qgt,Si as YEr,Sj as vjr,Sk as WT,Sl as $t,Sn as T1e,So as rE,Tf as qge,Tg as wb,Th as m8e,Ti as fa,Tj as Ajr,Tk as jme,Tl as kb,Tn as egt,To as vh,Ug as tP,Ui as Btt,Uj as wjr,Uk as BH,Ul as Xn,Un as ogt,Uo as $x,Vf as Art,Vg as rP,Vh as E_r,Vi as qhe,Vj as Zzr,Vk as zme,Vl as hs,Vm as Y6,Vn as PO,Vo as Afr,Wf as wrt,Wg as iP,Wi as k7,Wj as Ujr,Wk as Ume,Wl as C4,Wm as _wr,Wn as fgt,Wo as ya,Xg as nP,Xh as Ws,Xi as _6,Xj as qjr,Xk as qme,Xl as VT,Xm as M_r,Xn as RO,Yg as oP,Yi as woe,Yj as Wjr,Yk as D9,Yl as kn,Ym as Fwr,Yn as djr,Zf as Srt,Zg as jhe,Zi as Soe,Zj as ezr,Zk as $me,Zl as ht,Zm as DEr,Zn as c7e,_g as _9,_h as bb,_i as MT,_j as tzr,_m as Mwr,_n as sgt,ah as kh,aj as vS,ak as epe,an as Owr,ao as kz,bh as Sb,bi as QS,bj as bTe,bk as Yzr,bl as ao,bm as Pi,bn as Lwr,bo as cgt,ch as HA,ck as Kjr,cm as Q_r,co as GJ,dh as Jw,dj as dw,dk as ajr,dm as u$,do as lgt,eh as ZIr,ei as pc,ej as PHe,el as HS,em as Y_r,eo as Djr,fh as $it,fi as jt,fj as Olt,fl as Hme,fm as Zme,fo as xgt,gh as jye,gi as Xne,gj as Nlt,gm as Vr,go as wgt,hi as T9,hk as BA,ho as Ijr,ii as lm,ik as $S,in as yue,io as Cjr,jg as uOr,jh as Kie,ji as dc,jk as Cme,jn as R0,jo as tgt,kh as Yie,ki as d1,kk as Gx,kl as ZT,km as Ab,ko as Uie,lg as dOr,lh as Jie,li as co,ll as Wme,lm as bt,lo as Ez,mg as Ivr,mh as Qie,mi as pf,mm as Hx,mo as rhr,nf as Fhe,nh as Dhr,ni as yyr,nm as pa,no as cm,of as Mhe,oh as Ihr,oi as _hr,om as klt,oo as n5,pf as Sme,ph as jIe,pi as XI,pj as Eb,pk as GT,pl as cjr,pm as fl,pn as ljr,po as Bb,qf as ep,qh as d6,qi as cx,qk as Dme,qm as KT,qn as ujr,qo as Cb,rf as qS,ri as Gxt,rk as Ime,rm as Vme,rn as HJ,ro as Db,sf as kme,sh as po,si as O9,sk as _me,sm as Kme,sn as ggt,so as ed,tf as C9,th as Ygt,ti as $l,tk as HT,tl as R0r,tm as zt,tn as ygt,to as Jme,uf as st,ug as tu,uh as Ie,ui as OI,uk as Tme,ul as Lne,um as qx,un as bgt,uo as ZS,vf as kr,vg as UT,vh as M0,vi as ct,vj as aOr,vk as Pme,vl as khr,vm as Hie,vn as P3,vo as CH,wg as _i,wh as Nn,wi as Au,wk as Rme,wl as oH,wm as Wie,wn as FO,xf as fe,xg as sm,xh as KJ,xi as VGe,xk as Fme,xm as NWe,yf as xw,yg as Vf,yh as Vgt,yi as Uhe,yk as Mme,ym as wo,yn as Nge,yo as VS,zf as ft,zg as Ur,zh as P2,zk as Ome,zl as nm,zm as Rn,zo as KS}from"./chunks/index-gx72qzwf.js";import{$o as xf,$p as Qn,$q as wlt,$r as Bue,$s as rd,Ap as Z8,Aq as US,Ar as rgr,As as eTr,Bp as BAr,Bq as NHe,Br as lhr,Bs as kTr,Cp as CAr,Cq as DWe,Cr as $ie,Cs as tTr,Dp as VLr,Dq as Ux,Dr as qie,Ds as oTr,Ep as Zde,Eq as IWe,Es as xne,Fp as KLr,Fq as lH,Fs as i3,Gp as TAr,Gq as EH,Gr as h_r,Gs as une,Hp as YLr,Hq as vH,Hr as hw,Hs as rY,Ip as sRe,Iq as mR,Ir as _z,Is as iY,Jp as aRe,Js as tne,Kp as zU,Kq as kue,Ks as Slt,Lp as cRe,Lq as zgr,Mp as PAr,Mq as cs,Ms as xyr,Np as lRe,Nq as oFr,Ns as jwe,Op as RAr,Oq as tbr,Or as Nse,Pp as FAr,Pq as I8,Pr as I7,Ps as Hv,Qp as Rse,Qq as sfr,Qr as one,Qs as y7r,Rp as Fse,Rq as ane,Rr as lne,Rs as Ale,Sp as MAr,Sq as moe,Sr as Bi,Ss as AB,Tp as Mse,Tq as iRr,Tr as lOr,Ts as f6,Up as Er,Uq as nRr,Ur as IOr,Us as Xpe,Vp as k5,Vq as tY,Vr as PZ,Vs as Gie,Wp as Ht,Wr as Rf,Ws as wm,Xo as jAr,Xp as rx,Xq as wit,Xs as Qw,Yo as hde,Yp as BZ,Yq as Sit,Yr as x_,Ys as ua,Zp as jp,Zq as Frt,Zr as qse,Zs as Fbr,_o as Sn,_p as hy,_q as Mrt,_r as I$,_s as qp,ap as vne,aq as Jde,ar as En,as as DUe,at as ru,br as sd,bs as p$,bt as Ke,cp as Sr,cq as wzr,cr as lS,cs as m$,dp as mi,dq as Szr,dr as ele,ds as J$,ep as PI,er as IIr,es as ZNr,et as $T,fp as qB,fr as tle,fs as Q$,ft as Gf,gp as mde,gq as eT,gr as Hge,gs as Sne,gt as eme,hp as FB,hr as QZ,hs as Xfr,ip as Yq,is as t0r,it as ime,jp as OJ,jr as p1,js as a0r,kp as va,kq as zT,kr as he,ks as r0r,lp as qv,lq as XPr,ls as i0r,mp as MB,mr as Io,ms as m1,np as vje,ns as Thr,oq as qzr,pp as Ose,ps as Yle,qp as Uv,qq as cRr,qr as Rr,qs as H_r,rp as Ise,rq as Ztt,rr as A4,rs as W_r,sp as _se,sr as Pzr,ss as r3,tp as ZLr,tq as vme,tr as B9,ts as Pde,up as Ooe,uq as xH,ur as cne,us as Rde,ut as rp,vp as W6,vq as gH,vr as kJ,vs as Kle,vt as om,wp as qxe,wq as yH,wr as w3,ws as S_,wt as Xu,xp as Pse,xq as bH,xs as gze,yp as Z6,yq as wH,ys as bze,zp as Tse,zq as SH,zr as yoe,zs as STr,zt as WS}from"./chunks/index-wxxzncf6.js";import{Bt as jje,Dt as cH}from"./chunks/index-88nn119k.js";import{BB as Up,CB as xxr,DB as Ki,EB as Vzr,Ix as eu,Kx as q4,Wx as lc,ez as WJ,iB as et,jy as Hs,pB as Sgt,sv as a1e,wB as yh,xB as U4,zB as Pc}from"./chunks/index-ahk2enhj.js";import{WC as u}from"./chunks/index-gdatxzx2.js";import"./chunks/index-qefyds15.js";import{$C as aYr,_C as to,aD as E,bD as Kx,cD as fs,dD as ce}from"./chunks/index-3dxmcttv.js";function BVe(e){return e===0||e>=55296&&e<=57343||e>1114111}function CVe(e){if(BVe(e))return 65533;if(e>=128&&e<=159)return UHr[e-128]||e;return e}function DVe(e){return BVe(e)?65533:e}var UHr;var IVe=fs(()=>{UHr=[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 _Ve(e,t,r,i,n,o){let a=e.length,c=o*90,l=0,d=()=>{let L=e0[e.charCodeAt(l++)];return L<o?L:L*91-c+e0[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,H){let V=0,ee=H,q=H+L;while(ee<q){let S=e0[e.charCodeAt(l++)];if(S<89)V+=S,h[ee++]=V;else if(S===89){let I=e0[e.charCodeAt(l++)]+2;while(I--)h[ee++]=++V}else{let I=e0[e.charCodeAt(l++)];V+=89+(I<90?I*91+e0[e.charCodeAt(l++)]:e0[e.charCodeAt(l++)]*8281+e0[e.charCodeAt(l++)]*91+e0[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,H){for(let V=0;V<L;V++){let ee=H+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 H=0;H<2;H++){let V=b[L*2+H],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=e0[e.charCodeAt(l++)];if(L>=o)L=L*91-c+e0[e.charCodeAt(l++)];let H=h[L];if(H<0){let V=f[L],ee=V+g[L];while(V<ee)k[N++]=F[V++]}else k[N++]=H}return k}var e0;var TVe=fs(()=>{e0=(()=>{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 Dfe;var PVe=fs(()=>{TVe();Dfe=_Ve("!}.&u%}'&}*'~!6*)%&,~!J~!J~%L~y<~!R,~~%Lu~~#GD~~#|)1#%}^%}2%+#.##%##%}&%##%'#%##&%#%#'%#&#%#&#'#%%#&#%##%#)%''%&%#%#'%#%%#%%}%%%#%#&(23#%%#&-%0%('1#(##%#'##+%'*.:1}#%#6-+(%'%%#%%%}#L'2351&('%}&/N'(0(/*-%(%%}#'+&T%7.2}#&%&#%#36/5##%&%%#&#%%#))2%%##%&&'0~!#*+&'%1~!%).'3q?&%'1~!.##%6(~!+%%%(Gw'rT~!E#<nA%#jZ~!H%(~!42##~!*31&~!G%U~#)5~#`3~!J~!Z~%]~%Y~%C~!q~!u~#kz~%#~!6'~!D~!U~!?~#T~!c%~!G#'~%7|~!G~!J~!G&~#pb~(Df}#%}*&}#%##%##%##&#-}&'#'&%#.++}%mI,#,@&(}*%}*'%&##&#%##%}&0}#.},U},%}+%}&%}#%##&}B%(}(%}+%)})%##%#&}&%##%&}<%}>%#%&}*%}(%}9%}/%})%}*%}*%}?&}&%}3%}&*#%})%#%#)}#&#-#+*%E%%'%'#%}#*V##&##I}#&&##%&%#&&Qf%%))w/0+&%#(#.%-''''++++7}>%4'',##1,#%#&%##&#'##&#*#9)%&%}#*}%,#+P(%A&%#'&##wSD',9E00#y#@}(+}&%&>~!#~!X}#*}(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5<H|Eg>unwfh;9:4E|YjQsBt|vjx'hYq3!(?C2F|J:2<BaY?C2F|GOu!5x,g|p{ah!-(?C2F|c9:4E|OjXuvvNr}:Rh&i[w*t|cd+U#jJvsu)vsSn~Mkfrmu9p}u7vwv]So!McW#Xa!ax5@A5aY:5;5<H|>kJv~vYrquJu3x4ib#T)2@SmZM?C2F|Bj:rmu9@xPhI(a*a#U#`a3-5Abb|L~@:RhK9:4E|0@52B5G|#C::aY?C2F|-:2<BaY?C2F|.5Jvk!a)javYrquJu3x4ia#T)2@SmYM?C2F|HAxPhH(!a#U#`a*-5Abb|4~@:RhJ9:4E|R@52B5G|F:2<BaY?C2F|Sc^#Xa2j=Qq5CJvB!-g<v{z;hhM?C2F|Zi[vrv{z;hiM?C2F|XKsA>!a)-g<v{z;h[eb?C2F|]i[vrv{z;h]eb?C2F|^iZu.vix,hZq3ah!.(?C2F|QOu!5ShXM:2<BaY?C2F|P",13494,2713,49,25,61)});var EP;var Ife=fs(()=>{EP=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 Mc;var RVe=fs(()=>{(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"})(Mc||(Mc={}))});function FVe(e){return e-nu.ZERO>>>0<=9}function qHr(e){return(e|KH)-nu.LOWER_A>>>0<=5}function $Hr(e){return(e|KH)-nu.LOWER_A>>>0<=25}function GHr(e){return e===nu.EQUALS||$Hr(e)||FVe(e)}class _fe{decodeTree;emitCodePoint;errors;state=iu.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=t0.Strict;runConsumed=0;constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r}startEntity(e){this.decodeMode=e,this.state=iu.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case iu.EntityStart:{if(e.charCodeAt(t)===nu.NUM)return this.state=iu.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=iu.NamedEntity,this.stateNamedEntity(e,t)}case iu.NumericStart:return this.stateNumericStart(e,t);case iu.NumericDecimal:return this.stateNumericDecimal(e,t);case iu.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)|KH)===nu.LOWER_X)return this.state=iu.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=iu.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(FVe(o)||qHr(o)){let s=o<=nu.NINE?o-nu.ZERO:(o|KH)-nu.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)-nu.ZERO;if(o>>>0>9)return this.result=i,this.consumed=n,this.emitNumericEntity(o+nu.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===nu.SEMI)this.consumed+=1;else if(this.decodeMode===t0.Strict)return 0;if(this.emitCodePoint((this.decodeTree===EP?DVe:CVe)(this.result),this.consumed),this.errors){if(e!==nu.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===t0.Attribute&&(i===0||t>1||GHr(r))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:r}=this,i=e.length,n=this.decodeMode===t0.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=r[o];while(t<i){while((c&(Mc.VALUE_LENGTH|Mc.FLAG13))===0&&(c&Mc.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&Mc.JUMP_TABLE,f=(c&Mc.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&(Mc.VALUE_LENGTH|Mc.FLAG13))===Mc.FLAG13){let m=(c&Mc.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&Mc.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&Mc.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===nu.SEMI)return this.emitNamedEntityData(o,l,a+s);if(l===1)return this.flushAndEmitLegacyOrReject(a,s,d,l)}let p=HHr(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&Mc.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]&Mc.VALUE_MASK:i[e+1],r),t===3)this.emitCodePoint(i[e+2],r);return r}end(){switch(this.state){case iu.NamedEntity:return this.result!==0&&(this.decodeMode!==t0.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case iu.NumericDecimal:return this.emitNumericEntity(0,2);case iu.NumericHex:return this.emitNumericEntity(0,3);case iu.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function HHr(e,t,r,i){let n=(t&Mc.BRANCH_LENGTH)>>7,o=t&Mc.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 nu,KH=32,iu,t0;var MVe=fs(()=>{IVe();Ife();RVe();PVe();Ife();(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"})(nu||(nu={}));(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"})(iu||(iu={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(t0||(t0={}))});function a5(e){return e===br.Space||e===br.NewLine||e===br.Tab||e===br.FormFeed||e===br.CarriageReturn}function z9(e){return e===br.Slash||e===br.Gt||a5(e)}function WHr(e){return e>=br.LowerA&&e<=br.LowerZ||e>=br.UpperA&&e<=br.UpperZ}class U9{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 _fe(e?EP:Dfe,(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(z9(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?!z9(e):WHr(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(z9(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:ZHr.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(z9(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(a5(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(z9(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(!a5(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(!a5(e))this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===br.Eq||z9(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(um.NoValue,this.sectionStart),this.sectionStart=-1,this.state=We.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!a5(e))this.cbs.onattribend(um.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(!a5(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?um.Double:um.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(a5(e)||e===br.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(um.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?t0.Strict:this.baseState===We.Text||this.baseState===We.InSpecialTag?t0.Legacy:t0.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,um,oi,ZHr;var Tfe=fs(()=>{MVe();(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"})(um||(um={}));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])},ZHr=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 G9{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??U9)(this.options,this),this.foreignContext=[Pb.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?.(OVe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==Pb.None}isVoidElement(e){return this.htmlMode&&KHr.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]===Pb.Svg)return qVe.get(r)??r;if(this.foreignContext.length>1){let i=qVe.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&&VHr.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(Pb.Svg);else if(e==="math")this.foreignContext.unshift(Pb.MathML);else if(UVe.has(e))this.foreignContext.unshift(Pb.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&&(YHr.has(t)||UVe.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+=OVe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===um.Double?'"':e===um.Single?"'":e===um.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(JHr),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?zVe:r.slice(0,zVe.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(Pb.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 OVe,q9,Zs,$9,NVe,LVe,jVe,VHr,zVe="doctype",KHr,YHr,UVe,qVe,Pb,JHr;var Pfe=fs(()=>{Tfe();({fromCodePoint:OVe}=String),q9=new Set(["input","option","optgroup","select","button","datalist","textarea"]),Zs=new Set(["p"]),$9=new Set(["h1","h2","h3","h4","h5","h6","p"]),NVe=new Set(["thead","tbody"]),LVe=new Set(["dd","dt"]),jVe=new Set(["rt","rp"]),VHr=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",Zs],["h1",$9],["h2",$9],["h3",$9],["h4",$9],["h5",$9],["h6",$9],["select",q9],["input",q9],["output",q9],["button",q9],["datalist",q9],["textarea",q9],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",LVe],["dt",LVe],["address",Zs],["article",Zs],["aside",Zs],["blockquote",Zs],["details",Zs],["div",Zs],["dl",Zs],["fieldset",Zs],["figcaption",Zs],["figure",Zs],["footer",Zs],["form",Zs],["header",Zs],["hr",Zs],["main",Zs],["nav",Zs],["ol",Zs],["pre",Zs],["section",Zs],["table",Zs],["ul",Zs],["rt",jVe],["rp",jVe],["tbody",NVe],["tfoot",NVe]]),KHr=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),YHr=new Set(["math","svg"]),UVe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),qVe=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"})(Pb||(Pb={}));JHr=/\s|\//});var YH={};Kx(YH,{CDATA:()=>Ufe,Comment:()=>Nfe,Directive:()=>Ofe,Doctype:()=>QHr,ElementType:()=>pn,Root:()=>Ffe,Script:()=>Lfe,Style:()=>jfe,Tag:()=>zfe,Text:()=>Mfe,isTag:()=>Rfe});function Rfe(e){return e.type===pn.Tag||e.type===pn.Script||e.type===pn.Style}var pn,Ffe,Mfe,Ofe,Nfe,Lfe,jfe,zfe,Ufe,QHr;var H9=fs(()=>{(function(e){e.Root="root",e.Text="text",e.Directive="directive",e.Comment="comment",e.Script="script",e.Style="style",e.Tag="tag",e.CDATA="cdata",e.Doctype="doctype"})(pn||(pn={}));Ffe=pn.Root,Mfe=pn.Text,Ofe=pn.Directive,Nfe=pn.Comment,Lfe=pn.Script,jfe=pn.Style,zfe=pn.Tag,Ufe=pn.CDATA,QHr=pn.Doctype});class $fe{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 $Ve(this,e)}}function ou(e){return Rfe(e)}function iW(e){return e.type===pn.CDATA}function YA(e){return e.type===pn.Text}function Gfe(e){return e.type===pn.Comment}function XHr(e){return e.type===pn.Directive}function eWr(e){return e.type===pn.Root}function ip(e){return Object.hasOwn(e,"children")}function $Ve(e,t=!1){let r;if(YA(e))r=new vP(e.data);else if(Gfe(e))r=new QH(e.data);else if(ou(e)){let i=t?qfe(e.children):[],n=new rW(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(iW(e)){let i=t?qfe(e.children):[],n=new tW(i);for(let o of i)o.parent=n;r=n}else if(eWr(e)){let i=t?qfe(e.children):[],n=new AP(i);for(let o of i)o.parent=n;if(e["x-mode"])n["x-mode"]=e["x-mode"];r=n}else if(XHr(e)){let i=new XH(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 qfe(e){let t=e.map((r)=>$Ve(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 JH,vP,QH,XH,eW,tW,AP,rW;var Hfe=fs(()=>{H9();JH=class JH extends $fe{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};vP=class vP extends JH{type=pn.Text;get nodeType(){return 3}};QH=class QH extends JH{type=pn.Comment;get nodeType(){return 8}};XH=class XH extends JH{type=pn.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};eW=class eW extends $fe{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}};tW=class tW extends eW{type=pn.CDATA;get nodeType(){return 4}};AP=class AP extends eW{type=pn.Root;get nodeType(){return 9}};rW=class rW extends eW{name;attribs;type;constructor(e,t,r=[],i=e==="script"?pn.Script:e==="style"?pn.Style:pn.Tag){super(r);this.name=e,this.attribs=t,this.type=i}get nodeType(){return 1}get tagName(){return this.name}set tagName(e){this.name=e}get attributes(){return Object.keys(this.attribs).map((e)=>({name:e,value:this.attribs[e],namespace:this["x-attribsNamespace"]?.[e],prefix:this["x-attribsPrefix"]?.[e]}))}namespace;"x-attribsNamespace";"x-attribsPrefix"}});class c5{dom=[];root=new AP(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=GVe;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??GVe,this.elementCB=r??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new AP(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){if(this.done)return;this.done=!0,this.parser=null,this.handleCallback(null)}onerror(e){this.handleCallback(e)}onclosetag(){this.lastNode=null;let e=this.tagStack.pop();if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(this.elementCB)this.elementCB(e)}onopentag(e,t){let r=this.options.xmlMode?pn.Tag:void 0,i=new rW(e,t,void 0,r);this.addNode(i),this.tagStack.push(i)}ontext(e){let{lastNode:t}=this;if(t&&t.type===pn.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let r=new vP(e);this.addNode(r),this.lastNode=r}}oncomment(e){if(this.lastNode&&this.lastNode.type===pn.Comment){this.lastNode.data+=e;return}let t=new QH(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new vP(""),t=new tW([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let r=new XH(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 GVe;var JA=fs(()=>{H9();Hfe();Hfe();GVe={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function W9(e,t,r=!0,i=Number.POSITIVE_INFINITY){return HVe(e,Array.isArray(t)?t:[t],r,i)}function HVe(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&&ip(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function nW(e,t,r=!0){let i=Array.isArray(t)?t:[t];for(let n of i){if(ou(n)&&e(n))return n;if(r&&ip(n)&&n.children.length>0){let o=nW(e,n.children,!0);if(o)return o}}return null}function WVe(e,t){return(Array.isArray(t)?t:[t]).some((r)=>ou(r)&&e(r)||ip(r)&&WVe(e,r.children))}function tWr(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(ou(o)&&e(o))r.push(o);if(ip(o)&&o.children.length>0)n.unshift(0),i.unshift(o.children)}}var Wfe=fs(()=>{JA()});function Zfe(e,t){if(typeof t==="function")return(r)=>ou(r)&&t(r.attribs[e]);return(r)=>ou(r)&&r.attribs[e]===t}function rWr(e,t){return(r)=>e(r)||t(r)}function ZVe(e){let t=Object.keys(e).map((r)=>{let i=e[r];return Object.hasOwn(oW,r)?oW[r](i):Zfe(r,i)});return t.length===0?null:t.reduce(rWr)}function iWr(e,t){let r=ZVe(e);return r?r(t):!0}function nWr(e,t,r,i=Number.POSITIVE_INFINITY){let n=ZVe(e);return n?W9(n,t,r,i):[]}function oWr(e,t,r=!0){if(!Array.isArray(t))t=[t];return nW(Zfe("id",e),t,r)}function l5(e,t,r=!0,i=Number.POSITIVE_INFINITY){return W9(oW.tag_name(e),t,r,i)}function sWr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return W9(Zfe("class",e),t,r,i)}function aWr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return W9(oW.tag_type(e),t,r,i)}var oW;var Vfe=fs(()=>{JA();Wfe();oW={tag_name(e){if(typeof e==="function")return(t)=>ou(t)&&e(t.name);if(e==="*")return ou;return(t)=>ou(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)=>YA(t)&&e(t.data);return(t)=>YA(t)&&t.data===e}}});function KVe(e){return e===34?""":e===38?"&":e===39?"'":e===60?"<":e===62?">":" "}function VVe(e){return e>=128||e>=32&&e<64&&(cWr>>>e&1)===1}function sW(e){let{length:t}=e,r,i=0,n=0;while(n<t){let o=e.charCodeAt(n);if(!VVe(o)){let a=Math.min(n+32,t),c=n+1;while(c<a&&!VVe(e.charCodeAt(c)))c++;if(c<a){n=c;continue}if(c>=t)break;if(Kfe.lastIndex=c,!Kfe.test(e))break;n=Kfe.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+=KVe(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 YVe(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+=KVe(o),i=n+1}while(e.test(t));return r+t.substring(i)}function Yfe(e){return YVe(lWr,e)}function Jfe(e){return YVe(uWr,e)}var cWr=1342177476,Kfe,lWr,uWr;var JVe=fs(()=>{Kfe=/["&'<>\u0080-\uFFFF]/g;lWr=/["&\u{A0}]/gu;uWr=/[&<>\u{A0}]/gu});var QVe,XVe;var eKe=fs(()=>{JVe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(QVe||(QVe={}));(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"})(XVe||(XVe={}))});var tKe,rKe;var iKe=fs(()=>{tKe=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])),rKe=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 fWr(e,t={}){let r="length"in e?e:[e],i=t.xmlMode??!1,n="";for(let o=0;o<r.length;o++)n+=oKe(r[o],t,i);return n}function nKe(e,t,r){let i="";for(let n=0;n<e.length;n++)i+=oKe(e[n],t,r);return i}function oKe(e,t,r){switch(e.type){case Ffe:return nKe(e.children,t,r);case Ofe:return`<${e.data}>`;case Nfe:return`<!--${e.data}-->`;case Ufe:return`<![CDATA[${e.children[0].data}]]>`;case Lfe:case jfe:case zfe:return xWr(e,t,r);case Mfe:{let i=e,n=i.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!r&&i.parent&&dWr.has(i.parent.name)))return r||t.encodeEntities!=="utf8"?sW(n):Jfe(n);return n}}}function xWr(e,t,r){if(r==="foreign"){if(e.name=tKe.get(e.name)??e.name,e.parent&&hWr.has(e.parent.name))r=!1}if(!r&&mWr.has(e.name))r="foreign";let{name:i,children:n}=e,o=!r&&pWr.has(i),s=`<${i}${yWr(e.attribs,t,r)}`;if(n.length===0&&(r?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=r?"/>":" />";else{if(s+=">",n.length>0)s+=nKe(n,t,r);if(!o)s+=`</${i}>`}return s}function gWr(e){return e.replaceAll('"',""")}function yWr(e,t,r){if(!e)return"";let i=(t.encodeEntities??t.decodeEntities)===!1?gWr:r||t.encodeEntities!=="utf8"?sW:Yfe,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?rKe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${l}`:` ${l}="${i(c==null?"":String(c))}"`}return s}var dWr,pWr,mWr,hWr,sKe;var aKe=fs(()=>{H9();eKe();iKe();dWr=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),pWr=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),mWr=new Set(["svg","math"]),hWr=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));sKe=fWr});function cKe(e,t){return sKe(e,t)}function bWr(e,t){return ip(e)?e.children.map((r)=>cKe(r,t)).join(""):""}function aW(e){if(Array.isArray(e))return e.map(aW).join("");if(ou(e))return e.name==="br"?`
|
|
3
3
|
`:aW(e.children);if(iW(e))return aW(e.children);if(YA(e))return e.data;return""}function wP(e){if(Array.isArray(e))return e.map(wP).join("");if(ip(e)&&!Gfe(e))return wP(e.children);if(YA(e))return e.data;return""}function Qfe(e){if(Array.isArray(e))return e.map(Qfe).join("");if(ip(e)&&(e.type===pn.Tag||iW(e)))return Qfe(e.children);if(YA(e))return e.data;return""}var Xfe=fs(()=>{aKe();H9();JA()});function SP(e){let t=cW(SWr,e);return t?t.name==="feed"?EWr(t):vWr(t):null}function EWr(e){let t=e.children,r={type:"atom",items:l5("entry",t).map((o)=>{let{children:s}=o,a={media:lKe(s)};np(a,"id","id",s),np(a,"title","title",s);let c=cW("link",s)?.attribs.href;if(c)a.link=c;let l=QA("summary",s)||QA("content",s);if(l)a.description=l;let d=QA("updated",s);if(d)a.pubDate=new Date(d);return a})};np(r,"id","id",t),np(r,"title","title",t);let i=cW("link",t)?.attribs.href;if(i)r.link=i;np(r,"description","subtitle",t);let n=QA("updated",t);if(n)r.updated=new Date(n);return np(r,"author","email",t,!0),r}function vWr(e){let t=cW("channel",e.children)?.children??[],r={type:e.name.substr(0,3),id:"",items:l5("item",e.children).map((n)=>{let{children:o}=n,s={media:lKe(o)};np(s,"id","guid",o),np(s,"title","title",o),np(s,"link","link",o),np(s,"description","description",o);let a=QA("pubDate",o)||QA("dc:date",o);if(a)s.pubDate=new Date(a);return s})};np(r,"title","title",t),np(r,"link","link",t),np(r,"description","description",t);let i=QA("lastBuildDate",t);if(i)r.updated=new Date(i);return np(r,"author","managingEditor",t,!0),r}function lKe(e){return l5("media:content",e).map((t)=>{let{attribs:r}=t,i={medium:r.medium,isDefault:!!r.isDefault};for(let n of AWr)if(r[n])i[n]=r[n];for(let n of wWr)if(r[n])i[n]=Number.parseInt(r[n],10);if(r.expression)i.expression=r.expression;return i})}function cW(e,t){return l5(e,t,!0,1)[0]}function QA(e,t,r=!1){return wP(l5(e,t,r,1)).trim()}function np(e,t,r,i,n=!1){let o=QA(r,i,n);if(o)e[t]=o}function SWr(e){return e==="rss"||e==="feed"||e==="rdf:RDF"}var AWr,wWr;var uKe=fs(()=>{Vfe();Xfe();AWr=["url","type","lang"],wWr=["fileSize","bitrate","framerate","samplingrate","channels","duration","height","width"]});function kWr(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 dKe(e,t){let r=[],i=[];if(e===t)return 0;let n=ip(e)?e:e.parent;while(n)r.unshift(n),n=n.parent;n=ip(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 Bh.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 Bh.FOLLOWING|Bh.CONTAINED_BY;return Bh.FOLLOWING}if(a===e)return Bh.PRECEDING|Bh.CONTAINS;return Bh.PRECEDING}function BWr(e){return e=e.filter((t,r,i)=>!i.includes(t,r+1)),e.sort((t,r)=>{let i=dKe(t,r);if(i&Bh.PRECEDING)return-1;if(i&Bh.FOLLOWING)return 1;return 0}),e}var Bh;var pKe=fs(()=>{JA();(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"})(Bh||(Bh={}))});function kP(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 CWr(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 DWr(e,t){if(kP(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 IWr(e,t){kP(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 _Wr(e,t){if(kP(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 TWr(e,t){kP(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 mKe=()=>{};function hKe(e){return ip(e)?e.children:[]}function fKe(e){return e.parent||null}function PWr(e){let t=fKe(e);if(t!=null)return hKe(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 RWr(e,t){let{attribs:r}=e;return r?.[t]}function FWr(e,t){let{attribs:r}=e;return r!=null&&Object.hasOwn(r,t)&&r[t]!=null}function MWr(e){return e.name}function OWr(e){let{next:t}=e;while(t!==null&&!ou(t))({next:t}=t);return t}function NWr(e){let{prev:t}=e;while(t!==null&&!ou(t))({prev:t}=t);return t}var xKe=fs(()=>{JA()});var e0e={};Kx(e0e,{DocumentPosition:()=>Bh,append:()=>IWr,appendChild:()=>DWr,compareDocumentPosition:()=>dKe,existsOne:()=>WVe,filter:()=>W9,find:()=>HVe,findAll:()=>tWr,findOne:()=>nW,getAttributeValue:()=>RWr,getChildren:()=>hKe,getElementById:()=>oWr,getElements:()=>nWr,getElementsByClassName:()=>sWr,getElementsByTagName:()=>l5,getElementsByTagType:()=>aWr,getFeed:()=>SP,getInnerHTML:()=>bWr,getName:()=>MWr,getOuterHTML:()=>cKe,getParent:()=>fKe,getSiblings:()=>PWr,getText:()=>aW,hasAttrib:()=>FWr,innerText:()=>Qfe,nextElementSibling:()=>OWr,prepend:()=>TWr,prependChild:()=>_Wr,prevElementSibling:()=>NWr,removeElement:()=>kP,removeSubsets:()=>kWr,replaceElement:()=>CWr,testElement:()=>iWr,textContent:()=>wP,uniqueSort:()=>BWr});var lW=fs(()=>{uKe();pKe();Vfe();mKe();Wfe();Xfe();xKe()});var yKe={};Kx(yKe,{DefaultHandler:()=>c5,DomHandler:()=>c5,DomUtils:()=>e0e,ElementType:()=>YH,Parser:()=>G9,QuoteType:()=>um,Tokenizer:()=>U9,createDocumentStream:()=>LWr,getFeed:()=>SP,parseDocument:()=>gKe,parseFeed:()=>zWr});function gKe(e,t){let r=new c5(void 0,t);return new G9(r,t).end(e),r.root}function LWr(e,t,r){let i=new c5((n)=>e(n,i.root),t,r);return new G9(i,t)}function zWr(e,t=jWr){return SP(gKe(e,t).children)}var jWr;var bKe=fs(()=>{Pfe();Pfe();JA();JA();H9();Tfe();lW();lW();lW();jWr={xmlMode:!0}});var vKe=E(function(sBo,EKe){EKe.exports=(e)=>{if(typeof e!=="string")throw TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}});var wKe=E(function(qWr){/*!
|
|
4
4
|
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
|
|
5
5
|
*
|
|
@@ -1035,7 +1035,7 @@ ${aA(e.cont)}`}}function sto(e,t){return t.map((r,i,{length:n})=>ato(e,r,i===n-1
|
|
|
1035
1035
|
`).find((b)=>b.startsWith("data: "));if(!d)continue;let p;try{let b=Oqr.safeParse(JSON.parse(d.slice(6)));if(!b.success)continue;p=b.data}catch{return await yme(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 yme(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:Fqr(a)}}}s=await kWe(i,t,r)}return{success:!1,error:"Stream ended without a terminal event"}}class Eme extends Error{timeoutMs;constructor(e){super(`request timed out after ${e}ms`);this.timeoutMs=e,this.name="A2ARequestTimeoutError"}}class jT extends Error{timeoutMs;constructor(e){super(`A2A stream stalled waiting for final event after ${e}ms`);this.timeoutMs=e,this.name="A2AStreamIdleTimeoutError"}}async function Gqr(e,t,r,i,n){return xme((o)=>e(t,{...r,signal:o}),{timeoutMs:i,onTimeout:()=>new Eme(i),signal:n})}async function kWe(e,t,r){try{return await xme(()=>e.read(),{timeoutMs:t,onTimeout:()=>new jT(t),signal:r})}catch(i){if(i instanceof jT||r?.aborted)await yme(e,i);throw i}}async function yme(e,t){try{await e.cancel(t)}catch{}}function Hqr(e){if(e instanceof Eme||e instanceof jT)return!1;return e instanceof Error}function gme(e,t){let r=t>1?` after ${t} attempts`:"";if(e instanceof jT)return`${e.message}${r}`;let i=he(e,"Unknown network error");return`Failed to reach remote agent${r}: ${i}`}async function hH(e,t={},r={}){let i=t.fetch??globalThis.fetch,n=r.signal;n?.throwIfAborted();let o={requestTimeoutMs:t.requestTimeoutMs??Nqr,streamIdleTimeoutMs:t.streamIdleTimeoutMs??Lqr,maxNetworkAttempts:t.maxNetworkAttempts??jqr},s=qqr(e.agent),a=_i(r.userPermissionLevel);if(!s.ok){let p=t.entityService?await AWe(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&&!wWe(c)){let p=await AWe(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(!wWe(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 bh(c,{fetch:i,timeoutMs:o.requestTimeoutMs,signal:n});if(!p.ok){if(OA(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 SWe(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 bh(c,{fetch:i,timeoutMs:o.requestTimeoutMs,signal:n});if(!d.ok){if(OA(d.reason))return{success:!1,error:d.error};return{success:!1,error:`Could not fetch Agent Card from https://${c}`}}return SWe(d.card.url,e.message,i,t.requestSigner,o,n)}function CWe(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:zqr,visibility:"trusted",sideEffects:"external",handler:async(t,r)=>{let i=Uqr.safeParse(t);if(!i.success)return{success:!1,error:`Invalid input: ${i.error.message}`};return hH(i.data,e,{userPermissionLevel:r.userPermissionLevel,...r.signal?{signal:r.signal}:{}})}}}var Wqr=30000,Zqr=u.looseObject({result:u.looseObject({parts:u.array(u.looseObject({kind:u.string(),data:u.unknown()}))})});function Wf(e,t){return{status:"refused",code:e,error:t}}async function _We(e,t,r){let i=e.trim().toLowerCase(),n=await r.entityService?.getEntity({entityType:"agent",id:i,visibilityScope:_i("admin")});if(!n)return Wf("agent_not_saved",`Agent ${i} is not saved.`);if(n.metadata.status==="archived")return Wf("agent_archived",`Agent ${i} is archived.`);if(!await r.isContactApproved?.(i))return Wf("agent_not_approved",`Agent ${i} is not approved yet. Approve it first.`);let{requestSigner:o}=r;if(!o)return Wf("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??Wqr,c=await bh(i,{fetch:s,timeoutMs:a});if(!c.ok)return Wf("agent_card_unavailable",c.error);if(!c.card.extensions.includes(US))return Wf("not_offered",`${i} does not offer shared entities.`);let l={"Content-Type":"application/json","X-A2A-Extensions":US},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 Wf("peer_failed",he(h,`${i} did not answer`))}if(p.status===404)return{status:"not-found"};if(!p.ok)return Wf("peer_failed",`${i} answered HTTP ${p.status}`);let m=Zqr.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 TWe(e,t){let r=await _We(e.agent,{op:"list"},t);if(r.status!=="answered")return r;let i=r.data.map((n)=>DWe.safeParse(n)).find((n)=>n.success)?.data;return i?{status:"found",entities:i.entities}:Wf("unreadable_answer",`${r.agentId} did not answer with a list.`)}async function PWe(e,t){let r=await _We(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)=>IWe.safeParse(c)).find((c)=>c.success)?.data;if(s?.entityType!==e.entityType||s.id!==e.id)return Wf("unreadable_answer",`${i} did not answer with the entity asked for.`);let a=Wf("unverified",`${i} did not sign what it served, so it was not taken.`);if(s.contentHash!==Ht(s.markdown))return a;try{if((await JHe(lH(s),s.attestation.signature,s.attestation.keyId,new OT({fetch:(l)=>n(l,{signal:AbortSignal.timeout(o)})}))).domain!==i)return a}catch{return a}return{status:"found",entity:s}}var Vqr=new Set(["agent_not_saved","agent_not_approved","agent_archived"]);function FWe(e,t){let r="code"in e&&Vqr.has(e.code??"")?"permission_denied":"handler_failed",i="error"in e?e.error:t;return new Rr(r,{publicMessage:B9(i)})}function Kqr(e){return[e,"","Asked on behalf of a visitor to another brain's site. Answer briefly, from your own public content, and cite what you draw on."].join(`
|
|
1037
1037
|
`)}async function RWe(e,t,r,i){let n=AbortSignal.timeout(i),o=(c)=>new Rr("deadline_exceeded",{publicMessage:`${t} did not answer within ${i} ms`,cause:c}),s;try{s=await hH({agent:t,message:r},{...e,maxNetworkAttempts:1},{requireSaved:!0,signal:n})}catch(c){if(n.aborted)throw o(c);throw new Rr("handler_failed",{message:he(c,`${t} did not answer`),publicMessage:`${t} did not answer`,cause:c})}if(n.aborted)throw o();if(!("success"in s)||s.success!==!0)throw FWe(s,`${t} did not answer`);let a=vme.safeParse(s.data);if(!a.success)throw new Rr("handler_failed",{publicMessage:`${t} gave no readable answer`});if(a.data.state!=="completed")throw new Rr("handler_failed",{publicMessage:B9(`${t} did not answer: ${a.data.response}`)});return a.data}var fH={everyProcess:!0};function MWe(e,t,r={networkAskTimeoutMs:30000,turnTimeoutMs:90000}){e.answer(xH,({request:{agent:i,question:n}})=>RWe(t,i,Kqr(n),r.networkAskTimeoutMs),fH),e.answer(gH,({request:{agent:i,message:n}})=>RWe(t,i,n,r.turnTimeoutMs),fH),e.answer(EH,({request:i})=>PWe(i,t),fH),e.answer(vH,({request:i})=>TWe(i,t),fH),e.answer(yH,async({request:{agent:i,instruction:n,selection:o,userPermissionLevel:s}})=>{let a=await hH({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 FWe(a,"Agent call failed");let c=vme.safeParse(a.data);if(!c.success)throw new Rr("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(bH,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 OWe={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.790",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 AH(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 Jqr={"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"},Qu=(e)=>AH(e,Jqr);function Qqr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(vh(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();await VHe(i,n.privateJwk,n.keyId)}}function Xqr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(vh(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();return{keyId:n.keyId,signature:YHe(i,n.privateJwk)}}}function Ame(e,t,r){let i=Qqr(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:wH,schema:SH}).has(n.trim().toLowerCase()))}}async function e$r(e,t,r){if(!r.cardReady)return;return lWe({character:e.identity.get(),profile:e.identity.getProfile(),version:OWe.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 t$r(e,t,r,i){let n=new URL(r.url),o=new URL(`${n.pathname}${n.search}`,$x(r)),s=await KHe({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 r$r(e,t,r){let i=new LWe,n=e.agent;return i.get("/.well-known/agent-card.json",async(o)=>{let s=await e$r(e,t,r);if(!s)return Qu(o.json({error:"Agent Card not ready"},503));return Qu(o.json(s))}),i.get("/.well-known/agent-directory.json",async(o)=>{let s=await uWe(e.entityReads);return Qu(o.json(s))}),i.get("/a2a",(o)=>Qu(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),i.options("/a2a",()=>Qu(new Response(null,{status:204}))),i.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return Qu(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await t$r(e,r,o.req.raw,s)}catch{return Qu(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return Qu(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let l=mWe.safeParse(c);if(!l.success)return Qu(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(LHe(o.req.raw.headers)){let p=l.data.method==="message/send"?jHe(l.data.params):void 0,m=p?.op==="list"?await qHe(e.entityReads,a.permissionLevel):await UHe(e.entityReads,a.permissionLevel,p,Xqr(e));if(!m)return Qu(o.json({error:"Not found"},404));return Qu(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=bWe.safeParse(l.data.params??{});if(!p.success)return Qu(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:l.data.id}));let m=EWe(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 Qu(o.json(m));return Qu(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await xWe(l.data,{taskManager:r.taskManager,turnSupervisor:r.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:r.publicAsks});return Qu(o.json(d))}),i}function wme(e={}){let t=Eh({id:"a2a",config:aWe,setup:(o)=>{let{config:s}=o,a=Ko(o),{servesHttp:c}=a,l=Ame(a,s,e),d={cardReady:!1,servesHttp:c,taskManager:new hme,turnSupervisor:new fme,jwksResolver:new OT(e.fetch?{fetch:e.fetch}:{}),clientDeps:l,publicAsks:new mme(s.publicAsks,a.classRuntimeState)};if(c)a.endpoint({label:"A2A",url:"/a2a",priority:25}),a.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),a.logger.info("A2A interface registered",{domain:a.domain});else a.logger.info("A2A interface registered in tool-only mode",{domain:a.domain});return a.ready(()=>{d.cardReady=!0}),d}}),r=NWe(t,(o)=>{let s=Ko(o);MWe(s,Ame(s,o.config,e),{networkAskTimeoutMs:o.config.networkAskTimeoutMs,turnTimeoutMs:o.config.turnTimeoutMs})}),i=wo(r,(o)=>{let{config:s,state:a}=o;if(!a.servesHttp)return[];let c=Ko(o),l=r$r(c,s,a),d=(m)=>Promise.resolve(l.fetch(m)),p=(m,h)=>({path:m,method:h,public:!0,handler:d});return[p("/.well-known/agent-card.json","GET"),p("/.well-known/agent-directory.json","GET"),p("/a2a","GET"),p("/a2a","POST"),p("/a2a","OPTIONS")]}),n=qx(i,(o)=>{let{state:s}=o,{logger:a}=Ko(o);return{id:"a2a",start:async()=>{if(s.servesHttp)a.info("A2A mounted on shared webserver host");else a.info("A2A running without webserver routes")},stop:async()=>{await s.turnSupervisor.close(),a.info("A2A server stopped")}}});return Rn(n,(o)=>{let{config:s}=o,a=Ko(o),c=()=>CWe(Ame(a,s,e));return[{...c(),handler:(l,d)=>c().handler(l,d)}]})}var i$r=wme(),jWe=i$r;function Ah(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function UA(e,t){return{registration:e,actionIds:t.map((r)=>r.name)}}var n$r=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function wh(e){return n$r.format(new Date(e))}function Sh(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function Rc(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function DH(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function YS(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 o$r={"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 ihe(e){let t=o$r[e];if(t)return t;let r=e.replaceAll(/[._-]+/g," ").trim();return r.length===0?e:co(r)}var nhe=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(Ah,u.number().int().min(0).max(1e5)).default(0),limit:u.preprocess(Ah,u.number().int().min(1).max(100)).default(25)}),zWe=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()}),s$r=u.strictObject({userId:u.string().min(1),displayName:u.string().min(1)}),a$r=u.strictObject({query:nhe,events:u.array(zWe),selectedEvent:zWe.optional(),users:u.array(s$r),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 UWe(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 qWe(e,t){return e?t.get(e)??"Former Admin":"System"}function $We(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 rhe=hs({id:"audit",label:"Audit",priority:90,permission:"admin",query:nhe,data:a$r,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:ihe(r.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:qWe(r.actorUserId,t)},{label:"Action",value:r.action},{label:"Target",value:$We(r,t)},{label:"Occurred",value:wh(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:ihe(o.action),description:`${qWe(o.actorUserId,t)} \u2192 ${$We(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 GWe(e){let t=e.studio.source({definition:rhe,bind:(r)=>rhe.bind(r,{load:async({query:i})=>{let n=Sh(e),o=i.get(nhe),[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(UWe),...s.selectedEvent?{selectedEvent:UWe(s.selectedEvent)}:{},users:DH(a),actions:s.actions.map(({action:c,count:l})=>({value:c,label:ihe(c),count:l})).sort((c,l)=>c.label.localeCompare(l.label)),total:s.total}},actions:[]})});return UA(t,rhe.actions)}var Zf=u.strictObject({status:u.string()}),IH=u.strictObject({status:u.string(),setupUrl:u.url(),expiresAt:u.string()});function I9(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var _H=u.strictObject({type:u.string(),displayName:u.string(),subjectLabel:u.string(),deliveryModes:u.array(u.enum(["automatic","manual"]))});function TH(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function PH(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function RH(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 c$r}from"crypto";var HWe=new Set(["claimed","expired","cancelled"]),l$r=new Set(["claimed","cancelled"]),lhe=u.strictObject({state:u.enum(["pending","history"]).optional().default("pending"),selected:u.string().trim().min(1).max(200).optional(),offset:u.preprocess(Ah,u.number().int().min(0)).optional().default(0),limit:u.preprocess(Ah,u.number().int().min(1).max(100)).optional().default(25)}),KWe=u.strictObject({status:u.string(),setupUrl:u.url().nullable(),expiresAt:u.string().nullable()}),u$r=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"])}),YWe=u.strictObject({invitationId:u.string().min(1)}),d$r=u.strictObject({invitationId:u.string().min(1),deliveryAttemptId:u.string().min(1)}),JWe=u.strictObject({invitationId:u.string(),state:u.string()}),ahe=Vr({name:"create-invitation",label:"Add a person",permission:"admin",input:u$r,output:KWe}),uhe=Vr({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:YWe,output:KWe}),dhe=Vr({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:YWe,output:JWe}),phe=Vr({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:d$r,output:JWe}),WWe=u.strictObject({id:u.string(),displayName:u.string(),role:u.string(),state:u.string(),destination:u.string(),updatedAt:u.number(),deliveryAttemptId:u.string().optional()}),p$r=u.strictObject({query:lhe,idempotencyKey:u.string(),channels:u.array(_H),invitations:u.array(WWe),selectedInvitation:WWe.optional(),selectedTotal:u.number().int().nonnegative(),pendingCount:u.number().int().nonnegative(),historyCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()});function che(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 ohe(e,t){let r=che(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 QWe(e,t){let r=che(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")?[ohe(e,"create-invitation-unavailable")]:[],n=che(e,"invitations");if(n.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=ohe(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,ohe(e,"invitation-filters"),n,{...o,presentation:"disclosure",blocks:[...o.blocks,r,...s]}]}}var XWe=I9("Invitation setup");function m$r(e){if(l$r.has(e.state))return[];return[...e.deliveryAttemptId?[{action:phe,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:uhe,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:XWe}]:[],...e.state!=="expired"?[{action:dhe,input:{invitationId:e.id}}]:[]]}function ZWe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return co(e.state)}var she=hs({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:lhe,data:p$r,actions:[ahe,uhe,dhe,phe],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=TH(e.channels),i;if(e.channels.length>0&&r.length>0)i={action:ahe,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:PH("Role"),...RH(e.channels,r)}},result:XWe};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:`${co(o.role)} \xB7 ${ZWe(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:co(n.role)},{label:"Delivery",value:ZWe(n)},{label:"Destination",value:n.destination},{label:"Updated",value:wh(n.updatedAt)}]},{type:"actions",id:"invitation-actions",items:m$r(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(co).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 VWe(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 eZe(e){let t=Sh(e),r=new Map,i=e.studio.source({definition:she,bind:(n)=>{let o=ahe.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}},Rc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return VWe(p)}),s=uhe.bind(n,async({input:l,caller:d})=>{let p=await t.resendInvitation(l.invitationId,Rc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return VWe(p)}),a=dhe.bind(n,async({input:l,caller:d})=>{let p=await t.cancelInvitation(l.invitationId,Rc(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=phe.bind(n,async({input:l,caller:d})=>{let p=await t.confirmManualInvitationDelivery(l.invitationId,l.deliveryAttemptId,Rc(d));return r.delete(l.invitationId),{invitationId:p.id,state:p.state}});return she.bind(n,{actions:[o,s,a,c],load:async({query:l})=>{let d=l.get(lhe),[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&&!HWe.has(F.invitation.state)),y=f.filter((F)=>F.invitation&&HWe.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:c$r(),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 UA(i,she.actions)}var xhe=u.strictObject({peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional()}),h$r=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"])}),f$r=u.strictObject({peerId:u.string().trim().min(1).max(2000),userId:u.string().min(1)}),hhe=Vr({name:"invite-external-peer-person",label:"Invite peer person",permission:"admin",confirmation:{kind:"static",message:"Create this local member and bind them to the external peer?"},input:h$r,output:IH}),fhe=Vr({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:f$r,output:Zf}),x$r=u.strictObject({query:xhe,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(_H)});function FH(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 ghe(e){let t=e.some((r)=>r.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[FH(e,"peers"),FH(e,"link-peer"),FH(e,t)],invitations:[FH(e,t)]}}var g$r=I9("Peer invitation setup"),mhe=hs({id:"peers",label:"Peers",priority:12,permission:"admin",query:xhe,data:x$r,actions:[hhe,fhe],view:({data:e})=>{let t=TH(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:hhe,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:PH("Local role"),...RH(e.channels,t)}},result:g$r}]});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:fhe,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:YS(i.peerId),person:i.displayName,role:i.role,verification:i.verificationStatus,linked:wh(i.createdAt)},compact:{title:YS(i.peerId),metadata:[i.displayName,co(i.role),wh(i.createdAt)],badges:[{label:co(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 tZe(e){let t=Sh(e),r=e.studio.source({definition:mhe,bind:(i)=>{let n=hhe.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}},Rc(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=fhe.bind(i,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},Rc(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 mhe.bind(i,{actions:[n,o],load:async({query:s})=>{let a=s.get(xhe),[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:DH(d),channels:l.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return UA(r,mhe.actions)}function yhe(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 rZe(e,t,r){let i=yhe(e,"people-summary");if(i.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let n=yhe(e,"people");if(n.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=yhe(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 Dhe=u.strictObject({selected:u.string().trim().min(1).max(200).optional()}),Ihe=u.strictObject({userId:u.string().min(1)}),y$r=u.strictObject({userId:u.string().min(1),role:u.enum(["admin","trusted","public"])}),b$r=u.strictObject({userId:u.string().min(1),status:u.enum(["active","suspended"])});function E$r(e){return e.revokedAt===void 0&&e.type!=="passkey"}function v$r(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var A$r=u.strictObject({userId:u.string().min(1),credentialId:u.string().min(1)}),w$r=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()}),S$r=u.strictObject({userId:u.string().min(1),identityId:u.string().min(1)}),k$r=u.strictObject({userId:u.string().min(1),peerId:u.string().trim().min(1).max(2000)}),vhe=Vr({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:y$r,output:Zf}),Ahe=Vr({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:b$r,output:Zf}),whe=Vr({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:Ihe,output:Zf}),She=Vr({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:A$r,output:Zf}),_he=Vr({name:"start-person-passkey-registration",label:"Create setup link",permission:"admin",confirmation:{kind:"static",message:"Create a single-use passkey setup link for this person?"},input:Ihe,output:IH}),khe=Vr({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:Ihe,output:Zf}),The=Vr({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:w$r,output:Zf}),Bhe=Vr({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:S$r,output:Zf}),Che=Vr({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:k$r,output:Zf}),B$r=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"])}))}),C$r=u.strictObject({query:Dhe,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(B$r),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()}))}),D$r=I9("Passkey setup");function I$r(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function bhe(e){return{type:"notice",tone:"warn",text:e}}function _$r(e){return{type:"action",action:_he,input:{userId:e},result:D$r}}function T$r(e,t){return{type:"action",action:The,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 P$r(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var Ehe=hs({id:"people",label:"People",priority:10,permission:"admin",query:Dhe,data:C$r,actions:[vhe,Ahe,whe,She,_he,khe,The,Bhe,Che],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:co(t.role)},{label:"Status",value:co(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:vhe,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:Ahe,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:khe,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:whe,input:{userId:t.userId}}]:[]]},...t.isSelf?[I$r()]:[],...s&&t.status==="active"?[bhe(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:wh(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${wh(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:She,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[_$r(t.userId)]:[bhe("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:Bhe,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[T$r(t.userId,e.channelTypes)]:[bhe("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:YS(a.peerId),description:`Vouched in by ${YS(a.peerId)} \xB7 ${a.peerId}`,metadata:[co(a.verificationStatus)],actions:[{action:Che,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:[co(n.role),co(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 ${YS(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 MH(e,t){return e.find((r)=>r.userId===t)?.displayName??"person"}async function R$r(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function iZe(e){let t=Sh(e),r=e.studio.source({definition:Ehe,bind:(i)=>{let n=vhe.bind(i,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,Rc(f)),{status:`Role changed to ${co(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${MH(f,h.userId)}\u2019s role to ${co(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=Ahe.bind(i,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,Rc(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${MH(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=whe.bind(i,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,Rc(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${MH(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=She.bind(i,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,Rc(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=_he.bind(i,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,Rc(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=khe.bind(i,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,Rc(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${MH(f,h.userId)} out everywhere?`,revision:h.userId}}),d=The.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"}},Rc(f)),{status:"Verified channel attached."})),p=Bhe.bind(i,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,Rc(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=Che.bind(i,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,Rc(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 Ehe.bind(i,{actions:[n,o,s,a,c,l,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(Dhe),[y,b,A]=await Promise.all([R$r(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??P$r(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:v$r(L),createdAt:L.createdAt})),identities:N.identities.filter(E$r).map((L)=>({id:L.id,type:L.type,displayName:k.get(L.type)??co(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 UA(r,Ehe.actions)}var F$r=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(Ah,u.number().int().min(0).max(1e5)).optional(),limit:u.preprocess(Ah,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 M$r(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function O$r(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 N$r(e,t){if(!O$r(e))throw Error(`${t} tab returned invalid workspace data`);return e}function nZe(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 Phe(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function JT(e,t,r,i){return N$r(await e.dataProvider(t,r,i),e.label)}async function L$r(e,t,r,i){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,r,i)}function j$r(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 z$r(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 oZe(e){if(!e.studio.isAvailable())return;let t=iZe(e),r=eZe(e),i=tZe(e),n=GWe(e),o=j$r([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:GT,priority:10,permission:"admin",section:"brain",urlQuery:!0,aliases:[{id:"admin:people",query:{tab:"people"}},{id:"admin:invitations",query:{tab:"invitations"}},{id:"admin:peers",query:{tab:"people"}},{id:"admin:audit",query:{tab:"audit"}}],entityTypes:[],accessHandler:(d)=>s.accessHandler(d),dataProvider:async(d,p,m)=>{let h=F$r.parse(p??{}),f,g=Phe("People"),y=Phe("Invitations"),b=Phe("Audit");if(h.tab==="people"){let[A,w]=await Promise.all([JT(s,d,{...h.selected?{selected:h.selected}:{}},m),JT(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),C=ghe(w.view.blocks);g=[...rZe(nZe(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([JT(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...Qn({offset:h.offset,limit:h.limit})},m),JT(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),C=ghe(w.view.blocks),F=QWe(A.view.blocks,C.invitations);f=A.view.primaryAction,y=[...F.blocks]}else{let A=await JT(l,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...Qn({offset:h.offset,limit:h.limit})},m);b=nZe(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=M$r(d);if(!h)throw new Rr("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new Rr("not_found",{publicMessage:`Unknown Administration action: ${h}`});return L$r(f,d,p,m)},badgeProvider:async()=>z$r(await Sh(e).listAdminUsers())})}var U$r=259200000,q$r=u.strictObject({id:u.string(),displayName:u.string(),state:u.string(),reason:u.enum(["expiring","delivery-failed"]),expiresAt:u.number().optional()}),$$r=u.strictObject({invitations:u.array(q$r),expiringCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()}),sZe=Xn({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:$$r,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 ${wh(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function G$r(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+U$r)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 aZe(e,t){t.throwIfAborted();let r=await Sh(e).listAdminUsers();return t.throwIfAborted(),G$r(r,Date.now())}var H$r=u.strictObject({}),W$r=zt({id:"admin",config:H$r},{subscriptions:(e)=>{let t=bt(e);return t.registered(async()=>{await oZe(t)}),[]},dashboardWidgets:(e)=>{let t=bt(e);return[sZe.bind(e,({signal:r})=>aZe(t,r))]}}),Rhe=W$r;var Vi="agent",cZe="agent-network",lZe="agent-proximity",Jhe="agent-discovery:entities",uZe="agent-discovery:proximity-map",Qhe="proximity-map",Xhe="agent-list",efe="agent-detail",Fc="skill",dZe=30,pZe=120;var NH="skill-derivation",mZe="skill-derivation",tfe="skill:skill-derivation",hZe="skills";var Z$r=u.string().trim().min(1).max(pZe),rfe=u.array(Z$r).max(dZe),$A=u.object({name:u.string(),description:u.string(),tags:rfe,examples:u.array(u.string())}),cP=$A,GA=Vf.extend({entityType:u.literal(Fc),metadata:cP});var LH=u.object({name:u.string(),description:u.string(),tags:rfe}),Ib=u.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),V$r=VS,Kf=u.object({name:u.string(),kind:V$r,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:Ib,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"})}),lP=u.object({name:u.string(),url:u.string().url(),status:Ib,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()}),Fn=Vf.extend({entityType:u.literal(Vi),metadata:lP}),K$r=Ur.extend({entityType:u.literal(Vi),metadata:lP}),uP=K$r.extend({frontmatter:Kf,about:u.string(),skills:u.array(LH),notes:u.string()}),Y$r=uP.extend({url:u.string().optional(),typeLabel:u.string().optional()}),J$r=uP.extend({url:u.string(),typeLabel:u.string()});var Q$r=u.record(u.string(),u.unknown());function X$r(e){try{return So(e,Q$r).content}catch{return e}}function ife(e){return{name:e.name,url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:T9(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 fZe(e){return Ws(Vi,e,Kf)}function dP(e){return{content:e,metadata:ife(fZe(e))}}function P9(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:Ib.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},r=ehe({about:e.about,skills:e.skills,notes:e.notes});return dn(r,t)}function Yf(e,t={}){return P9({...e.frontmatter,...e.body,...t})}function pP(e){return YT(X$r(e))}function uc(e){return{frontmatter:fZe(e.content),body:pP(e.content)}}function nfe(e){return dn("",e)}function tGr(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function xZe(e,t,r={}){let i=r.minCount??1,n=r.topN??12,o=new Map,s=(a)=>{for(let c of dc(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=pP(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(tGr).slice(0,n)}function gZe(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 FWe(a,"Agent call failed");let c=vme.safeParse(a.data);if(!c.success)throw new Rr("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(bH,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 OWe={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.791",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 AH(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 Jqr={"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"},Qu=(e)=>AH(e,Jqr);function Qqr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(vh(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();await VHe(i,n.privateJwk,n.keyId)}}function Xqr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(vh(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();return{keyId:n.keyId,signature:YHe(i,n.privateJwk)}}}function Ame(e,t,r){let i=Qqr(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:wH,schema:SH}).has(n.trim().toLowerCase()))}}async function e$r(e,t,r){if(!r.cardReady)return;return lWe({character:e.identity.get(),profile:e.identity.getProfile(),version:OWe.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 t$r(e,t,r,i){let n=new URL(r.url),o=new URL(`${n.pathname}${n.search}`,$x(r)),s=await KHe({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 r$r(e,t,r){let i=new LWe,n=e.agent;return i.get("/.well-known/agent-card.json",async(o)=>{let s=await e$r(e,t,r);if(!s)return Qu(o.json({error:"Agent Card not ready"},503));return Qu(o.json(s))}),i.get("/.well-known/agent-directory.json",async(o)=>{let s=await uWe(e.entityReads);return Qu(o.json(s))}),i.get("/a2a",(o)=>Qu(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),i.options("/a2a",()=>Qu(new Response(null,{status:204}))),i.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return Qu(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await t$r(e,r,o.req.raw,s)}catch{return Qu(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return Qu(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let l=mWe.safeParse(c);if(!l.success)return Qu(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(LHe(o.req.raw.headers)){let p=l.data.method==="message/send"?jHe(l.data.params):void 0,m=p?.op==="list"?await qHe(e.entityReads,a.permissionLevel):await UHe(e.entityReads,a.permissionLevel,p,Xqr(e));if(!m)return Qu(o.json({error:"Not found"},404));return Qu(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=bWe.safeParse(l.data.params??{});if(!p.success)return Qu(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:l.data.id}));let m=EWe(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 Qu(o.json(m));return Qu(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await xWe(l.data,{taskManager:r.taskManager,turnSupervisor:r.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:r.publicAsks});return Qu(o.json(d))}),i}function wme(e={}){let t=Eh({id:"a2a",config:aWe,setup:(o)=>{let{config:s}=o,a=Ko(o),{servesHttp:c}=a,l=Ame(a,s,e),d={cardReady:!1,servesHttp:c,taskManager:new hme,turnSupervisor:new fme,jwksResolver:new OT(e.fetch?{fetch:e.fetch}:{}),clientDeps:l,publicAsks:new mme(s.publicAsks,a.classRuntimeState)};if(c)a.endpoint({label:"A2A",url:"/a2a",priority:25}),a.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),a.logger.info("A2A interface registered",{domain:a.domain});else a.logger.info("A2A interface registered in tool-only mode",{domain:a.domain});return a.ready(()=>{d.cardReady=!0}),d}}),r=NWe(t,(o)=>{let s=Ko(o);MWe(s,Ame(s,o.config,e),{networkAskTimeoutMs:o.config.networkAskTimeoutMs,turnTimeoutMs:o.config.turnTimeoutMs})}),i=wo(r,(o)=>{let{config:s,state:a}=o;if(!a.servesHttp)return[];let c=Ko(o),l=r$r(c,s,a),d=(m)=>Promise.resolve(l.fetch(m)),p=(m,h)=>({path:m,method:h,public:!0,handler:d});return[p("/.well-known/agent-card.json","GET"),p("/.well-known/agent-directory.json","GET"),p("/a2a","GET"),p("/a2a","POST"),p("/a2a","OPTIONS")]}),n=qx(i,(o)=>{let{state:s}=o,{logger:a}=Ko(o);return{id:"a2a",start:async()=>{if(s.servesHttp)a.info("A2A mounted on shared webserver host");else a.info("A2A running without webserver routes")},stop:async()=>{await s.turnSupervisor.close(),a.info("A2A server stopped")}}});return Rn(n,(o)=>{let{config:s}=o,a=Ko(o),c=()=>CWe(Ame(a,s,e));return[{...c(),handler:(l,d)=>c().handler(l,d)}]})}var i$r=wme(),jWe=i$r;function Ah(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function UA(e,t){return{registration:e,actionIds:t.map((r)=>r.name)}}var n$r=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function wh(e){return n$r.format(new Date(e))}function Sh(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function Rc(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function DH(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function YS(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 o$r={"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 ihe(e){let t=o$r[e];if(t)return t;let r=e.replaceAll(/[._-]+/g," ").trim();return r.length===0?e:co(r)}var nhe=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(Ah,u.number().int().min(0).max(1e5)).default(0),limit:u.preprocess(Ah,u.number().int().min(1).max(100)).default(25)}),zWe=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()}),s$r=u.strictObject({userId:u.string().min(1),displayName:u.string().min(1)}),a$r=u.strictObject({query:nhe,events:u.array(zWe),selectedEvent:zWe.optional(),users:u.array(s$r),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 UWe(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 qWe(e,t){return e?t.get(e)??"Former Admin":"System"}function $We(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 rhe=hs({id:"audit",label:"Audit",priority:90,permission:"admin",query:nhe,data:a$r,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:ihe(r.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:qWe(r.actorUserId,t)},{label:"Action",value:r.action},{label:"Target",value:$We(r,t)},{label:"Occurred",value:wh(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:ihe(o.action),description:`${qWe(o.actorUserId,t)} \u2192 ${$We(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 GWe(e){let t=e.studio.source({definition:rhe,bind:(r)=>rhe.bind(r,{load:async({query:i})=>{let n=Sh(e),o=i.get(nhe),[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(UWe),...s.selectedEvent?{selectedEvent:UWe(s.selectedEvent)}:{},users:DH(a),actions:s.actions.map(({action:c,count:l})=>({value:c,label:ihe(c),count:l})).sort((c,l)=>c.label.localeCompare(l.label)),total:s.total}},actions:[]})});return UA(t,rhe.actions)}var Zf=u.strictObject({status:u.string()}),IH=u.strictObject({status:u.string(),setupUrl:u.url(),expiresAt:u.string()});function I9(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var _H=u.strictObject({type:u.string(),displayName:u.string(),subjectLabel:u.string(),deliveryModes:u.array(u.enum(["automatic","manual"]))});function TH(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function PH(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function RH(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 c$r}from"crypto";var HWe=new Set(["claimed","expired","cancelled"]),l$r=new Set(["claimed","cancelled"]),lhe=u.strictObject({state:u.enum(["pending","history"]).optional().default("pending"),selected:u.string().trim().min(1).max(200).optional(),offset:u.preprocess(Ah,u.number().int().min(0)).optional().default(0),limit:u.preprocess(Ah,u.number().int().min(1).max(100)).optional().default(25)}),KWe=u.strictObject({status:u.string(),setupUrl:u.url().nullable(),expiresAt:u.string().nullable()}),u$r=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"])}),YWe=u.strictObject({invitationId:u.string().min(1)}),d$r=u.strictObject({invitationId:u.string().min(1),deliveryAttemptId:u.string().min(1)}),JWe=u.strictObject({invitationId:u.string(),state:u.string()}),ahe=Vr({name:"create-invitation",label:"Add a person",permission:"admin",input:u$r,output:KWe}),uhe=Vr({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:YWe,output:KWe}),dhe=Vr({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:YWe,output:JWe}),phe=Vr({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:d$r,output:JWe}),WWe=u.strictObject({id:u.string(),displayName:u.string(),role:u.string(),state:u.string(),destination:u.string(),updatedAt:u.number(),deliveryAttemptId:u.string().optional()}),p$r=u.strictObject({query:lhe,idempotencyKey:u.string(),channels:u.array(_H),invitations:u.array(WWe),selectedInvitation:WWe.optional(),selectedTotal:u.number().int().nonnegative(),pendingCount:u.number().int().nonnegative(),historyCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()});function che(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 ohe(e,t){let r=che(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 QWe(e,t){let r=che(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")?[ohe(e,"create-invitation-unavailable")]:[],n=che(e,"invitations");if(n.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=ohe(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,ohe(e,"invitation-filters"),n,{...o,presentation:"disclosure",blocks:[...o.blocks,r,...s]}]}}var XWe=I9("Invitation setup");function m$r(e){if(l$r.has(e.state))return[];return[...e.deliveryAttemptId?[{action:phe,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:uhe,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:XWe}]:[],...e.state!=="expired"?[{action:dhe,input:{invitationId:e.id}}]:[]]}function ZWe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return co(e.state)}var she=hs({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:lhe,data:p$r,actions:[ahe,uhe,dhe,phe],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=TH(e.channels),i;if(e.channels.length>0&&r.length>0)i={action:ahe,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:PH("Role"),...RH(e.channels,r)}},result:XWe};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:`${co(o.role)} \xB7 ${ZWe(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:co(n.role)},{label:"Delivery",value:ZWe(n)},{label:"Destination",value:n.destination},{label:"Updated",value:wh(n.updatedAt)}]},{type:"actions",id:"invitation-actions",items:m$r(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(co).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 VWe(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 eZe(e){let t=Sh(e),r=new Map,i=e.studio.source({definition:she,bind:(n)=>{let o=ahe.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}},Rc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return VWe(p)}),s=uhe.bind(n,async({input:l,caller:d})=>{let p=await t.resendInvitation(l.invitationId,Rc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return VWe(p)}),a=dhe.bind(n,async({input:l,caller:d})=>{let p=await t.cancelInvitation(l.invitationId,Rc(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=phe.bind(n,async({input:l,caller:d})=>{let p=await t.confirmManualInvitationDelivery(l.invitationId,l.deliveryAttemptId,Rc(d));return r.delete(l.invitationId),{invitationId:p.id,state:p.state}});return she.bind(n,{actions:[o,s,a,c],load:async({query:l})=>{let d=l.get(lhe),[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&&!HWe.has(F.invitation.state)),y=f.filter((F)=>F.invitation&&HWe.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:c$r(),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 UA(i,she.actions)}var xhe=u.strictObject({peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional()}),h$r=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"])}),f$r=u.strictObject({peerId:u.string().trim().min(1).max(2000),userId:u.string().min(1)}),hhe=Vr({name:"invite-external-peer-person",label:"Invite peer person",permission:"admin",confirmation:{kind:"static",message:"Create this local member and bind them to the external peer?"},input:h$r,output:IH}),fhe=Vr({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:f$r,output:Zf}),x$r=u.strictObject({query:xhe,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(_H)});function FH(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 ghe(e){let t=e.some((r)=>r.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[FH(e,"peers"),FH(e,"link-peer"),FH(e,t)],invitations:[FH(e,t)]}}var g$r=I9("Peer invitation setup"),mhe=hs({id:"peers",label:"Peers",priority:12,permission:"admin",query:xhe,data:x$r,actions:[hhe,fhe],view:({data:e})=>{let t=TH(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:hhe,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:PH("Local role"),...RH(e.channels,t)}},result:g$r}]});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:fhe,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:YS(i.peerId),person:i.displayName,role:i.role,verification:i.verificationStatus,linked:wh(i.createdAt)},compact:{title:YS(i.peerId),metadata:[i.displayName,co(i.role),wh(i.createdAt)],badges:[{label:co(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 tZe(e){let t=Sh(e),r=e.studio.source({definition:mhe,bind:(i)=>{let n=hhe.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}},Rc(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=fhe.bind(i,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},Rc(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 mhe.bind(i,{actions:[n,o],load:async({query:s})=>{let a=s.get(xhe),[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:DH(d),channels:l.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return UA(r,mhe.actions)}function yhe(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 rZe(e,t,r){let i=yhe(e,"people-summary");if(i.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let n=yhe(e,"people");if(n.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=yhe(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 Dhe=u.strictObject({selected:u.string().trim().min(1).max(200).optional()}),Ihe=u.strictObject({userId:u.string().min(1)}),y$r=u.strictObject({userId:u.string().min(1),role:u.enum(["admin","trusted","public"])}),b$r=u.strictObject({userId:u.string().min(1),status:u.enum(["active","suspended"])});function E$r(e){return e.revokedAt===void 0&&e.type!=="passkey"}function v$r(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var A$r=u.strictObject({userId:u.string().min(1),credentialId:u.string().min(1)}),w$r=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()}),S$r=u.strictObject({userId:u.string().min(1),identityId:u.string().min(1)}),k$r=u.strictObject({userId:u.string().min(1),peerId:u.string().trim().min(1).max(2000)}),vhe=Vr({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:y$r,output:Zf}),Ahe=Vr({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:b$r,output:Zf}),whe=Vr({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:Ihe,output:Zf}),She=Vr({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:A$r,output:Zf}),_he=Vr({name:"start-person-passkey-registration",label:"Create setup link",permission:"admin",confirmation:{kind:"static",message:"Create a single-use passkey setup link for this person?"},input:Ihe,output:IH}),khe=Vr({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:Ihe,output:Zf}),The=Vr({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:w$r,output:Zf}),Bhe=Vr({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:S$r,output:Zf}),Che=Vr({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:k$r,output:Zf}),B$r=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"])}))}),C$r=u.strictObject({query:Dhe,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(B$r),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()}))}),D$r=I9("Passkey setup");function I$r(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function bhe(e){return{type:"notice",tone:"warn",text:e}}function _$r(e){return{type:"action",action:_he,input:{userId:e},result:D$r}}function T$r(e,t){return{type:"action",action:The,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 P$r(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var Ehe=hs({id:"people",label:"People",priority:10,permission:"admin",query:Dhe,data:C$r,actions:[vhe,Ahe,whe,She,_he,khe,The,Bhe,Che],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:co(t.role)},{label:"Status",value:co(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:vhe,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:Ahe,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:khe,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:whe,input:{userId:t.userId}}]:[]]},...t.isSelf?[I$r()]:[],...s&&t.status==="active"?[bhe(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:wh(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${wh(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:She,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[_$r(t.userId)]:[bhe("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:Bhe,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[T$r(t.userId,e.channelTypes)]:[bhe("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:YS(a.peerId),description:`Vouched in by ${YS(a.peerId)} \xB7 ${a.peerId}`,metadata:[co(a.verificationStatus)],actions:[{action:Che,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:[co(n.role),co(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 ${YS(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 MH(e,t){return e.find((r)=>r.userId===t)?.displayName??"person"}async function R$r(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function iZe(e){let t=Sh(e),r=e.studio.source({definition:Ehe,bind:(i)=>{let n=vhe.bind(i,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,Rc(f)),{status:`Role changed to ${co(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${MH(f,h.userId)}\u2019s role to ${co(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=Ahe.bind(i,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,Rc(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${MH(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=whe.bind(i,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,Rc(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${MH(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=She.bind(i,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,Rc(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=_he.bind(i,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,Rc(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=khe.bind(i,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,Rc(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${MH(f,h.userId)} out everywhere?`,revision:h.userId}}),d=The.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"}},Rc(f)),{status:"Verified channel attached."})),p=Bhe.bind(i,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,Rc(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=Che.bind(i,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,Rc(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 Ehe.bind(i,{actions:[n,o,s,a,c,l,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(Dhe),[y,b,A]=await Promise.all([R$r(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??P$r(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:v$r(L),createdAt:L.createdAt})),identities:N.identities.filter(E$r).map((L)=>({id:L.id,type:L.type,displayName:k.get(L.type)??co(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 UA(r,Ehe.actions)}var F$r=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(Ah,u.number().int().min(0).max(1e5)).optional(),limit:u.preprocess(Ah,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 M$r(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function O$r(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 N$r(e,t){if(!O$r(e))throw Error(`${t} tab returned invalid workspace data`);return e}function nZe(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 Phe(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function JT(e,t,r,i){return N$r(await e.dataProvider(t,r,i),e.label)}async function L$r(e,t,r,i){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,r,i)}function j$r(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 z$r(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 oZe(e){if(!e.studio.isAvailable())return;let t=iZe(e),r=eZe(e),i=tZe(e),n=GWe(e),o=j$r([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:GT,priority:10,permission:"admin",section:"brain",urlQuery:!0,aliases:[{id:"admin:people",query:{tab:"people"}},{id:"admin:invitations",query:{tab:"invitations"}},{id:"admin:peers",query:{tab:"people"}},{id:"admin:audit",query:{tab:"audit"}}],entityTypes:[],accessHandler:(d)=>s.accessHandler(d),dataProvider:async(d,p,m)=>{let h=F$r.parse(p??{}),f,g=Phe("People"),y=Phe("Invitations"),b=Phe("Audit");if(h.tab==="people"){let[A,w]=await Promise.all([JT(s,d,{...h.selected?{selected:h.selected}:{}},m),JT(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),C=ghe(w.view.blocks);g=[...rZe(nZe(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([JT(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...Qn({offset:h.offset,limit:h.limit})},m),JT(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),C=ghe(w.view.blocks),F=QWe(A.view.blocks,C.invitations);f=A.view.primaryAction,y=[...F.blocks]}else{let A=await JT(l,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...Qn({offset:h.offset,limit:h.limit})},m);b=nZe(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=M$r(d);if(!h)throw new Rr("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new Rr("not_found",{publicMessage:`Unknown Administration action: ${h}`});return L$r(f,d,p,m)},badgeProvider:async()=>z$r(await Sh(e).listAdminUsers())})}var U$r=259200000,q$r=u.strictObject({id:u.string(),displayName:u.string(),state:u.string(),reason:u.enum(["expiring","delivery-failed"]),expiresAt:u.number().optional()}),$$r=u.strictObject({invitations:u.array(q$r),expiringCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()}),sZe=Xn({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:$$r,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 ${wh(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function G$r(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+U$r)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 aZe(e,t){t.throwIfAborted();let r=await Sh(e).listAdminUsers();return t.throwIfAborted(),G$r(r,Date.now())}var H$r=u.strictObject({}),W$r=zt({id:"admin",config:H$r},{subscriptions:(e)=>{let t=bt(e);return t.registered(async()=>{await oZe(t)}),[]},dashboardWidgets:(e)=>{let t=bt(e);return[sZe.bind(e,({signal:r})=>aZe(t,r))]}}),Rhe=W$r;var Vi="agent",cZe="agent-network",lZe="agent-proximity",Jhe="agent-discovery:entities",uZe="agent-discovery:proximity-map",Qhe="proximity-map",Xhe="agent-list",efe="agent-detail",Fc="skill",dZe=30,pZe=120;var NH="skill-derivation",mZe="skill-derivation",tfe="skill:skill-derivation",hZe="skills";var Z$r=u.string().trim().min(1).max(pZe),rfe=u.array(Z$r).max(dZe),$A=u.object({name:u.string(),description:u.string(),tags:rfe,examples:u.array(u.string())}),cP=$A,GA=Vf.extend({entityType:u.literal(Fc),metadata:cP});var LH=u.object({name:u.string(),description:u.string(),tags:rfe}),Ib=u.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),V$r=VS,Kf=u.object({name:u.string(),kind:V$r,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:Ib,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"})}),lP=u.object({name:u.string(),url:u.string().url(),status:Ib,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()}),Fn=Vf.extend({entityType:u.literal(Vi),metadata:lP}),K$r=Ur.extend({entityType:u.literal(Vi),metadata:lP}),uP=K$r.extend({frontmatter:Kf,about:u.string(),skills:u.array(LH),notes:u.string()}),Y$r=uP.extend({url:u.string().optional(),typeLabel:u.string().optional()}),J$r=uP.extend({url:u.string(),typeLabel:u.string()});var Q$r=u.record(u.string(),u.unknown());function X$r(e){try{return So(e,Q$r).content}catch{return e}}function ife(e){return{name:e.name,url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:T9(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 fZe(e){return Ws(Vi,e,Kf)}function dP(e){return{content:e,metadata:ife(fZe(e))}}function P9(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:Ib.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},r=ehe({about:e.about,skills:e.skills,notes:e.notes});return dn(r,t)}function Yf(e,t={}){return P9({...e.frontmatter,...e.body,...t})}function pP(e){return YT(X$r(e))}function uc(e){return{frontmatter:fZe(e.content),body:pP(e.content)}}function nfe(e){return dn("",e)}function tGr(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function xZe(e,t,r={}){let i=r.minCount??1,n=r.topN??12,o=new Map,s=(a)=>{for(let c of dc(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=pP(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(tGr).slice(0,n)}function gZe(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 R9(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:P9({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:dc(c.tags)})),notes:""}),metadata:{name:r,url:e.url,status:o,discoveredAt:s,slug:T9(e.url)},anchorName:r}}function Wx(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 rGr=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 yZe(e){return{input:rGr,generate:async({input:t})=>{let r=Wx(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 bh(r,{fetch:e??globalThis.fetch});if(!i.ok)return{success:!1,error:OA(i.reason)?i.error:`Could not fetch Agent Card from ${r}. Make sure the agent is running and accessible.`};let{content:n,metadata:o}=R9(i.card,{...t.status!==void 0?{status:t.status}:{}});return{success:!0,id:r,content:n,metadata:o}}}}var iGr=100,bZe=50000,sfe="connect",EZe="dismiss";function ofe(e){let t=Fn.parse(e),r=nGr(t);return r?{entity:t,parsed:r}:void 0}function vZe(e){return{sourceId:"agent-sightings",displayName:"Agent sightings",list:async({records:r})=>(await r.list()).flatMap((i)=>{let n=ofe(i);return n?[n]:[]}).sort((i,n)=>n.parsed.frontmatter.discoveredAt.localeCompare(i.parsed.frontmatter.discoveredAt)).slice(0,iGr).map(({entity:i,parsed:n})=>oGr(i,n)),resolveDetail:async(r,{records:i,signal:n})=>{n.throwIfAborted();let o=ofe(await i.get(r));if(n.throwIfAborted(),!o)throw Error("Agent sighting not found");let s=aGr(o.entity,o.parsed);return{kind:"plain",text:s.slice(0,bZe),truncated:s.length>bZe}},act:async(r,i,{records:n,edits:o})=>{if(i!==sfe&&i!==EZe)throw Error("Invalid agent sighting Inbox action");let s=await n.get(r),a=s?ofe(s):void 0;if(!s||!a)throw Error("Agent sighting not found");let c=i===sfe?"approved":"archived";if(c==="approved")await e.approve(s.id);else await e.revoke(s.id);await o.update(s,{content:Yf(a.parsed,{status:c,...c==="approved"?{introducedBy:void 0,hops:void 0}:{}}),metadata:{...s.metadata,status:c}})}}}function nGr(e){let t=uc(e);return t.frontmatter.status==="discovered"&&(t.frontmatter.introducedBy?.length??0)>0?t:void 0}function oGr(e,t){let r=Jf(t.frontmatter.name),i=Jf(e.id),n=AZe(r===i?r:`${r} \xB7 ${i}`,160);return{id:e.id,title:n,summary:sGr(t),receivedAt:t.frontmatter.discoveredAt,urgency:"normal",entityRef:{entityType:Vi,entityId:e.id},actions:[{id:sfe,label:"Connect",confirm:!0},{id:EZe,label:"Dismiss",confirm:!0}]}}function sGr(e){let t=e.frontmatter.introducedBy??[],r=`Introduced by ${afe(t.map(Jf))}.`,i=Jf(e.body.about),n=e.body.skills.map((s)=>Jf(s.name)).filter(Boolean).slice(0,4),o=n.length>0?` Declared skills: ${afe(n)}.`:"";return AZe(`${r}${i?` ${i}`:""}${o}`,1000)}function aGr(e,t){let r=[`Agent: ${Jf(t.frontmatter.name)}`,`Domain: ${Jf(e.id)}`,`Introduced by: ${afe((t.frontmatter.introducedBy??[]).map(Jf))}`],i=Jf(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=Jf(n.description);return`- ${Jf(n.name)}${o?`: ${o}`:""}`}));return r.join(`
|
|
@@ -4399,7 +4399,7 @@ ${JSON.stringify(t,null,2)}`}function NZ(e){return e.map((t)=>{let r=t.title.tri
|
|
|
4399
4399
|
return body;
|
|
4400
4400
|
}
|
|
4401
4401
|
`}function sni(e){let t=e?.split(/\s+/).filter(Boolean)??[];if(t.length===0)return Lrt("Sign-in only","Issue an authorization code without additional requested scopes.");return t.map((r)=>{let i=ani(r);return Lrt(i.title,i.description)}).join(`
|
|
4402
|
-
`)}function Lrt(e,t){return`<li><b>${ct(e)}</b><span>${ct(t)}</span></li>`}function ani(e){switch(e){case"openid":return{title:"Sign in",description:"Identify this browser session to the OAuth client."};case"profile":return{title:"Basic profile",description:"Share the authenticated user's local profile subject with the client."};case"email":return{title:"Email address",description:"Share the verified email address when one is configured."};case"offline_access":return{title:"Offline access",description:"Allow the client to refresh access without asking again."};case"mcp":return{title:"MCP access",description:"Use Model Context Protocol tools exposed by this brain."};default:return{title:e,description:"Requested by the OAuth client."}}}function $rt(e,t){let r=sni(e.scope),i={response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUri,code_challenge:e.codeChallenge,code_challenge_method:"S256",approval_token:t,...e.scope?{scope:e.scope}:{},...e.state?{state:e.state}:{}};return`<!doctype html>
|
|
4402
|
+
`)}function Lrt(e,t){return`<li><b>${ct(e)}</b><span>${ct(t)}</span></li>`}function ani(e){switch(e){case"openid":return{title:"Sign in",description:"Identify this browser session to the OAuth client."};case"profile":return{title:"Basic profile",description:"Share the authenticated user's local profile subject with the client."};case"email":return{title:"Email address",description:"Share the verified email address when one is configured."};case"offline_access":return{title:"Offline access",description:"Allow the client to refresh access without asking again."};case"mcp":return{title:"MCP access",description:"Use Model Context Protocol tools exposed by this brain."};default:return{title:e,description:"Requested by the OAuth client."}}}function $rt(e,t){let r=sni(e.scope),i={response_type:"code",client_id:e.clientId,redirect_uri:e.redirectUri,code_challenge:e.codeChallenge,code_challenge_method:"S256",approval_token:t,...e.scope?{scope:e.scope}:{},...e.state?{state:e.state}:{},...e.nonce?{nonce:e.nonce}:{}};return`<!doctype html>
|
|
4403
4403
|
<html lang="en">
|
|
4404
4404
|
<head>
|
|
4405
4405
|
<meta charset="utf-8" />
|
|
@@ -9524,7 +9524,7 @@ Guidelines:
|
|
|
9524
9524
|
3. Depth: Provide enough detail to be useful as a reference, but stay focused on the topic.
|
|
9525
9525
|
4. Style: Informative and educational. Write as if explaining to yourself for future reference.
|
|
9526
9526
|
5. Length: Adjust based on topic complexity - concise for simple topics, more detailed for complex ones.
|
|
9527
|
-
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var qco="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.",w_=Zi(Ghe(ht({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:Wle,markdown:Zle,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:qco,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:Qje(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:rze},generation:Xje,create:{fromUpload:q_r},jobs:{"upload-import":U_r(()=>w_)},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:Jje}),[$he(Kle,async({request:e,entities:t})=>{let{id:r,title:i,body:n}=e;if(await t.get(w_,r))return{noteId:r,created:!1};return await t.create(w_,{id:r,content:n,metadata:{title:i,titleStated:!0},visibility:"restricted"}),{noteId:r,created:!0}})]),A_);var $co=Pi({id:"note",config:Yje,entities:[w_]}),G_r=$co;var Gco=u.object({type:u.literal("email"),address:u.string().max(0).optional()}).transform(()=>{return}),Hco=u.looseObject({defaultRecipient:Gco.or(H_r).optional()}),Wco=zt({id:"notifications",config:Hco},{subscriptions:(e)=>{let{config:t}=e,r=bt(e),{logger:i}=r;return r.answer(r3,async({request:n})=>{let o=n.recipient??t.defaultRecipient;if(!o)return i.warn(Yle.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=r.deliveryProvider(o.type);if(!s||!await s.isAvailable())return i.warn(Yle.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(Yle.deliveryFailed,{transportCode:a.failureCode});let c=W_r.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}),[]}}),Z_r=Wco;var K_r=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],Zco=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()}),Vco="https://api.linkedin.com/rest",Kco="202312",V_r=1000,Yco=1000;function Jco(e){return e.toLowerCase().includes("no data found for this memberid")}function Qco(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 l${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===V_r)throw Error(`LinkedIn snapshot exceeded ${V_r} 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,Qco(i,t),r+1)]}async fetchPage(e,t){let r=new URL(`${Vco}/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":Kco}});if(i.ok)return Zco.parse(await i.json());let n=await i.text();if(i.status<500&&Jco(n))return null;throw new Jle(i.status,n.slice(0,Yco))}}class Jle extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var Xco=Y_r({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 ize{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:Xco})}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 nze(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var elo="https://www.linkedin.com/oauth/v2/authorization",tlo="https://www.linkedin.com/oauth/v2/accessToken",J_r="r_dma_portability_3rd_party",rlo=500,ilo=u.looseObject({access_token:u.string().min(1),expires_in:u.number().int().positive(),scope:u.string().optional()}),nlo=u.looseObject({error:u.string().optional(),error_description:u.string().optional()});async function olo(e){try{return await e.json()}catch{return null}}class d${config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(elo);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",J_r),t}async exchange(e,t){let r=await this.fetchFn(tlo,{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 olo(r);if(!r.ok){let o=nlo.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,rlo)}`:""}`)}let n=ilo.parse(i);if(n.scope!==void 0&&n.scope!==J_r)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 X_r(e){return new u$({...Q_r,now:e})}var Qle="linkedin",slo=u.strictObject({accessToken:u.string().min(1),expiresAt:u.iso.datetime()});function oze(e,t={}){let r=(n)=>new d$({...e,redirectUri:n},t.fetch),i=t.now??Date.now;return{id:Qle,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 sze{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(S_.authorizations,{provider:Qle,brainState:e},"the connection");return new URL(eTr.parse(t).authorizationUrl)}async redeem(e){let t=tTr.parse(await this.post(S_.redeem,{provider:Qle,grant:e},"grant redemption"));if(t.provider!==Qle)throw Error("OAuth broker redeemed a grant for another provider");return slo.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 alo(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function SB(e,t){return e.map((r)=>alo(r[t])).find(Boolean)}function rTr(e){let t=[SB(e,"First Name"),SB(e,"Last Name")].filter(Boolean).join(" ")||void 0,r=SB(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],i={name:t,headline:SB(e,"Headline"),industry:SB(e,"Industry"),location:SB(e,"Geo Location"),website:r,story:SB(e,"Summary")};return Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))}function iTr(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new Rr(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new Rr("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class aze{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 iTr(await this.messaging.request(m$,{fields:t,revision:r}))}async previewFields(e){return iTr(await this.messaging.request(p$,{fields:e}))}async imported(e){let t=new l$(e,this.fetchFn);return rTr(await t.fetchProfile())}}var cze="/linkedin/oauth/start",f$="/linkedin/oauth/callback",x$="/linkedin/oauth/broker/return";function nTr(e){return e?.permissionLevel==="admin"&&e.isAnchor}function h$(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function sTr(e){let t=(c)=>{let l=e.workspaceUrl(),d=l.includes("?")?"&":"?";return h$(303,`${l}${d}connection=${c}`)},r=async(c,l)=>{let d=e.states.take(l),p=await e.resolveSession(c);return d&&nTr(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: ${he(d)}`),t("failed")}},n=async(c)=>{let l=await e.resolveSession(c);if(!l)return h$(401);if(!nTr(l))return h$(403);let d=e.states.issue(l.userId),{mode:p}=e;if(p.kind==="direct")return h$(302,p.oauth.authorizationUrl(d).toString());try{return h$(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${he(m)}`),t("failed")}},o=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await 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=oTr.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:cze,method:"GET",public:!0,handler:n},a.kind==="direct"?{path:f$,method:"GET",public:!0,handler:o(a.oauth)}:{path:x$,method:"GET",public:!0,handler:s(a.broker)}]}var clo=/^(?: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,llo=[[/^$/,"<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>"],[clo,"<month-year>"]];function lTr(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 aTr(e){if(typeof e!=="string")return`<${lTr(e)}>`;let t=e.trim();return llo.find(([r])=>r.test(t))?.[1]??"<string>"}function ulo(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(aTr))].sort();return aTr(e)}function cTr([e],[t]){return e.localeCompare(t)}function dlo(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])=>lTr(a)))].sort(),presentCount:s.length}}),n=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(cTr).map(([a,c])=>[a,ulo(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:i,recordShapes:[...n].sort(cTr).map(([,o])=>o)}}async function uTr(e){let t=await Promise.all(K_r.map(async(r)=>[r,dlo(await e.fetchDomain(r))]));return Object.fromEntries(t)}var xTr={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},plo={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},mlo={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."}},dTr=200,pze=Vr({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())})}),Xle=Vr({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:u.object({}),output:u.object({disconnected:u.boolean()})}),mze=Vr({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:u.object({}),output:u.object({shapes:u.string()})}),hze=u.object({connection:u.enum(["connected","declined","failed"]).optional()}),hlo=u.object({field:u.enum(["name","headline","industry","location","website","story"]),current:u.string().nullable(),imported:u.string(),outcome:u.enum(["fill","preserve","unchanged"])}),lze=hze.shape.connection,flo=u.discriminatedUnion("status",[u.object({status:u.literal("disconnected"),expired:u.boolean(),startUrl:u.string(),connection:lze}),u.object({status:u.literal("unavailable"),message:u.string(),startUrl:u.string(),connection:lze}),u.object({status:u.literal("ready"),fields:u.array(hlo),connection:lze})]);function pTr(e){if(e===null)return"\u2014";return e.length>dTr?`${e.slice(0,dTr-1)}\u2026`:e}function mTr(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function hTr(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function uze(e){let t=e.connection?mlo[e.connection]:null;return t?[{type:"notice",...t}]:[]}var fTr=hs({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",section:"library",query:hze,data:flo,actions:[pze,Xle,mze],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:[...uze(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],hTr(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...uze(e),{type:"notice",tone:"warn",text:e.message},hTr(e.startUrl,"Connect LinkedIn again"),{type:"action",action:Xle,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:pze,input:{}}}:{},blocks:[...uze(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:xTr[r.field],current:pTr(r.current),imported:pTr(r.imported),outcome:plo[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:mze,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:Xle,input:{}}]}}});function dze(e){if(e?.permission!=="admin"||!e.isAnchor)throw new Rr("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function xlo(e){if(e instanceof Jle&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${he(e)}`}async function gTr(e,t){if(!e.isAvailable())return;let r=async(n)=>{let o=await t.connections.get(dze(n));if(!o||nze(o))throw new Rr("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},i=e.source({definition:fTr,bind:(n)=>fTr.bind(n,{load:async({caller:o,query:s})=>{let a=dze(o),{connection:c}=s.get(hze),l=await t.connections.get(a);if(!l||nze(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:xlo(d),startUrl:t.startUrl,connection:c}}},actions:[pze.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)=>xTr[p.field].toLowerCase()),c=a("fill"),l=a("preserve");if(c.length===0)throw new Rr("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${mTr(c)} from LinkedIn?${l.length>0?` Your ${mTr(l)} stay as you wrote them.`:""}`,revision:s.revision}}),mze.bind(n,async({caller:o})=>{let s=await uTr(t.clientFor((await r(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),Xle.bind(n,async({caller:o})=>(await t.connections.forget(dze(o)),{disconnected:!0}))]})});return e.register({...i,accessHandler:async(n)=>n.isAnchor&&await i.accessHandler(n)})}var yTr={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.790",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 ylo="/studio",blo=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 ${f$}, registered with the LinkedIn app`)}),Elo=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 ${x$}, registered with the broker`)}),bTr=u.object({oauth:blo.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:Elo.optional().describe("The managed broker holding the shared LinkedIn app")});function vlo(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!==f$)throw Error(`linkedin-import: oauth.redirectUri must end at ${f$}`);if(i&&new URL(i.returnUri).pathname!==x$)throw Error(`linkedin-import: broker.returnUri must end at ${x$}`);if(r)return{kind:"direct",oauth:new d$(r,t.fetch)};if(i)return{kind:"broker",broker:new sze(i,t.fetch)};return null}function ETr(e={}){let t=zt({id:"linkedin-import",config:bTr,setup:(r)=>{let{config:i}=r,n=vlo(i,e),o=i.oauth?.redirectUri??i.broker?.returnUri;if(!n||!o)return{routes:[]};let s=bt(r),a=new ize(s.accountSettings,{pluginId:s.pluginId,packageName:yTr.name}),c=ylo;return s.registered(async()=>{let l=await gTr(s.studio,{profileImport:new aze(s.messaging,e.fetch),clientFor:(d)=>new l$(d,e.fetch),connections:a,startUrl:new URL(cze,o).toString()});if(l)c=l}),{routes:sTr({mode:n,states:X_r(),connections:a,resolveSession:async(l)=>s.auth()?.resolveSession(l),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return wo(t,({state:r})=>r.routes)}var fze=ETr();import{createHash as Alo,timingSafeEqual as wlo}from"crypto";function vTr(e){return Alo("sha256").update(e).digest()}function Slo(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 xze{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:vTr(t.secret)}]))}authenticate(e){let t=Slo(e.headers.get("authorization")),r=t?this.instances.get(t.id):void 0;if(!t||!r)return null;return wlo(vTr(t.secret),r.secretHash)?{id:r.id,returnUris:r.returnUris}:null}}var klo=10,Blo=600000,yze={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function fS(e,t=200){return Response.json(e,{status:t,headers:yze})}function ATr(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...yze,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function wTr(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function eue(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:{...yze,Location:r.toString()}})}function BTr(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-Blo),p=d.length<klo;return r.set(c,p?[...d,l]:d),p},n=(c)=>new URL(gze(c),e.publicUrl).toString(),o=async(c)=>{let l=e.instances.authenticate(c);if(!l)return ATr();let d=STr.safeParse(await wTr(c));if(!d.success)return fS({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=l.returnUris[d.data.provider];if(!p||!m)return fS({error:"Provider is unavailable for this instance"},400);if(!i(l.id))return fS({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 fS({authorizationUrl:f})},s=async(c)=>{let l=e.instances.authenticate(c);if(!l)return ATr();let d=kTr.safeParse(await wTr(c));if(!d.success)return fS({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 fS({error:"Invalid or expired grant"},400);return fS({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 fS({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return eue(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return eue(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 eue(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${he(h)}`),eue(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:gze(c.id),method:"GET",public:!0,handler:a(c)}))]}var Clo=600000,Dlo=120000,CTr=1000,Ilo=u.object({clientId:u.string().trim().min(1),clientSecret:u.string().trim().min(1)}),_lo=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(bze,u.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),DTr=u.object({publicUrl:u.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:u.record(bze,Ilo).default({}).describe("Per provider, the shared app the broker holds"),instances:u.array(_lo).default([])});function Tlo(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 Eze(e){let t=zt({id:"oauth-broker",config:DTr,setup:(r)=>{let{config:i}=r,n=Tlo(i,e);if(i.instances.length===0||n.length===0)return{routes:[]};return{routes:BTr({publicUrl:i.publicUrl,providers:n,instances:new xze(i.instances),authorizations:new u$({ttlMs:Clo,maxPending:CTr,now:e.now}),grants:new u$({ttlMs:Dlo,maxPending:CTr,now:e.now}),now:e.now??Date.now,logger:bt(r).logger})}}});return wo(t,({state:r})=>r.routes)}var Plo=2592000000,g$=(e,t)=>Ht(`${e}
|
|
9527
|
+
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var qco="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.",w_=Zi(Ghe(ht({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:Wle,markdown:Zle,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:qco,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:Qje(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:rze},generation:Xje,create:{fromUpload:q_r},jobs:{"upload-import":U_r(()=>w_)},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:Jje}),[$he(Kle,async({request:e,entities:t})=>{let{id:r,title:i,body:n}=e;if(await t.get(w_,r))return{noteId:r,created:!1};return await t.create(w_,{id:r,content:n,metadata:{title:i,titleStated:!0},visibility:"restricted"}),{noteId:r,created:!0}})]),A_);var $co=Pi({id:"note",config:Yje,entities:[w_]}),G_r=$co;var Gco=u.object({type:u.literal("email"),address:u.string().max(0).optional()}).transform(()=>{return}),Hco=u.looseObject({defaultRecipient:Gco.or(H_r).optional()}),Wco=zt({id:"notifications",config:Hco},{subscriptions:(e)=>{let{config:t}=e,r=bt(e),{logger:i}=r;return r.answer(r3,async({request:n})=>{let o=n.recipient??t.defaultRecipient;if(!o)return i.warn(Yle.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=r.deliveryProvider(o.type);if(!s||!await s.isAvailable())return i.warn(Yle.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(Yle.deliveryFailed,{transportCode:a.failureCode});let c=W_r.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}),[]}}),Z_r=Wco;var K_r=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],Zco=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()}),Vco="https://api.linkedin.com/rest",Kco="202312",V_r=1000,Yco=1000;function Jco(e){return e.toLowerCase().includes("no data found for this memberid")}function Qco(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 l${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===V_r)throw Error(`LinkedIn snapshot exceeded ${V_r} 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,Qco(i,t),r+1)]}async fetchPage(e,t){let r=new URL(`${Vco}/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":Kco}});if(i.ok)return Zco.parse(await i.json());let n=await i.text();if(i.status<500&&Jco(n))return null;throw new Jle(i.status,n.slice(0,Yco))}}class Jle extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var Xco=Y_r({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 ize{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:Xco})}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 nze(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var elo="https://www.linkedin.com/oauth/v2/authorization",tlo="https://www.linkedin.com/oauth/v2/accessToken",J_r="r_dma_portability_3rd_party",rlo=500,ilo=u.looseObject({access_token:u.string().min(1),expires_in:u.number().int().positive(),scope:u.string().optional()}),nlo=u.looseObject({error:u.string().optional(),error_description:u.string().optional()});async function olo(e){try{return await e.json()}catch{return null}}class d${config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(elo);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",J_r),t}async exchange(e,t){let r=await this.fetchFn(tlo,{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 olo(r);if(!r.ok){let o=nlo.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,rlo)}`:""}`)}let n=ilo.parse(i);if(n.scope!==void 0&&n.scope!==J_r)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 X_r(e){return new u$({...Q_r,now:e})}var Qle="linkedin",slo=u.strictObject({accessToken:u.string().min(1),expiresAt:u.iso.datetime()});function oze(e,t={}){let r=(n)=>new d$({...e,redirectUri:n},t.fetch),i=t.now??Date.now;return{id:Qle,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 sze{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(S_.authorizations,{provider:Qle,brainState:e},"the connection");return new URL(eTr.parse(t).authorizationUrl)}async redeem(e){let t=tTr.parse(await this.post(S_.redeem,{provider:Qle,grant:e},"grant redemption"));if(t.provider!==Qle)throw Error("OAuth broker redeemed a grant for another provider");return slo.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 alo(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function SB(e,t){return e.map((r)=>alo(r[t])).find(Boolean)}function rTr(e){let t=[SB(e,"First Name"),SB(e,"Last Name")].filter(Boolean).join(" ")||void 0,r=SB(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],i={name:t,headline:SB(e,"Headline"),industry:SB(e,"Industry"),location:SB(e,"Geo Location"),website:r,story:SB(e,"Summary")};return Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))}function iTr(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new Rr(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new Rr("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class aze{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 iTr(await this.messaging.request(m$,{fields:t,revision:r}))}async previewFields(e){return iTr(await this.messaging.request(p$,{fields:e}))}async imported(e){let t=new l$(e,this.fetchFn);return rTr(await t.fetchProfile())}}var cze="/linkedin/oauth/start",f$="/linkedin/oauth/callback",x$="/linkedin/oauth/broker/return";function nTr(e){return e?.permissionLevel==="admin"&&e.isAnchor}function h$(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function sTr(e){let t=(c)=>{let l=e.workspaceUrl(),d=l.includes("?")?"&":"?";return h$(303,`${l}${d}connection=${c}`)},r=async(c,l)=>{let d=e.states.take(l),p=await e.resolveSession(c);return d&&nTr(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: ${he(d)}`),t("failed")}},n=async(c)=>{let l=await e.resolveSession(c);if(!l)return h$(401);if(!nTr(l))return h$(403);let d=e.states.issue(l.userId),{mode:p}=e;if(p.kind==="direct")return h$(302,p.oauth.authorizationUrl(d).toString());try{return h$(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${he(m)}`),t("failed")}},o=(c)=>async(l)=>{let d=new URL(l.url).searchParams,p=await 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=oTr.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:cze,method:"GET",public:!0,handler:n},a.kind==="direct"?{path:f$,method:"GET",public:!0,handler:o(a.oauth)}:{path:x$,method:"GET",public:!0,handler:s(a.broker)}]}var clo=/^(?: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,llo=[[/^$/,"<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>"],[clo,"<month-year>"]];function lTr(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 aTr(e){if(typeof e!=="string")return`<${lTr(e)}>`;let t=e.trim();return llo.find(([r])=>r.test(t))?.[1]??"<string>"}function ulo(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(aTr))].sort();return aTr(e)}function cTr([e],[t]){return e.localeCompare(t)}function dlo(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])=>lTr(a)))].sort(),presentCount:s.length}}),n=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(cTr).map(([a,c])=>[a,ulo(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:i,recordShapes:[...n].sort(cTr).map(([,o])=>o)}}async function uTr(e){let t=await Promise.all(K_r.map(async(r)=>[r,dlo(await e.fetchDomain(r))]));return Object.fromEntries(t)}var xTr={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},plo={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},mlo={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."}},dTr=200,pze=Vr({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())})}),Xle=Vr({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:u.object({}),output:u.object({disconnected:u.boolean()})}),mze=Vr({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:u.object({}),output:u.object({shapes:u.string()})}),hze=u.object({connection:u.enum(["connected","declined","failed"]).optional()}),hlo=u.object({field:u.enum(["name","headline","industry","location","website","story"]),current:u.string().nullable(),imported:u.string(),outcome:u.enum(["fill","preserve","unchanged"])}),lze=hze.shape.connection,flo=u.discriminatedUnion("status",[u.object({status:u.literal("disconnected"),expired:u.boolean(),startUrl:u.string(),connection:lze}),u.object({status:u.literal("unavailable"),message:u.string(),startUrl:u.string(),connection:lze}),u.object({status:u.literal("ready"),fields:u.array(hlo),connection:lze})]);function pTr(e){if(e===null)return"\u2014";return e.length>dTr?`${e.slice(0,dTr-1)}\u2026`:e}function mTr(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function hTr(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function uze(e){let t=e.connection?mlo[e.connection]:null;return t?[{type:"notice",...t}]:[]}var fTr=hs({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",section:"library",query:hze,data:flo,actions:[pze,Xle,mze],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:[...uze(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],hTr(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...uze(e),{type:"notice",tone:"warn",text:e.message},hTr(e.startUrl,"Connect LinkedIn again"),{type:"action",action:Xle,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:pze,input:{}}}:{},blocks:[...uze(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:xTr[r.field],current:pTr(r.current),imported:pTr(r.imported),outcome:plo[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:mze,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:Xle,input:{}}]}}});function dze(e){if(e?.permission!=="admin"||!e.isAnchor)throw new Rr("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function xlo(e){if(e instanceof Jle&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${he(e)}`}async function gTr(e,t){if(!e.isAvailable())return;let r=async(n)=>{let o=await t.connections.get(dze(n));if(!o||nze(o))throw new Rr("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},i=e.source({definition:fTr,bind:(n)=>fTr.bind(n,{load:async({caller:o,query:s})=>{let a=dze(o),{connection:c}=s.get(hze),l=await t.connections.get(a);if(!l||nze(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:xlo(d),startUrl:t.startUrl,connection:c}}},actions:[pze.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)=>xTr[p.field].toLowerCase()),c=a("fill"),l=a("preserve");if(c.length===0)throw new Rr("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${mTr(c)} from LinkedIn?${l.length>0?` Your ${mTr(l)} stay as you wrote them.`:""}`,revision:s.revision}}),mze.bind(n,async({caller:o})=>{let s=await uTr(t.clientFor((await r(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),Xle.bind(n,async({caller:o})=>(await t.connections.forget(dze(o)),{disconnected:!0}))]})});return e.register({...i,accessHandler:async(n)=>n.isAnchor&&await i.accessHandler(n)})}var yTr={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.791",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 ylo="/studio",blo=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 ${f$}, registered with the LinkedIn app`)}),Elo=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 ${x$}, registered with the broker`)}),bTr=u.object({oauth:blo.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:Elo.optional().describe("The managed broker holding the shared LinkedIn app")});function vlo(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!==f$)throw Error(`linkedin-import: oauth.redirectUri must end at ${f$}`);if(i&&new URL(i.returnUri).pathname!==x$)throw Error(`linkedin-import: broker.returnUri must end at ${x$}`);if(r)return{kind:"direct",oauth:new d$(r,t.fetch)};if(i)return{kind:"broker",broker:new sze(i,t.fetch)};return null}function ETr(e={}){let t=zt({id:"linkedin-import",config:bTr,setup:(r)=>{let{config:i}=r,n=vlo(i,e),o=i.oauth?.redirectUri??i.broker?.returnUri;if(!n||!o)return{routes:[]};let s=bt(r),a=new ize(s.accountSettings,{pluginId:s.pluginId,packageName:yTr.name}),c=ylo;return s.registered(async()=>{let l=await gTr(s.studio,{profileImport:new aze(s.messaging,e.fetch),clientFor:(d)=>new l$(d,e.fetch),connections:a,startUrl:new URL(cze,o).toString()});if(l)c=l}),{routes:sTr({mode:n,states:X_r(),connections:a,resolveSession:async(l)=>s.auth()?.resolveSession(l),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return wo(t,({state:r})=>r.routes)}var fze=ETr();import{createHash as Alo,timingSafeEqual as wlo}from"crypto";function vTr(e){return Alo("sha256").update(e).digest()}function Slo(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 xze{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:vTr(t.secret)}]))}authenticate(e){let t=Slo(e.headers.get("authorization")),r=t?this.instances.get(t.id):void 0;if(!t||!r)return null;return wlo(vTr(t.secret),r.secretHash)?{id:r.id,returnUris:r.returnUris}:null}}var klo=10,Blo=600000,yze={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function fS(e,t=200){return Response.json(e,{status:t,headers:yze})}function ATr(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...yze,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function wTr(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function eue(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:{...yze,Location:r.toString()}})}function BTr(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-Blo),p=d.length<klo;return r.set(c,p?[...d,l]:d),p},n=(c)=>new URL(gze(c),e.publicUrl).toString(),o=async(c)=>{let l=e.instances.authenticate(c);if(!l)return ATr();let d=STr.safeParse(await wTr(c));if(!d.success)return fS({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=l.returnUris[d.data.provider];if(!p||!m)return fS({error:"Provider is unavailable for this instance"},400);if(!i(l.id))return fS({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 fS({authorizationUrl:f})},s=async(c)=>{let l=e.instances.authenticate(c);if(!l)return ATr();let d=kTr.safeParse(await wTr(c));if(!d.success)return fS({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 fS({error:"Invalid or expired grant"},400);return fS({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 fS({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return eue(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return eue(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 eue(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${he(h)}`),eue(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:gze(c.id),method:"GET",public:!0,handler:a(c)}))]}var Clo=600000,Dlo=120000,CTr=1000,Ilo=u.object({clientId:u.string().trim().min(1),clientSecret:u.string().trim().min(1)}),_lo=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(bze,u.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),DTr=u.object({publicUrl:u.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:u.record(bze,Ilo).default({}).describe("Per provider, the shared app the broker holds"),instances:u.array(_lo).default([])});function Tlo(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 Eze(e){let t=zt({id:"oauth-broker",config:DTr,setup:(r)=>{let{config:i}=r,n=Tlo(i,e);if(i.instances.length===0||n.length===0)return{routes:[]};return{routes:BTr({publicUrl:i.publicUrl,providers:n,instances:new xze(i.instances),authorizations:new u$({ttlMs:Clo,maxPending:CTr,now:e.now}),grants:new u$({ttlMs:Dlo,maxPending:CTr,now:e.now}),now:e.now??Date.now,logger:bt(r).logger})}}});return wo(t,({state:r})=>r.routes)}var Plo=2592000000,g$=(e,t)=>Ht(`${e}
|
|
9528
9528
|
${t}`);function ITr(e,t){let r=(i)=>i!==void 0&&t()-i.usedAt<Plo;return{get:async(i,n)=>{let o=await e.get(g$(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(g$(i,n),{hash:o,usedAt:t()})},conflictKept:async(i,n,o,s)=>{let a=await e.get(g$(i,n));if(!r(a))return;await e.set(g$(i,n),{hash:a.hash,conflictEdit:o,...s!==void 0&&{conflictId:s},usedAt:t()})},forget:async(i,n)=>{await e.delete(g$(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 _Tr(e=Date.now){let t=new Map;return ITr({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 Rlo="webdav.mount-base",Flo=u.object({hash:u.string().min(1),conflictEdit:u.string().min(1).optional(),conflictId:u.string().min(1).optional(),usedAt:u.number()});function TTr(e,t=Date.now){let r=e.scoped({namespace:Rlo,schema:Flo});return ITr({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 Mlo=new Set([".obsidian"]),PTr=33554432;function kB(e){let[t]=e;return t!==void 0&&Mlo.has(t)}function RTr(){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 Olo="webdav.kept",Nlo=u.object({path:u.string().min(1),bytes:u.string().optional(),modified:u.number()});function FTr(e){let t=e.scoped({namespace:Olo,schema:Nlo}),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 Llo}from"crypto";var jlo=500;class vze{run=Llo().slice(0,8);keep;sequence=0;recent=[];waiting=new Set;closed=!1;constructor(e={}){this.keep=e.keep??jlo}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 $lo}from"crypto";import{posix as Glo}from"path";var y$="note",zlo=100,OTr=new Set(["image","document"]);function NTr(e){return OTr.has(e)}var Ulo={".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 wze{reader;scope;containment;everyType;constructor(e,t,r={}){this.reader=e,this.scope=t,this.containment=Ay(e),this.everyType=r.everyType??!1}async resolve(e){if(e.length===0)return{kind:"folder",segments:e};if(!e.every(Aze))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(MTr).map((i)=>({kind:"folder",segments:[...e,i]})),...r.sort((i,n)=>MTr(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(y$)?(await this.hierarchy(y$,[])).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:zlo,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(Aze))return;let{entityType:t,id:r}=N6(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(Aze))return;let r=e.join("/"),{entityType:i,id:n}=N6(r,this.containment);if(!this.reader.getEntityTypes().includes(i))return;let o=wy(i,n,t,this.containment);return o.writable&&o.relativePath===r?{entityType:i,id:n}:void 0}async fileOf(e){let t=$8(e,this.reader.fileExtension(e.entityType));if(!wy(e.entityType,e.id,t,this.containment).writable)return;let i={kind:"file",segments:a7(e.id,e.entityType,t,this.containment).split("/"),contentType:Ulo[t]??"application/octet-stream",etag:`"${e.contentHash}"`,modified:new Date(e.updated)};if(!OTr.has(e.entityType)||t===".md"){let a=t===".yaml"?XT(e.content):e.content;return{...i,size:Buffer.byteLength(a),open:async()=>a}}if(e.content==="")return;let n=ep.safeParse(e.content);if(n.success){let a=await this.reader.statAsset(n.data);if(!a)return;return{...i,size:a.sizeBytes,open:async()=>qlo(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!==y$&&!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 MTr(e,t){return e<t?-1:e>t?1:0}function Aze(e){return e.length>0&&e!=="."&&e!==".."&&!/[/\\\0]/.test(e)}function qlo(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 Sze="image",LTr="note",kze="webdav";async function Bze(e,t){let r=Glo.extname(t.segments[t.segments.length-1]??"").toLowerCase();if(Uu.includes(r))return Klo(e,t,r);let i=r===".yaml"?Hlo(e,t):t;if(i===void 0)return await tue(e,t)?xS("No entry can be stored at this path"):rue();if(r!==".md"&&r!==".yaml")return await tue(e,i)?xS("The drive cannot take documents"):rue();if(i.bytes.byteLength>e.writes.maxFileBytes)return HTr();let n=await e.tree.entityAt(i.segments),o=n?.entity.entityType??e.tree.placementAt(i.segments,r)?.entityType;if(o!==void 0&&NTr(o))return xS(o===Sze?"An image is stored as its image file":"The drive cannot take documents");return n?Wlo(e,i,n):Vlo(e,i,r)}function Hlo(e,t){let r=e.tree.placementAt(t.segments,".yaml")?.entityType;if(r===void 0||e.tree.textExtension(r)!==".yaml")return;let i=ZTr(t.bytes);if(i===void 0)return t;return{...t,bytes:new Uint8Array(Buffer.from(eP(i),"utf8"))}}async function Wlo(e,t,{entity:r,file:i}){let{writes:n}=e,o=t.onlyIfAbsent===!0||!Cze(t.ifMatch,i.etag);if(o&&!t.keepAsConflict)return t.onlyIfAbsent?iue():gS();let s=$Tr(n,t.bytes,r.entityType);if("status"in s)return s;if(Zlo(n,s.parsed,r))return await e.mount.held(r.contentHash),{status:204,etag:await GTr(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=await b$(e,t.grant,"update",l,QS(r.entityType,r,l,e.reader));if(d)return d;if(o)return jTr(e,t,{existing:r,base:t.onlyIfAbsent||t.ifMatch===null?void 0:{hash:t.ifMatch.replace(/^"|"$/g,"")},text:s.text,declared:s.parsed.visibility});if(t.ifMatch===null){let h=await e.mount.base();if(h!==void 0&&h.hash!==r.contentHash)return jTr(e,t,{existing:r,base:h,text:s.text,declared:s.parsed.visibility})}let p=await nue(()=>n.updateEntity({entity:l,options:{expectedContentHash:r.contentHash,eventContext:E$(t.grant)}}));if(!p.ok)return WTr(p.error);if(p.value.skipReason==="content-conflict")return gS();if(!p.value.skipped)await BB(n,t.grant,"update","allowed",l);let m=await e.tree.entityAt(t.segments);if(m)await e.mount.held(m.entity.contentHash);return{status:204,etag:m?.entity.content===s.text?m.file.etag:void 0}}function Zlo(e,t,r){let i=Ize(()=>e.deserializeEntity(r.content,r.entityType));return i.ok&&(t.visibility??r.visibility)===r.visibility&&Bun.deepEquals(t,i.value)}async function jTr(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 gS();return await e.mount.conflictKept(a,c),{status:204,conflictId:c}}async function Vlo(e,t,r){let{writes:i,tree:n}=e,{segments:o}=t;if(!await tue(e,t))return rue();let s=n.placementAt(o,r);if(!s)return xS("No entry can be stored at this path");let a=$Tr(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=zhe(s.entityType,void 0,l.status,e.reader)!=="non-publish",h=await b$(e,t.grant,"create",p,m?["create","publish"]:["create"]);if(h)return h;let f=await nue(()=>i.createEntity({entity:p,options:{conditionalWrite:{expectedRevision:null},eventContext:E$(t.grant)}}));if(!f.ok)return Dze(f.error);return await BB(i,t.grant,"create","allowed",p),{status:201,etag:await GTr(e,t,a.text)}}async function Klo(e,t,r){let{writes:i,tree:n}=e,{segments:o,bytes:s,grant:a}=t,c=await n.entityAt(o);if(!c&&!await tue(e,t))return rue();let l=c?{entityType:c.entity.entityType,id:c.entity.id}:n.placementAt(o,r);if(l?.entityType!==Sze)return xS("An image can only be stored in the image folder");if(s.byteLength>i.maxAssetBytes)return HTr();if(c&&t.onlyIfAbsent)return iue();if(c&&!Cze(t.ifMatch,c.file.etag))return gS();let d=await p7(zTr(s));if(!d)return{status:422,message:"The file is not a PNG, JPEG, GIF or WebP image"};let p=s7(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"&&m7($lo("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:Sze,visibility:c?.entity.visibility??"public"},g=await b$(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:E$(a)},w=await nue(async()=>{if(c)return(await i.updateEntity({entity:{...c.entity,...b},stagedAsset:y,options:{...A,expectedContentHash:c.entity.contentHash}})).skipReason==="content-conflict"?gS():void 0;await i.createEntity({entity:{...f,...b},stagedAsset:y,options:{...A,conditionalWrite:{expectedRevision:null}}});return}),C=w.ok?w.value:Dze(w.error);if(C)return await i.discardStagedAsset(y),C;await BB(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 UTr(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!==LTr||s?.entityType!==LTr)return xS("The drive renames notes only, to another note's name");if(await i.entityAt(t.to))return iue();let a=await b$(e,t.grant,"rename",o,["update"]);if(a)return a;let c=await nue(()=>r.renameEntity({entityType:o.entityType,id:o.id,newId:s.id,options:{expectedContentHash:o.contentHash,eventContext:E$(t.grant)}}));if(!c.ok)return Dze(c.error);if(!c.value.renamed)return gS();return await BB(r,t.grant,"rename","allowed",o),{status:201}}async function qTr(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(!Cze(t.ifMatch,n.etag))return gS();let o=await b$(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:E$(t.grant)}}))return gS();return await e.mount.forget(),await BB(e.writes,t.grant,"delete","allowed",i),{status:204}}function $Tr(e,t,r){let i=ZTr(t);if(i===void 0)return{status:422,message:"The file is not UTF-8 text"};let n=Ize(()=>e.deserializeEntity(i,r));return n.ok?{text:i,parsed:n.value}:{status:422,message:he(n.error,"The file cannot be read")}}async function b$(e,t,r,i,n){let o=t.principal.permissionLevel,s=Ize(()=>n.forEach((a)=>e.writes.permissions.assertEntityActionAllowed(i.entityType,a,{userPermissionLevel:o})));if(!s.ok)return await BB(e.writes,t,r,"denied",i,"entity-action-policy"),xS(he(s.error,"Not allowed"));if(r!=="delete"&&!sm(o,i.visibility))return await BB(e.writes,t,r,"denied",i,"visibility-policy"),xS(`Cannot set visibility to "${i.visibility}" at ${o} permission`);return}function BB(e,t,r,i,n,o){return e.recordAudit({actorUserId:t.principal.userId,action:`${kze}.entity.${r}.${i}`,targetType:"entity",targetId:n.id,metadata:{entityType:n.entityType,interfaceType:kze,outcome:i,...o?{reason:o}:{}}})}async function GTr(e,t,r){let i=await e.tree.entityAt(t.segments);return i?.entity.content===r?i.file.etag:void 0}function E$(e){return{actor:{kind:"user",userId:e.principal.userId},interfaceType:kze}}function Cze(e,t){return e===null||e==="*"||e===t}function tue(e,t){return e.folderExists(t.segments.slice(0,-1))}function rue(){return{status:409,message:"The folder does not exist"}}function HTr(){return{status:413,message:"The file is larger than the drive accepts"}}function iue(){return{status:412,message:"An entry already exists at this path"}}function Dze(e){return e instanceof Error&&e.name==="EntityWriteConflictError"?iue():WTr(e)}function xS(e){return{status:403,message:e}}function gS(){return{status:412,message:"The file changed since it was opened"}}function WTr(e){if(JS(e))return{status:422,message:he(e,"The file cannot be saved")};throw e}function ZTr(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}}function Ize(e){try{return{ok:!0,value:e()}}catch(t){return{ok:!1,error:t}}}async function nue(e){try{return{ok:!0,value:await e()}}catch(t){return{ok:!1,error:t}}}import{posix as Ylo}from"path";var Jlo=new Set([".md",".yaml",...Uu,...q8]),Qlo=600000,Xlo=16777216,VTr=(e,t,r)=>!kB(e.split("/"))&&r-t>=Qlo;function KTr(e){return e.startsWith(".")||!Jlo.has(Ylo.extname(e).toLowerCase())}class _ze{files=new Map;folders=new Map;now;kept;opened=new Map;pending=Promise.resolve();constructor(e=Date.now,t=RTr()){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=kB(t);if([...i.values()].filter((l)=>kB(l.segments)===s).reduce((l,d)=>l+d.bytes.byteLength,0)-(o?.bytes.byteLength??0)+r.byteLength>(s?PTr:Xlo))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&&kB(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&&kB(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)}),kB(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(VTr(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(VTr(i,n.touched,r))t.delete(i)}),t.size===0)this.files.delete(e);return t}}class Tze{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(YTr(e,t),r+30000)}take(e,t){let r=YTr(e,t),i=this.expected.get(r);if(i===void 0)return!1;return this.expected.delete(r),i>this.now()}}function YTr(e,t){return`${e}
|
|
9529
9529
|
${t.join("/")}`}import{createHash as euo}from"crypto";var tuo=600000,ruo=16777216;class Pze{held=new Map;now;capBytes;constructor(e=Date.now,t=ruo){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-${euo("sha256").update(r.bytes).digest("hex")}"`,until:o+tuo});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 iuo}from"crypto";var JTr=600;class Rze{locks=new Map;now;constructor(e=Date.now){this.now=e}acquire(e,t,r){if(this.live(e))return;let i={token:`opaquelocktoken:${iuo()}`,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||!QTr(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||QTr(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 QTr(e,t,r){return e.userId===t&&r.includes(`<${e.token}>`)}function XTr(e){let t=/Second-(\d+)/i.exec(e??"")?.[1];return Math.min(t?Number(t):JTr,JTr)}function nuo(e){let t=Kie(e);if(t==="enum"){let r=Jie(e);return r?{type:"enum",enumValues:r}:{type:"enum"}}if(t==="literal")return{type:"string",defaultValue:Qie(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 ouo(e){let t=[];for(let[r,i]of Object.entries(e.shape)){if(d6(i)?.studioWidget==="hidden")continue;let{inner:n,required:o,defaultValue:s}=Yie(i),a=nuo(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 Fze(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:ouo(r)}]})}var suo={"&":"&","<":"<",">":">"};function CB(e){return e.replace(/[&<>]/g,(t)=>suo[t]??t)}var ePr="<D:lockscope><D:exclusive/></D:lockscope><D:locktype><D:write/></D:locktype>";function auo(e){return[`<D:supportedlock><D:lockentry>${ePr}</D:lockentry></D:supportedlock>`,`<D:displayname>${CB(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>${CB(e.contentType)}</D:getcontenttype>`:"",e.etag?`<D:getetag>${CB(e.etag)}</D:getetag>`:"",e.lastModified?`<D:getlastmodified>${e.lastModified.toUTCString()}</D:getlastmodified>`:""].join("")}function tPr(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:">${e.map((r)=>`<D:response><D:href>${CB(r.href)}</D:href><D:propstat><D:prop>${auo(r)}</D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>`).join("")}</D:multistatus>`}function rPr(e){return`<?xml version="1.0" encoding="utf-8"?><D:error xmlns:D="DAV:"><D:${e}/></D:error>`}function iPr(e){return`<?xml version="1.0" encoding="utf-8"?><D:prop xmlns:D="DAV:"><D:lockdiscovery><D:activelock>${ePr}<D:depth>0</D:depth><D:timeout>Second-${e.seconds}</D:timeout><D:locktoken><D:href>${CB(e.token)}</D:href></D:locktoken><D:lockroot><D:href>${CB(e.href)}</D:href></D:lockroot></D:activelock></D:lockdiscovery></D:prop>`}function nPr(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"><D:response><D:href>${CB(e)}</D:href><D:status>HTTP/1.1 200 OK</D:status></D:response></D:multistatus>`}var cuo=[".brain","changes"],luo=50,oPr=25,uuo=[".brain","vault-shapes.json"],duo=["OPTIONS","GET","HEAD","PROPFIND"],dPr=["PUT","DELETE","MOVE","COPY","PROPPATCH","MKCOL","LOCK","UNLOCK"],pPr=[...duo,...dPr],puo=pPr.join(", "),sue='application/xml; charset="utf-8"',muo={"X-Content-Type-Options":"nosniff","Content-Security-Policy":"sandbox","Cache-Control":"no-store"};function mPr(e){let t={options:e,mounts:e.mounts??_Tr(e.now),scratch:new _ze(e.now,e.kept),locks:new Rze(e.now),cleanups:new Tze(e.now),holds:new Pze(e.now)},r={GET:(i,n)=>cPr(i,n,!0),HEAD:(i,n)=>cPr(i,n,!1),PROPFIND:fuo,PUT:xuo,DELETE:Euo,MOVE:wuo,COPY:async()=>w$("The drive does not copy files"),PROPPATCH:vuo,MKCOL:Auo,LOCK:Buo,UNLOCK:Cuo};return pPr.map((i)=>({path:e.basePath,match:"prefix",method:i,public:!0,handler:async(n)=>{if(i==="OPTIONS")return v$(Tuo());let o=await e.resolveAppPassword(n);if(!o)return v$(Puo(e.realm));if(sPr(i)&&o.access!=="write")return v$(w$("This app password is read-only"));let s=n.headers.get("x-brain-sync")?.trim()==="1",a={request:n,grant:o,tree:new wze(e.reader,_i(o.principal.permissionLevel),{everyType:s}),path:EPr(e.basePath,new URL(n.url).pathname),sync:s};if(sPr(i)&&i!=="LOCK"&&i!=="UNLOCK"&&a.path&&!hPr(t,a,a.path.segments))return v$(Uze());await t.scratch.open(o.principal.userId);let c=await r[i](t,a);return await t.scratch.settle(),v$(c)}}))}function hPr(e,t,r){return e.locks.permits(r,t.grant.principal.userId,t.request.headers.get("if"))}function sPr(e){return dPr.some((t)=>t===e)}function aue(e,t){let{path:r}=t;return r&&!r.asFolder&&k_(r.segments)?e.scratch.get(t.grant.principal.userId,r.segments):void 0}function k_(e){let t=e[e.length-1];return t!==void 0&&(fPr(e)||KTr(t))}function fPr(e){return e.some((t)=>t.startsWith("."))}async function cue(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 jze(e,t,r){return r.length===0||e.scratch.hasFolder(t.grant.principal.userId,r)||(await t.tree.resolve(r))?.kind==="folder"}async function zze(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 xPr(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 zze(e,t,n):void 0)?.etag===i?null:i}async function huo(e,t){let r=new URL(t.request.url).searchParams,i=Number(r.get("wait")??oPr),n=Number.isFinite(i)?Math.min(Math.max(i,0),luo):oPr,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 aPr(e,t,r){let i=Oze(r,e.options.basePath),n=await zze(e,t,r);return n?{...i,contentLength:n.bytes.byteLength,etag:n.etag,lastModified:n.savedAt}:i}function gPr(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 lue(e,t){return{tree:t.tree,reader:e.options.reader,writes:e.options.writes,mount:gPr(e,t),recordConflict:async(r)=>e.options.recordConflict?.(r),folderExists:(r)=>jze(e,t,r)}}async function cPr(e,t,r){let{shapes:i,changes:n}=e.options;if(t.sync&&n!==void 0&&t.path?.segments.join("/")===cuo.join("/"))return huo(n,t);if(t.sync&&i!==void 0&&t.path?.segments.join("/")===uuo.join("/")){let c=JSON.stringify({shapes:Fze(i).filter((l)=>l.entityType===y$||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=aue(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:bPr(o),"Last-Modified":o.modified.toUTCString()}});let s=await cue(e,t);if(!s)return dh();if(s.kind==="folder")return Nze();let a=await zze(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 gPr(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 fuo(e,t){let r=t.request.headers.get("depth");if(r!=="0"&&r!=="1")return new Response(rPr("propfind-finite-depth"),{status:403,headers:{"Content-Type":sue}});let{basePath:i}=e.options,n=aue(e,t);if(n)return Mze([uPr(n,i)]);let o=await cue(e,t);if(!o)return dh();if(o.kind==="file"||r==="0")return Mze([await aPr(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 Mze([Oze(o,i),...await Promise.all(a.map((l)=>aPr(e,t,l))),...e.scratch.listFolders(s,o.segments).filter((l)=>!c.has(l)).map((l)=>Oze({kind:"folder",segments:[...o.segments,l]},i)),...e.scratch.list(s,o.segments).map((l)=>uPr(l,i))])}async function xuo(e,t){let{path:r}=t;if(!r)return dh();if(r.asFolder||r.segments.length===0)return Nze();let{maxFileBytes:i,maxAssetBytes:n}=e.options.writes,o=await Duo(t.request,Math.max(i,n)),s=t.grant.principal.userId,a=k_(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 jze(e,t,r.segments))return Nze();return yPr(e.scratch.put(s,r.segments,o))}let c=await Bze(lue(e,t),{segments:r.segments,bytes:o,ifMatch:await xPr(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 guo(e,t,r.segments,o,c);if("message"in c||c.etag===void 0)e.cleanups.expect(s,r.segments);return await buo(e,t,r.segments,o,c),S$(e,t,r.segments,c)}async function guo(e,t,r,i,n){if("message"in n)return S$(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 yuo(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 yuo(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 buo(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 Euo(e,t){let{path:r}=t;if(!r)return dh();let i=t.grant.principal.userId;if(e.scratch.removeFolder(i,r.segments))return Lze();if(!r.asFolder&&k_(r.segments)){if(e.scratch.delete(i,r.segments))return Lze()}if(r.segments.length===0||(await t.tree.resolve(r.segments))?.kind==="folder")return w$("The drive does not delete folders");if(r.asFolder)return dh();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 qTr(lue(e,t),{segments:r.segments,ifMatch:await xPr(e,t,r.segments),grant:t.grant});if(!("message"in n))e.holds.release(t.grant.appPasswordId,r.segments);return S$(e,t,r.segments,n)}async function vuo(e,t){let r=aue(e,t)??await cue(e,t);if(!r||!t.path)return dh();let i="kind"in r&&r.kind==="folder",n=A$(t.path.segments);return new Response(nPr(`${e.options.basePath}/${n}${i&&n?"/":""}`),{status:207,headers:{"Content-Type":sue}})}async function Auo(e,t){let{path:r}=t;if(!r)return dh();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 jze(e,t,i.slice(0,-1)))return new Response("The parent folder does not exist",{status:409});let[o]=i;if(!fPr(i)&&(o===void 0||!t.tree.isFolderType(o)))return w$("Only an entity type can be a folder here");return e.scratch.makeFolder(n,i),new Response(null,{status:201})}async function wuo(e,t){let r=t.request.headers.get("destination");if(!r)return new Response("Destination required",{status:400});let i=Iuo(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 dh();if(!hPr(e,t,i.segments))return Uze();let o=t.request.headers.get("overwrite")?.toUpperCase()!=="F";if(n.asFolder)return w$("The drive does not rename files");if(!k_(n.segments))return k_(i.segments)?kuo(e,t,n.segments,i.segments,o):Suo(e,t,n.segments,i.segments);let s=t.grant.principal.userId,a=e.scratch.get(s,n.segments);if(!a)return dh();if(k_(i.segments)){if(!o&&e.scratch.get(s,i.segments))return oue("The destination exists");let l=e.scratch.rename(s,n.segments,i.segments);return l==="missing"?dh():new Response(null,{status:l==="created"?201:204})}if(!o&&await t.tree.entityAt(i.segments))return oue("The destination exists");let c=await Bze(lue(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 S$(e,t,i.segments,c)}async function Suo(e,t,r,i){let n=await UTr(lue(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 S$(e,t,i,n)}async function kuo(e,t,r,i,n){let o=await t.tree.entityAt(r);if(!o)return dh();let s=t.grant.principal.userId;if(!n&&e.scratch.get(s,i))return oue("The destination exists");let a=new Uint8Array(await new Response(await o.file.open()).arrayBuffer());return yPr(e.scratch.put(s,i,a))}async function Buo(e,t){let{path:r}=t;if(!r||r.segments.length===0)return dh();let i=t.grant.principal.userId,n=XTr(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?lPr(e,r.segments,l,200):oue("No such lock to refresh")}let a=e.locks.acquire(r.segments,i,n);if(!a)return Uze();let c=aue(e,t)!==void 0||await cue(e,t)!==void 0;return lPr(e,r.segments,a,c?200:201)}function lPr(e,t,r,i){return new Response(iPr({...r,href:`${e.options.basePath}/${A$(t)}`}),{status:i,headers:{"Content-Type":sue,"Lock-Token":`<${r.token}>`}})}async function Cuo(e,t){let{path:r}=t;if(!r)return dh();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)?Lze():new Response("No such lock",{status:409})}function S$(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 yPr(e){return e==="full"?new Response("Too many temporary files",{status:507}):new Response(null,{status:e==="created"?201:204})}async function Duo(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 Oze(e,t){let r=e.segments[e.segments.length-1]??"";if(e.kind==="folder"){let i=A$(e.segments);return{href:i?`${t}/${i}/`:`${t}/`,displayName:r,collection:!0}}return{href:`${t}/${A$(e.segments)}`,displayName:r,collection:!1,contentLength:e.size,contentType:e.contentType,etag:e.etag,lastModified:e.modified}}function uPr(e,t){return{href:`${t}/${A$(e.segments)}`,displayName:e.segments[e.segments.length-1]??"",collection:!1,contentLength:e.bytes.byteLength,contentType:"application/octet-stream",etag:bPr(e),lastModified:e.modified}}function bPr(e){return`"scratch-${e.modified.getTime()}-${e.bytes.byteLength}"`}function A$(e){return e.map(encodeURIComponent).join("/")}function EPr(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(_uo);return o.every((s)=>s!==void 0&&s!==""&&!/[/\\\0]/.test(s))?{segments:o.filter((s)=>s!==void 0),asFolder:i}:void 0}function Iuo(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=EPr(e,n.pathname);return o&&!o.asFolder&&o.segments.length>0?o:void 0}function _uo(e){try{return decodeURIComponent(e)}catch{return}}function Mze(e){return new Response(tPr(e),{status:207,headers:{"Content-Type":sue}})}function Tuo(){return new Response(null,{status:200,headers:{DAV:"1, 2",Allow:puo,"MS-Author-Via":"DAV"}})}function Puo(e){return new Response("Authentication required",{status:401,headers:{"WWW-Authenticate":`Basic realm="${e.replace(/["\\]/g,"")}", charset="UTF-8"`}})}function Nze(){return new Response("A folder has no content",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}})}function Lze(){return new Response(null,{status:204})}function dh(){return new Response("Not found",{status:404})}function w$(e){return new Response(e,{status:403})}function Uze(){return new Response("The file is locked",{status:423})}function oue(e){return new Response(e,{status:412})}function v$(e){let t=new Headers(e.headers);return Object.entries(muo).forEach(([r,i])=>t.set(r,i)),new Response(e.body,{status:e.status,headers:t})}var qze="/dav",Ruo=5242880,vPr=u.strictObject({maxFileBytes:u.number().int().positive().describe("Maximum bytes of a file a client may save").default(Ruo)}),Fuo=zt({id:"webdav",config:vPr,setup:(e)=>{let t=bt(e);if(t.executionOnly)return{routes:[]};t.registered(()=>{if(t.entityReads.getEntityTypes().includes(cs))return;throw Error(`webdav needs the "${cs}" entity type to keep saves that lose to a newer version. Add "conflict" to this brain, which the core bundle includes.`)});let r=new vze;for(let n of[da,ms,tp,yb])t.listen(n,({payload:o})=>r.record(o.entityType),{mode:"observe"});t.listen(ao.shuttingDown,()=>r.close(),{mode:"observe"});let i=TTr(t.classRuntimeState);return t.ready(()=>i.sweep()),t.interaction({id:une,label:"Drive",description:"Mount the brain as a network drive over WebDAV.",href:`${qze}/`,kind:"protocol",priority:40,visibility:"trusted"}),{routes:mPr({basePath:qze,realm:t.identity.get().name,reader:t.entityReads,shapes:t.entityShapes,changes:r,writes:{maxFileBytes:e.config.maxFileBytes,maxAssetBytes:i7,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:FTr(t.classRuntimeState),recordConflict:async(n)=>{let o=await t.messaging.request(I8,n);return o.status==="answered"?o.data.conflictId:void 0},conflictPending:async(n)=>await t.entityReads.getEntityRaw({entityType:cs,id:n,visibilityScope:st("ask only whether a conflict is still waiting to be resolved")})!==null})}}}),$ze=wo(Fuo,({state:e})=>e.routes);var APr=$ze;var Muo=u.object({errcode:u.string()}),Ouo=u.object({session:u.string()});async function Gze(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 wPr(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=Ouo.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 wPr(d)??d.status}`);return"registered"}async function wPr(e){let t=Muo.safeParse(await e.json().catch(()=>{return}));return t.success?t.data.errcode:void 0}var Hze="matrix-homeserver";function uue(e){return`${e.replace(/\/+$/,"")}/_matrix/client/unstable/login/sso/callback/matrix-homeserver`}function Hy(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`}function Wze(e){let t=e.publicBaseUrl.replace(/\/+$/,"");return`[global]
|
|
9530
9530
|
server_name = ${Hy(e.serverName)}
|
|
@@ -11109,5 +11109,5 @@ ${Xde}</style><link rel="stylesheet" href="${hbo}"></head><body class="guest-pag
|
|
|
11109
11109
|
`);return{kind:"text",filename:"inbox-source.txt",mediaType:"text/plain",content:l,sizeBytes:new TextEncoder().encode(l).byteLength}}catch{return Kzr()}}async handleContextSessionRequest(e){let t=ya(e);if(t)return t;return Zjr(e,{conversations:this.runtime.conversations,resolveAccess:(r)=>this.resolveConversationAccess(r),interfaceType:Yp,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 izr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Yp})}async handleDeleteSessionRequest(e){return nzr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Yp})}async handleRenameSessionRequest(e){return ozr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Yp})}async handleArchiveSessionRequest(e){return szr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Yp})}async handleDocumentAttachmentRequest(e){return ijr(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleImageAttachmentRequest(e){return njr(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleJobStatusRequest(e){return Yjr(e,{resolveAuthSession:this.resolveAuthSession,createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),jobs:this.runtime.jobs})}async handleMessagesRequest(e){return lzr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Yp})}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,Yp,t)}ensureWebChatConversation(e,t){return this.ensureBrowserConversation(e,Yp,"Web Chat",t)}async requireExistingBrowserConversation(e,t,r){let i=await this.runtime.conversations.get(e);return Xy(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 Xy(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 Xy(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 Yde(e,t,r,(i)=>this.createId(i))}createId(e){return`${e}-${crypto.randomUUID()}`}}function Kzr(){return new Response("Inbox context is unavailable",{status:409})}function rHe(e={}){let t=Eh({id:Yp,config:qGe,setup:async(n)=>{let o=Ko(n),s=new Qzr(n.config,e,o,n.runtimeState(I7));return await s.register(),o.ready(()=>s.onReady()),s}}),r=wo(t,({state:n})=>n.webRoutes()),i=qx(r,({state:n})=>{let o=n.maintenanceDaemon();return{id:"guest-maintenance",start:()=>o.start(),stop:()=>o.stop(),healthCheck:()=>o.healthCheck()}});return Hie(i,({state:n})=>n.transport())}var Jbo=rHe(),Xzr=Jbo;var iHe='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 eUr={critical:0,high:1,medium:2,low:3};function tUr(e){return[...e].sort((t,r)=>{let i=r.metadata.requested-t.metadata.requested;if(i!==0)return i;return eUr[t.metadata.priority]-eUr[r.metadata.priority]})}var vG=u.enum(["new","planned","in-progress","done","declined"]),AG=u.enum(["low","medium","high","critical"]),dpe=u.object({title:u.string(),status:vG,priority:AG.default("medium"),requested:u.number().int().default(1).meta({studioWidget:"provenance"}),declinedReason:u.string().optional()}),nHe=u.object({title:u.string(),status:vG,priority:AG,requested:u.number().int().meta({studioWidget:"provenance"}),slug:u.string().optional().meta({studioWidget:"hidden"}),declinedReason:u.string().optional()});var Qbo=u.object({items:u.array(u.object({id:u.string(),name:u.string(),count:u.number().int().nonnegative(),priority:AG,status:vG}))});function Xbo(e){if(e==="critical")return"error";if(e==="high")return"warn";return"neutral"}var oHe=Xn({id:"top-wishes",title:"Top Wishes",group:"knowledge",placement:"secondary",priority:30,permission:"public",data:Qbo,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:Xbo(t.priority)},{label:t.status,tone:t.status==="done"?"good":"neutral"}]}))}]})});function eEo(e){return oHe.bind(e,async({entities:t,signal:r})=>(r.throwIfAborted(),{items:tUr(await t.list(tb,{limit:10})).map((n)=>({id:n.id,name:n.metadata.title,count:n.metadata.requested,priority:n.metadata.priority,status:n.metadata.status}))}))}var tb=Zi(ht({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:nHe,markdown:{decode:({content:e,frontmatter:t})=>{let r=dpe.parse(t);return{content:e,metadata:{title:r.title,status:r.status,priority:r.priority,requested:r.requested,slug:jt(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:iHe,dashboardWidgets:(e)=>[eEo(e)]}),dpe);var rUr=0.3,tEo="Do these two wishes ask for the same thing?",rEo=u.object({same:u.boolean().describe("True only when delivering one would fulfil the other.")});async function iEo(e,t,r){let{same:i}=await e.generateObject([tEo,"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(`
|
|
11110
11110
|
`),rEo);return i}function ppe(e,t,r){return{nearest:(i,n)=>e.nearest(tb,i,{maxDistance:n}),getEntity:(i)=>t.get(tb,i),maxDistance:r,ai:e}}async function mpe(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 iEo(e.ai,t.content,nEo(a))?a:i(s+1)},n=await i(0);if(n)return n;let o=await e.getEntity(jt(t.title));return o?.visibility==="public"?o:null}function nEo(e){let{title:t,status:r,priority:i,requested:n,declinedReason:o}=e.metadata;return wG({title:t,status:r,priority:i,requested:n,declinedReason:o},e.content)}function wG(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 iUr=u.object({title:u.string(),description:u.string()}),oEo=u.object({stored:iUr,incoming:iUr}),sHe="eval-stored-wish";function nUr(e){return wG({title:e.title,status:"new",priority:"medium",requested:1},e.description)}function oUr(e){return{sameWish:async(t,r)=>{let{stored:i,incoming:n}=oEo.parse(t),{fixtures:o}=r;await o.reset(),await o.seed({id:sHe,entityType:"wish",content:nUr(i),metadata:{title:i.title,status:"new",priority:"medium",requested:1,slug:jt(i.title)}}),await o.settleEmbeddings();let s=$t(r),a=nUr(n),c=(await s.nearest(tb,a,{maxDistance:2})).find(({entity:d})=>d.id===sHe)?.distance;if(c===void 0)throw Error("The stored wish was not embedded");let l=await mpe(ppe(s,r.entities,e),{title:n.title,content:a});return{distance:c,shortlisted:c<=e,sameWish:l?.id===sHe}}}}async function sEo(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 mpe(ppe($t(e),e.entities,t),{title:i,content:wG(o,n)});if(s)return{update:{id:s.id,content:s.content.trim(),metadata:{...s.metadata,requested:s.metadata.requested+1}}};let a=jt(i);return{create:{id:a,content:n,metadata:{...o,slug:a}}}}function sUr(e){let t={resolve:(r)=>sEo(r,e)};return{fromPrompt:t,fromContent:t,fromUpload:t}}var aHe=u.object({sameWishDistance:u.number().min(0).max(1).default(rUr)});var aEo=Pi({id:"wishlist",config:aHe,entities:[tb],configure:({config:e})=>({entities:[{entity:tb,create:sUr(e.sameWishDistance),evals:oUr(e.sameWishDistance)}]})}),aUr=aEo;var cUr="gpt-6-luna";var BS={create:"trusted",update:"trusted",delete:"admin",extract:"admin",publish:"admin"},lUr=[{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}}],uUr=["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.'],dUr=[{member:"topics",value:{extractableStatuses:["published","draft"]}},{member:"conversation-memory",value:{memoryVisibility:"shared"}},{member:"action-board",value:{cardVisibility:"shared"}}],pUr=["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 CS="capability-bundles-v1",cHe="core",lHe="media",uHe="automation",SG="web",dHe="chat",pHe="site",mHe="publishing",hHe="federation",fHe="team",cEo="matrix",hpe=im({id:cHe,members:["profile","prompt","conflict","style-guide","directory-sync","note","refined-note","link","topics","unified-inbox","mcp","a2a","agents"],evalDisable:["mcp"]}),fpe=im({id:lHe,members:["document","image"]}),xpe=im({id:uHe,members:["playbooks","onboarding"]}),gpe=im({id:SG,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"]}),ype=im({id:dHe,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"]}),bpe=im({id:pHe,members:["site-info","site-content","site-builder","form","analytics"],config:[{member:"dashboard",value:{routePath:"/dashboard"},overrides:SG}]}),Epe=im({id:mHe,members:["blog","series","portfolio","decks","content-pipeline","social-media","newsletter","stock-photo"],config:lUr,agentInstructions:uUr}),vpe=im({id:hHe,members:["atproto","references"],evalDisable:["atproto"]}),Ape=im({id:fHe,members:[],config:dUr,permissions:[{member:"note",config:{entityActions:{note:BS}}},{member:"refined-note",config:{entityActions:{"refined-note":BS}}},{member:"link",config:{entityActions:{link:BS}}},{member:"image",config:{entityActions:{image:BS}}},{member:"docs",config:{entityActions:{doc:BS}}},{member:"conversation-memory",config:{entityActions:{decision:BS,"action-item":BS}}},{member:"mcp",config:{rules:[{pattern:"mcp:http",level:"admin"}]},overrides:SG}],agentInstructions:pUr}),lEo=im({id:cEo,members:["matrix-server"],http:!0,permissions:[{member:"chat",config:{rules:[{pattern:"matrix:*",level:"public"}]}}]}),mUr=[hpe,fpe,xpe,gpe,ype,bpe,Epe,vpe,lEo,Ape];function BG(e,t,r){let i={name:e,version:DS.version};return(n)=>nm(t,n,i,r)}function uEo(e){let{entity:t,provider:r}=D_r(e),i={name:"@brains/newsletter",version:DS.version};return[...nm(t.definition,t.config,i,{pluginId:"newsletter"}),...r?nm(r.definition,r.config,i,{pluginId:r.kind}):[]]}function $r(e,t,r,i={},n=void 0){return[e,BG(t,r,i),n]}function kG(e,t,r,i,n={}){return[e,BG(t,r,n),i]}var hUr=Kpe({name:"brain",version:DS.version,bundleContract:CS,model:cUr,reasoningEffort:"low",capabilities:[$r("prompt","@brains/prompt",gFr,{pluginId:"prompt"}),$r("conflict","@brains/conflict",fFr,{pluginId:"conflicts"}),$r("profile","@brains/profile",$Ue,{pluginId:"profile"}),$r("style-guide","@brains/style-guide",rNr,{pluginId:"style-guide"}),$r("ask-content","@brains/ask-content",nNr,{pluginId:"ask-content"}),["image",(e)=>[...BG("@brains/image-plugin",E7r,{pluginId:"image"})(e),...BG("@brains/image-plugin",b7r,{})({})],void 0],$r("document","@brains/document-plugin",jwr,{pluginId:"document"}),$r("note","@brains/note",G_r,{pluginId:"note"}),$r("refined-note","@brains/refined-note",EFr,{pluginId:"refined-note"}),$r("link","@brains/link",O7r,{pluginId:"link"}),$r("references","@brains/reference",X7r,{pluginId:"references",ownedTypePluginId:"reference"}),$r("wishlist","@brains/wishlist",aUr,{pluginId:"wishlist"}),["topics",(e)=>[...nm(tLr,e,{name:"@brains/topics",version:DS.version},{pluginId:"topics"}),...nm(cGe,{},{name:"@brains/knowledge-map",version:DS.version},{pluginId:"knowledge-map"})],void 0],$r("decks","@brains/decks",Yyr,{pluginId:"decks"}),$r("directory-sync","@brains/directory-sync",Tvr,{pluginId:"directory-sync"},{seedContent:!0,seedContentPath:"./seed-content",initialSync:!0}),$r("atproto-registry","@brains/atproto-registry",Uge,{pluginId:"atproto-registry"}),["agents",(e)=>{let{enableSkillDerivation:t,notifyOnNewAgents:r,askAllApproved:i}=ttt.parse(e),n={name:"@brains/agent-discovery",version:DS.version};return[...nm(Gxe,{},n,{pluginId:"agent-discovery",ownedTypePluginId:"agent-entity"}),...nm(Hxe,{notifyOnNewAgents:r,askAllApproved:i},n,{pluginId:"agent"}),...nm(t?Wxe:Vxe,{},n,{pluginId:"skill",ownedTypePluginId:"skill-entity"}),...nm(Zxe,{},n,{pluginId:"shared-copies",ownedTypePluginId:"shared-copy"})]},void 0],["assessment",(e)=>nm(bge.parse(e).enableSwotDerivation?Ege:vge,{},{name:"@brains/assessment",version:DS.version},{pluginId:"swot"}),void 0],$r("auth-service","@brains/auth-service",Wve,{pluginId:"auth-service"}),$r("notifications","@brains/notifications",Z_r,{pluginId:"notifications"}),$r("contact","@brains/contact",q0r,{pluginId:"contact",dependencies:U0r}),$r("quiz","@brains/quiz",txr,{pluginId:"quiz",dependencies:exr}),$r("playbooks","@brains/playbooks",fUe,{pluginId:"playbooks"}),$r("onboarding","@brains/onboarding",SFr,{pluginId:"onboarding",dependencies:["playbook","playbooks"]}),$r("studio","@brains/studio",Hfr,{pluginId:"studio"}),$r("dashboard","@brains/dashboard",Ayr,{pluginId:"dashboard"}),$r("admin","@brains/admin",Rhe,{pluginId:"admin"}),$r("site-info","@brains/site-info",b$e,{pluginId:"site-metadata"}),$r("site-content","@brains/site-content",ROr,{pluginId:"site-content",ownedTypePluginId:"site-content-entity"}),$r("site-builder","@brains/site-builder-plugin",_Or,{pluginId:"site-builder"}),$r("form","@brains/form",G0r,{pluginId:"form"}),$r("analytics","@brains/analytics",Stt,{pluginId:"analytics"}),$r("blog","@brains/blog",Vxt,{pluginId:"blog"}),$r("series","@brains/series",gMr,{pluginId:"series"}),$r("portfolio","@brains/portfolio",MRr,{pluginId:"portfolio"}),$r("content-pipeline","@brains/content-pipeline",A0r,{pluginId:"content-pipeline"}),$r("social-media","@brains/social-media",YOr,{pluginId:"social-media"}),["newsletter",uEo,void 0],$r("stock-photo","@brains/stock-photo",eNr,{pluginId:"stock-photo"}),["atproto",BG("@brains/atproto",crt,{pluginId:"atproto"}),(e)=>({...e.ATPROTO_APP_PASSWORD?{appPassword:e.ATPROTO_APP_PASSWORD}:{}})],$r("conversation-memory","@brains/conversation-memory",L_e,{pluginId:"conversation-memory"}),$r("action-board","@brains/action-board",NGe,{pluginId:"action-board"}),$r("faq","@brains/faq",qgr,{pluginId:"faq",ownedTypePluginId:"faq-entity"}),$r("docs","@brains/doc",Xvr,{pluginId:"docs"}),$r("guides","@brains/guide",wAr,{pluginId:"guides"}),$r("book","@brains/book",Bwr,{pluginId:"book",ownedTypePluginId:"book-entity"}),$r("seminar","@brains/seminar",iMr,{pluginId:"seminar",ownedTypePluginId:"seminar-entity"}),$r("email-workflows","@brains/email-workflows",JIr,{pluginId:"email-workflows"}),$r("unified-inbox","@brains/unified-inbox",kGe,{pluginId:"unified-inbox"}),$r("linkedin-import","@brains/linkedin-import",fze,{pluginId:"linkedin-import"}),$r("oauth-broker","@brains/oauth-broker",Eze({providers:{linkedin:oze}}),{pluginId:"oauth-broker"}),$r("webdav","@brains/webdav",APr,{pluginId:"webdav"}),$r("matrix-server","@brains/matrix-server",zPr,{pluginId:"matrix-server"},(e)=>Jze(e))],interfaces:[kG("mcp","@brains/mcp",c_r,(e)=>({...e.MCP_AUTH_TOKEN?{authToken:e.MCP_AUTH_TOKEN}:{}}),{pluginId:"mcp"}),kG("email","@brains/email",MIr,()=>({}),{pluginId:"email"}),kG("web-chat","@brains/web-chat",Xzr,()=>({}),{pluginId:"web-chat"}),kG("chat","@brains/chat",yhr,(e)=>NIe(e,{captureUrls:!0}),{pluginId:"chat"}),kG("a2a","@brains/a2a",jWe,()=>({}),{pluginId:"a2a"})],bundles:mUr,permissions:{rules:[{pattern:"cli:*",level:"admin"},{pattern:"mcp:stdio",level:"admin"}]},deployment:{cdn:{enabled:!0,provider:"bunny"},dns:{enabled:!0,provider:"bunny"}}});var dEo=["headless","personal","professional","team"];var pEo={headless:{bundleContract:CS,bundles:["core"]},personal:{bundleContract:CS,anchor:"person",kind:"professional",bundles:["core","media","web","chat"],plugins:{"directory-sync":{seedContentPath:"./seed-content"}}},professional:{bundleContract:CS,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:CS,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 mEo(e){return structuredClone(e)}function hEo(e){return mEo(pEo[e])}var fEo=hUr,coc=hpe,loc=fpe,uoc=xpe,doc=gpe,poc=ype,moc=bpe,hoc=Epe,foc=vpe,xoc=Ape,yoc=fEo;export{uHe as AUTOMATION_BUNDLE_ID,dEo as BRAIN_RECIPE_NAMES,CS as CANONICAL_BUNDLE_CONTRACT,dHe as CHAT_BUNDLE_ID,cHe as CORE_BUNDLE_ID,hHe as FEDERATION_BUNDLE_ID,lHe as MEDIA_BUNDLE_ID,mHe as PUBLISHING_BUNDLE_ID,pHe as SITE_BUNDLE_ID,fHe as TEAM_BUNDLE_ID,SG as WEB_BUNDLE_ID,uoc as automationBundle,fEo as canonicalBrain,poc as chatBundle,coc as coreBundle,yoc as default,hEo as expandBrainRecipe,foc as federationBundle,loc as mediaBundle,hoc as publishingBundle,moc as siteBundle,xoc as teamBundle,doc as webBundle};
|
|
11111
11111
|
|
|
11112
|
-
//# debugId=
|
|
11112
|
+
//# debugId=F0A8C0D7F998713964756E2164756E21
|
|
11113
11113
|
//# sourceMappingURL=model.js.map
|