@rizom/brain 0.2.0-alpha.818 → 0.2.0-alpha.819
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brain.js +4 -4
- package/dist/chunks/{app-edmp8201.js → app-5vsjv0bx.js} +2 -2
- package/dist/chunks/{index-xfvfc637.js → index-wzhtx0w9.js} +2 -2
- package/dist/chunks/{index-4v3bhxch.js → index-ymf8bdmg.js} +3 -3
- package/dist/chunks/{index-4v3bhxch.js.map → index-ymf8bdmg.js.map} +1 -1
- package/dist/chunks/{package-27yjpkwb.js → package-dftxrpd3.js} +3 -3
- package/dist/chunks/{package-27yjpkwb.js.map → package-dftxrpd3.js.map} +1 -1
- package/dist/model.js +4 -4
- package/dist/model.js.map +1 -1
- package/dist/testing.js +1 -1
- package/dist/ui/{studio-app-073e3nsr.js → studio-app-5wf0chc4.js} +90 -90
- package/dist/ui/{studio-app-073e3nsr.js.map → studio-app-5wf0chc4.js.map} +11 -12
- package/dist/ui/{studio-app-70f8cb17b11c4ae4bb0ceee02c8ead933816ed55051403304c181bf263738790.css → studio-app-a59ab675c76ca274e4d6b64348b36f918b3a7ecfa81d4f4249fc0cc494fdfb8c.css} +20 -11
- package/dist/ui/studio-asset-manifest.json +23 -23
- package/dist/ui/studio-chunks/{account-view-qdwwhy8a.js → account-view-y32wpsyq.js} +1 -1
- package/dist/ui/studio-chunks/main-1h3h013a.js +4 -0
- package/dist/ui/studio-chunks/main-1h3h013a.js.map +13 -0
- package/dist/ui/studio-chunks/main-n8b4hwpq.js +4 -0
- package/dist/ui/studio-chunks/{main-x4eqqte5.js.map → main-n8b4hwpq.js.map} +4 -4
- package/dist/ui/studio-chunks/{main-ntg9v72p.js → main-qqw5r5ap.js} +1 -1
- package/dist/ui/studio-chunks/{main-77snes8p.js → main-sf9xp8er.js} +1 -1
- package/dist/ui/studio-chunks/{main-e0gm5z75.js → main-wvz8aths.js} +1 -1
- package/dist/ui/studio-chunks/{main-qtwkt52a.js → main-wxhbkhkc.js} +32 -32
- package/dist/ui/studio-chunks/{main-qtwkt52a.js.map → main-wxhbkhkc.js.map} +3 -3
- package/dist/ui/studio-chunks/{studio-ask-panel-j4r3wbrv.js → studio-ask-panel-436q7m2q.js} +1 -1
- package/dist/ui/studio-chunks/{studio-chat-workspace-essbhwrc.js → studio-chat-workspace-3q0cw97n.js} +1 -1
- package/package.json +1 -1
- package/dist/ui/studio-chunks/main-tn4apj9j.js +0 -4
- package/dist/ui/studio-chunks/main-tn4apj9j.js.map +0 -13
- package/dist/ui/studio-chunks/main-x4eqqte5.js +0 -4
- /package/dist/chunks/{app-edmp8201.js.map → app-5vsjv0bx.js.map} +0 -0
- /package/dist/chunks/{index-xfvfc637.js.map → index-wzhtx0w9.js.map} +0 -0
- /package/dist/ui/studio-chunks/{account-view-qdwwhy8a.js.map → account-view-y32wpsyq.js.map} +0 -0
- /package/dist/ui/studio-chunks/{main-ntg9v72p.js.map → main-qqw5r5ap.js.map} +0 -0
- /package/dist/ui/studio-chunks/{main-77snes8p.js.map → main-sf9xp8er.js.map} +0 -0
- /package/dist/ui/studio-chunks/{main-e0gm5z75.js.map → main-wvz8aths.js.map} +0 -0
- /package/dist/ui/studio-chunks/{studio-ask-panel-j4r3wbrv.js.map → studio-ask-panel-436q7m2q.js.map} +0 -0
- /package/dist/ui/studio-chunks/{studio-chat-workspace-essbhwrc.js.map → studio-chat-workspace-3q0cw97n.js.map} +0 -0
package/dist/model.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunks/index-xfvfc637.js";import{$ as Eo,$a as fvn,$b as Jvn,$c as SAn,Aa as ox,Ab as nz,Ad as KAn,Ba as Edr,Bb as jvn,Bd as n6,C as ly,Ca as vdr,Cb as zvn,Cc as mfr,Cd as YAn,D as uEn,Da as KEn,Db as vv,Dd as JAn,E as ldr,Ea as YEn,Eb as Sdr,Ed as QAn,F as ydr,Fa as Die,Fb as ez,Fd as dy,G as vEn,Ga as JEn,Gb as Uvn,Gd as iz,H as AEn,Hb as qvn,Hd as XAn,I as wEn,Ia as pIe,Ib as $vn,Id as ewn,J as SEn,Ja as QEn,Jb as Gvn,Jd as twn,K as kEn,Ka as XEn,Kd as rwn,La as evn,Lb as kdr,Ld as iwn,M as _ie,Ma as tvn,Mb as Bdr,Md as nwn,Na as rvn,Nb as Cdr,Nd as own,Oa as ivn,Ob as Ddr,Od as swn,P as s6,Pa as nvn,Pb as Idr,Pd as awn,Q as tdr,Qa as Adr,Qb as Tdr,Qd as Rie,R as o6,Ra as ovn,Rb as _dr,Rc as Ndr,Rd as vIe,S as cy,Sa as svn,Sb as Pdr,Sc as xAn,Sd as cwn,Ta as avn,Tb as Rdr,Tc as gAn,Td as mIe,U as bIe,Ua as cvn,Ub as Fdr,Uc as yAn,Ud as lwn,V as BEn,Va as lvn,Vb as Hvn,Vc as bAn,Vd as ih,W as Vt,Wa as uvn,Wb as Wvn,Wc as i6,Wd as aie,Xa as dvn,Xb as Zvn,Xc as EAn,Xd as uwn,Y as bdr,Ya as pvn,Yb as Vvn,Yc as vAn,Z as CEn,Za as mvn,Zb as Kvn,Zc as AAn,_ as kS,_a as hvn,_b as Yvn,_c as wAn,aa as DS,ab as xvn,ac as Qvn,ad as kAn,ba as il,bb as gvn,bc as Xvn,bd as BAn,ca as DEn,cb as yvn,cc as eAn,cd as CAn,da as IEn,db as BS,dc as tAn,dd as DAn,ea as TEn,eb as bvn,ec as rAn,ed as IAn,fa as _En,fb as cIe,fc as iAn,fd as TAn,ga as PEn,gb as Evn,gc as nAn,gd as _An,ha as REn,hb as vvn,hc as oAn,hd as PAn,ia as FEn,ib as Avn,ic as sAn,id as RAn,ja as MEn,jb as wvn,jc as lIe,jd as FAn,ka as OEn,kb as Svn,kc as rz,kd as MAn,la as NEn,lb as kvn,lc as aAn,ld as OAn,ma as LEn,mb as Bvn,mc as cAn,md as NAn,na as jEn,nb as Cvn,nc as lAn,nd as LAn,oa as zEn,ob as Dvn,oc as uAn,od as jAn,pa as UEn,pb as Ivn,pc as dAn,qa as qEn,qb as Tvn,qc as pAn,qd as zAn,ra as $En,rb as _vn,rc as mAn,rd as UAn,sa as GEn,sb as Pvn,sc as Mdr,sd as qAn,ta as gDe,tb as Rvn,tc as Odr,td as odr,ua as HEn,ub as Fvn,uc as edr,ud as $An,va as WEn,vb as Mvn,vc as hAn,vd as GAn,wa as ZEn,wb as wdr,wc as fAn,wd as HAn,xa as VEn,xb as Ovn,xc as EIe,xd as WAn,ya as aIe,yb as Nvn,yd as ZAn,za as cz,zb as Lvn,zd as VAn}from"./chunks/index-femxb8zf.js";import{$d as zAr,Yd as NT,Zd as bwr,be as _Re}from"./chunks/index-k4strh3v.js";import{de as Uxe}from"./chunks/index-27h92m2e.js";import"./chunks/index-e84v85w3.js";import"./chunks/index-e0qz6mam.js";import"./chunks/index-624fhq2j.js";import"./chunks/index-z0k97qgd.js";import"./chunks/index-x8e40qwv.js";import{ie as z8}from"./chunks/index-4v3bhxch.js";import{Ce as iVe,De as IPr,Ee as AOr,Fe as Mg,Ge as JJ,He as tq,Ie as kAr,Je as Ty,Ke as X7r,Le as FT,Me as URr,Ne as AAr,Oe as BAr,Pe as s_r,Qe as Y7r,Re as Pgt,Se as rLr,Te as sGe,Ue as aGe,Ve as cGe,We as Gvr,Xe as kT,Ye as J7r,Ze as _f,_e as MT,gf as RH,ke as ZWe,le as MH,ne as Bo,oe as L5,pe as Lye,qe as qye,re as oE,se as KZ,te as YZ,ue as JZ,ve as jtt,we as QZ,xe as PC,ye as Tit,ze as ys}from"./chunks/index-3vnrdc3q.js";import{jf as rfe,kf as R$r}from"./chunks/index-kcgba22z.js";import"./chunks/index-gtyh93sb.js";import{$f as Kit,$g as JA,$h as Ufe,$j as The,$l as Khe,$m as EQ,$n as Fb,Af as PV,Ag as ma,Ah as H3,Ai as ga,Aj as nqr,Ak as mP,Al as $t,An as RSe,Ao as lE,Bf as Il,Bg as fs,Bh as wQ,Bi as Yrt,Bj as oqr,Bk as zhe,Bl as _b,Bn as Syt,Bo as Ph,Cf as Knt,Cg as lp,Ch as obt,Ci as $fe,Cj as I$r,Ck as eW,Cl as ro,Cn as Iyt,Co as Yx,Df as pF,Dg as Sb,Dh as Vk,Di as ZT,Dj as wqr,Dk as Uhe,Dl as Po,Dm as aB,Dn as JO,Do as J0r,Ef as mF,Eg as Bhe,Eh as jl,Ei as U6,Ej as Sqr,Ek as qhe,El as Aw,Em as Oae,En as jyt,Eo as Ea,Ff as gr,Fh as B1,Fi as mse,Fj as Dqr,Fk as $he,Fl as fP,Fm as DPr,Fn as QO,Gf as GC,Gh as tN,Gi as hse,Gj as Oqr,Gk as $9,Gl as Bn,Gm as DSr,Gn as ZUr,Hf as RV,Hg as Nfe,Hh as k1,Hi as iP,Hj as Nqr,Hk as Ghe,Hl as dt,Hm as Kse,Hn as g7e,If as YR,Ig as dn,Ih as W0,Ii as tGe,Ij as Lqr,Im as zae,In as Tyt,Jg as Mn,Jh as u8e,Ji as R8,Jj as eme,Jk as Hhe,Jl as j_r,Jm as kSr,Jn as _yt,Kf as kw,Kg as Ogt,Kh as fbt,Ki as NPe,Kj as P$r,Km as ISr,Kn as $z,Lf as Wye,Lg as Lfe,Lh as hbt,Lj as _qr,Lk as uo,Ll as Pi,Lm as _Sr,Ln as Pyt,Mf as FV,Mh as Fre,Mi as vw,Mj as $Ur,Ml as HPr,Mn as bQ,Nf as gs,Ng as bP,Nh as vbt,Ni as JWe,Nl as z$,Nn as Ryt,Of as nr,Og as l5,Oh as Kyt,Oi as sdt,Ok as i5,Ol as $Pr,On as uqr,Pf as Qe,Pg as U9,Ph as Yyt,Pi as adt,Pk as Whe,Pl as Vhe,Pn as zyt,Qf as Oo,Qg as EP,Qj as FA,Ql as Vr,Qn as Zyt,Rf as Ys,Rg as vP,Rh as AQ,Rj as t5,Rn as dqr,Sf as Gh,Sg as jfe,Sh as Abt,Sj as Che,Sm as fde,Sn as lqr,Tf as Gye,Tg as Ib,Th as f8e,Tj as Jx,Tm as $0,Tn as kyt,Ug as AP,Uk as hP,Ul as Db,Un as xne,Vf as Wit,Vg as u5,Vh as mPr,Vk as Zhe,Vl as bt,Vn as jz,Wf as Zit,Wg as d5,Wl as Qx,Wn as Cfr,Xg as wP,Xh as Ws,Xl as ha,Xn as ym,Yg as SP,Yi as Bb,Yj as q9,Yl as Kut,Yn as y5,Zf as Vit,Zg as zfe,Zj as Dhe,Zk as GUr,Zl as El,Zm as HUr,Zn as Pb,_g as H9,_h as kb,_j as Ihe,_l as xP,_m as WUr,_n as Rb,ah as Mh,ak as _he,am as Yhe,an as Uyt,ao as sd,bh as Tb,bi as p5,bk as pP,bl as ugr,bm as zt,bn as qyt,bo as Qhe,ch as ew,cj as DLr,ck as Phe,cl as Eoe,cm as Kx,cn as $yt,co as o5,dh as a1,dk as Rhe,dl as Zfr,dm as Ene,dn as G3,do as tW,eh as z7r,ei as hc,ek as Fhe,el as FH,em as vne,en as XO,fh as mot,fi as qfe,fk as Mhe,fm as rVe,gh as Ube,gk as Ohe,gm as ko,gn as jye,go as s5,hk as Nhe,hl as mm,hm as Fn,ho as a5,ii as uP,ik as Lhe,im as Q_r,in as _h,jg as _Lr,jh as Ane,ji as WA,jj as RA,jl as ad,jm as Jo,kh as wne,ki as tw,kj as yqr,kl as Gfe,lg as PLr,lh as Sne,li as eT,lj as Vqr,ll as Hfe,mg as Swr,mh as kne,mi as iGe,mj as xWe,ml as Wfe,mo as VA,nf as Mfe,nh as Gfr,ni as YWe,nj as k$r,nk as c0,nl as Zfe,no as Xhe,of as Ofe,oh as Hfr,oi as NLr,oj as B$r,ok as m5,ol as Vfe,om as VO,on as Jhe,oo as CZe,pf as She,ph as zTe,pi as iQ,pj as qU,pk as h5,pl as Kfe,pm as wyt,po as efe,qf as cp,qh as S6,qi as Boe,qj as Vf,qk as uW,ql as x5,qm as hQ,qo as HA,rf as e5,ri as Jde,rj as c9,rl as kP,rm as lme,rn as Ufr,ro as Th,sf as khe,sh as fo,si as Coe,sj as Fqr,sk as f5,sl as g5,sm as ume,sn as qfr,so as tfe,tf as z9,th as Ebt,ti as Fue,tj as Mqr,tl as fa,tn as fQ,to as gP,uf as ot,ug as su,uh as Ie,ui as tQ,uj as tme,ul as Qo,un as Myt,uo as X_r,vf as Br,vg as lP,vh as H0,vi as P8,vj as C$r,vl as BP,vm as bqr,vn as Oyt,wg as ai,wh as jn,wi as nT,wj as D$r,wk as jhe,wl as Vi,wn as $qr,xf as xe,xg as xm,xh as SQ,xi as oT,xj as tqr,xk as ZA,xl as Yfe,xn as Gqr,yf as Bw,yg as o0,yh as ybt,yi as H1e,yj as rqr,yk as Cb,yl as Jfe,yn as Nyt,zf as ft,zg as jr,zh as Wk,zi as HAr,zj as iqr,zk as r5,zl as gm,zn as Lyt,zo as KA}from"./chunks/index-hvtxk8x8.js";import{$o as Eae,$p as git,$q as OC,$r as w1,$s as po,Ap as T1r,Aq as Xoe,Ar as Di,As as PY,Bp as Bae,Bq as dMr,Br as TLr,Bs as Pne,Cp as vr,Cq as pMr,Cr as XLr,Cs as Vut,Dp as j5,Dq as TY,Dr as aV,Ep as Ht,Er as Gf,Es as pEr,Fo as F1r,Fp as dx,Fq as Znt,Fs as U1e,Go as mpe,Gp as tV,Gq as Vnt,Gr as L7,Hp as Zp,Hq as nnt,Hr as Rae,Hs as Xv,Ht as up,Io as kn,Ip as vy,Iq as ont,Ir as nG,Is as d_r,It as hm,Jo as Cf,Jp as Hn,Jq as Zut,Jr as wde,Js as fue,Jt as od,Ko as eoe,Kp as Jpe,Kq as vn,Kr as Gqe,Ks as RB,Lq as md,Lr as q$,Ls as D6,Mo as kr,Mp as o$r,Mq as v8,Mr as $$,Ms as Xme,No as fi,Np as s$r,Nq as Zle,Nr as BG,Ns as bne,Oo as ZI,Oq as A7r,Or as gzr,Os as NI,Ot as n5,Po as e9,Pq as Vle,Pr as CG,Ps as wfr,Qo as ppe,Qp as A_,Qq as Zye,Qr as noe,Qs as Rm,Ro as WB,Rq as CV,Rr as _xr,Rs as c1,So as B$,Sr as Rxr,Ss as pa,To as dQ,Tq as A1,Tr as ooe,Ts as Tvr,Uo as wa,Up as cP,Uq as fe,Ur as Vue,Us as Jp,Vo as Yv,Vp as aMr,Vr as DRr,Vs as Lt,Wo as ZB,Wq as To,Wr as ode,Ws as Moe,Xo as jze,Xr as sde,Xs as W9,Yp as S$r,Yr as jxr,Ys as ld,Zo as Cae,Zr as Fxr,Zs as mc,_o as Kv,_p as xMr,_q as br,_r as Mxr,_s as v1,ap as vae,ar as h$r,as as y0r,at as Ay,bp as bUr,bq as vhe,br as j9,bt as hEr,cp as Bse,cq as HH,cr as Gne,cs as $ue,ct as Wfr,dp as iB,dq as WH,dr as eQ,ds as LPr,dt as vT,ep as qge,eq as ZH,er as M3,es as jPr,et as fx,fp as wae,fq as VH,fs as h3,ft as hyt,gp as nB,gq as QH,gs as Ppe,gt as rw,hp as Aae,hq as XH,hr as ase,hs as Une,ht as sc,ip as o8,iq as X8,ir as Nyr,is as qne,it as QI,jp as v1r,jq as rZe,jr as Ffr,js as EWe,jt as ct,kp as A1r,kq as ZZe,kr as yne,ks as _$r,kt as Cu,lp as EUr,lq as Vx,lr as gne,ls as Vne,lt as dWe,mp as Zpe,mq as VZe,ms as Rpe,mt as cd,np as vUr,nq as LH,ns as que,nt as au,op as B1r,oq as KH,or as aPr,os as W7,ot as We,pp as AUr,pq as YH,pr as Sw,ps as MUe,qp as SFe,qq as PR,qr as Jz,qs as NUe,rp as kFe,rs as gRr,rt as dP,sp as xq,sq as Ade,ss as ZPr,st as t0,tp as BFe,tq as Obr,ts as yRr,tt as ehe,up as C1r,uq as us,us as VPr,vp as CFe,vq as mOr,vs as QPr,vt as ihe,wp as D1r,wq as JEr,wr as Dae,ws as Kne,xp as I1r,xq as LS,xr as JT,xs as f3,yp as Sae,yq as M0r,yr as Ine,ys as Wne,zp as kae,zq as qI,zr as Hne,zs as _Y}from"./chunks/index-63p1xma2.js";import{Qt as iUe,St as NH}from"./chunks/index-agfrkbxw.js";import{EB as Vyt,Hv as lSe,LB as Ih,MB as XC,OB as Mc,QB as Yp,RB as Zgr,SB as Yi,TB as T$r,Xx as ou,Zx as e4,jy as pc,tz as vQ,xB as et,yy as Hs}from"./chunks/index-g1c4y6gc.js";import{jD as u}from"./chunks/index-bshgrg07.js";import"./chunks/index-pmvk8xga.js";import{nD as no,oD as $Qr,pD as E,qD as rg,rD as xs,sD as ce}from"./chunks/index-7ysxtpwx.js";function WKe(e){return e===0||e>=55296&&e<=57343||e>1114111}function ZKe(e){if(WKe(e))return 65533;if(e>=128&&e<=159)return wVr[e-128]||e;return e}function VKe(e){return WKe(e)?65533:e}var wVr;var KKe=xs(()=>{wVr=[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 YKe(e,t,r,i,n,o){let a=e.length,c=o*90,l=0,d=()=>{let L=u0[e.charCodeAt(l++)];return L<o?L:L*91-c+u0[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 K=0,ee=H,q=H+L;while(ee<q){let S=u0[e.charCodeAt(l++)];if(S<89)K+=S,h[ee++]=K;else if(S===89){let _=u0[e.charCodeAt(l++)]+2;while(_--)h[ee++]=++K}else{let _=u0[e.charCodeAt(l++)];K+=89+(_<90?_*91+u0[e.charCodeAt(l++)]:u0[e.charCodeAt(l++)]*8281+u0[e.charCodeAt(l++)]*91+u0[e.charCodeAt(l++)]),h[ee++]=K}}}y(i,0),y(p,o);let b=new Int32Array(n*2),A=0,w=0;function B(L,H){for(let K=0;K<L;K++){let ee=H+K,q=d(),S=d();b[w*2]=q,b[w*2+1]=S,w+=1,f[ee]=A;let _=(h[q]<0?g[q]:1)+(h[S]<0?g[S]:1);g[ee]=_,A+=_}}B(n-o+i,o+p),B(o-i,i);let R=new Uint16Array(A),M=0;for(let L=0;L<w;L++)for(let H=0;H<2;H++){let K=b[L*2+H],ee=h[K];if(ee<0){let q=f[K],S=q+g[K];while(q<S)R[M++]=R[q++]}else R[M++]=ee}let k=new Uint16Array(t),N=0;while(l<a){let L=u0[e.charCodeAt(l++)];if(L>=o)L=L*91-c+u0[e.charCodeAt(l++)];let H=h[L];if(H<0){let K=f[L],ee=K+g[L];while(K<ee)k[N++]=R[K++]}else k[N++]=H}return k}var u0;var JKe=xs(()=>{u0=(()=>{let e=new Uint8Array(127),t=0;for(let r=33;r<=126;r++)if(r!==34&&r!==36&&r!==92)e[r]=t++;return e})()});var I0e;var QKe=xs(()=>{JKe();I0e=YKe("!}.&u%}'&}*'~!6*)%&,~!J~!J~%L~y<~!R,~~%Lu~~#GD~~#|)1#%}^%}2%+#.##%##%}&%##%'#%##&%#%#'%#&#%#&#'#%%#&#%##%#)%''%&%#%#'%#%%#%%}%%%#%#&(23#%%#&-%0%('1#(##%#'##+%'*.:1}#%#6-+(%'%%#%%%}#L'2351&('%}&/N'(0(/*-%(%%}#'+&T%7.2}#&%&#%#36/5##%&%%#&#%%#))2%%##%&&'0~!#*+&'%1~!%).'3q?&%'1~!.##%6(~!+%%%(Gw'rT~!E#<nA%#jZ~!H%(~!42##~!*31&~!G%U~#)5~#`3~!J~!Z~%]~%Y~%C~!q~!u~#kz~%#~!6'~!D~!U~!?~#T~!c%~!G#'~%7|~!G~!J~!G&~#pb~(Df}#%}*&}#%##%##%##&#-}&'#'&%#.++}%mI,#,@&(}*%}*'%&##&#%##%}&0}#.},U},%}+%}&%}#%##&}B%(}(%}+%)})%##%#&}&%##%&}<%}>%#%&}*%}(%}9%}/%})%}*%}*%}?&}&%}3%}&*#%})%#%#)}#&#-#+*%E%%'%'#%}#*V##&##I}#&&##%&%#&&Qf%%))w/0+&%#(#.%-''''++++7}>%4'',##1,#%#&%##&#'##&#*#9)%&%}#*}%,#+P(%A&%#'&##wSD',9E00#y#@}(+}&%&>~!#~!X}#*}(&&}(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Eg>unwfh;9:4E|YjQsBt|vjx'hYq3!(?C2F|J:2<BaY?C2F|GOu!5x,g|p{ah!-(?C2F|c9:4E|OjXuvvNr}:Rh&i[w*t|cd+U#jJvsu)vsSn~Mkfrmu9p}u7vwv]So!McW#Xa!ax5@A5aY:5;5<H|>kJv~vYrquJu3x4ib#T)2@SmZM?C2F|Bj:rmu9@xPhI(a*a#U#`a3-5Abb|L~@:RhK9:4E|0@52B5G|#C::aY?C2F|-:2<BaY?C2F|.5Jvk!a)javYrquJu3x4ia#T)2@SmYM?C2F|HAxPhH(!a#U#`a*-5Abb|4~@:RhJ9:4E|R@52B5G|F:2<BaY?C2F|Sc^#Xa2j=Qq5CJvB!-g<v{z;hhM?C2F|Zi[vrv{z;hiM?C2F|XKsA>!a)-g<v{z;h[eb?C2F|]i[vrv{z;h]eb?C2F|^iZu.vix,hZq3ah!.(?C2F|QOu!5ShXM:2<BaY?C2F|P",13494,2713,49,25,61)});var jP;var T0e=xs(()=>{jP=new Uint16Array([512,26465,29036,7,0,2,4,116,24638,116,24636,8693,29807,24610,621,1,0,0,3,112,24614,111,115,24615])});var Lc;var XKe=xs(()=>{(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.FLAG13=8192]="FLAG13",e[e.BRANCH_LENGTH=8064]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE",e[e.VALUE_MASK=8191]="VALUE_MASK"})(Lc||(Lc={}))});function eYe(e){return e-lu.ZERO>>>0<=9}function SVr(e){return(e|wW)-lu.LOWER_A>>>0<=5}function kVr(e){return(e|wW)-lu.LOWER_A>>>0<=25}function BVr(e){return e===lu.EQUALS||kVr(e)||eYe(e)}class _0e{decodeTree;emitCodePoint;errors;state=cu.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=d0.Strict;runConsumed=0;constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r}startEntity(e){this.decodeMode=e,this.state=cu.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case cu.EntityStart:{if(e.charCodeAt(t)===lu.NUM)return this.state=cu.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=cu.NamedEntity,this.stateNamedEntity(e,t)}case cu.NumericStart:return this.stateNumericStart(e,t);case cu.NumericDecimal:return this.stateNumericDecimal(e,t);case cu.NumericHex:return this.stateNumericHex(e,t);default:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){if(t>=e.length)return-1;if((e.charCodeAt(t)|wW)===lu.LOWER_X)return this.state=cu.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=cu.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){let r=e.length,{result:i}=this,{consumed:n}=this;while(t<r){let o=e.charCodeAt(t);if(eYe(o)||SVr(o)){let s=o<=lu.NINE?o-lu.ZERO:(o|wW)-lu.LOWER_A+10;i=i*16+s,n+=1,t+=1}else return this.result=i,this.consumed=n,this.emitNumericEntity(o,3)}return this.result=i,this.consumed=n,-1}stateNumericDecimal(e,t){let r=e.length,{result:i}=this,{consumed:n}=this;while(t<r){let o=e.charCodeAt(t)-lu.ZERO;if(o>>>0>9)return this.result=i,this.consumed=n,this.emitNumericEntity(o+lu.ZERO,2);i=i*10+o,n+=1,t+=1}return this.result=i,this.consumed=n,-1}emitNumericEntity(e,t){if(this.consumed<=t)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===lu.SEMI)this.consumed+=1;else if(this.decodeMode===d0.Strict)return 0;if(this.emitCodePoint((this.decodeTree===jP?VKe:ZKe)(this.result),this.consumed),this.errors){if(e!==lu.SEMI)this.errors.missingSemicolonAfterCharacterReference();this.errors.validateNumericCharacterReference(this.result)}return this.consumed}flushAndEmitLegacyOrReject(e,t,r,i){return this.consumed=e,this.excess=t,this.result===0||this.decodeMode===d0.Attribute&&(i===0||t>1||BVr(r))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:r}=this,i=e.length,n=this.decodeMode===d0.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=r[o];while(t<i){while((c&(Lc.VALUE_LENGTH|Lc.FLAG13))===0&&(c&Lc.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&Lc.JUMP_TABLE,f=(c&Lc.BRANCH_LENGTH)>>7;if(f===0){if(m!==h)return this.flushAndEmitLegacyOrReject(a,s,m,0);o+=1}else{let g=m-h;if(g>>>0>=f)return this.flushAndEmitLegacyOrReject(a,s,m,0);let y=r[o+1+g];if(y===0)return this.flushAndEmitLegacyOrReject(a,s,m,0);o=o+f+y&65535}if(c=r[o],t+=1,s+=1,t>=i)break}if(t>=i)break;if((c&(Lc.VALUE_LENGTH|Lc.FLAG13))===Lc.FLAG13){let m=(c&Lc.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&Lc.JUMP_TABLE))return this.flushAndEmitLegacyOrReject(a,s,f,0);t+=1,s+=1,h=1}while(h<m){if(t>=i)return this.treeIndex=o,this.excess=s,this.consumed=a,this.runConsumed=h,-1;let f=h-1,y=r[o+1+(f>>1)]>>((f&1)<<3)&255,b=e.charCodeAt(t);if(b!==y)return this.runConsumed=0,this.flushAndEmitLegacyOrReject(a,s,b,0);t+=1,s+=1,h+=1}this.runConsumed=0,o+=1+(m>>1),c=r[o];continue}let l=c>>>14,d=e.charCodeAt(t);if(l!==0){if(!n&&(c&Lc.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===lu.SEMI)return this.emitNamedEntityData(o,l,a+s);if(l===1)return this.flushAndEmitLegacyOrReject(a,s,d,l)}let p=CVr(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&Lc.FLAG13)===0)this.result=o,a+=s-1,s=1;return this.treeIndex=o,this.excess=s,this.consumed=a,-1}emitNotTerminatedNamedEntity(){let{result:e,decodeTree:t}=this,r=t[e]>>>14;return this.emitNamedEntityData(e,r,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,r){let{decodeTree:i}=this;if(this.emitCodePoint(t===1?i[e]&Lc.VALUE_MASK:i[e+1],r),t===3)this.emitCodePoint(i[e+2],r);return r}end(){switch(this.state){case cu.NamedEntity:return this.result!==0&&(this.decodeMode!==d0.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case cu.NumericDecimal:return this.emitNumericEntity(0,2);case cu.NumericHex:return this.emitNumericEntity(0,3);case cu.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function CVr(e,t,r,i){let n=(t&Lc.BRANCH_LENGTH)>>7,o=t&Lc.JUMP_TABLE;if(o){if(n===0)return i===o?r:-1;let c=i-o;if(c>>>0>=n)return-1;let 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 lu,wW=32,cu,d0;var tYe=xs(()=>{KKe();T0e();XKe();QKe();T0e();(function(e){e[e.AMP=38]="AMP",e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_X=120]="LOWER_X"})(lu||(lu={}));(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(cu||(cu={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(d0||(d0={}))});function v5(e){return e===Er.Space||e===Er.NewLine||e===Er.Tab||e===Er.FormFeed||e===Er.CarriageReturn}function eC(e){return e===Er.Slash||e===Er.Gt||v5(e)}function DVr(e){return e>=Er.LowerA&&e<=Er.LowerZ||e>=Er.UpperA&&e<=Er.UpperZ}class tC{cbs;state=Ze.Text;buffer="";sectionStart=0;index=0;entityStart=0;baseState=Ze.Text;isSpecial=!1;running=!0;offset=0;xmlMode;decodeEntities;recognizeSelfClosing;entityDecoder;constructor({xmlMode:e=!1,decodeEntities:t=!0,recognizeSelfClosing:r=e},i){this.cbs=i,this.xmlMode=e,this.decodeEntities=t,this.recognizeSelfClosing=r,this.entityDecoder=new _0e(e?jP:I0e,(n,o)=>this.emitCodePoint(n,o))}reset(){this.state=Ze.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=Ze.Text,this.isSpecial=!1,this.currentSequence=ci.Empty,this.sequenceIndex=0,this.running=!0,this.offset=0}write(e){this.offset+=this.buffer.length,this.buffer=e,this.parse()}end(){if(this.running)this.finish()}pause(){this.running=!1}resume(){if(this.running=!0,this.index<this.buffer.length+this.offset)this.parse()}stateText(e){if(e===Er.Lt||!this.decodeEntities&&this.fastForwardTo(Er.Lt)){if(this.index>this.sectionStart)this.cbs.ontext(this.sectionStart,this.index);this.state=Ze.BeforeTagName,this.sectionStart=this.index}else if(this.decodeEntities&&e===Er.Amp)this.startEntity()}currentSequence=ci.Empty;sequenceIndex=0;enterTagBody(){if(this.currentSequence===ci.Plaintext)this.currentSequence=ci.Empty,this.state=Ze.InPlainText;else if(this.isSpecial)this.state=Ze.InSpecialTag,this.sequenceIndex=0;else this.state=Ze.Text}stateSpecialStartSequence(e){let t=e|32;if(this.sequenceIndex<this.currentSequence.length){if(t===this.currentSequence[this.sequenceIndex]){this.sequenceIndex++;return}if(this.sequenceIndex===3){if(this.currentSequence===ci.ScriptEnd&&t===ci.StyleEnd[3]){this.currentSequence=ci.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===ci.TitleEnd&&t===ci.TextareaEnd[3]){this.currentSequence=ci.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===ci.NoembedEnd&&t===ci.NoframesEnd[4]){this.currentSequence=ci.NoframesEnd,this.sequenceIndex=5;return}}else if(eC(e)){this.sequenceIndex=0,this.state=Ze.InTagName,this.stateInTagName(e);return}this.isSpecial=!1,this.currentSequence=ci.Empty,this.sequenceIndex=0,this.state=Ze.InTagName,this.stateInTagName(e)}stateCDATASequence(e){if(e===ci.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===ci.Cdata.length)this.state=Ze.InCommentLike,this.currentSequence=ci.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1}else if(this.sequenceIndex=0,this.xmlMode)this.state=Ze.InDeclaration,this.stateInDeclaration(e);else this.state=Ze.InSpecialComment,this.stateInSpecialComment(e)}fastForwardTo(e){while(++this.index<this.buffer.length+this.offset)if(this.buffer.charCodeAt(this.index-this.offset)===e)return!0;return this.index=this.buffer.length+this.offset-1,!1}emitComment(e){this.cbs.oncomment(this.sectionStart,this.index,e),this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=Ze.Text}stateInCommentLike(e){if(!this.xmlMode&&this.currentSequence===ci.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&e===Er.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===ci.CommentEnd&&this.sequenceIndex===2&&e===Er.Gt)this.emitComment(2);else if(this.currentSequence===ci.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&e!==Er.Gt)this.sequenceIndex=Number(e===Er.Dash);else if(e===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===ci.CdataEnd)this.cbs.oncdata(this.sectionStart,this.index,2);else this.cbs.oncomment(this.sectionStart,this.index,3);this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=Ze.Text}}else if(this.sequenceIndex===0){if(this.fastForwardTo(this.currentSequence[0]))this.sequenceIndex=1}else if(e!==this.currentSequence[this.sequenceIndex-1])this.sequenceIndex=0}isTagStartChar(e){return this.xmlMode?!eC(e):DVr(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(eC(e)){let t=this.index-this.currentSequence.length;if(this.sectionStart<t){let r=this.index;this.index=t,this.cbs.ontext(this.sectionStart,t),this.index=r}this.isSpecial=!1,this.sectionStart=t+2,this.stateInClosingTagName(e);return}this.sequenceIndex=0}if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(this.sequenceIndex===0){if(this.currentSequence===ci.TitleEnd||this.currentSequence===ci.TextareaEnd){if(this.decodeEntities&&e===Er.Amp)this.startEntity()}else if(this.fastForwardTo(Er.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(e===Er.Lt)}stateBeforeTagName(e){if(e===Er.ExclamationMark)this.state=Ze.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===Er.Questionmark)if(this.xmlMode)this.state=Ze.InProcessingInstruction,this.sequenceIndex=0,this.sectionStart=this.index+1;else this.state=Ze.InSpecialComment,this.sectionStart=this.index;else if(this.isTagStartChar(e)){this.sectionStart=this.index;let t=this.xmlMode||this.cbs.isInForeignContext?.()?void 0:IVr.get(e|32);if(t===void 0)this.state=Ze.InTagName;else this.isSpecial=!0,this.currentSequence=t,this.sequenceIndex=3,this.state=Ze.SpecialStartSequence}else if(e===Er.Slash)this.state=Ze.BeforeClosingTagName;else this.state=Ze.Text,this.stateText(e)}stateInTagName(e){if(eC(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(v5(e))if(this.xmlMode);else this.state=Ze.InSpecialComment,this.sectionStart=this.index;else if(e===Er.Gt){if(this.state=Ze.Text,!this.xmlMode)this.sectionStart=this.index+1}else this.state=this.isTagStartChar(e)?Ze.InClosingTagName:Ze.InSpecialComment,this.sectionStart=this.index}stateInClosingTagName(e){if(eC(e))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=Ze.AfterClosingTagName,this.stateAfterClosingTagName(e)}stateAfterClosingTagName(e){if(e===Er.Gt||this.fastForwardTo(Er.Gt))this.state=Ze.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(e){if(e===Er.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(e===Er.Slash)this.state=Ze.InSelfClosingTag;else if(!v5(e))this.state=Ze.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(e){if(e===Er.Gt){if(this.cbs.onselfclosingtag(this.index),this.sectionStart=this.index+1,!this.recognizeSelfClosing){this.enterTagBody();return}this.state=Ze.Text,this.isSpecial=!1,this.currentSequence=ci.Empty}else if(!v5(e))this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===Er.Eq||eC(e))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=Ze.AfterAttributeName,this.stateAfterAttributeName(e)}stateAfterAttributeName(e){if(e===Er.Eq)this.state=Ze.BeforeAttributeValue;else if(e===Er.Slash||e===Er.Gt)this.cbs.onattribend(Em.NoValue,this.sectionStart),this.sectionStart=-1,this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!v5(e))this.cbs.onattribend(Em.NoValue,this.sectionStart),this.state=Ze.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(e){if(e===Er.DoubleQuote)this.state=Ze.InAttributeValueDq,this.sectionStart=this.index+1;else if(e===Er.SingleQuote)this.state=Ze.InAttributeValueSq,this.sectionStart=this.index+1;else if(!v5(e))this.sectionStart=this.index,this.state=Ze.InAttributeValueNq,this.stateInAttributeValueNoQuotes(e)}handleInAttributeValue(e,t){if(e===t||!this.decodeEntities&&this.fastForwardTo(t))this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(t===Er.DoubleQuote?Em.Double:Em.Single,this.index+1),this.state=Ze.BeforeAttributeName;else if(this.decodeEntities&&e===Er.Amp)this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,Er.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,Er.SingleQuote)}stateInAttributeValueNoQuotes(e){if(v5(e)||e===Er.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(Em.Unquoted,this.index),this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(this.decodeEntities&&e===Er.Amp)this.startEntity()}stateBeforeDeclaration(e){if(e===Er.OpeningSquareBracket)this.state=Ze.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=e===Er.Dash?Ze.BeforeComment:Ze.InDeclaration;else if((e|32)===ci.Doctype[0])this.state=Ze.DeclarationSequence,this.currentSequence=ci.Doctype,this.sequenceIndex=1;else if(e===Er.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else if(e===Er.Dash)this.state=Ze.BeforeComment;else this.state=Ze.InSpecialComment}stateDeclarationSequence(e){if(this.sequenceIndex===this.currentSequence.length)this.state=Ze.InDeclaration,this.stateInDeclaration(e);else if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(e===Er.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else this.state=Ze.InSpecialComment}stateInDeclaration(e){if(e===Er.Gt||this.fastForwardTo(Er.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=Ze.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(e){if(e===Er.Questionmark)this.sequenceIndex=1;else if(e===Er.Gt&&this.sequenceIndex===1)this.cbs.onprocessinginstruction(this.sectionStart,this.index-1),this.sequenceIndex=0,this.state=Ze.Text,this.sectionStart=this.index+1;else this.sequenceIndex=Number(this.fastForwardTo(Er.Questionmark))}stateBeforeComment(e){if(e===Er.Dash)this.state=Ze.InCommentLike,this.currentSequence=ci.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=Ze.InDeclaration;else if(e===Er.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else this.state=Ze.InSpecialComment}stateInSpecialComment(e){if(e===Er.Gt||this.fastForwardTo(Er.Gt))this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1}startEntity(){this.baseState=this.state,this.state=Ze.InEntity,this.entityStart=this.index,this.entityDecoder.startEntity(this.xmlMode?d0.Strict:this.baseState===Ze.Text||this.baseState===Ze.InSpecialTag?d0.Legacy:d0.Attribute)}stateInEntity(){let e=this.index-this.offset,t=this.entityDecoder.write(this.buffer,e);if(t>=0){if(this.state=this.baseState,t===0)this.index-=1}else{if(e<this.buffer.length&&this.buffer.charCodeAt(e)===Er.Amp){this.state=this.baseState,this.index-=1;return}this.index=this.offset+this.buffer.length-1}}cleanup(){if(this.running&&this.sectionStart!==this.index){if(this.state===Ze.Text||this.state===Ze.InPlainText||this.state===Ze.InSpecialTag&&this.sequenceIndex===0)this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index;else if(this.state===Ze.InAttributeValueDq||this.state===Ze.InAttributeValueSq||this.state===Ze.InAttributeValueNq)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=this.index}}shouldContinue(){return this.index<this.buffer.length+this.offset&&this.running}parse(){while(this.shouldContinue()){let e=this.buffer.charCodeAt(this.index-this.offset);switch(this.state){case Ze.Text:{this.stateText(e);break}case Ze.InPlainText:{this.index=this.buffer.length+this.offset-1;break}case Ze.SpecialStartSequence:{this.stateSpecialStartSequence(e);break}case Ze.InSpecialTag:{this.stateInSpecialTag(e);break}case Ze.CDATASequence:{this.stateCDATASequence(e);break}case Ze.DeclarationSequence:{this.stateDeclarationSequence(e);break}case Ze.InAttributeValueDq:{this.stateInAttributeValueDoubleQuotes(e);break}case Ze.InAttributeName:{this.stateInAttributeName(e);break}case Ze.InCommentLike:{this.stateInCommentLike(e);break}case Ze.InSpecialComment:{this.stateInSpecialComment(e);break}case Ze.BeforeAttributeName:{this.stateBeforeAttributeName(e);break}case Ze.InTagName:{this.stateInTagName(e);break}case Ze.InClosingTagName:{this.stateInClosingTagName(e);break}case Ze.BeforeTagName:{this.stateBeforeTagName(e);break}case Ze.AfterAttributeName:{this.stateAfterAttributeName(e);break}case Ze.InAttributeValueSq:{this.stateInAttributeValueSingleQuotes(e);break}case Ze.BeforeAttributeValue:{this.stateBeforeAttributeValue(e);break}case Ze.BeforeClosingTagName:{this.stateBeforeClosingTagName(e);break}case Ze.AfterClosingTagName:{this.stateAfterClosingTagName(e);break}case Ze.InAttributeValueNq:{this.stateInAttributeValueNoQuotes(e);break}case Ze.InSelfClosingTag:{this.stateInSelfClosingTag(e);break}case Ze.InDeclaration:{this.stateInDeclaration(e);break}case Ze.BeforeDeclaration:{this.stateBeforeDeclaration(e);break}case Ze.BeforeComment:{this.stateBeforeComment(e);break}case Ze.InProcessingInstruction:{this.stateInProcessingInstruction(e);break}case Ze.InEntity:{this.stateInEntity();break}}this.index++}this.cleanup()}finish(){if(this.state===Ze.InEntity)this.entityDecoder.end(),this.state=this.baseState;this.handleTrailingData(),this.cbs.onend()}handleTrailingCommentLikeData(e){if(this.state!==Ze.InCommentLike)return!1;if(this.currentSequence===ci.CdataEnd)if(this.xmlMode){if(this.sectionStart<e)this.cbs.oncdata(this.sectionStart,e,0)}else{let t=this.sectionStart-ci.Cdata.length-1;this.cbs.oncomment(t,e,0)}else{let t=this.xmlMode?0:Math.min(this.sequenceIndex,ci.CommentEnd.length-1);this.cbs.oncomment(this.sectionStart,e,t)}return!0}handleTrailingMarkupDeclaration(e){if(this.xmlMode)switch(this.state){case Ze.InSpecialComment:case Ze.BeforeComment:case Ze.CDATASequence:case Ze.DeclarationSequence:case Ze.InDeclaration:return this.cbs.ontext(this.sectionStart,e),!0;default:return!1}switch(this.state){case Ze.BeforeDeclaration:case Ze.InSpecialComment:case Ze.BeforeComment:case Ze.CDATASequence:return this.cbs.oncomment(this.sectionStart,e,0),!0;case Ze.DeclarationSequence:{if(this.sequenceIndex!==ci.Doctype.length)this.cbs.oncomment(this.sectionStart,e,0);return!0}case Ze.InDeclaration:return!0;default:return!1}}handleTrailingData(){let e=this.buffer.length+this.offset;if(this.handleTrailingCommentLikeData(e)||this.handleTrailingMarkupDeclaration(e))return;if(this.sectionStart>=e)return;switch(this.state){case Ze.InTagName:case Ze.BeforeAttributeName:case Ze.BeforeAttributeValue:case Ze.AfterAttributeName:case Ze.InAttributeName:case Ze.InAttributeValueSq:case Ze.InAttributeValueDq:case Ze.InAttributeValueNq:case Ze.InClosingTagName:break;default:this.cbs.ontext(this.sectionStart,e)}}emitCodePoint(e,t){if(this.baseState!==Ze.Text&&this.baseState!==Ze.InSpecialTag){if(this.sectionStart<this.entityStart)this.cbs.onattribdata(this.sectionStart,this.entityStart);this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.onattribentity(e)}else{if(this.sectionStart<this.entityStart)this.cbs.ontext(this.sectionStart,this.entityStart);this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.ontextentity(e,this.sectionStart)}}}var Er,Ze,Em,ci,IVr;var P0e=xs(()=>{tYe();(function(e){e[e.Tab=9]="Tab",e[e.NewLine=10]="NewLine",e[e.FormFeed=12]="FormFeed",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.ExclamationMark=33]="ExclamationMark",e[e.Number=35]="Number",e[e.Amp=38]="Amp",e[e.SingleQuote=39]="SingleQuote",e[e.DoubleQuote=34]="DoubleQuote",e[e.Dash=45]="Dash",e[e.Slash=47]="Slash",e[e.Zero=48]="Zero",e[e.Nine=57]="Nine",e[e.Semi=59]="Semi",e[e.Lt=60]="Lt",e[e.Eq=61]="Eq",e[e.Gt=62]="Gt",e[e.Questionmark=63]="Questionmark",e[e.UpperA=65]="UpperA",e[e.LowerA=97]="LowerA",e[e.UpperF=70]="UpperF",e[e.LowerF=102]="LowerF",e[e.UpperZ=90]="UpperZ",e[e.LowerZ=122]="LowerZ",e[e.LowerX=120]="LowerX",e[e.OpeningSquareBracket=91]="OpeningSquareBracket"})(Er||(Er={}));(function(e){e[e.Text=1]="Text",e[e.BeforeTagName=2]="BeforeTagName",e[e.InTagName=3]="InTagName",e[e.InSelfClosingTag=4]="InSelfClosingTag",e[e.BeforeClosingTagName=5]="BeforeClosingTagName",e[e.InClosingTagName=6]="InClosingTagName",e[e.AfterClosingTagName=7]="AfterClosingTagName",e[e.BeforeAttributeName=8]="BeforeAttributeName",e[e.InAttributeName=9]="InAttributeName",e[e.AfterAttributeName=10]="AfterAttributeName",e[e.BeforeAttributeValue=11]="BeforeAttributeValue",e[e.InAttributeValueDq=12]="InAttributeValueDq",e[e.InAttributeValueSq=13]="InAttributeValueSq",e[e.InAttributeValueNq=14]="InAttributeValueNq",e[e.BeforeDeclaration=15]="BeforeDeclaration",e[e.InDeclaration=16]="InDeclaration",e[e.InProcessingInstruction=17]="InProcessingInstruction",e[e.BeforeComment=18]="BeforeComment",e[e.CDATASequence=19]="CDATASequence",e[e.DeclarationSequence=20]="DeclarationSequence",e[e.InSpecialComment=21]="InSpecialComment",e[e.InCommentLike=22]="InCommentLike",e[e.SpecialStartSequence=23]="SpecialStartSequence",e[e.InSpecialTag=24]="InSpecialTag",e[e.InPlainText=25]="InPlainText",e[e.InEntity=26]="InEntity"})(Ze||(Ze={}));(function(e){e[e.NoValue=0]="NoValue",e[e.Unquoted=1]="Unquoted",e[e.Single=2]="Single",e[e.Double=3]="Double"})(Em||(Em={}));ci={Empty:new Uint8Array(0),Cdata:new Uint8Array([67,68,65,84,65,91]),CdataEnd:new Uint8Array([93,93,62]),CommentEnd:new Uint8Array([45,45,33,62]),Doctype:new Uint8Array([100,111,99,116,121,112,101]),IframeEnd:new Uint8Array([60,47,105,102,114,97,109,101]),NoembedEnd:new Uint8Array([60,47,110,111,101,109,98,101,100]),NoframesEnd:new Uint8Array([60,47,110,111,102,114,97,109,101,115]),Plaintext:new Uint8Array([60,47,112,108,97,105,110,116,101,120,116]),ScriptEnd:new Uint8Array([60,47,115,99,114,105,112,116]),StyleEnd:new Uint8Array([60,47,115,116,121,108,101]),TitleEnd:new Uint8Array([60,47,116,105,116,108,101]),TextareaEnd:new Uint8Array([60,47,116,101,120,116,97,114,101,97]),XmpEnd:new Uint8Array([60,47,120,109,112])},IVr=new Map([[ci.IframeEnd[2],ci.IframeEnd],[ci.NoembedEnd[2],ci.NoembedEnd],[ci.Plaintext[2],ci.Plaintext],[ci.ScriptEnd[2],ci.ScriptEnd],[ci.TitleEnd[2],ci.TitleEnd],[ci.XmpEnd[2],ci.XmpEnd]])});class nC{options;startIndex=0;endIndex=0;openTagStart=0;tagname="";attribname="";attribvalue="";attribs=null;stack=[];foreignContext;cbs;lowerCaseTagNames;lowerCaseAttributeNames;recognizeSelfClosing;htmlMode;tokenizer;buffers=[];bufferOffset=0;writeIndex=0;ended=!1;constructor(e,t={}){this.options=t,this.cbs=e??{},this.htmlMode=!this.options.xmlMode,this.lowerCaseTagNames=t.lowerCaseTags??this.htmlMode,this.lowerCaseAttributeNames=t.lowerCaseAttributeNames??this.htmlMode,this.recognizeSelfClosing=t.recognizeSelfClosing??!this.htmlMode,this.tokenizer=new(t.Tokenizer??tC)(this.options,this),this.foreignContext=[Lb.None],this.cbs.onparserinit?.(this)}ontext(e,t){let r=this.getSlice(e,t);this.endIndex=t-1,this.cbs.ontext?.(r),this.startIndex=t}ontextentity(e,t){this.endIndex=t-1,this.cbs.ontext?.(rYe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==Lb.None}isVoidElement(e){return this.htmlMode&&_Vr.has(e)}readTagName(e,t){let r=this.lowerCaseTagNames?this.getSlice(e,t).toLowerCase():this.getSlice(e,t);if(!(this.lowerCaseTagNames&&this.htmlMode))return r;if(this.foreignContext[0]===Lb.Svg)return cYe.get(r)??r;if(this.foreignContext.length>1){let i=cYe.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&&TVr.get(e);if(t)while(this.stack.length>0&&t.has(this.stack[0]))this.popElement(!0);if(!this.isVoidElement(e)){if(this.stack.unshift(e),this.htmlMode){if(e==="svg")this.foreignContext.unshift(Lb.Svg);else if(e==="math")this.foreignContext.unshift(Lb.MathML);else if(aYe.has(e))this.foreignContext.unshift(Lb.None)}}if(this.cbs.onopentagname?.(e),this.cbs.onopentag)this.attribs={}}endOpenTag(e){if(this.startIndex=this.openTagStart,this.attribs)this.cbs.onopentag?.(this.tagname,this.attribs,e),this.attribs=null;if(this.cbs.onclosetag&&this.isVoidElement(this.tagname))this.cbs.onclosetag(this.tagname,!0);this.tagname=""}onopentagend(e){this.endIndex=e,this.endOpenTag(!1),this.startIndex=e+1}onclosetag(e,t){this.endIndex=t;let r=this.readTagName(e,t);if(!this.isVoidElement(r)){let i=this.stack.indexOf(r);if(i!==-1){for(let n=0;n<i;n++)this.popElement(!0);this.popElement(!1)}else if(this.htmlMode&&r==="p")this.emitOpenTag("p"),this.closeCurrentTag(!0)}else if(this.htmlMode&&r==="br")this.cbs.onopentagname?.("br"),this.cbs.onopentag?.("br",{},!0),this.cbs.onclosetag?.("br",!1);this.startIndex=t+1}onselfclosingtag(e){if(this.endIndex=e,this.recognizeSelfClosing||this.isInForeignContext())this.closeCurrentTag(!1),this.startIndex=e+1;else this.onopentagend(e)}popElement(e){let t=this.stack.shift();if(this.htmlMode&&(PVr.has(t)||aYe.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+=rYe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===Em.Double?'"':e===Em.Single?"'":e===Em.NoValue?void 0:null),this.attribs&&!Object.hasOwn(this.attribs,this.attribname))this.attribs[this.attribname]=this.attribvalue;this.attribvalue=""}getInstructionName(e){let t=e.search(RVr),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?sYe:r.slice(0,sYe.length):this.getInstructionName(r);this.cbs.onprocessinginstruction(`!${i}`,`!${r}`)}this.startIndex=t+1}onprocessinginstruction(e,t){this.endIndex=t;let r=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let i=this.getInstructionName(r);this.cbs.onprocessinginstruction(`?${i}`,`?${r}`)}this.startIndex=t+1}oncomment(e,t,r){this.endIndex=t,this.cbs.oncomment?.(this.getSlice(e,t-r)),this.cbs.oncommentend?.(),this.startIndex=t+1}oncdata(e,t,r){this.endIndex=t;let i=this.getSlice(e,t-r);if(!this.htmlMode||this.options.recognizeCDATA)this.cbs.oncdatastart?.(),this.cbs.ontext?.(i),this.cbs.oncdataend?.();else if(this.isInForeignContext())this.cbs.ontext?.(i);else this.cbs.oncomment?.(`[CDATA[${i}]]`),this.cbs.oncommentend?.();this.startIndex=t+1}onend(){if(this.cbs.onclosetag){this.endIndex=this.startIndex;for(let e=0;e<this.stack.length;e++)this.cbs.onclosetag(this.stack[e],!0)}this.cbs.onend?.()}reset(){this.cbs.onreset?.(),this.tokenizer.reset(),this.tagname="",this.attribname="",this.attribvalue="",this.attribs=null,this.stack.length=0,this.startIndex=0,this.endIndex=0,this.cbs.onparserinit?.(this),this.buffers.length=0,this.foreignContext.length=0,this.foreignContext.unshift(Lb.None),this.bufferOffset=0,this.writeIndex=0,this.ended=!1}parseComplete(e){this.reset(),this.end(e)}getSlice(e,t){if(e===t)return"";while(e-this.bufferOffset>=this.buffers[0].length)this.shiftBuffer();let r=this.buffers[0].slice(e-this.bufferOffset,t-this.bufferOffset);while(t-this.bufferOffset>this.buffers[0].length)this.shiftBuffer(),r+=this.buffers[0].slice(0,t-this.bufferOffset);return r}shiftBuffer(){this.bufferOffset+=this.buffers[0].length,this.writeIndex--,this.buffers.shift()}write(e){if(this.ended){this.cbs.onerror?.(Error(".write() after done!"));return}if(this.buffers.push(e),this.tokenizer.running)this.tokenizer.write(e),this.writeIndex++}end(e){if(this.ended){this.cbs.onerror?.(Error(".end() after done!"));return}if(e)this.write(e);this.ended=!0,this.tokenizer.end()}pause(){this.tokenizer.pause()}resume(){this.tokenizer.resume();while(this.tokenizer.running&&this.writeIndex<this.buffers.length)this.tokenizer.write(this.buffers[this.writeIndex++]);if(this.ended)this.tokenizer.end()}}var rYe,rC,Vs,iC,iYe,nYe,oYe,TVr,sYe="doctype",_Vr,PVr,aYe,cYe,Lb,RVr;var R0e=xs(()=>{P0e();({fromCodePoint:rYe}=String),rC=new Set(["input","option","optgroup","select","button","datalist","textarea"]),Vs=new Set(["p"]),iC=new Set(["h1","h2","h3","h4","h5","h6","p"]),iYe=new Set(["thead","tbody"]),nYe=new Set(["dd","dt"]),oYe=new Set(["rt","rp"]),TVr=new Map([["tr",new Set(["tr","th","td"])],["th",new Set(["th"])],["td",new Set(["thead","th","td"])],["body",new Set(["head","link","script"])],["a",new Set(["a"])],["li",new Set(["li"])],["p",Vs],["h1",iC],["h2",iC],["h3",iC],["h4",iC],["h5",iC],["h6",iC],["select",rC],["input",rC],["output",rC],["button",rC],["datalist",rC],["textarea",rC],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",nYe],["dt",nYe],["address",Vs],["article",Vs],["aside",Vs],["blockquote",Vs],["details",Vs],["div",Vs],["dl",Vs],["fieldset",Vs],["figcaption",Vs],["figure",Vs],["footer",Vs],["form",Vs],["header",Vs],["hr",Vs],["main",Vs],["nav",Vs],["ol",Vs],["pre",Vs],["section",Vs],["table",Vs],["ul",Vs],["rt",oYe],["rp",oYe],["tbody",iYe],["tfoot",iYe]]),_Vr=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),PVr=new Set(["math","svg"]),aYe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),cYe=new Map([["altglyph","altGlyph"],["altglyphdef","altGlyphDef"],["altglyphitem","altGlyphItem"],["animatecolor","animateColor"],["animatemotion","animateMotion"],["animatetransform","animateTransform"],["clippath","clipPath"],["feblend","feBlend"],["fecolormatrix","feColorMatrix"],["fecomponenttransfer","feComponentTransfer"],["fecomposite","feComposite"],["feconvolvematrix","feConvolveMatrix"],["fediffuselighting","feDiffuseLighting"],["fedisplacementmap","feDisplacementMap"],["fedistantlight","feDistantLight"],["fedropshadow","feDropShadow"],["feflood","feFlood"],["fefunca","feFuncA"],["fefuncb","feFuncB"],["fefuncg","feFuncG"],["fefuncr","feFuncR"],["fegaussianblur","feGaussianBlur"],["feimage","feImage"],["femerge","feMerge"],["femergenode","feMergeNode"],["femorphology","feMorphology"],["feoffset","feOffset"],["fepointlight","fePointLight"],["fespecularlighting","feSpecularLighting"],["fespotlight","feSpotLight"],["fetile","feTile"],["feturbulence","feTurbulence"],["foreignobject","foreignObject"],["glyphref","glyphRef"],["lineargradient","linearGradient"],["radialgradient","radialGradient"],["textpath","textPath"]]);(function(e){e[e.None=0]="None",e[e.Svg=1]="Svg",e[e.MathML=2]="MathML"})(Lb||(Lb={}));RVr=/\s|\//});var SW={};rg(SW,{CDATA:()=>q0e,Comment:()=>L0e,Directive:()=>N0e,Doctype:()=>FVr,ElementType:()=>pn,Root:()=>M0e,Script:()=>j0e,Style:()=>z0e,Tag:()=>U0e,Text:()=>O0e,isTag:()=>F0e});function F0e(e){return e.type===pn.Tag||e.type===pn.Script||e.type===pn.Style}var pn,M0e,O0e,N0e,L0e,j0e,z0e,U0e,q0e,FVr;var oC=xs(()=>{(function(e){e.Root="root",e.Text="text",e.Directive="directive",e.Comment="comment",e.Script="script",e.Style="style",e.Tag="tag",e.CDATA="cdata",e.Doctype="doctype"})(pn||(pn={}));M0e=pn.Root,O0e=pn.Text,N0e=pn.Directive,L0e=pn.Comment,j0e=pn.Script,z0e=pn.Style,U0e=pn.Tag,q0e=pn.CDATA,FVr=pn.Doctype});class G0e{parent=null;prev=null;next=null;startIndex=null;endIndex=null;get parentNode(){return this.parent}set parentNode(e){this.parent=e}get previousSibling(){return this.prev}set previousSibling(e){this.prev=e}get nextSibling(){return this.next}set nextSibling(e){this.next=e}cloneNode(e=!1){return lYe(this,e)}}function uu(e){return F0e(e)}function _W(e){return e.type===pn.CDATA}function sw(e){return e.type===pn.Text}function H0e(e){return e.type===pn.Comment}function MVr(e){return e.type===pn.Directive}function OVr(e){return e.type===pn.Root}function dp(e){return Object.hasOwn(e,"children")}function lYe(e,t=!1){let r;if(sw(e))r=new zP(e.data);else if(H0e(e))r=new BW(e.data);else if(uu(e)){let i=t?$0e(e.children):[],n=new TW(e.name,{...e.attribs},i);for(let o of i)o.parent=n;if(e.namespace!=null)n.namespace=e.namespace;if(e["x-attribsNamespace"])n["x-attribsNamespace"]={...e["x-attribsNamespace"]};if(e["x-attribsPrefix"])n["x-attribsPrefix"]={...e["x-attribsPrefix"]};r=n}else if(_W(e)){let i=t?$0e(e.children):[],n=new IW(i);for(let o of i)o.parent=n;r=n}else if(OVr(e)){let i=t?$0e(e.children):[],n=new UP(i);for(let o of i)o.parent=n;if(e["x-mode"])n["x-mode"]=e["x-mode"];r=n}else if(MVr(e)){let i=new CW(e.name,e.data);if(e["x-name"]!=null)i["x-name"]=e["x-name"],i["x-publicId"]=e["x-publicId"],i["x-systemId"]=e["x-systemId"];r=i}else throw Error(`Not implemented yet: ${e.type}`);if(r.startIndex=e.startIndex,r.endIndex=e.endIndex,e.sourceCodeLocation!=null)r.sourceCodeLocation=e.sourceCodeLocation;return r}function $0e(e){let t=e.map((r)=>lYe(r,!0));for(let r=1;r<t.length;r++)t[r].prev=t[r-1],t[r-1].next=t[r];return t}var kW,zP,BW,CW,DW,IW,UP,TW;var W0e=xs(()=>{oC();kW=class kW extends G0e{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};zP=class zP extends kW{type=pn.Text;get nodeType(){return 3}};BW=class BW extends kW{type=pn.Comment;get nodeType(){return 8}};CW=class CW extends kW{type=pn.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};DW=class DW extends G0e{children;constructor(e){super();this.children=e}get firstChild(){return this.children[0]??null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(e){this.children=e}};IW=class IW extends DW{type=pn.CDATA;get nodeType(){return 4}};UP=class UP extends DW{type=pn.Root;get nodeType(){return 9}};TW=class TW extends DW{name;attribs;type;constructor(e,t,r=[],i=e==="script"?pn.Script:e==="style"?pn.Style:pn.Tag){super(r);this.name=e,this.attribs=t,this.type=i}get nodeType(){return 1}get tagName(){return this.name}set tagName(e){this.name=e}get attributes(){return Object.keys(this.attribs).map((e)=>({name:e,value:this.attribs[e],namespace:this["x-attribsNamespace"]?.[e],prefix:this["x-attribsPrefix"]?.[e]}))}namespace;"x-attribsNamespace";"x-attribsPrefix"}});class A5{dom=[];root=new UP(this.dom);callback;options;elementCB;done=!1;tagStack=[this.root];lastNode=null;parser=null;constructor(e,t,r){if(typeof t==="function")r=t,t=uYe;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??uYe,this.elementCB=r??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new UP(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){if(this.done)return;this.done=!0,this.parser=null,this.handleCallback(null)}onerror(e){this.handleCallback(e)}onclosetag(){this.lastNode=null;let e=this.tagStack.pop();if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(this.elementCB)this.elementCB(e)}onopentag(e,t){let r=this.options.xmlMode?pn.Tag:void 0,i=new TW(e,t,void 0,r);this.addNode(i),this.tagStack.push(i)}ontext(e){let{lastNode:t}=this;if(t&&t.type===pn.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let r=new zP(e);this.addNode(r),this.lastNode=r}}oncomment(e){if(this.lastNode&&this.lastNode.type===pn.Comment){this.lastNode.data+=e;return}let t=new BW(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new zP(""),t=new IW([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let r=new CW(e,t);this.addNode(r)}handleCallback(e){if(typeof this.callback==="function")this.callback(e,this.dom);else if(e)throw e}addNode(e){let t=this.tagStack[this.tagStack.length-1],r=t.children[t.children.length-1];if(this.options.withStartIndices&&this.parser)e.startIndex=this.parser.startIndex;if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(t.children.push(e),r)e.prev=r,r.next=e;e.parent=t,this.lastNode=null}}var uYe;var aw=xs(()=>{oC();W0e();W0e();uYe={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function sC(e,t,r=!0,i=Number.POSITIVE_INFINITY){return dYe(e,Array.isArray(t)?t:[t],r,i)}function dYe(e,t,r,i){let n=[],o=[Array.isArray(t)?t:[t]],s=[0];for(;;){if(s[0]>=o[0].length){if(s.length===1)return n;o.shift(),s.shift();continue}let a=o[0][s[0]++];if(e(a)){if(n.push(a),--i<=0)return n}if(r&&dp(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function PW(e,t,r=!0){let i=Array.isArray(t)?t:[t];for(let n of i){if(uu(n)&&e(n))return n;if(r&&dp(n)&&n.children.length>0){let o=PW(e,n.children,!0);if(o)return o}}return null}function pYe(e,t){return(Array.isArray(t)?t:[t]).some((r)=>uu(r)&&e(r)||dp(r)&&pYe(e,r.children))}function NVr(e,t){let r=[],i=[Array.isArray(t)?t:[t]],n=[0];for(;;){if(n[0]>=i[0].length){if(i.length===1)return r;i.shift(),n.shift();continue}let o=i[0][n[0]++];if(uu(o)&&e(o))r.push(o);if(dp(o)&&o.children.length>0)n.unshift(0),i.unshift(o.children)}}var Z0e=xs(()=>{aw()});function V0e(e,t){if(typeof t==="function")return(r)=>uu(r)&&t(r.attribs[e]);return(r)=>uu(r)&&r.attribs[e]===t}function LVr(e,t){return(r)=>e(r)||t(r)}function mYe(e){let t=Object.keys(e).map((r)=>{let i=e[r];return Object.hasOwn(RW,r)?RW[r](i):V0e(r,i)});return t.length===0?null:t.reduce(LVr)}function jVr(e,t){let r=mYe(e);return r?r(t):!0}function zVr(e,t,r,i=Number.POSITIVE_INFINITY){let n=mYe(e);return n?sC(n,t,r,i):[]}function UVr(e,t,r=!0){if(!Array.isArray(t))t=[t];return PW(V0e("id",e),t,r)}function w5(e,t,r=!0,i=Number.POSITIVE_INFINITY){return sC(RW.tag_name(e),t,r,i)}function qVr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return sC(V0e("class",e),t,r,i)}function $Vr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return sC(RW.tag_type(e),t,r,i)}var RW;var K0e=xs(()=>{aw();Z0e();RW={tag_name(e){if(typeof e==="function")return(t)=>uu(t)&&e(t.name);if(e==="*")return uu;return(t)=>uu(t)&&t.name===e},tag_type(e){if(typeof e==="function")return(t)=>e(t.type);return(t)=>t.type===e},tag_contains(e){if(typeof e==="function")return(t)=>sw(t)&&e(t.data);return(t)=>sw(t)&&t.data===e}}});function fYe(e){return e===34?""":e===38?"&":e===39?"'":e===60?"<":e===62?">":" "}function hYe(e){return e>=128||e>=32&&e<64&&(GVr>>>e&1)===1}function FW(e){let{length:t}=e,r,i=0,n=0;while(n<t){let o=e.charCodeAt(n);if(!hYe(o)){let a=Math.min(n+32,t),c=n+1;while(c<a&&!hYe(e.charCodeAt(c)))c++;if(c<a){n=c;continue}if(c>=t)break;if(Y0e.lastIndex=c,!Y0e.test(e))break;n=Y0e.lastIndex-1;continue}if(r===void 0)r=e.substring(0,n);else if(i!==n)r+=e.substring(i,n);if(o<64){r+=fYe(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 xYe(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+=fYe(o),i=n+1}while(e.test(t));return r+t.substring(i)}function J0e(e){return xYe(HVr,e)}function Q0e(e){return xYe(WVr,e)}var GVr=1342177476,Y0e,HVr,WVr;var gYe=xs(()=>{Y0e=/["&'<>\u0080-\uFFFF]/g;HVr=/["&\u{A0}]/gu;WVr=/[&<>\u{A0}]/gu});var yYe,bYe;var EYe=xs(()=>{gYe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(yYe||(yYe={}));(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"})(bYe||(bYe={}))});var vYe,AYe;var wYe=xs(()=>{vYe=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])),AYe=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 JVr(e,t={}){let r="length"in e?e:[e],i=t.xmlMode??!1,n="";for(let o=0;o<r.length;o++)n+=kYe(r[o],t,i);return n}function SYe(e,t,r){let i="";for(let n=0;n<e.length;n++)i+=kYe(e[n],t,r);return i}function kYe(e,t,r){switch(e.type){case M0e:return SYe(e.children,t,r);case N0e:return`<${e.data}>`;case L0e:return`<!--${e.data}-->`;case q0e:return`<![CDATA[${e.children[0].data}]]>`;case j0e:case z0e:case U0e:return QVr(e,t,r);case O0e:{let i=e,n=i.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!r&&i.parent&&ZVr.has(i.parent.name)))return r||t.encodeEntities!=="utf8"?FW(n):Q0e(n);return n}}}function QVr(e,t,r){if(r==="foreign"){if(e.name=vYe.get(e.name)??e.name,e.parent&&YVr.has(e.parent.name))r=!1}if(!r&&KVr.has(e.name))r="foreign";let{name:i,children:n}=e,o=!r&&VVr.has(i),s=`<${i}${eKr(e.attribs,t,r)}`;if(n.length===0&&(r?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=r?"/>":" />";else{if(s+=">",n.length>0)s+=SYe(n,t,r);if(!o)s+=`</${i}>`}return s}function XVr(e){return e.replaceAll('"',""")}function eKr(e,t,r){if(!e)return"";let i=(t.encodeEntities??t.decodeEntities)===!1?XVr:r||t.encodeEntities!=="utf8"?FW:J0e,n=r==="foreign",o=!!(t.emptyAttrs??r),s="";for(let a in e){if(!Object.hasOwn(e,a))continue;let c=e[a],l=n?AYe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${l}`:` ${l}="${i(c==null?"":String(c))}"`}return s}var ZVr,VVr,KVr,YVr,BYe;var CYe=xs(()=>{oC();EYe();wYe();ZVr=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),VVr=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),KVr=new Set(["svg","math"]),YVr=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));BYe=JVr});function DYe(e,t){return BYe(e,t)}function tKr(e,t){return dp(e)?e.children.map((r)=>DYe(r,t)).join(""):""}function MW(e){if(Array.isArray(e))return e.map(MW).join("");if(uu(e))return e.name==="br"?`
|
|
2
|
+
import"./chunks/index-wzhtx0w9.js";import{$ as Eo,$a as fvn,$b as Jvn,$c as SAn,Aa as ox,Ab as nz,Ad as KAn,Ba as Edr,Bb as jvn,Bd as n6,C as ly,Ca as vdr,Cb as zvn,Cc as mfr,Cd as YAn,D as uEn,Da as KEn,Db as vv,Dd as JAn,E as ldr,Ea as YEn,Eb as Sdr,Ed as QAn,F as ydr,Fa as Die,Fb as ez,Fd as dy,G as vEn,Ga as JEn,Gb as Uvn,Gd as iz,H as AEn,Hb as qvn,Hd as XAn,I as wEn,Ia as pIe,Ib as $vn,Id as ewn,J as SEn,Ja as QEn,Jb as Gvn,Jd as twn,K as kEn,Ka as XEn,Kd as rwn,La as evn,Lb as kdr,Ld as iwn,M as _ie,Ma as tvn,Mb as Bdr,Md as nwn,Na as rvn,Nb as Cdr,Nd as own,Oa as ivn,Ob as Ddr,Od as swn,P as s6,Pa as nvn,Pb as Idr,Pd as awn,Q as tdr,Qa as Adr,Qb as Tdr,Qd as Rie,R as o6,Ra as ovn,Rb as _dr,Rc as Ndr,Rd as vIe,S as cy,Sa as svn,Sb as Pdr,Sc as xAn,Sd as cwn,Ta as avn,Tb as Rdr,Tc as gAn,Td as mIe,U as bIe,Ua as cvn,Ub as Fdr,Uc as yAn,Ud as lwn,V as BEn,Va as lvn,Vb as Hvn,Vc as bAn,Vd as ih,W as Vt,Wa as uvn,Wb as Wvn,Wc as i6,Wd as aie,Xa as dvn,Xb as Zvn,Xc as EAn,Xd as uwn,Y as bdr,Ya as pvn,Yb as Vvn,Yc as vAn,Z as CEn,Za as mvn,Zb as Kvn,Zc as AAn,_ as kS,_a as hvn,_b as Yvn,_c as wAn,aa as DS,ab as xvn,ac as Qvn,ad as kAn,ba as il,bb as gvn,bc as Xvn,bd as BAn,ca as DEn,cb as yvn,cc as eAn,cd as CAn,da as IEn,db as BS,dc as tAn,dd as DAn,ea as TEn,eb as bvn,ec as rAn,ed as IAn,fa as _En,fb as cIe,fc as iAn,fd as TAn,ga as PEn,gb as Evn,gc as nAn,gd as _An,ha as REn,hb as vvn,hc as oAn,hd as PAn,ia as FEn,ib as Avn,ic as sAn,id as RAn,ja as MEn,jb as wvn,jc as lIe,jd as FAn,ka as OEn,kb as Svn,kc as rz,kd as MAn,la as NEn,lb as kvn,lc as aAn,ld as OAn,ma as LEn,mb as Bvn,mc as cAn,md as NAn,na as jEn,nb as Cvn,nc as lAn,nd as LAn,oa as zEn,ob as Dvn,oc as uAn,od as jAn,pa as UEn,pb as Ivn,pc as dAn,qa as qEn,qb as Tvn,qc as pAn,qd as zAn,ra as $En,rb as _vn,rc as mAn,rd as UAn,sa as GEn,sb as Pvn,sc as Mdr,sd as qAn,ta as gDe,tb as Rvn,tc as Odr,td as odr,ua as HEn,ub as Fvn,uc as edr,ud as $An,va as WEn,vb as Mvn,vc as hAn,vd as GAn,wa as ZEn,wb as wdr,wc as fAn,wd as HAn,xa as VEn,xb as Ovn,xc as EIe,xd as WAn,ya as aIe,yb as Nvn,yd as ZAn,za as cz,zb as Lvn,zd as VAn}from"./chunks/index-femxb8zf.js";import{$d as zAr,Yd as NT,Zd as bwr,be as _Re}from"./chunks/index-k4strh3v.js";import{de as Uxe}from"./chunks/index-27h92m2e.js";import"./chunks/index-e84v85w3.js";import"./chunks/index-e0qz6mam.js";import"./chunks/index-624fhq2j.js";import"./chunks/index-z0k97qgd.js";import"./chunks/index-x8e40qwv.js";import{ie as z8}from"./chunks/index-ymf8bdmg.js";import{Ce as iVe,De as IPr,Ee as AOr,Fe as Mg,Ge as JJ,He as tq,Ie as kAr,Je as Ty,Ke as X7r,Le as FT,Me as URr,Ne as AAr,Oe as BAr,Pe as s_r,Qe as Y7r,Re as Pgt,Se as rLr,Te as sGe,Ue as aGe,Ve as cGe,We as Gvr,Xe as kT,Ye as J7r,Ze as _f,_e as MT,gf as RH,ke as ZWe,le as MH,ne as Bo,oe as L5,pe as Lye,qe as qye,re as oE,se as KZ,te as YZ,ue as JZ,ve as jtt,we as QZ,xe as PC,ye as Tit,ze as ys}from"./chunks/index-3vnrdc3q.js";import{jf as rfe,kf as R$r}from"./chunks/index-kcgba22z.js";import"./chunks/index-gtyh93sb.js";import{$f as Kit,$g as JA,$h as Ufe,$j as The,$l as Khe,$m as EQ,$n as Fb,Af as PV,Ag as ma,Ah as H3,Ai as ga,Aj as nqr,Ak as mP,Al as $t,An as RSe,Ao as lE,Bf as Il,Bg as fs,Bh as wQ,Bi as Yrt,Bj as oqr,Bk as zhe,Bl as _b,Bn as Syt,Bo as Ph,Cf as Knt,Cg as lp,Ch as obt,Ci as $fe,Cj as I$r,Ck as eW,Cl as ro,Cn as Iyt,Co as Yx,Df as pF,Dg as Sb,Dh as Vk,Di as ZT,Dj as wqr,Dk as Uhe,Dl as Po,Dm as aB,Dn as JO,Do as J0r,Ef as mF,Eg as Bhe,Eh as jl,Ei as U6,Ej as Sqr,Ek as qhe,El as Aw,Em as Oae,En as jyt,Eo as Ea,Ff as gr,Fh as B1,Fi as mse,Fj as Dqr,Fk as $he,Fl as fP,Fm as DPr,Fn as QO,Gf as GC,Gh as tN,Gi as hse,Gj as Oqr,Gk as $9,Gl as Bn,Gm as DSr,Gn as ZUr,Hf as RV,Hg as Nfe,Hh as k1,Hi as iP,Hj as Nqr,Hk as Ghe,Hl as dt,Hm as Kse,Hn as g7e,If as YR,Ig as dn,Ih as W0,Ii as tGe,Ij as Lqr,Im as zae,In as Tyt,Jg as Mn,Jh as u8e,Ji as R8,Jj as eme,Jk as Hhe,Jl as j_r,Jm as kSr,Jn as _yt,Kf as kw,Kg as Ogt,Kh as fbt,Ki as NPe,Kj as P$r,Km as ISr,Kn as $z,Lf as Wye,Lg as Lfe,Lh as hbt,Lj as _qr,Lk as uo,Ll as Pi,Lm as _Sr,Ln as Pyt,Mf as FV,Mh as Fre,Mi as vw,Mj as $Ur,Ml as HPr,Mn as bQ,Nf as gs,Ng as bP,Nh as vbt,Ni as JWe,Nl as z$,Nn as Ryt,Of as nr,Og as l5,Oh as Kyt,Oi as sdt,Ok as i5,Ol as $Pr,On as uqr,Pf as Qe,Pg as U9,Ph as Yyt,Pi as adt,Pk as Whe,Pl as Vhe,Pn as zyt,Qf as Oo,Qg as EP,Qj as FA,Ql as Vr,Qn as Zyt,Rf as Ys,Rg as vP,Rh as AQ,Rj as t5,Rn as dqr,Sf as Gh,Sg as jfe,Sh as Abt,Sj as Che,Sm as fde,Sn as lqr,Tf as Gye,Tg as Ib,Th as f8e,Tj as Jx,Tm as $0,Tn as kyt,Ug as AP,Uk as hP,Ul as Db,Un as xne,Vf as Wit,Vg as u5,Vh as mPr,Vk as Zhe,Vl as bt,Vn as jz,Wf as Zit,Wg as d5,Wl as Qx,Wn as Cfr,Xg as wP,Xh as Ws,Xl as ha,Xn as ym,Yg as SP,Yi as Bb,Yj as q9,Yl as Kut,Yn as y5,Zf as Vit,Zg as zfe,Zj as Dhe,Zk as GUr,Zl as El,Zm as HUr,Zn as Pb,_g as H9,_h as kb,_j as Ihe,_l as xP,_m as WUr,_n as Rb,ah as Mh,ak as _he,am as Yhe,an as Uyt,ao as sd,bh as Tb,bi as p5,bk as pP,bl as ugr,bm as zt,bn as qyt,bo as Qhe,ch as ew,cj as DLr,ck as Phe,cl as Eoe,cm as Kx,cn as $yt,co as o5,dh as a1,dk as Rhe,dl as Zfr,dm as Ene,dn as G3,do as tW,eh as z7r,ei as hc,ek as Fhe,el as FH,em as vne,en as XO,fh as mot,fi as qfe,fk as Mhe,fm as rVe,gh as Ube,gk as Ohe,gm as ko,gn as jye,go as s5,hk as Nhe,hl as mm,hm as Fn,ho as a5,ii as uP,ik as Lhe,im as Q_r,in as _h,jg as _Lr,jh as Ane,ji as WA,jj as RA,jl as ad,jm as Jo,kh as wne,ki as tw,kj as yqr,kl as Gfe,lg as PLr,lh as Sne,li as eT,lj as Vqr,ll as Hfe,mg as Swr,mh as kne,mi as iGe,mj as xWe,ml as Wfe,mo as VA,nf as Mfe,nh as Gfr,ni as YWe,nj as k$r,nk as c0,nl as Zfe,no as Xhe,of as Ofe,oh as Hfr,oi as NLr,oj as B$r,ok as m5,ol as Vfe,om as VO,on as Jhe,oo as CZe,pf as She,ph as zTe,pi as iQ,pj as qU,pk as h5,pl as Kfe,pm as wyt,po as efe,qf as cp,qh as S6,qi as Boe,qj as Vf,qk as uW,ql as x5,qm as hQ,qo as HA,rf as e5,ri as Jde,rj as c9,rl as kP,rm as lme,rn as Ufr,ro as Th,sf as khe,sh as fo,si as Coe,sj as Fqr,sk as f5,sl as g5,sm as ume,sn as qfr,so as tfe,tf as z9,th as Ebt,ti as Fue,tj as Mqr,tl as fa,tn as fQ,to as gP,uf as ot,ug as su,uh as Ie,ui as tQ,uj as tme,ul as Qo,un as Myt,uo as X_r,vf as Br,vg as lP,vh as H0,vi as P8,vj as C$r,vl as BP,vm as bqr,vn as Oyt,wg as ai,wh as jn,wi as nT,wj as D$r,wk as jhe,wl as Vi,wn as $qr,xf as xe,xg as xm,xh as SQ,xi as oT,xj as tqr,xk as ZA,xl as Yfe,xn as Gqr,yf as Bw,yg as o0,yh as ybt,yi as H1e,yj as rqr,yk as Cb,yl as Jfe,yn as Nyt,zf as ft,zg as jr,zh as Wk,zi as HAr,zj as iqr,zk as r5,zl as gm,zn as Lyt,zo as KA}from"./chunks/index-hvtxk8x8.js";import{$o as Eae,$p as git,$q as OC,$r as w1,$s as po,Ap as T1r,Aq as Xoe,Ar as Di,As as PY,Bp as Bae,Bq as dMr,Br as TLr,Bs as Pne,Cp as vr,Cq as pMr,Cr as XLr,Cs as Vut,Dp as j5,Dq as TY,Dr as aV,Ep as Ht,Er as Gf,Es as pEr,Fo as F1r,Fp as dx,Fq as Znt,Fs as U1e,Go as mpe,Gp as tV,Gq as Vnt,Gr as L7,Hp as Zp,Hq as nnt,Hr as Rae,Hs as Xv,Ht as up,Io as kn,Ip as vy,Iq as ont,Ir as nG,Is as d_r,It as hm,Jo as Cf,Jp as Hn,Jq as Zut,Jr as wde,Js as fue,Jt as od,Ko as eoe,Kp as Jpe,Kq as vn,Kr as Gqe,Ks as RB,Lq as md,Lr as q$,Ls as D6,Mo as kr,Mp as o$r,Mq as v8,Mr as $$,Ms as Xme,No as fi,Np as s$r,Nq as Zle,Nr as BG,Ns as bne,Oo as ZI,Oq as A7r,Or as gzr,Os as NI,Ot as n5,Po as e9,Pq as Vle,Pr as CG,Ps as wfr,Qo as ppe,Qp as A_,Qq as Zye,Qr as noe,Qs as Rm,Ro as WB,Rq as CV,Rr as _xr,Rs as c1,So as B$,Sr as Rxr,Ss as pa,To as dQ,Tq as A1,Tr as ooe,Ts as Tvr,Uo as wa,Up as cP,Uq as fe,Ur as Vue,Us as Jp,Vo as Yv,Vp as aMr,Vr as DRr,Vs as Lt,Wo as ZB,Wq as To,Wr as ode,Ws as Moe,Xo as jze,Xr as sde,Xs as W9,Yp as S$r,Yr as jxr,Ys as ld,Zo as Cae,Zr as Fxr,Zs as mc,_o as Kv,_p as xMr,_q as br,_r as Mxr,_s as v1,ap as vae,ar as h$r,as as y0r,at as Ay,bp as bUr,bq as vhe,br as j9,bt as hEr,cp as Bse,cq as HH,cr as Gne,cs as $ue,ct as Wfr,dp as iB,dq as WH,dr as eQ,ds as LPr,dt as vT,ep as qge,eq as ZH,er as M3,es as jPr,et as fx,fp as wae,fq as VH,fs as h3,ft as hyt,gp as nB,gq as QH,gs as Ppe,gt as rw,hp as Aae,hq as XH,hr as ase,hs as Une,ht as sc,ip as o8,iq as X8,ir as Nyr,is as qne,it as QI,jp as v1r,jq as rZe,jr as Ffr,js as EWe,jt as ct,kp as A1r,kq as ZZe,kr as yne,ks as _$r,kt as Cu,lp as EUr,lq as Vx,lr as gne,ls as Vne,lt as dWe,mp as Zpe,mq as VZe,ms as Rpe,mt as cd,np as vUr,nq as LH,ns as que,nt as au,op as B1r,oq as KH,or as aPr,os as W7,ot as We,pp as AUr,pq as YH,pr as Sw,ps as MUe,qp as SFe,qq as PR,qr as Jz,qs as NUe,rp as kFe,rs as gRr,rt as dP,sp as xq,sq as Ade,ss as ZPr,st as t0,tp as BFe,tq as Obr,ts as yRr,tt as ehe,up as C1r,uq as us,us as VPr,vp as CFe,vq as mOr,vs as QPr,vt as ihe,wp as D1r,wq as JEr,wr as Dae,ws as Kne,xp as I1r,xq as LS,xr as JT,xs as f3,yp as Sae,yq as M0r,yr as Ine,ys as Wne,zp as kae,zq as qI,zr as Hne,zs as _Y}from"./chunks/index-63p1xma2.js";import{Qt as iUe,St as NH}from"./chunks/index-agfrkbxw.js";import{EB as Vyt,Hv as lSe,LB as Ih,MB as XC,OB as Mc,QB as Yp,RB as Zgr,SB as Yi,TB as T$r,Xx as ou,Zx as e4,jy as pc,tz as vQ,xB as et,yy as Hs}from"./chunks/index-g1c4y6gc.js";import{jD as u}from"./chunks/index-bshgrg07.js";import"./chunks/index-pmvk8xga.js";import{nD as no,oD as $Qr,pD as E,qD as rg,rD as xs,sD as ce}from"./chunks/index-7ysxtpwx.js";function WKe(e){return e===0||e>=55296&&e<=57343||e>1114111}function ZKe(e){if(WKe(e))return 65533;if(e>=128&&e<=159)return wVr[e-128]||e;return e}function VKe(e){return WKe(e)?65533:e}var wVr;var KKe=xs(()=>{wVr=[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 YKe(e,t,r,i,n,o){let a=e.length,c=o*90,l=0,d=()=>{let L=u0[e.charCodeAt(l++)];return L<o?L:L*91-c+u0[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 K=0,ee=H,q=H+L;while(ee<q){let S=u0[e.charCodeAt(l++)];if(S<89)K+=S,h[ee++]=K;else if(S===89){let _=u0[e.charCodeAt(l++)]+2;while(_--)h[ee++]=++K}else{let _=u0[e.charCodeAt(l++)];K+=89+(_<90?_*91+u0[e.charCodeAt(l++)]:u0[e.charCodeAt(l++)]*8281+u0[e.charCodeAt(l++)]*91+u0[e.charCodeAt(l++)]),h[ee++]=K}}}y(i,0),y(p,o);let b=new Int32Array(n*2),A=0,w=0;function B(L,H){for(let K=0;K<L;K++){let ee=H+K,q=d(),S=d();b[w*2]=q,b[w*2+1]=S,w+=1,f[ee]=A;let _=(h[q]<0?g[q]:1)+(h[S]<0?g[S]:1);g[ee]=_,A+=_}}B(n-o+i,o+p),B(o-i,i);let R=new Uint16Array(A),M=0;for(let L=0;L<w;L++)for(let H=0;H<2;H++){let K=b[L*2+H],ee=h[K];if(ee<0){let q=f[K],S=q+g[K];while(q<S)R[M++]=R[q++]}else R[M++]=ee}let k=new Uint16Array(t),N=0;while(l<a){let L=u0[e.charCodeAt(l++)];if(L>=o)L=L*91-c+u0[e.charCodeAt(l++)];let H=h[L];if(H<0){let K=f[L],ee=K+g[L];while(K<ee)k[N++]=R[K++]}else k[N++]=H}return k}var u0;var JKe=xs(()=>{u0=(()=>{let e=new Uint8Array(127),t=0;for(let r=33;r<=126;r++)if(r!==34&&r!==36&&r!==92)e[r]=t++;return e})()});var I0e;var QKe=xs(()=>{JKe();I0e=YKe("!}.&u%}'&}*'~!6*)%&,~!J~!J~%L~y<~!R,~~%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2F|XKsA>!a)-g<v{z;h[eb?C2F|]i[vrv{z;h]eb?C2F|^iZu.vix,hZq3ah!.(?C2F|QOu!5ShXM:2<BaY?C2F|P",13494,2713,49,25,61)});var jP;var T0e=xs(()=>{jP=new Uint16Array([512,26465,29036,7,0,2,4,116,24638,116,24636,8693,29807,24610,621,1,0,0,3,112,24614,111,115,24615])});var Lc;var XKe=xs(()=>{(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.FLAG13=8192]="FLAG13",e[e.BRANCH_LENGTH=8064]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE",e[e.VALUE_MASK=8191]="VALUE_MASK"})(Lc||(Lc={}))});function eYe(e){return e-lu.ZERO>>>0<=9}function SVr(e){return(e|wW)-lu.LOWER_A>>>0<=5}function kVr(e){return(e|wW)-lu.LOWER_A>>>0<=25}function BVr(e){return e===lu.EQUALS||kVr(e)||eYe(e)}class _0e{decodeTree;emitCodePoint;errors;state=cu.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=d0.Strict;runConsumed=0;constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r}startEntity(e){this.decodeMode=e,this.state=cu.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case cu.EntityStart:{if(e.charCodeAt(t)===lu.NUM)return this.state=cu.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=cu.NamedEntity,this.stateNamedEntity(e,t)}case cu.NumericStart:return this.stateNumericStart(e,t);case cu.NumericDecimal:return this.stateNumericDecimal(e,t);case cu.NumericHex:return this.stateNumericHex(e,t);default:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){if(t>=e.length)return-1;if((e.charCodeAt(t)|wW)===lu.LOWER_X)return this.state=cu.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=cu.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){let r=e.length,{result:i}=this,{consumed:n}=this;while(t<r){let o=e.charCodeAt(t);if(eYe(o)||SVr(o)){let s=o<=lu.NINE?o-lu.ZERO:(o|wW)-lu.LOWER_A+10;i=i*16+s,n+=1,t+=1}else return this.result=i,this.consumed=n,this.emitNumericEntity(o,3)}return this.result=i,this.consumed=n,-1}stateNumericDecimal(e,t){let r=e.length,{result:i}=this,{consumed:n}=this;while(t<r){let o=e.charCodeAt(t)-lu.ZERO;if(o>>>0>9)return this.result=i,this.consumed=n,this.emitNumericEntity(o+lu.ZERO,2);i=i*10+o,n+=1,t+=1}return this.result=i,this.consumed=n,-1}emitNumericEntity(e,t){if(this.consumed<=t)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===lu.SEMI)this.consumed+=1;else if(this.decodeMode===d0.Strict)return 0;if(this.emitCodePoint((this.decodeTree===jP?VKe:ZKe)(this.result),this.consumed),this.errors){if(e!==lu.SEMI)this.errors.missingSemicolonAfterCharacterReference();this.errors.validateNumericCharacterReference(this.result)}return this.consumed}flushAndEmitLegacyOrReject(e,t,r,i){return this.consumed=e,this.excess=t,this.result===0||this.decodeMode===d0.Attribute&&(i===0||t>1||BVr(r))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:r}=this,i=e.length,n=this.decodeMode===d0.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=r[o];while(t<i){while((c&(Lc.VALUE_LENGTH|Lc.FLAG13))===0&&(c&Lc.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&Lc.JUMP_TABLE,f=(c&Lc.BRANCH_LENGTH)>>7;if(f===0){if(m!==h)return this.flushAndEmitLegacyOrReject(a,s,m,0);o+=1}else{let g=m-h;if(g>>>0>=f)return this.flushAndEmitLegacyOrReject(a,s,m,0);let y=r[o+1+g];if(y===0)return this.flushAndEmitLegacyOrReject(a,s,m,0);o=o+f+y&65535}if(c=r[o],t+=1,s+=1,t>=i)break}if(t>=i)break;if((c&(Lc.VALUE_LENGTH|Lc.FLAG13))===Lc.FLAG13){let m=(c&Lc.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&Lc.JUMP_TABLE))return this.flushAndEmitLegacyOrReject(a,s,f,0);t+=1,s+=1,h=1}while(h<m){if(t>=i)return this.treeIndex=o,this.excess=s,this.consumed=a,this.runConsumed=h,-1;let f=h-1,y=r[o+1+(f>>1)]>>((f&1)<<3)&255,b=e.charCodeAt(t);if(b!==y)return this.runConsumed=0,this.flushAndEmitLegacyOrReject(a,s,b,0);t+=1,s+=1,h+=1}this.runConsumed=0,o+=1+(m>>1),c=r[o];continue}let l=c>>>14,d=e.charCodeAt(t);if(l!==0){if(!n&&(c&Lc.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===lu.SEMI)return this.emitNamedEntityData(o,l,a+s);if(l===1)return this.flushAndEmitLegacyOrReject(a,s,d,l)}let p=CVr(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&Lc.FLAG13)===0)this.result=o,a+=s-1,s=1;return this.treeIndex=o,this.excess=s,this.consumed=a,-1}emitNotTerminatedNamedEntity(){let{result:e,decodeTree:t}=this,r=t[e]>>>14;return this.emitNamedEntityData(e,r,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,r){let{decodeTree:i}=this;if(this.emitCodePoint(t===1?i[e]&Lc.VALUE_MASK:i[e+1],r),t===3)this.emitCodePoint(i[e+2],r);return r}end(){switch(this.state){case cu.NamedEntity:return this.result!==0&&(this.decodeMode!==d0.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case cu.NumericDecimal:return this.emitNumericEntity(0,2);case cu.NumericHex:return this.emitNumericEntity(0,3);case cu.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function CVr(e,t,r,i){let n=(t&Lc.BRANCH_LENGTH)>>7,o=t&Lc.JUMP_TABLE;if(o){if(n===0)return i===o?r:-1;let c=i-o;if(c>>>0>=n)return-1;let 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 lu,wW=32,cu,d0;var tYe=xs(()=>{KKe();T0e();XKe();QKe();T0e();(function(e){e[e.AMP=38]="AMP",e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_X=120]="LOWER_X"})(lu||(lu={}));(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(cu||(cu={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(d0||(d0={}))});function v5(e){return e===Er.Space||e===Er.NewLine||e===Er.Tab||e===Er.FormFeed||e===Er.CarriageReturn}function eC(e){return e===Er.Slash||e===Er.Gt||v5(e)}function DVr(e){return e>=Er.LowerA&&e<=Er.LowerZ||e>=Er.UpperA&&e<=Er.UpperZ}class tC{cbs;state=Ze.Text;buffer="";sectionStart=0;index=0;entityStart=0;baseState=Ze.Text;isSpecial=!1;running=!0;offset=0;xmlMode;decodeEntities;recognizeSelfClosing;entityDecoder;constructor({xmlMode:e=!1,decodeEntities:t=!0,recognizeSelfClosing:r=e},i){this.cbs=i,this.xmlMode=e,this.decodeEntities=t,this.recognizeSelfClosing=r,this.entityDecoder=new _0e(e?jP:I0e,(n,o)=>this.emitCodePoint(n,o))}reset(){this.state=Ze.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=Ze.Text,this.isSpecial=!1,this.currentSequence=ci.Empty,this.sequenceIndex=0,this.running=!0,this.offset=0}write(e){this.offset+=this.buffer.length,this.buffer=e,this.parse()}end(){if(this.running)this.finish()}pause(){this.running=!1}resume(){if(this.running=!0,this.index<this.buffer.length+this.offset)this.parse()}stateText(e){if(e===Er.Lt||!this.decodeEntities&&this.fastForwardTo(Er.Lt)){if(this.index>this.sectionStart)this.cbs.ontext(this.sectionStart,this.index);this.state=Ze.BeforeTagName,this.sectionStart=this.index}else if(this.decodeEntities&&e===Er.Amp)this.startEntity()}currentSequence=ci.Empty;sequenceIndex=0;enterTagBody(){if(this.currentSequence===ci.Plaintext)this.currentSequence=ci.Empty,this.state=Ze.InPlainText;else if(this.isSpecial)this.state=Ze.InSpecialTag,this.sequenceIndex=0;else this.state=Ze.Text}stateSpecialStartSequence(e){let t=e|32;if(this.sequenceIndex<this.currentSequence.length){if(t===this.currentSequence[this.sequenceIndex]){this.sequenceIndex++;return}if(this.sequenceIndex===3){if(this.currentSequence===ci.ScriptEnd&&t===ci.StyleEnd[3]){this.currentSequence=ci.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===ci.TitleEnd&&t===ci.TextareaEnd[3]){this.currentSequence=ci.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===ci.NoembedEnd&&t===ci.NoframesEnd[4]){this.currentSequence=ci.NoframesEnd,this.sequenceIndex=5;return}}else if(eC(e)){this.sequenceIndex=0,this.state=Ze.InTagName,this.stateInTagName(e);return}this.isSpecial=!1,this.currentSequence=ci.Empty,this.sequenceIndex=0,this.state=Ze.InTagName,this.stateInTagName(e)}stateCDATASequence(e){if(e===ci.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===ci.Cdata.length)this.state=Ze.InCommentLike,this.currentSequence=ci.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1}else if(this.sequenceIndex=0,this.xmlMode)this.state=Ze.InDeclaration,this.stateInDeclaration(e);else this.state=Ze.InSpecialComment,this.stateInSpecialComment(e)}fastForwardTo(e){while(++this.index<this.buffer.length+this.offset)if(this.buffer.charCodeAt(this.index-this.offset)===e)return!0;return this.index=this.buffer.length+this.offset-1,!1}emitComment(e){this.cbs.oncomment(this.sectionStart,this.index,e),this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=Ze.Text}stateInCommentLike(e){if(!this.xmlMode&&this.currentSequence===ci.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&e===Er.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===ci.CommentEnd&&this.sequenceIndex===2&&e===Er.Gt)this.emitComment(2);else if(this.currentSequence===ci.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&e!==Er.Gt)this.sequenceIndex=Number(e===Er.Dash);else if(e===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===ci.CdataEnd)this.cbs.oncdata(this.sectionStart,this.index,2);else this.cbs.oncomment(this.sectionStart,this.index,3);this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=Ze.Text}}else if(this.sequenceIndex===0){if(this.fastForwardTo(this.currentSequence[0]))this.sequenceIndex=1}else if(e!==this.currentSequence[this.sequenceIndex-1])this.sequenceIndex=0}isTagStartChar(e){return this.xmlMode?!eC(e):DVr(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(eC(e)){let t=this.index-this.currentSequence.length;if(this.sectionStart<t){let r=this.index;this.index=t,this.cbs.ontext(this.sectionStart,t),this.index=r}this.isSpecial=!1,this.sectionStart=t+2,this.stateInClosingTagName(e);return}this.sequenceIndex=0}if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(this.sequenceIndex===0){if(this.currentSequence===ci.TitleEnd||this.currentSequence===ci.TextareaEnd){if(this.decodeEntities&&e===Er.Amp)this.startEntity()}else if(this.fastForwardTo(Er.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(e===Er.Lt)}stateBeforeTagName(e){if(e===Er.ExclamationMark)this.state=Ze.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===Er.Questionmark)if(this.xmlMode)this.state=Ze.InProcessingInstruction,this.sequenceIndex=0,this.sectionStart=this.index+1;else this.state=Ze.InSpecialComment,this.sectionStart=this.index;else if(this.isTagStartChar(e)){this.sectionStart=this.index;let t=this.xmlMode||this.cbs.isInForeignContext?.()?void 0:IVr.get(e|32);if(t===void 0)this.state=Ze.InTagName;else this.isSpecial=!0,this.currentSequence=t,this.sequenceIndex=3,this.state=Ze.SpecialStartSequence}else if(e===Er.Slash)this.state=Ze.BeforeClosingTagName;else this.state=Ze.Text,this.stateText(e)}stateInTagName(e){if(eC(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(v5(e))if(this.xmlMode);else this.state=Ze.InSpecialComment,this.sectionStart=this.index;else if(e===Er.Gt){if(this.state=Ze.Text,!this.xmlMode)this.sectionStart=this.index+1}else this.state=this.isTagStartChar(e)?Ze.InClosingTagName:Ze.InSpecialComment,this.sectionStart=this.index}stateInClosingTagName(e){if(eC(e))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=Ze.AfterClosingTagName,this.stateAfterClosingTagName(e)}stateAfterClosingTagName(e){if(e===Er.Gt||this.fastForwardTo(Er.Gt))this.state=Ze.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(e){if(e===Er.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(e===Er.Slash)this.state=Ze.InSelfClosingTag;else if(!v5(e))this.state=Ze.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(e){if(e===Er.Gt){if(this.cbs.onselfclosingtag(this.index),this.sectionStart=this.index+1,!this.recognizeSelfClosing){this.enterTagBody();return}this.state=Ze.Text,this.isSpecial=!1,this.currentSequence=ci.Empty}else if(!v5(e))this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===Er.Eq||eC(e))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=Ze.AfterAttributeName,this.stateAfterAttributeName(e)}stateAfterAttributeName(e){if(e===Er.Eq)this.state=Ze.BeforeAttributeValue;else if(e===Er.Slash||e===Er.Gt)this.cbs.onattribend(Em.NoValue,this.sectionStart),this.sectionStart=-1,this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!v5(e))this.cbs.onattribend(Em.NoValue,this.sectionStart),this.state=Ze.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(e){if(e===Er.DoubleQuote)this.state=Ze.InAttributeValueDq,this.sectionStart=this.index+1;else if(e===Er.SingleQuote)this.state=Ze.InAttributeValueSq,this.sectionStart=this.index+1;else if(!v5(e))this.sectionStart=this.index,this.state=Ze.InAttributeValueNq,this.stateInAttributeValueNoQuotes(e)}handleInAttributeValue(e,t){if(e===t||!this.decodeEntities&&this.fastForwardTo(t))this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(t===Er.DoubleQuote?Em.Double:Em.Single,this.index+1),this.state=Ze.BeforeAttributeName;else if(this.decodeEntities&&e===Er.Amp)this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,Er.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,Er.SingleQuote)}stateInAttributeValueNoQuotes(e){if(v5(e)||e===Er.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(Em.Unquoted,this.index),this.state=Ze.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(this.decodeEntities&&e===Er.Amp)this.startEntity()}stateBeforeDeclaration(e){if(e===Er.OpeningSquareBracket)this.state=Ze.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=e===Er.Dash?Ze.BeforeComment:Ze.InDeclaration;else if((e|32)===ci.Doctype[0])this.state=Ze.DeclarationSequence,this.currentSequence=ci.Doctype,this.sequenceIndex=1;else if(e===Er.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else if(e===Er.Dash)this.state=Ze.BeforeComment;else this.state=Ze.InSpecialComment}stateDeclarationSequence(e){if(this.sequenceIndex===this.currentSequence.length)this.state=Ze.InDeclaration,this.stateInDeclaration(e);else if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(e===Er.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else this.state=Ze.InSpecialComment}stateInDeclaration(e){if(e===Er.Gt||this.fastForwardTo(Er.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=Ze.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(e){if(e===Er.Questionmark)this.sequenceIndex=1;else if(e===Er.Gt&&this.sequenceIndex===1)this.cbs.onprocessinginstruction(this.sectionStart,this.index-1),this.sequenceIndex=0,this.state=Ze.Text,this.sectionStart=this.index+1;else this.sequenceIndex=Number(this.fastForwardTo(Er.Questionmark))}stateBeforeComment(e){if(e===Er.Dash)this.state=Ze.InCommentLike,this.currentSequence=ci.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=Ze.InDeclaration;else if(e===Er.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1;else this.state=Ze.InSpecialComment}stateInSpecialComment(e){if(e===Er.Gt||this.fastForwardTo(Er.Gt))this.cbs.oncomment(this.sectionStart,this.index,0),this.state=Ze.Text,this.sectionStart=this.index+1}startEntity(){this.baseState=this.state,this.state=Ze.InEntity,this.entityStart=this.index,this.entityDecoder.startEntity(this.xmlMode?d0.Strict:this.baseState===Ze.Text||this.baseState===Ze.InSpecialTag?d0.Legacy:d0.Attribute)}stateInEntity(){let e=this.index-this.offset,t=this.entityDecoder.write(this.buffer,e);if(t>=0){if(this.state=this.baseState,t===0)this.index-=1}else{if(e<this.buffer.length&&this.buffer.charCodeAt(e)===Er.Amp){this.state=this.baseState,this.index-=1;return}this.index=this.offset+this.buffer.length-1}}cleanup(){if(this.running&&this.sectionStart!==this.index){if(this.state===Ze.Text||this.state===Ze.InPlainText||this.state===Ze.InSpecialTag&&this.sequenceIndex===0)this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index;else if(this.state===Ze.InAttributeValueDq||this.state===Ze.InAttributeValueSq||this.state===Ze.InAttributeValueNq)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=this.index}}shouldContinue(){return this.index<this.buffer.length+this.offset&&this.running}parse(){while(this.shouldContinue()){let e=this.buffer.charCodeAt(this.index-this.offset);switch(this.state){case Ze.Text:{this.stateText(e);break}case Ze.InPlainText:{this.index=this.buffer.length+this.offset-1;break}case Ze.SpecialStartSequence:{this.stateSpecialStartSequence(e);break}case Ze.InSpecialTag:{this.stateInSpecialTag(e);break}case Ze.CDATASequence:{this.stateCDATASequence(e);break}case Ze.DeclarationSequence:{this.stateDeclarationSequence(e);break}case Ze.InAttributeValueDq:{this.stateInAttributeValueDoubleQuotes(e);break}case Ze.InAttributeName:{this.stateInAttributeName(e);break}case Ze.InCommentLike:{this.stateInCommentLike(e);break}case Ze.InSpecialComment:{this.stateInSpecialComment(e);break}case Ze.BeforeAttributeName:{this.stateBeforeAttributeName(e);break}case Ze.InTagName:{this.stateInTagName(e);break}case Ze.InClosingTagName:{this.stateInClosingTagName(e);break}case Ze.BeforeTagName:{this.stateBeforeTagName(e);break}case Ze.AfterAttributeName:{this.stateAfterAttributeName(e);break}case Ze.InAttributeValueSq:{this.stateInAttributeValueSingleQuotes(e);break}case Ze.BeforeAttributeValue:{this.stateBeforeAttributeValue(e);break}case Ze.BeforeClosingTagName:{this.stateBeforeClosingTagName(e);break}case Ze.AfterClosingTagName:{this.stateAfterClosingTagName(e);break}case Ze.InAttributeValueNq:{this.stateInAttributeValueNoQuotes(e);break}case Ze.InSelfClosingTag:{this.stateInSelfClosingTag(e);break}case Ze.InDeclaration:{this.stateInDeclaration(e);break}case Ze.BeforeDeclaration:{this.stateBeforeDeclaration(e);break}case Ze.BeforeComment:{this.stateBeforeComment(e);break}case Ze.InProcessingInstruction:{this.stateInProcessingInstruction(e);break}case Ze.InEntity:{this.stateInEntity();break}}this.index++}this.cleanup()}finish(){if(this.state===Ze.InEntity)this.entityDecoder.end(),this.state=this.baseState;this.handleTrailingData(),this.cbs.onend()}handleTrailingCommentLikeData(e){if(this.state!==Ze.InCommentLike)return!1;if(this.currentSequence===ci.CdataEnd)if(this.xmlMode){if(this.sectionStart<e)this.cbs.oncdata(this.sectionStart,e,0)}else{let t=this.sectionStart-ci.Cdata.length-1;this.cbs.oncomment(t,e,0)}else{let t=this.xmlMode?0:Math.min(this.sequenceIndex,ci.CommentEnd.length-1);this.cbs.oncomment(this.sectionStart,e,t)}return!0}handleTrailingMarkupDeclaration(e){if(this.xmlMode)switch(this.state){case Ze.InSpecialComment:case Ze.BeforeComment:case Ze.CDATASequence:case Ze.DeclarationSequence:case Ze.InDeclaration:return this.cbs.ontext(this.sectionStart,e),!0;default:return!1}switch(this.state){case Ze.BeforeDeclaration:case Ze.InSpecialComment:case Ze.BeforeComment:case Ze.CDATASequence:return this.cbs.oncomment(this.sectionStart,e,0),!0;case Ze.DeclarationSequence:{if(this.sequenceIndex!==ci.Doctype.length)this.cbs.oncomment(this.sectionStart,e,0);return!0}case Ze.InDeclaration:return!0;default:return!1}}handleTrailingData(){let e=this.buffer.length+this.offset;if(this.handleTrailingCommentLikeData(e)||this.handleTrailingMarkupDeclaration(e))return;if(this.sectionStart>=e)return;switch(this.state){case Ze.InTagName:case Ze.BeforeAttributeName:case Ze.BeforeAttributeValue:case Ze.AfterAttributeName:case Ze.InAttributeName:case Ze.InAttributeValueSq:case Ze.InAttributeValueDq:case Ze.InAttributeValueNq:case Ze.InClosingTagName:break;default:this.cbs.ontext(this.sectionStart,e)}}emitCodePoint(e,t){if(this.baseState!==Ze.Text&&this.baseState!==Ze.InSpecialTag){if(this.sectionStart<this.entityStart)this.cbs.onattribdata(this.sectionStart,this.entityStart);this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.onattribentity(e)}else{if(this.sectionStart<this.entityStart)this.cbs.ontext(this.sectionStart,this.entityStart);this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.ontextentity(e,this.sectionStart)}}}var Er,Ze,Em,ci,IVr;var P0e=xs(()=>{tYe();(function(e){e[e.Tab=9]="Tab",e[e.NewLine=10]="NewLine",e[e.FormFeed=12]="FormFeed",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.ExclamationMark=33]="ExclamationMark",e[e.Number=35]="Number",e[e.Amp=38]="Amp",e[e.SingleQuote=39]="SingleQuote",e[e.DoubleQuote=34]="DoubleQuote",e[e.Dash=45]="Dash",e[e.Slash=47]="Slash",e[e.Zero=48]="Zero",e[e.Nine=57]="Nine",e[e.Semi=59]="Semi",e[e.Lt=60]="Lt",e[e.Eq=61]="Eq",e[e.Gt=62]="Gt",e[e.Questionmark=63]="Questionmark",e[e.UpperA=65]="UpperA",e[e.LowerA=97]="LowerA",e[e.UpperF=70]="UpperF",e[e.LowerF=102]="LowerF",e[e.UpperZ=90]="UpperZ",e[e.LowerZ=122]="LowerZ",e[e.LowerX=120]="LowerX",e[e.OpeningSquareBracket=91]="OpeningSquareBracket"})(Er||(Er={}));(function(e){e[e.Text=1]="Text",e[e.BeforeTagName=2]="BeforeTagName",e[e.InTagName=3]="InTagName",e[e.InSelfClosingTag=4]="InSelfClosingTag",e[e.BeforeClosingTagName=5]="BeforeClosingTagName",e[e.InClosingTagName=6]="InClosingTagName",e[e.AfterClosingTagName=7]="AfterClosingTagName",e[e.BeforeAttributeName=8]="BeforeAttributeName",e[e.InAttributeName=9]="InAttributeName",e[e.AfterAttributeName=10]="AfterAttributeName",e[e.BeforeAttributeValue=11]="BeforeAttributeValue",e[e.InAttributeValueDq=12]="InAttributeValueDq",e[e.InAttributeValueSq=13]="InAttributeValueSq",e[e.InAttributeValueNq=14]="InAttributeValueNq",e[e.BeforeDeclaration=15]="BeforeDeclaration",e[e.InDeclaration=16]="InDeclaration",e[e.InProcessingInstruction=17]="InProcessingInstruction",e[e.BeforeComment=18]="BeforeComment",e[e.CDATASequence=19]="CDATASequence",e[e.DeclarationSequence=20]="DeclarationSequence",e[e.InSpecialComment=21]="InSpecialComment",e[e.InCommentLike=22]="InCommentLike",e[e.SpecialStartSequence=23]="SpecialStartSequence",e[e.InSpecialTag=24]="InSpecialTag",e[e.InPlainText=25]="InPlainText",e[e.InEntity=26]="InEntity"})(Ze||(Ze={}));(function(e){e[e.NoValue=0]="NoValue",e[e.Unquoted=1]="Unquoted",e[e.Single=2]="Single",e[e.Double=3]="Double"})(Em||(Em={}));ci={Empty:new Uint8Array(0),Cdata:new Uint8Array([67,68,65,84,65,91]),CdataEnd:new Uint8Array([93,93,62]),CommentEnd:new Uint8Array([45,45,33,62]),Doctype:new Uint8Array([100,111,99,116,121,112,101]),IframeEnd:new Uint8Array([60,47,105,102,114,97,109,101]),NoembedEnd:new Uint8Array([60,47,110,111,101,109,98,101,100]),NoframesEnd:new Uint8Array([60,47,110,111,102,114,97,109,101,115]),Plaintext:new Uint8Array([60,47,112,108,97,105,110,116,101,120,116]),ScriptEnd:new Uint8Array([60,47,115,99,114,105,112,116]),StyleEnd:new Uint8Array([60,47,115,116,121,108,101]),TitleEnd:new Uint8Array([60,47,116,105,116,108,101]),TextareaEnd:new Uint8Array([60,47,116,101,120,116,97,114,101,97]),XmpEnd:new Uint8Array([60,47,120,109,112])},IVr=new Map([[ci.IframeEnd[2],ci.IframeEnd],[ci.NoembedEnd[2],ci.NoembedEnd],[ci.Plaintext[2],ci.Plaintext],[ci.ScriptEnd[2],ci.ScriptEnd],[ci.TitleEnd[2],ci.TitleEnd],[ci.XmpEnd[2],ci.XmpEnd]])});class nC{options;startIndex=0;endIndex=0;openTagStart=0;tagname="";attribname="";attribvalue="";attribs=null;stack=[];foreignContext;cbs;lowerCaseTagNames;lowerCaseAttributeNames;recognizeSelfClosing;htmlMode;tokenizer;buffers=[];bufferOffset=0;writeIndex=0;ended=!1;constructor(e,t={}){this.options=t,this.cbs=e??{},this.htmlMode=!this.options.xmlMode,this.lowerCaseTagNames=t.lowerCaseTags??this.htmlMode,this.lowerCaseAttributeNames=t.lowerCaseAttributeNames??this.htmlMode,this.recognizeSelfClosing=t.recognizeSelfClosing??!this.htmlMode,this.tokenizer=new(t.Tokenizer??tC)(this.options,this),this.foreignContext=[Lb.None],this.cbs.onparserinit?.(this)}ontext(e,t){let r=this.getSlice(e,t);this.endIndex=t-1,this.cbs.ontext?.(r),this.startIndex=t}ontextentity(e,t){this.endIndex=t-1,this.cbs.ontext?.(rYe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==Lb.None}isVoidElement(e){return this.htmlMode&&_Vr.has(e)}readTagName(e,t){let r=this.lowerCaseTagNames?this.getSlice(e,t).toLowerCase():this.getSlice(e,t);if(!(this.lowerCaseTagNames&&this.htmlMode))return r;if(this.foreignContext[0]===Lb.Svg)return cYe.get(r)??r;if(this.foreignContext.length>1){let i=cYe.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&&TVr.get(e);if(t)while(this.stack.length>0&&t.has(this.stack[0]))this.popElement(!0);if(!this.isVoidElement(e)){if(this.stack.unshift(e),this.htmlMode){if(e==="svg")this.foreignContext.unshift(Lb.Svg);else if(e==="math")this.foreignContext.unshift(Lb.MathML);else if(aYe.has(e))this.foreignContext.unshift(Lb.None)}}if(this.cbs.onopentagname?.(e),this.cbs.onopentag)this.attribs={}}endOpenTag(e){if(this.startIndex=this.openTagStart,this.attribs)this.cbs.onopentag?.(this.tagname,this.attribs,e),this.attribs=null;if(this.cbs.onclosetag&&this.isVoidElement(this.tagname))this.cbs.onclosetag(this.tagname,!0);this.tagname=""}onopentagend(e){this.endIndex=e,this.endOpenTag(!1),this.startIndex=e+1}onclosetag(e,t){this.endIndex=t;let r=this.readTagName(e,t);if(!this.isVoidElement(r)){let i=this.stack.indexOf(r);if(i!==-1){for(let n=0;n<i;n++)this.popElement(!0);this.popElement(!1)}else if(this.htmlMode&&r==="p")this.emitOpenTag("p"),this.closeCurrentTag(!0)}else if(this.htmlMode&&r==="br")this.cbs.onopentagname?.("br"),this.cbs.onopentag?.("br",{},!0),this.cbs.onclosetag?.("br",!1);this.startIndex=t+1}onselfclosingtag(e){if(this.endIndex=e,this.recognizeSelfClosing||this.isInForeignContext())this.closeCurrentTag(!1),this.startIndex=e+1;else this.onopentagend(e)}popElement(e){let t=this.stack.shift();if(this.htmlMode&&(PVr.has(t)||aYe.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+=rYe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===Em.Double?'"':e===Em.Single?"'":e===Em.NoValue?void 0:null),this.attribs&&!Object.hasOwn(this.attribs,this.attribname))this.attribs[this.attribname]=this.attribvalue;this.attribvalue=""}getInstructionName(e){let t=e.search(RVr),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?sYe:r.slice(0,sYe.length):this.getInstructionName(r);this.cbs.onprocessinginstruction(`!${i}`,`!${r}`)}this.startIndex=t+1}onprocessinginstruction(e,t){this.endIndex=t;let r=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let i=this.getInstructionName(r);this.cbs.onprocessinginstruction(`?${i}`,`?${r}`)}this.startIndex=t+1}oncomment(e,t,r){this.endIndex=t,this.cbs.oncomment?.(this.getSlice(e,t-r)),this.cbs.oncommentend?.(),this.startIndex=t+1}oncdata(e,t,r){this.endIndex=t;let i=this.getSlice(e,t-r);if(!this.htmlMode||this.options.recognizeCDATA)this.cbs.oncdatastart?.(),this.cbs.ontext?.(i),this.cbs.oncdataend?.();else if(this.isInForeignContext())this.cbs.ontext?.(i);else this.cbs.oncomment?.(`[CDATA[${i}]]`),this.cbs.oncommentend?.();this.startIndex=t+1}onend(){if(this.cbs.onclosetag){this.endIndex=this.startIndex;for(let e=0;e<this.stack.length;e++)this.cbs.onclosetag(this.stack[e],!0)}this.cbs.onend?.()}reset(){this.cbs.onreset?.(),this.tokenizer.reset(),this.tagname="",this.attribname="",this.attribvalue="",this.attribs=null,this.stack.length=0,this.startIndex=0,this.endIndex=0,this.cbs.onparserinit?.(this),this.buffers.length=0,this.foreignContext.length=0,this.foreignContext.unshift(Lb.None),this.bufferOffset=0,this.writeIndex=0,this.ended=!1}parseComplete(e){this.reset(),this.end(e)}getSlice(e,t){if(e===t)return"";while(e-this.bufferOffset>=this.buffers[0].length)this.shiftBuffer();let r=this.buffers[0].slice(e-this.bufferOffset,t-this.bufferOffset);while(t-this.bufferOffset>this.buffers[0].length)this.shiftBuffer(),r+=this.buffers[0].slice(0,t-this.bufferOffset);return r}shiftBuffer(){this.bufferOffset+=this.buffers[0].length,this.writeIndex--,this.buffers.shift()}write(e){if(this.ended){this.cbs.onerror?.(Error(".write() after done!"));return}if(this.buffers.push(e),this.tokenizer.running)this.tokenizer.write(e),this.writeIndex++}end(e){if(this.ended){this.cbs.onerror?.(Error(".end() after done!"));return}if(e)this.write(e);this.ended=!0,this.tokenizer.end()}pause(){this.tokenizer.pause()}resume(){this.tokenizer.resume();while(this.tokenizer.running&&this.writeIndex<this.buffers.length)this.tokenizer.write(this.buffers[this.writeIndex++]);if(this.ended)this.tokenizer.end()}}var rYe,rC,Vs,iC,iYe,nYe,oYe,TVr,sYe="doctype",_Vr,PVr,aYe,cYe,Lb,RVr;var R0e=xs(()=>{P0e();({fromCodePoint:rYe}=String),rC=new Set(["input","option","optgroup","select","button","datalist","textarea"]),Vs=new Set(["p"]),iC=new Set(["h1","h2","h3","h4","h5","h6","p"]),iYe=new Set(["thead","tbody"]),nYe=new Set(["dd","dt"]),oYe=new Set(["rt","rp"]),TVr=new Map([["tr",new Set(["tr","th","td"])],["th",new Set(["th"])],["td",new Set(["thead","th","td"])],["body",new Set(["head","link","script"])],["a",new Set(["a"])],["li",new Set(["li"])],["p",Vs],["h1",iC],["h2",iC],["h3",iC],["h4",iC],["h5",iC],["h6",iC],["select",rC],["input",rC],["output",rC],["button",rC],["datalist",rC],["textarea",rC],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",nYe],["dt",nYe],["address",Vs],["article",Vs],["aside",Vs],["blockquote",Vs],["details",Vs],["div",Vs],["dl",Vs],["fieldset",Vs],["figcaption",Vs],["figure",Vs],["footer",Vs],["form",Vs],["header",Vs],["hr",Vs],["main",Vs],["nav",Vs],["ol",Vs],["pre",Vs],["section",Vs],["table",Vs],["ul",Vs],["rt",oYe],["rp",oYe],["tbody",iYe],["tfoot",iYe]]),_Vr=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),PVr=new Set(["math","svg"]),aYe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),cYe=new Map([["altglyph","altGlyph"],["altglyphdef","altGlyphDef"],["altglyphitem","altGlyphItem"],["animatecolor","animateColor"],["animatemotion","animateMotion"],["animatetransform","animateTransform"],["clippath","clipPath"],["feblend","feBlend"],["fecolormatrix","feColorMatrix"],["fecomponenttransfer","feComponentTransfer"],["fecomposite","feComposite"],["feconvolvematrix","feConvolveMatrix"],["fediffuselighting","feDiffuseLighting"],["fedisplacementmap","feDisplacementMap"],["fedistantlight","feDistantLight"],["fedropshadow","feDropShadow"],["feflood","feFlood"],["fefunca","feFuncA"],["fefuncb","feFuncB"],["fefuncg","feFuncG"],["fefuncr","feFuncR"],["fegaussianblur","feGaussianBlur"],["feimage","feImage"],["femerge","feMerge"],["femergenode","feMergeNode"],["femorphology","feMorphology"],["feoffset","feOffset"],["fepointlight","fePointLight"],["fespecularlighting","feSpecularLighting"],["fespotlight","feSpotLight"],["fetile","feTile"],["feturbulence","feTurbulence"],["foreignobject","foreignObject"],["glyphref","glyphRef"],["lineargradient","linearGradient"],["radialgradient","radialGradient"],["textpath","textPath"]]);(function(e){e[e.None=0]="None",e[e.Svg=1]="Svg",e[e.MathML=2]="MathML"})(Lb||(Lb={}));RVr=/\s|\//});var SW={};rg(SW,{CDATA:()=>q0e,Comment:()=>L0e,Directive:()=>N0e,Doctype:()=>FVr,ElementType:()=>pn,Root:()=>M0e,Script:()=>j0e,Style:()=>z0e,Tag:()=>U0e,Text:()=>O0e,isTag:()=>F0e});function F0e(e){return e.type===pn.Tag||e.type===pn.Script||e.type===pn.Style}var pn,M0e,O0e,N0e,L0e,j0e,z0e,U0e,q0e,FVr;var oC=xs(()=>{(function(e){e.Root="root",e.Text="text",e.Directive="directive",e.Comment="comment",e.Script="script",e.Style="style",e.Tag="tag",e.CDATA="cdata",e.Doctype="doctype"})(pn||(pn={}));M0e=pn.Root,O0e=pn.Text,N0e=pn.Directive,L0e=pn.Comment,j0e=pn.Script,z0e=pn.Style,U0e=pn.Tag,q0e=pn.CDATA,FVr=pn.Doctype});class G0e{parent=null;prev=null;next=null;startIndex=null;endIndex=null;get parentNode(){return this.parent}set parentNode(e){this.parent=e}get previousSibling(){return this.prev}set previousSibling(e){this.prev=e}get nextSibling(){return this.next}set nextSibling(e){this.next=e}cloneNode(e=!1){return lYe(this,e)}}function uu(e){return F0e(e)}function _W(e){return e.type===pn.CDATA}function sw(e){return e.type===pn.Text}function H0e(e){return e.type===pn.Comment}function MVr(e){return e.type===pn.Directive}function OVr(e){return e.type===pn.Root}function dp(e){return Object.hasOwn(e,"children")}function lYe(e,t=!1){let r;if(sw(e))r=new zP(e.data);else if(H0e(e))r=new BW(e.data);else if(uu(e)){let i=t?$0e(e.children):[],n=new TW(e.name,{...e.attribs},i);for(let o of i)o.parent=n;if(e.namespace!=null)n.namespace=e.namespace;if(e["x-attribsNamespace"])n["x-attribsNamespace"]={...e["x-attribsNamespace"]};if(e["x-attribsPrefix"])n["x-attribsPrefix"]={...e["x-attribsPrefix"]};r=n}else if(_W(e)){let i=t?$0e(e.children):[],n=new IW(i);for(let o of i)o.parent=n;r=n}else if(OVr(e)){let i=t?$0e(e.children):[],n=new UP(i);for(let o of i)o.parent=n;if(e["x-mode"])n["x-mode"]=e["x-mode"];r=n}else if(MVr(e)){let i=new CW(e.name,e.data);if(e["x-name"]!=null)i["x-name"]=e["x-name"],i["x-publicId"]=e["x-publicId"],i["x-systemId"]=e["x-systemId"];r=i}else throw Error(`Not implemented yet: ${e.type}`);if(r.startIndex=e.startIndex,r.endIndex=e.endIndex,e.sourceCodeLocation!=null)r.sourceCodeLocation=e.sourceCodeLocation;return r}function $0e(e){let t=e.map((r)=>lYe(r,!0));for(let r=1;r<t.length;r++)t[r].prev=t[r-1],t[r-1].next=t[r];return t}var kW,zP,BW,CW,DW,IW,UP,TW;var W0e=xs(()=>{oC();kW=class kW extends G0e{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};zP=class zP extends kW{type=pn.Text;get nodeType(){return 3}};BW=class BW extends kW{type=pn.Comment;get nodeType(){return 8}};CW=class CW extends kW{type=pn.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};DW=class DW extends G0e{children;constructor(e){super();this.children=e}get firstChild(){return this.children[0]??null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(e){this.children=e}};IW=class IW extends DW{type=pn.CDATA;get nodeType(){return 4}};UP=class UP extends DW{type=pn.Root;get nodeType(){return 9}};TW=class TW extends DW{name;attribs;type;constructor(e,t,r=[],i=e==="script"?pn.Script:e==="style"?pn.Style:pn.Tag){super(r);this.name=e,this.attribs=t,this.type=i}get nodeType(){return 1}get tagName(){return this.name}set tagName(e){this.name=e}get attributes(){return Object.keys(this.attribs).map((e)=>({name:e,value:this.attribs[e],namespace:this["x-attribsNamespace"]?.[e],prefix:this["x-attribsPrefix"]?.[e]}))}namespace;"x-attribsNamespace";"x-attribsPrefix"}});class A5{dom=[];root=new UP(this.dom);callback;options;elementCB;done=!1;tagStack=[this.root];lastNode=null;parser=null;constructor(e,t,r){if(typeof t==="function")r=t,t=uYe;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??uYe,this.elementCB=r??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new UP(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){if(this.done)return;this.done=!0,this.parser=null,this.handleCallback(null)}onerror(e){this.handleCallback(e)}onclosetag(){this.lastNode=null;let e=this.tagStack.pop();if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(this.elementCB)this.elementCB(e)}onopentag(e,t){let r=this.options.xmlMode?pn.Tag:void 0,i=new TW(e,t,void 0,r);this.addNode(i),this.tagStack.push(i)}ontext(e){let{lastNode:t}=this;if(t&&t.type===pn.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let r=new zP(e);this.addNode(r),this.lastNode=r}}oncomment(e){if(this.lastNode&&this.lastNode.type===pn.Comment){this.lastNode.data+=e;return}let t=new BW(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new zP(""),t=new IW([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let r=new CW(e,t);this.addNode(r)}handleCallback(e){if(typeof this.callback==="function")this.callback(e,this.dom);else if(e)throw e}addNode(e){let t=this.tagStack[this.tagStack.length-1],r=t.children[t.children.length-1];if(this.options.withStartIndices&&this.parser)e.startIndex=this.parser.startIndex;if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(t.children.push(e),r)e.prev=r,r.next=e;e.parent=t,this.lastNode=null}}var uYe;var aw=xs(()=>{oC();W0e();W0e();uYe={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function sC(e,t,r=!0,i=Number.POSITIVE_INFINITY){return dYe(e,Array.isArray(t)?t:[t],r,i)}function dYe(e,t,r,i){let n=[],o=[Array.isArray(t)?t:[t]],s=[0];for(;;){if(s[0]>=o[0].length){if(s.length===1)return n;o.shift(),s.shift();continue}let a=o[0][s[0]++];if(e(a)){if(n.push(a),--i<=0)return n}if(r&&dp(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function PW(e,t,r=!0){let i=Array.isArray(t)?t:[t];for(let n of i){if(uu(n)&&e(n))return n;if(r&&dp(n)&&n.children.length>0){let o=PW(e,n.children,!0);if(o)return o}}return null}function pYe(e,t){return(Array.isArray(t)?t:[t]).some((r)=>uu(r)&&e(r)||dp(r)&&pYe(e,r.children))}function NVr(e,t){let r=[],i=[Array.isArray(t)?t:[t]],n=[0];for(;;){if(n[0]>=i[0].length){if(i.length===1)return r;i.shift(),n.shift();continue}let o=i[0][n[0]++];if(uu(o)&&e(o))r.push(o);if(dp(o)&&o.children.length>0)n.unshift(0),i.unshift(o.children)}}var Z0e=xs(()=>{aw()});function V0e(e,t){if(typeof t==="function")return(r)=>uu(r)&&t(r.attribs[e]);return(r)=>uu(r)&&r.attribs[e]===t}function LVr(e,t){return(r)=>e(r)||t(r)}function mYe(e){let t=Object.keys(e).map((r)=>{let i=e[r];return Object.hasOwn(RW,r)?RW[r](i):V0e(r,i)});return t.length===0?null:t.reduce(LVr)}function jVr(e,t){let r=mYe(e);return r?r(t):!0}function zVr(e,t,r,i=Number.POSITIVE_INFINITY){let n=mYe(e);return n?sC(n,t,r,i):[]}function UVr(e,t,r=!0){if(!Array.isArray(t))t=[t];return PW(V0e("id",e),t,r)}function w5(e,t,r=!0,i=Number.POSITIVE_INFINITY){return sC(RW.tag_name(e),t,r,i)}function qVr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return sC(V0e("class",e),t,r,i)}function $Vr(e,t,r=!0,i=Number.POSITIVE_INFINITY){return sC(RW.tag_type(e),t,r,i)}var RW;var K0e=xs(()=>{aw();Z0e();RW={tag_name(e){if(typeof e==="function")return(t)=>uu(t)&&e(t.name);if(e==="*")return uu;return(t)=>uu(t)&&t.name===e},tag_type(e){if(typeof e==="function")return(t)=>e(t.type);return(t)=>t.type===e},tag_contains(e){if(typeof e==="function")return(t)=>sw(t)&&e(t.data);return(t)=>sw(t)&&t.data===e}}});function fYe(e){return e===34?""":e===38?"&":e===39?"'":e===60?"<":e===62?">":" "}function hYe(e){return e>=128||e>=32&&e<64&&(GVr>>>e&1)===1}function FW(e){let{length:t}=e,r,i=0,n=0;while(n<t){let o=e.charCodeAt(n);if(!hYe(o)){let a=Math.min(n+32,t),c=n+1;while(c<a&&!hYe(e.charCodeAt(c)))c++;if(c<a){n=c;continue}if(c>=t)break;if(Y0e.lastIndex=c,!Y0e.test(e))break;n=Y0e.lastIndex-1;continue}if(r===void 0)r=e.substring(0,n);else if(i!==n)r+=e.substring(i,n);if(o<64){r+=fYe(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 xYe(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+=fYe(o),i=n+1}while(e.test(t));return r+t.substring(i)}function J0e(e){return xYe(HVr,e)}function Q0e(e){return xYe(WVr,e)}var GVr=1342177476,Y0e,HVr,WVr;var gYe=xs(()=>{Y0e=/["&'<>\u0080-\uFFFF]/g;HVr=/["&\u{A0}]/gu;WVr=/[&<>\u{A0}]/gu});var yYe,bYe;var EYe=xs(()=>{gYe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(yYe||(yYe={}));(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"})(bYe||(bYe={}))});var vYe,AYe;var wYe=xs(()=>{vYe=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])),AYe=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 JVr(e,t={}){let r="length"in e?e:[e],i=t.xmlMode??!1,n="";for(let o=0;o<r.length;o++)n+=kYe(r[o],t,i);return n}function SYe(e,t,r){let i="";for(let n=0;n<e.length;n++)i+=kYe(e[n],t,r);return i}function kYe(e,t,r){switch(e.type){case M0e:return SYe(e.children,t,r);case N0e:return`<${e.data}>`;case L0e:return`<!--${e.data}-->`;case q0e:return`<![CDATA[${e.children[0].data}]]>`;case j0e:case z0e:case U0e:return QVr(e,t,r);case O0e:{let i=e,n=i.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!r&&i.parent&&ZVr.has(i.parent.name)))return r||t.encodeEntities!=="utf8"?FW(n):Q0e(n);return n}}}function QVr(e,t,r){if(r==="foreign"){if(e.name=vYe.get(e.name)??e.name,e.parent&&YVr.has(e.parent.name))r=!1}if(!r&&KVr.has(e.name))r="foreign";let{name:i,children:n}=e,o=!r&&VVr.has(i),s=`<${i}${eKr(e.attribs,t,r)}`;if(n.length===0&&(r?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=r?"/>":" />";else{if(s+=">",n.length>0)s+=SYe(n,t,r);if(!o)s+=`</${i}>`}return s}function XVr(e){return e.replaceAll('"',""")}function eKr(e,t,r){if(!e)return"";let i=(t.encodeEntities??t.decodeEntities)===!1?XVr:r||t.encodeEntities!=="utf8"?FW:J0e,n=r==="foreign",o=!!(t.emptyAttrs??r),s="";for(let a in e){if(!Object.hasOwn(e,a))continue;let c=e[a],l=n?AYe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${l}`:` ${l}="${i(c==null?"":String(c))}"`}return s}var ZVr,VVr,KVr,YVr,BYe;var CYe=xs(()=>{oC();EYe();wYe();ZVr=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),VVr=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),KVr=new Set(["svg","math"]),YVr=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));BYe=JVr});function DYe(e,t){return BYe(e,t)}function tKr(e,t){return dp(e)?e.children.map((r)=>DYe(r,t)).join(""):""}function MW(e){if(Array.isArray(e))return e.map(MW).join("");if(uu(e))return e.name==="br"?`
|
|
3
3
|
`:MW(e.children);if(_W(e))return MW(e.children);if(sw(e))return e.data;return""}function qP(e){if(Array.isArray(e))return e.map(qP).join("");if(dp(e)&&!H0e(e))return qP(e.children);if(sw(e))return e.data;return""}function X0e(e){if(Array.isArray(e))return e.map(X0e).join("");if(dp(e)&&(e.type===pn.Tag||_W(e)))return X0e(e.children);if(sw(e))return e.data;return""}var exe=xs(()=>{CYe();oC();aw()});function $P(e){let t=OW(sKr,e);return t?t.name==="feed"?rKr(t):iKr(t):null}function rKr(e){let t=e.children,r={type:"atom",items:w5("entry",t).map((o)=>{let{children:s}=o,a={media:IYe(s)};pp(a,"id","id",s),pp(a,"title","title",s);let c=OW("link",s)?.attribs.href;if(c)a.link=c;let l=cw("summary",s)||cw("content",s);if(l)a.description=l;let d=cw("updated",s);if(d)a.pubDate=new Date(d);return a})};pp(r,"id","id",t),pp(r,"title","title",t);let i=OW("link",t)?.attribs.href;if(i)r.link=i;pp(r,"description","subtitle",t);let n=cw("updated",t);if(n)r.updated=new Date(n);return pp(r,"author","email",t,!0),r}function iKr(e){let t=OW("channel",e.children)?.children??[],r={type:e.name.substr(0,3),id:"",items:w5("item",e.children).map((n)=>{let{children:o}=n,s={media:IYe(o)};pp(s,"id","guid",o),pp(s,"title","title",o),pp(s,"link","link",o),pp(s,"description","description",o);let a=cw("pubDate",o)||cw("dc:date",o);if(a)s.pubDate=new Date(a);return s})};pp(r,"title","title",t),pp(r,"link","link",t),pp(r,"description","description",t);let i=cw("lastBuildDate",t);if(i)r.updated=new Date(i);return pp(r,"author","managingEditor",t,!0),r}function IYe(e){return w5("media:content",e).map((t)=>{let{attribs:r}=t,i={medium:r.medium,isDefault:!!r.isDefault};for(let n of nKr)if(r[n])i[n]=r[n];for(let n of oKr)if(r[n])i[n]=Number.parseInt(r[n],10);if(r.expression)i.expression=r.expression;return i})}function OW(e,t){return w5(e,t,!0,1)[0]}function cw(e,t,r=!1){return qP(w5(e,t,r,1)).trim()}function pp(e,t,r,i,n=!1){let o=cw(r,i,n);if(o)e[t]=o}function sKr(e){return e==="rss"||e==="feed"||e==="rdf:RDF"}var nKr,oKr;var TYe=xs(()=>{K0e();exe();nKr=["url","type","lang"],oKr=["fileSize","bitrate","framerate","samplingrate","channels","duration","height","width"]});function aKr(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 _Ye(e,t){let r=[],i=[];if(e===t)return 0;let n=dp(e)?e:e.parent;while(n)r.unshift(n),n=n.parent;n=dp(t)?t:t.parent;while(n)i.unshift(n),n=n.parent;let o=Math.min(r.length,i.length),s=0;while(s<o&&r[s]===i[s])s++;if(s===0)return Oh.DISCONNECTED;let a=r[s-1],c=a.children,l=r[s],d=i[s];if(c.indexOf(l)>c.indexOf(d)){if(a===t)return Oh.FOLLOWING|Oh.CONTAINED_BY;return Oh.FOLLOWING}if(a===e)return Oh.PRECEDING|Oh.CONTAINS;return Oh.PRECEDING}function cKr(e){return e=e.filter((t,r,i)=>!i.includes(t,r+1)),e.sort((t,r)=>{let i=_Ye(t,r);if(i&Oh.PRECEDING)return-1;if(i&Oh.FOLLOWING)return 1;return 0}),e}var Oh;var PYe=xs(()=>{aw();(function(e){e[e.DISCONNECTED=1]="DISCONNECTED",e[e.PRECEDING=2]="PRECEDING",e[e.FOLLOWING=4]="FOLLOWING",e[e.CONTAINS=8]="CONTAINS",e[e.CONTAINED_BY=16]="CONTAINED_BY"})(Oh||(Oh={}))});function GP(e){if(e.prev)e.prev.next=e.next;if(e.next)e.next.prev=e.prev;if(e.parent){let t=e.parent.children,r=t.lastIndexOf(e);if(r!==-1)t.splice(r,1)}e.next=null,e.prev=null,e.parent=null}function lKr(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 uKr(e,t){if(GP(t),t.next=null,t.parent=e,e.children.push(t)>1){let r=e.children[e.children.length-2];r.next=t,t.prev=r}else t.prev=null}function dKr(e,t){GP(t);let{parent:r}=e,i=e.next;if(t.next=i,t.prev=e,e.next=t,t.parent=r,i){if(i.prev=t,r){let n=r.children;n.splice(n.lastIndexOf(i),0,t)}}else if(r)r.children.push(t)}function pKr(e,t){if(GP(t),t.parent=e,t.prev=null,e.children.unshift(t)===1)t.next=null;else{let r=e.children[1];r.prev=t,t.next=r}}function mKr(e,t){GP(t);let{parent:r}=e;if(r){let i=r.children;i.splice(i.indexOf(e),0,t)}if(e.prev)e.prev.next=t;t.parent=r,t.prev=e.prev,t.next=e,e.prev=t}var RYe=()=>{};function FYe(e){return dp(e)?e.children:[]}function MYe(e){return e.parent||null}function hKr(e){let t=MYe(e);if(t!=null)return FYe(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 fKr(e,t){let{attribs:r}=e;return r?.[t]}function xKr(e,t){let{attribs:r}=e;return r!=null&&Object.hasOwn(r,t)&&r[t]!=null}function gKr(e){return e.name}function yKr(e){let{next:t}=e;while(t!==null&&!uu(t))({next:t}=t);return t}function bKr(e){let{prev:t}=e;while(t!==null&&!uu(t))({prev:t}=t);return t}var OYe=xs(()=>{aw()});var txe={};rg(txe,{DocumentPosition:()=>Oh,append:()=>dKr,appendChild:()=>uKr,compareDocumentPosition:()=>_Ye,existsOne:()=>pYe,filter:()=>sC,find:()=>dYe,findAll:()=>NVr,findOne:()=>PW,getAttributeValue:()=>fKr,getChildren:()=>FYe,getElementById:()=>UVr,getElements:()=>zVr,getElementsByClassName:()=>qVr,getElementsByTagName:()=>w5,getElementsByTagType:()=>$Vr,getFeed:()=>$P,getInnerHTML:()=>tKr,getName:()=>gKr,getOuterHTML:()=>DYe,getParent:()=>MYe,getSiblings:()=>hKr,getText:()=>MW,hasAttrib:()=>xKr,innerText:()=>X0e,nextElementSibling:()=>yKr,prepend:()=>mKr,prependChild:()=>pKr,prevElementSibling:()=>bKr,removeElement:()=>GP,removeSubsets:()=>aKr,replaceElement:()=>lKr,testElement:()=>jVr,textContent:()=>qP,uniqueSort:()=>cKr});var NW=xs(()=>{TYe();PYe();K0e();RYe();Z0e();exe();OYe()});var LYe={};rg(LYe,{DefaultHandler:()=>A5,DomHandler:()=>A5,DomUtils:()=>txe,ElementType:()=>SW,Parser:()=>nC,QuoteType:()=>Em,Tokenizer:()=>tC,createDocumentStream:()=>EKr,getFeed:()=>$P,parseDocument:()=>NYe,parseFeed:()=>AKr});function NYe(e,t){let r=new A5(void 0,t);return new nC(r,t).end(e),r.root}function EKr(e,t,r){let i=new A5((n)=>e(n,i.root),t,r);return new nC(i,t)}function AKr(e,t=vKr){return $P(NYe(e,t).children)}var vKr;var jYe=xs(()=>{R0e();R0e();aw();aw();oC();P0e();NW();NW();NW();vKr={xmlMode:!0}});var UYe=E(function(x3o,zYe){zYe.exports=(e)=>{if(typeof e!=="string")throw TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}});var $Ye=E(function(SKr){/*!
|
|
4
4
|
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
|
|
5
5
|
*
|
|
@@ -1035,7 +1035,7 @@ ${fA(e.cont)}`}}function Pno(e,t){return t.map((r,i,{length:n})=>Rno(e,r,i===n-1
|
|
|
1035
1035
|
`).find((b)=>b.startsWith("data: "));if(!d)continue;let p;try{let b=yHr.safeParse(JSON.parse(d.slice(6)));if(!b.success)continue;p=b.data}catch{return await yhe(i),{success:!1,error:"Malformed SSE event from remote agent"}}let m=p.result;if(m?.kind==="artifact-update"&&m.artifact)a.push(m.artifact);if(!m?.final)continue;await yhe(i);let h=m.status,f=h?.state??"unknown",y=(h?.message?.parts??[]).filter((b)=>b.kind==="text"&&typeof b.text==="string").map((b)=>b.text).join(`
|
|
1036
1036
|
`)||"No response text";return{success:!0,data:{state:f,response:y,sources:xHr(a)}}}s=await GZe(i,t,r)}return{success:!1,error:"Stream ended without a terminal event"}}class Ehe extends Error{timeoutMs;constructor(e){super(`request timed out after ${e}ms`);this.timeoutMs=e,this.name="A2ARequestTimeoutError"}}class aP extends Error{timeoutMs;constructor(e){super(`A2A stream stalled waiting for final event after ${e}ms`);this.timeoutMs=e,this.name="A2AStreamIdleTimeoutError"}}async function BHr(e,t,r,i,n){return xhe((o)=>e(t,{...r,signal:o}),{timeoutMs:i,onTimeout:()=>new Ehe(i),signal:n})}async function GZe(e,t,r){try{return await xhe(()=>e.read(),{timeoutMs:t,onTimeout:()=>new aP(t),signal:r})}catch(i){if(i instanceof aP||r?.aborted)await yhe(e,i);throw i}}async function yhe(e,t){try{await e.cancel(t)}catch{}}function CHr(e){if(e instanceof Ehe||e instanceof aP)return!1;return e instanceof Error}function ghe(e,t){let r=t>1?` after ${t} attempts`:"";if(e instanceof aP)return`${e.message}${r}`;let i=fe(e,"Unknown network error");return`Failed to reach remote agent${r}: ${i}`}async function $H(e,t={},r={}){let i=t.fetch??globalThis.fetch,n=r.signal;n?.throwIfAborted();let o={requestTimeoutMs:t.requestTimeoutMs??bHr,streamIdleTimeoutMs:t.streamIdleTimeoutMs??EHr,maxNetworkAttempts:t.maxNetworkAttempts??vHr},s=SHr(e.agent),a=ai(r.userPermissionLevel);if(!s.ok){let p=t.entityService?await UZe(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&&!qZe(c)){let p=await UZe(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(!qZe(c))return{success:!1,error:`Agent ${e.agent} is not an exact domain-like id and is not saved. Connect or clarify the agent first.`,code:"agent_not_saved"};let p=await Th(c,{fetch:i,timeoutMs:o.requestTimeoutMs,signal:n});if(!p.ok){if(HA(p.reason))return{success:!1,error:p.error};return{success:!1,error:`Could not verify an A2A Agent Card for ${c}. Connect/save it first if you want to add it to the directory.`,code:"agent_card_unavailable"}}let m=await $Ze(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 Th(c,{fetch:i,timeoutMs:o.requestTimeoutMs,signal:n});if(!d.ok){if(HA(d.reason))return{success:!1,error:d.error};return{success:!1,error:`Could not fetch Agent Card from https://${c}`}}return $Ze(d.card.url,e.message,i,t.requestSigner,o,n)}function WZe(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:AHr,visibility:"trusted",sideEffects:"external",handler:async(t,r)=>{let i=wHr.safeParse(t);if(!i.success)return{success:!1,error:`Invalid input: ${i.error.message}`};return $H(i.data,e,{userPermissionLevel:r.userPermissionLevel,...r.signal?{signal:r.signal}:{}})}}}var DHr=30000,IHr=u.looseObject({result:u.looseObject({parts:u.array(u.looseObject({kind:u.string(),data:u.unknown()}))})});function i0(e,t){return{status:"refused",code:e,error:t}}async function KZe(e,t,r){let i=e.trim().toLowerCase(),n=await r.entityService?.getEntity({entityType:"agent",id:i,visibilityScope:ai("admin")});if(!n)return i0("agent_not_saved",`Agent ${i} is not saved.`);if(n.metadata.status==="archived")return i0("agent_archived",`Agent ${i} is archived.`);if(!await r.isContactApproved?.(i))return i0("agent_not_approved",`Agent ${i} is not approved yet. Approve it first.`);let{requestSigner:o}=r;if(!o)return i0("unsigned","This brain cannot sign A2A requests, and a peer shares only with callers it can verify.");let s=r.fetch??fetch,a=r.requestTimeoutMs??DHr,c=await Th(i,{fetch:s,timeoutMs:a});if(!c.ok)return i0("agent_card_unavailable",c.error);if(!c.card.extensions.includes(X8))return i0("not_offered",`${i} does not offer shared entities.`);let l={"Content-Type":"application/json","X-A2A-Extensions":X8},d=JSON.stringify({jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/send",params:{message:{kind:"message",messageId:crypto.randomUUID(),role:"user",parts:[{kind:"data",data:t}]}}});await o({method:"POST",url:c.card.url,headers: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 i0("peer_failed",fe(h,`${i} did not answer`))}if(p.status===404)return{status:"not-found"};if(!p.ok)return i0("peer_failed",`${i} answered HTTP ${p.status}`);let m=IHr.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 YZe(e,t){let r=await KZe(e.agent,{op:"list"},t);if(r.status!=="answered")return r;let i=r.data.map((n)=>ZZe.safeParse(n)).find((n)=>n.success)?.data;return i?{status:"found",entities:i.entities}:i0("unreadable_answer",`${r.agentId} did not answer with a list.`)}async function JZe(e,t){let r=await KZe(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)=>VZe.safeParse(c)).find((c)=>c.success)?.data;if(s?.entityType!==e.entityType||s.id!==e.id)return i0("unreadable_answer",`${i} did not answer with the entity asked for.`);let a=i0("unverified",`${i} did not sign what it served, so it was not taken.`);if(s.contentHash!==Ht(s.markdown))return a;try{if((await xZe(LH(s),s.attestation.signature,s.attestation.keyId,new nP({fetch:(l)=>n(l,{signal:AbortSignal.timeout(o)})}))).domain!==i)return a}catch{return a}return{status:"found",entity:s}}var THr=new Set(["agent_not_saved","agent_not_approved","agent_archived"]);function XZe(e,t){let r="code"in e&&THr.has(e.code??"")?"permission_denied":"handler_failed",i="error"in e?e.error:t;return new br(r,{publicMessage:j9(i)})}function _Hr(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 QZe(e,t,r,i){let n=AbortSignal.timeout(i),o=(c)=>new br("deadline_exceeded",{publicMessage:`${t} did not answer within ${i} ms`,cause:c}),s;try{s=await $H({agent:t,message:r},{...e,maxNetworkAttempts:1},{requireSaved:!0,signal:n})}catch(c){if(n.aborted)throw o(c);throw new br("handler_failed",{message:fe(c,`${t} did not answer`),publicMessage:`${t} did not answer`,cause:c})}if(n.aborted)throw o();if(!("success"in s)||s.success!==!0)throw XZe(s,`${t} did not answer`);let a=vhe.safeParse(s.data);if(!a.success)throw new br("handler_failed",{publicMessage:`${t} gave no readable answer`});if(a.data.state!=="completed")throw new br("handler_failed",{publicMessage:j9(`${t} did not answer: ${a.data.response}`)});return a.data}var GH={everyProcess:!0};function eVe(e,t,r={networkAskTimeoutMs:30000,turnTimeoutMs:90000}){e.answer(HH,({request:{agent:i,question:n}})=>QZe(t,i,_Hr(n),r.networkAskTimeoutMs),GH),e.answer(WH,({request:{agent:i,message:n}})=>QZe(t,i,n,r.turnTimeoutMs),GH),e.answer(KH,({request:i})=>JZe(i,t),GH),e.answer(YH,({request:i})=>YZe(i,t),GH),e.answer(ZH,async({request:{agent:i,instruction:n,selection:o,userPermissionLevel:s}})=>{let a=await $H({agent:i,message:["A Studio author is asking about selected markdown.",`Instruction: ${n}`,"","Selected markdown:",o].join(`
|
|
1038
|
-
`)},t,{requireSaved:!0,userPermissionLevel:s});if(!("success"in a)||a.success!==!0)throw XZe(a,"Agent call failed");let c=vhe.safeParse(a.data);if(!c.success)throw new br("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(VH,async({request:{userPermissionLevel:i}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:ai(i)}}})).filter((s)=>s.metadata.status==="approved").map((s)=>{let a=s.metadata.name;return{id:s.id,label:typeof a==="string"&&a.length>0?a:s.id}}).sort((s,a)=>s.label.localeCompare(a.label))}})}var tVe={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.818",dependencies:{"@a2a-js/sdk":"^0.3.13","@brains/contracts":"workspace:*","@brains/http-signatures":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*",hono:"^4.13.13"},devDependencies:{"@brains/auth-service":"workspace:*","@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};function JH(e,t){let r=new Headers(e.headers);for(let[i,n]of Object.entries(t))r.set(i,n);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}var RHr={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Signature, Signature-Input, Content-Digest, Date","X-Content-Type-Options":"nosniff"},nd=(e)=>JH(e,RHr);function FHr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(Ph(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();await mZe(i,n.privateJwk,n.keyId)}}function MHr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(Ph(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();return{keyId:n.keyId,signature:fZe(i,n.privateJwk)}}}function Ahe(e,t,r){let i=FHr(e);return{...i?{requestSigner:i}:{},...r.fetch?{fetch:r.fetch}:{},requestTimeoutMs:t.requestTimeoutMs,streamIdleTimeoutMs:t.streamIdleTimeoutMs,maxNetworkAttempts:t.maxNetworkAttempts,entityService:e.entityReads,isContactApproved:r.isContactApproved??((n)=>e.classRuntimeState.scoped({namespace:QH,schema:XH}).has(n.trim().toLowerCase()))}}async function OHr(e,t,r){if(!r.cardReady)return;return DZe({character:e.identity.get(),profile:e.identity.getProfile(),version:tVe.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 NHr(e,t,r,i){let n=new URL(r.url),o=new URL(`${n.pathname}${n.search}`,Yx(r)),s=await hZe({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 LHr(e,t,r){let i=new iVe,n=e.agent;return i.get("/.well-known/agent-card.json",async(o)=>{let s=await OHr(e,t,r);if(!s)return nd(o.json({error:"Agent Card not ready"},503));return nd(o.json(s))}),i.get("/.well-known/agent-directory.json",async(o)=>{let s=await IZe(e.entityReads);return nd(o.json(s))}),i.get("/a2a",(o)=>nd(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),i.options("/a2a",()=>nd(new Response(null,{status:204}))),i.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return nd(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await NHr(e,r,o.req.raw,s)}catch{return nd(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return nd(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let l=PZe.safeParse(c);if(!l.success)return nd(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(iZe(o.req.raw.headers)){let p=l.data.method==="message/send"?nZe(l.data.params):void 0,m=p?.op==="list"?await aZe(e.entityReads,a.permissionLevel):await sZe(e.entityReads,a.permissionLevel,p,MHr(e));if(!m)return nd(o.json({error:"Not found"},404));return nd(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=LZe.safeParse(l.data.params??{});if(!p.success)return nd(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:l.data.id}));let m=jZe(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 nd(o.json(m));return nd(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await MZe(l.data,{taskManager:r.taskManager,turnSupervisor:r.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:r.publicAsks});return nd(o.json(d))}),i}function whe(e={}){let t=_h({id:"a2a",config:BZe,setup:(o)=>{let{config:s}=o,a=Jo(o),{servesHttp:c}=a,l=Ahe(a,s,e),d={cardReady:!1,servesHttp:c,taskManager:new hhe,turnSupervisor:new fhe,jwksResolver:new nP(e.fetch?{fetch:e.fetch}:{}),clientDeps:l,publicAsks:new mhe(s.publicAsks,a.classRuntimeState)};if(c)a.endpoint({label:"A2A",url:"/a2a",priority:25}),a.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),a.logger.info("A2A interface registered",{domain:a.domain});else a.logger.info("A2A interface registered in tool-only mode",{domain:a.domain});return a.ready(()=>{d.cardReady=!0}),d}}),r=rVe(t,(o)=>{let s=Jo(o);eVe(s,Ahe(s,o.config,e),{networkAskTimeoutMs:o.config.networkAskTimeoutMs,turnTimeoutMs:o.config.turnTimeoutMs})}),i=ko(r,(o)=>{let{config:s,state:a}=o;if(!a.servesHttp)return[];let c=Jo(o),l=LHr(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=Kx(i,(o)=>{let{state:s}=o,{logger:a}=Jo(o);return{id:"a2a",start:async()=>{if(s.servesHttp)a.info("A2A mounted on shared webserver host");else a.info("A2A running without webserver routes")},stop:async()=>{await s.turnSupervisor.close(),a.info("A2A server stopped")}}});return Fn(n,(o)=>{let{config:s}=o,a=Jo(o),c=()=>WZe(Ahe(a,s,e));return[{...c(),handler:(l,d)=>c().handler(l,d)}]})}var jHr=whe(),nVe=jHr;function Rh(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function YA(e,t){return{registration:e,actionIds:t.map((r)=>r.name)}}var zHr=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function Fh(e){return zHr.format(new Date(e))}function fm(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function Oc(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function rW(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function c5(e){if(!e)return"This brain";let t="did:web:";if(!e.startsWith(t))return e;let r=e.slice(t.length);if(r.length===0)return e;return r.split(":").map(decodeURIComponent).join("/")}var UHr={"auth.a2a_peer_trust.granted":"Trusted an A2A peer","auth.a2a_peer_trust.revoked":"Revoked A2A peer trust","auth.access.reinitialized":"Reinitialized access from configuration","auth.external_peer.invited":"Invited a person from an external peer","auth.external_peer.linked":"Linked an external peer","auth.external_peer.unlinked":"Unlinked an external peer","auth.invitation.created":"Person invited","auth.invitation.cancelled":"Invitation cancelled","auth.invitation.manual_delivery_confirmed":"Manual delivery confirmed","auth.invitation.resent":"Invitation resent","auth.identity.attached":"Connected an identity","auth.identity.detached":"Disconnected an identity","auth.identity.delivery_bound":"Bound a verified delivery channel","auth.passkey.authentication_failed":"Recorded a failed passkey sign-in","auth.passkey.migrated":"Migrated a passkey","auth.passkey.registered":"Registered a passkey","auth.passkey.registration_failed":"Recorded a failed passkey registration","auth.passkey.registration_started":"Created a passkey setup link","auth.passkey.revoked":"Revoked a passkey","auth.setup_token.generated":"Generated a setup token","auth.user.created":"Created an account","auth.user.deleted":"Deleted a suspended account","auth.user.grants_revoked":"Revoked account grants","auth.user.role_updated":"Role changed","auth.user.status_updated":"Changed account status"};function nfe(e){let t=UHr[e];if(t)return t;let r=e.replaceAll(/[._-]+/g," ").trim();return r.length===0?e:po(r)}var ofe=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(Rh,u.number().int().min(0).max(1e5)).default(0),limit:u.preprocess(Rh,u.number().int().min(1).max(100)).default(25)}),oVe=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()}),qHr=u.strictObject({userId:u.string().min(1),displayName:u.string().min(1)}),$Hr=u.strictObject({query:ofe,events:u.array(oVe),selectedEvent:oVe.optional(),users:u.array(qHr),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 sVe(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 aVe(e,t){return e?t.get(e)??"Former Admin":"System"}function cVe(e,t){if(e.targetId)return t.get(e.targetId)??(e.targetUserId?t.get(e.targetUserId):void 0)??e.targetType??e.targetId;return e.targetType??"Access"}var ife=Po({id:"audit",label:"Audit",priority:90,permission:"admin",query:ofe,data:$Hr,actions:[],view:({data:e})=>{let t=new Map(e.users.map((o)=>[o.userId,o.displayName])),r=e.selectedEvent,n=[{type:"query",id:"audit-filters",...{controls:[{key:"actorUserId",label:"Actor",value:e.query.actorUserId,allLabel:"All actors",options:e.users.map((o)=>({value:o.userId,label:o.displayName}))},{key:"action",label:"Action",value:e.query.action,allLabel:"All actions",options:e.actions}],...e.total>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.total}}:{}}},{type:"detail",id:"audit-detail",queryKey:"selected",empty:"Select an event to inspect its audit record.",...r?{open:{forId:r.id,title:nfe(r.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:aVe(r.actorUserId,t)},{label:"Action",value:r.action},{label:"Target",value:cVe(r,t)},{label:"Occurred",value:Fh(r.createdAt)},{label:"Event ID",value:r.id},{label:"Action ID",value:r.action},...r.targetId?[{label:"Target ID",value:r.targetId}]:[],...r.actorUserId?[{label:"Actor ID",value:r.actorUserId}]:[]]}]}}:{},master:{type:"list",id:"audit-events",presentation:"standard",empty:"No audit events match these filters.",items:e.events.map((o)=>({id:o.id,title:nfe(o.action),description:`${aVe(o.actorUserId,t)} \u2192 ${cVe(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 lVe(e){let t=e.studio.source({definition:ife,bind:(r)=>ife.bind(r,{load:async({query:i})=>{let n=fm(e),o=i.get(ofe),[s,a]=await Promise.all([n.queryAuditEvents({...o.actorUserId?{actorUserId:o.actorUserId}:{},...o.action?{action:o.action}:{},...o.selected?{selectedId:o.selected}:{},offset:o.offset,limit:o.limit}),n.listUsers()]);return{query:o,events:s.events.map(sVe),...s.selectedEvent?{selectedEvent:sVe(s.selectedEvent)}:{},users:rW(a),actions:s.actions.map(({action:c,count:l})=>({value:c,label:nfe(c),count:l})).sort((c,l)=>c.label.localeCompare(l.label)),total:s.total}},actions:[]})});return YA(t,ife.actions)}var n0=u.strictObject({status:u.string()}),iW=u.strictObject({status:u.string(),setupUrl:u.url(),expiresAt:u.string()});function G9(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var nW=u.strictObject({type:u.string(),displayName:u.string(),subjectLabel:u.string(),deliveryModes:u.array(u.enum(["automatic","manual"]))});function oW(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function sW(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function aW(e,t){return{deliveryType:{label:"Delivery channel",control:"select",options:e.map((r)=>({value:r.type,label:r.displayName}))},deliverySubject:{label:"Delivery destination",labelBy:{field:"deliveryType",values:e.map((r)=>({value:r.type,label:r.subjectLabel}))},control:"text"},deliveryLabel:{label:"Delivery label (optional)",control:"text"},deliveryMode:{label:"Delivery mode",control:"select",options:t.map((r)=>({value:r,label:r==="automatic"?"Automatic":"Manual"}))}}}import{randomUUID as GHr}from"crypto";var uVe=new Set(["claimed","expired","cancelled"]),HHr=new Set(["claimed","cancelled"]),ufe=u.strictObject({state:u.enum(["pending","history"]).optional().default("pending"),selected:u.string().trim().min(1).max(200).optional(),offset:u.preprocess(Rh,u.number().int().min(0)).optional().default(0),limit:u.preprocess(Rh,u.number().int().min(1).max(100)).optional().default(25)}),hVe=u.strictObject({status:u.string(),setupUrl:u.url().nullable(),expiresAt:u.string().nullable()}),WHr=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"])}),fVe=u.strictObject({invitationId:u.string().min(1)}),ZHr=u.strictObject({invitationId:u.string().min(1),deliveryAttemptId:u.string().min(1)}),xVe=u.strictObject({invitationId:u.string(),state:u.string()}),cfe=Vr({name:"create-invitation",label:"Add a person",permission:"admin",input:WHr,output:hVe}),dfe=Vr({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:fVe,output:hVe}),pfe=Vr({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:fVe,output:xVe}),mfe=Vr({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:ZHr,output:xVe}),dVe=u.strictObject({id:u.string(),displayName:u.string(),role:u.string(),state:u.string(),destination:u.string(),updatedAt:u.number(),deliveryAttemptId:u.string().optional()}),VHr=u.strictObject({query:ufe,idempotencyKey:u.string(),channels:u.array(nW),invitations:u.array(dVe),selectedInvitation:dVe.optional(),selectedTotal:u.number().int().nonnegative(),pendingCount:u.number().int().nonnegative(),historyCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()});function lfe(e,t){let r=e.filter((i)=>i.id===t);if(r.length!==1||!r[0])throw Error(`Invitations tab composition requires block "${t}" exactly once`);return r[0]}function sfe(e,t){let r=lfe(e,t);switch(r.type){case"tabs":case"detail":case"columns":throw Error(`Invitations tab composition block "${t}" must be a region`);default:return r}}function gVe(e,t){let r=lfe(e,"invitation-totals");if(r.type!=="stats")throw Error('Invitations tab composition block "invitation-totals" must be stats');let i=e.some((a)=>a.id==="create-invitation-unavailable")?[sfe(e,"create-invitation-unavailable")]:[],n=lfe(e,"invitations");if(n.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=sfe(e,"invitation-delivery");if(o.type!=="card")throw Error("Invitations composition requires delivery capabilities");let s=t.flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[...i,sfe(e,"invitation-filters"),n,{...o,presentation:"disclosure",blocks:[...o.blocks,r,...s]}]}}var yVe=G9("Invitation setup");function KHr(e){if(HHr.has(e.state))return[];return[...e.deliveryAttemptId?[{action:mfe,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:dfe,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:yVe}]:[],...e.state!=="expired"?[{action:pfe,input:{invitationId:e.id}}]:[]]}function pVe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return po(e.state)}var afe=Po({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:ufe,data:VHr,actions:[cfe,dfe,pfe,mfe],badge:({data:e})=>e.pendingCount,view:({data:e})=>{let t=[{type:"stats",id:"invitation-totals",items:[{label:"Pending",value:e.pendingCount},{label:"History",value:e.historyCount},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"neutral"}]}],r=oW(e.channels),i;if(e.channels.length>0&&r.length>0)i={action:cfe,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:sW("Role"),...aW(e.channels,r)}},result:yVe};else t.push({type:"notice",id:"create-invitation-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});let n=e.selectedInvitation;return t.push({type:"query",id:"invitation-filters",controls:[{key:"state",label:"View",value:e.query.state,options:[{value:"pending",label:"Pending",count:e.pendingCount},{value:"history",label:"History",count:e.historyCount}]}],...e.selectedTotal>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.selectedTotal}}:{}},{type:"detail",id:"invitations",queryKey:"selected",empty:"Select an invitation to review its delivery.",master:{type:"list",id:"invitation-records",presentation:"standard",empty:e.query.state==="pending"?"No pending invitations.":"No invitation history yet.",items:e.invitations.map((o)=>({id:o.id,title:o.displayName,description:`${po(o.role)} \xB7 ${pVe(o)}`,metadata:[o.destination,`Updated ${new Date(o.updatedAt).toISOString()}`],links:[{label:"Review",target:{detail:{itemId:o.id}}}]}))},...n?{open:{forId:n.id,title:n.displayName,blocks:[{type:"key-values",id:"invitation-fields",items:[{label:"Role",value:po(n.role)},{label:"Delivery",value:pVe(n)},{label:"Destination",value:n.destination},{label:"Updated",value:Fh(n.updatedAt)}]},{type:"actions",id:"invitation-actions",items:KHr(n)}]}}:e.query.selected?{open:{forId:e.query.selected,title:"Invitation unavailable",blocks:[{type:"notice",tone:"neutral",text:"This invitation is no longer available. Return to the list to choose another."}]}}:{}},{type:"card",id:"invitation-delivery",label:"Delivery capabilities",blocks:[{type:"key-values",items:e.channels.map((o)=>({label:o.displayName,value:o.deliveryModes.map(po).join(" \xB7 ")}))}]}),{kicker:"Access administration",title:"Invitations",description:"Create, deliver, retry, and revoke passkey invitations without moving auth authority into Studio.",status:{label:`${e.pendingCount} pending`,tone:e.failureCount>0?"warn":"neutral"},...i?{primaryAction:i}:{},blocks:t}}});function mVe(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 bVe(e){let t=fm(e),r=new Map,i=e.studio.source({definition:afe,bind:(n)=>{let o=cfe.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}},Oc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return mVe(p)}),s=dfe.bind(n,async({input:l,caller:d})=>{let p=await t.resendInvitation(l.invitationId,Oc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return mVe(p)}),a=pfe.bind(n,async({input:l,caller:d})=>{let p=await t.cancelInvitation(l.invitationId,Oc(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=mfe.bind(n,async({input:l,caller:d})=>{let p=await t.confirmManualInvitationDelivery(l.invitationId,l.deliveryAttemptId,Oc(d));return r.delete(l.invitationId),{invitationId:p.id,state:p.state}});return afe.bind(n,{actions:[o,s,a,c],load:async({query:l})=>{let d=l.get(ufe),[p,m]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),h=m.filter((R)=>R.deliveryModes.length>0),f=p.filter((R)=>R.invitation!==void 0),g=f.filter((R)=>R.invitation&&!uVe.has(R.invitation.state)),y=f.filter((R)=>R.invitation&&uVe.has(R.invitation.state)),b=d.state==="pending"?g:y,A=f.flatMap((R)=>{let M=R.invitation;if(!M)return[];let k=R.identities.find((L)=>L.type!=="passkey")?.label??R.externalPeers[0]?.peerId??"Not recorded",N=r.get(M.id);return[{id:M.id,displayName:R.displayName,role:R.role,state:M.state,destination:k,updatedAt:M.claimedAt??M.cancelledAt??M.expiredAt??M.sentAt??M.updatedAt,...N?{deliveryAttemptId:N}:{}}]}),w=new Map(A.map((R)=>[R.id,R])),B=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:GHr(),channels:h.map((R)=>({type:R.type,displayName:R.displayName,subjectLabel:R.subjectLabel,deliveryModes:R.deliveryModes})),invitations:b.slice(d.offset,d.offset+d.limit).flatMap((R)=>{let M=R.invitation?w.get(R.invitation.id):void 0;return M?[M]:[]}),...B?{selectedInvitation:B}:{},selectedTotal:b.length,pendingCount:g.length,historyCount:y.length,failureCount:g.filter((R)=>R.invitation?.state==="failed").length}}})}});return YA(i,afe.actions)}var gfe=u.strictObject({peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional()}),YHr=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"])}),JHr=u.strictObject({peerId:u.string().trim().min(1).max(2000),userId:u.string().min(1)}),ffe=Vr({name:"invite-external-peer-person",label:"Invite peer person",permission:"admin",confirmation:{kind:"static",message:"Create this local member and bind them to the external peer?"},input:YHr,output:iW}),xfe=Vr({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:JHr,output:n0}),QHr=u.strictObject({query:gfe,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(nW)});function cW(e,t){let r=e.filter((n)=>n.id===t);if(r.length!==1)throw Error(`Peer tab composition requires block "${t}" exactly once`);let i=r[0];if(!i)throw Error(`Peer tab composition requires block "${t}" exactly once`);switch(i.type){case"tabs":case"detail":case"columns":throw Error(`Peer tab composition block "${t}" must be a region`);default:return i}}function yfe(e){let t=e.some((r)=>r.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[cW(e,"peers"),cW(e,"link-peer"),cW(e,t)],invitations:[cW(e,t)]}}var XHr=G9("Peer invitation setup"),hfe=Po({id:"peers",label:"Peers",priority:12,permission:"admin",query:gfe,data:QHr,actions:[ffe,xfe],view:({data:e})=>{let t=oW(e.channels),r=[{type:"stats",id:"peer-summary",items:[{label:"Linked peers",value:e.peers.length},{label:"Verified",value:e.peers.filter((i)=>i.verificationStatus==="verified").length},{label:"Available people",value:e.people.length}]}];if(e.channels.length>0&&t.length>0)r.push({type:"card",id:"invite-peer",label:"Peer-first invitation",blocks:[{type:"text",text:"Create a local member for a person known first through another brain, then issue their single-use passkey setup link."},{type:"action",action:ffe,input:{...e.query.peerId?{peerId:e.query.peerId}:{},...e.query.displayName?{displayName:e.query.displayName}:{}},form:{presentation:"disclosure",submitLabel:"Invite peer person",fields:{peerId:{label:"External peer ID",control:"text"},displayName:{label:"Display name",control:"text"},role:sW("Local role"),...aW(e.channels,t)}},result:XHr}]});else r.push({type:"notice",id:"invite-peer-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});return r.push({type:"card",id:"link-peer",label:"Link an existing person",blocks:[{type:"action",action:xfe,input:{...e.query.peerId?{peerId:e.query.peerId}:{}},form:{submitLabel:"Link peer",fields:{peerId:{label:"External peer ID",control:"text"},userId:{label:"Local person",control:"select",options:e.people.map((i)=>({value:i.userId,label:i.displayName}))}}}}]},{type:"table",id:"peers",empty:"No external peers linked.",columns:[{key:"peer",label:"Peer"},{key:"person",label:"Local person"},{key:"role",label:"Local role"},{key:"verification",label:"Verification"},{key:"linked",label:"Linked"}],rows:e.peers.map((i)=>({id:`${i.peerId}:${i.displayName}`,cells:{peer:c5(i.peerId),person:i.displayName,role:i.role,verification:i.verificationStatus,linked:Fh(i.createdAt)},compact:{title:c5(i.peerId),metadata:[i.displayName,po(i.role),Fh(i.createdAt)],badges:[{label:po(i.verificationStatus),tone:i.verificationStatus==="verified"?"good":"warn"}]}}))}),{kicker:"Network administration",title:"Peers",description:"List external brain relationships, invite peer-first people, and link known peers to existing members.",status:{label:`${e.peers.length} linked`},blocks:r}}});function EVe(e){let t=fm(e),r=e.studio.source({definition:hfe,bind:(i)=>{let n=ffe.bind(i,async({input:s,caller:a})=>{let c=await t.inviteExternalPeerPerson({peerId:s.peerId,displayName:s.displayName,role:s.role,delivery:{type:s.deliveryType,subject:s.deliverySubject,...s.deliveryLabel?{label:s.deliveryLabel}:{},mode:s.deliveryMode}},Oc(a));return{status:`Created ${c.user.displayName} and linked ${c.peer.peerId}. Deliver only through ${c.registration.delivery.label}.`,setupUrl:c.registration.setupUrl,expiresAt:new Date(c.registration.expiresAt*1000).toISOString()}}),o=xfe.bind(i,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},Oc(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((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 hfe.bind(i,{actions:[n,o],load:async({query:s})=>{let a=s.get(gfe),[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:rW(d),channels:l.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return YA(r,hfe.actions)}function bfe(e,t){let r=e.filter((i)=>i.id===t);if(r.length!==1||!r[0])throw Error(`People tab composition requires block "${t}" exactly once`);return r[0]}function vVe(e,t,r){let i=bfe(e,"people-summary");if(i.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let n=bfe(e,"people");if(n.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=bfe(e,"brain-anchor");if(o.type!=="card")throw Error('People tab composition block "brain-anchor" must be a card');let s=[t,...r].flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[n,{type:"card",id:"people-peers",label:"External brains",presentation:"disclosure",blocks:s},{...o,label:"Access reference",presentation:"disclosure",blocks:[i,...o.blocks]}]}}var Ife=u.strictObject({selected:u.string().trim().min(1).max(200).optional()}),Tfe=u.strictObject({userId:u.string().min(1)}),eWr=u.strictObject({userId:u.string().min(1),role:u.enum(["admin","trusted","public"])}),tWr=u.strictObject({userId:u.string().min(1),status:u.enum(["active","suspended"])});function rWr(e){return e.revokedAt===void 0&&e.type!=="passkey"}function iWr(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var nWr=u.strictObject({userId:u.string().min(1),credentialId:u.string().min(1)}),oWr=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()}),sWr=u.strictObject({userId:u.string().min(1),identityId:u.string().min(1)}),aWr=u.strictObject({userId:u.string().min(1),peerId:u.string().trim().min(1).max(2000)}),Afe=Vr({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:eWr,output:n0}),wfe=Vr({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:tWr,output:n0}),Sfe=Vr({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:Tfe,output:n0}),kfe=Vr({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:nWr,output:n0}),_fe=Vr({name:"start-person-passkey-registration",label:"Create setup link",permission:"admin",confirmation:{kind:"static",message:"Create a single-use passkey setup link for this person?"},input:Tfe,output:iW}),Bfe=Vr({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:Tfe,output:n0}),Pfe=Vr({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:oWr,output:n0}),Cfe=Vr({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:sWr,output:n0}),Dfe=Vr({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:aWr,output:n0}),cWr=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"])}))}),lWr=u.strictObject({query:Ife,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(cWr),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()}))}),uWr=G9("Passkey setup");function dWr(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function Efe(e){return{type:"notice",tone:"warn",text:e}}function pWr(e){return{type:"action",action:_fe,input:{userId:e},result:uWr}}function mWr(e,t){return{type:"action",action:Pfe,input:{userId:e},form:{submitLabel:"Attach channel",fields:{type:{label:"Channel type",control:"select",options:t.map((r)=>({value:r.type,label:r.displayName}))},subject:{label:"Channel subject",control:"text"},issuer:{label:"Issuer (optional)",control:"url"},label:{label:"Display label (optional)",control:"text"}}}}}function hWr(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var vfe=Po({id:"people",label:"People",priority:10,permission:"admin",query:Ife,data:lWr,actions:[Afe,wfe,Sfe,kfe,_fe,Bfe,Pfe,Cfe,Dfe],badge:({data:e})=>e.suspendedCount,view:({data:e})=>{let t=e.people.find((n)=>n.userId===e.query.selected),r=[];if(t){let n=t.role==="admin"&&t.status==="active"&&e.activeAdminCount<=1,o=t.isAnchor?"The protected brain identity must remain an active Admin.":t.status==="suspended"?"Reactivate this person before changing access.":n?"Add another active Admin before changing this role.":void 0,s=t.isAnchor?"The protected brain identity cannot be suspended.":n?"Add another active Admin before suspending this person.":void 0;if(r.push({type:"key-values",id:"person-summary",items:[{label:"Role",value:po(t.role)},{label:"Status",value:po(t.status)},{label:"Protected brain identity",value:t.isAnchor},{label:"Brain relationship",value:t.peers.length>0?"External peer + local member":"Hosted member"}]}),o)r.push({type:"notice",tone:"warn",text:o});else r.push({type:"card",id:"person-role",label:"Permission role",blocks:[{type:"action",action:Afe,input:{userId:t.userId,role:t.role},form:{submitLabel:"Change role",fields:{role:{label:"Role",control:"select",options:[{value:"admin",label:"Admin"},{value:"trusted",label:"Trusted"},{value:"public",label:"Public"}]}}}}]});r.push({type:"card",id:"person-access",label:"Access",blocks:[{type:"actions",items:[{action:wfe,input:{userId:t.userId,status:t.status==="suspended"?"active":"suspended"},capability:{id:t.status==="suspended"?"reactivate-person":"suspend-person",label:t.status==="suspended"?"Reactivate person":"Suspend person"},disabled:t.status==="active"&&s!==void 0},...t.status==="active"&&!t.isSelf?[{action:Bfe,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:Sfe,input:{userId:t.userId}}]:[]]},...t.isSelf?[dWr()]:[],...s&&t.status==="active"?[Efe(s)]:[]]}),r.push({type:"card",id:"person-sign-in",label:"Sign-in",blocks:[{type:"table",id:"person-passkeys",empty:"No passkeys registered.",columns:[{key:"kind",label:"Passkey"},{key:"created",label:"Added"}],rows:t.passkeys.map((a)=>({id:a.id,cells:{kind:a.kind,created:Fh(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${Fh(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:kfe,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[pWr(t.userId)]:[Efe("A verified channel is required for setup delivery.")]:[]]}),r.push({type:"card",id:"person-channels",label:"Linked identities",blocks:[{type:"table",id:"person-identities",empty:"No linked identity.",columns:[{key:"channel",label:"Channel"},{key:"identity",label:"Identity"},{key:"assurance",label:"Assurance"}],rows:t.identities.map((a)=>({id:a.id,cells:{channel:a.displayName,identity:a.label,assurance:a.verified?"Verified":"Asserted"},compact:{title:a.label,metadata:[a.displayName],badges:[{label:a.verified?"Verified":"Asserted",tone:a.verified?"good":"neutral"}]},actions:[{action:Cfe,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[mWr(t.userId,e.channelTypes)]:[Efe("No attachable channel type is configured.")]]}),r.push({type:"notice",tone:"neutral",text:"External peer links record provenance from another brain. They do not grant or change this person's local access."}),r.push({type:"list",id:"person-peers",empty:"No external peer linked; this person is hosted locally.",items:t.peers.map((a)=>({id:a.peerId,title:c5(a.peerId),description:`Vouched in by ${c5(a.peerId)} \xB7 ${a.peerId}`,metadata:[po(a.verificationStatus)],actions:[{action:Dfe,input:{userId:t.userId,peerId:a.peerId}}]}))})}let i=[{type:"stats",id:"people-summary",items:[{label:"Active members",value:e.activeCount},{label:"Active Admins",value:e.activeAdminCount},{label:"Suspended",value:e.suspendedCount,tone:e.suspendedCount>0?"warn":"neutral"}]},{type:"card",id:"brain-anchor",label:"Brain identity",blocks:[{type:"key-values",items:[{label:"Name",value:e.anchor.displayName},{label:"Kind",value:e.anchor.configuredKind},{label:"Ownership",value:e.anchor.kind},{label:"Administered by",value:e.anchor.administeredBy}]}]},{type:"detail",id:"people",queryKey:"selected",empty:"Select a person to inspect their access.",master:{type:"list",id:"people-roster",presentation:"standard",empty:"No people are available.",items:[...e.people].sort((n,o)=>Number(o.isSelf)-Number(n.isSelf)||Number(n.isAnchor)-Number(o.isAnchor)||n.displayName.localeCompare(o.displayName)).map((n)=>({id:n.userId,title:n.displayName,description:[po(n.role),po(n.status),...n.isSelf?["You"]:[],...n.isAnchor?["Protected brain identity"]:[]].join(" \xB7 "),metadata:[n.identities.length===0?"No linked identities":n.identities.length===1?"One linked identity":`${n.identities.length} linked identities`,...n.peers.length>0?[`Arrived via ${c5(n.peers[0]?.peerId)}`]:[]],...n.isSelf?{link:{detail:{itemId:n.userId}}}:{},links:[{label:n.isSelf?"Account \u2192":n.isAnchor?"View protection":"Manage person",target:n.isSelf?{launch:{target:"account-settings"}}:{detail:{itemId:n.userId}}}]}))},...t?{open:{forId:t.userId,title:t.displayName,blocks:r}}:{}}];return{kicker:"Access administration",title:"People",description:"Manage people\u2019s access to this brain, linked identities, and account recovery. Use Account for your own profile and sign-in settings.",status:{label:`${e.activeCount} active`,tone:e.suspendedCount>0?"warn":"neutral"},blocks:i}}});function lW(e,t){return e.find((r)=>r.userId===t)?.displayName??"person"}async function fWr(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function AVe(e){let t=fm(e),r=e.studio.source({definition:vfe,bind:(i)=>{let n=Afe.bind(i,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,Oc(f)),{status:`Role changed to ${po(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${lW(f,h.userId)}\u2019s role to ${po(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=wfe.bind(i,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,Oc(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${lW(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=Sfe.bind(i,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,Oc(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${lW(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=kfe.bind(i,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,Oc(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=_fe.bind(i,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,Oc(f));return{status:`Bound to ${g.delivery.label}. Deliver only through that confirmed private channel.`,setupUrl:g.setupUrl,expiresAt:new Date(g.expiresAt*1000).toISOString()}}),l=Bfe.bind(i,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,Oc(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${lW(f,h.userId)} out everywhere?`,revision:h.userId}}),d=Pfe.bind(i,async({input:h,caller:f})=>(await t.attachIdentity({userId:h.userId,type:h.type,subject:h.subject,...h.issuer?{issuer:h.issuer}:{},...h.label?{label:h.label}:{},verifiedAt:Date.now(),source:{kind:"admin"}},Oc(f)),{status:"Verified channel attached."})),p=Cfe.bind(i,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,Oc(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=Dfe.bind(i,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,Oc(f)),{status:"External peer unlinked from the local person."}),({input:h})=>({summary:`Unlink ${h.peerId}? Local access will not change.`,revision:`${h.peerId}:${h.userId}`}));return vfe.bind(i,{actions:[n,o,s,a,c,l,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(Ife),[y,b,A]=await Promise.all([fWr(t),t.listAdminUsers(),t.listInvitationChannels()]),w=b.filter((N)=>N.status!=="invited"),B=w.find((N)=>N.isAnchor)??w.find((N)=>N.role==="admin"&&N.status==="active"),R=y??hWr(B?.displayName??"Brain owner",w.filter((N)=>N.role==="admin"&&N.status==="active").length),M=w.filter((N)=>N.status==="active"),k=new Map(A.map((N)=>[N.type,N.displayName]));return{query:g,anchor:{kind:R.kind,configuredKind:R.configuredKind,displayName:R.displayName,administeredBy:R.administeredBy},people:w.flatMap((N)=>{if(N.status==="invited")return[];return[{userId:N.userId,displayName:N.displayName,role:N.role,status:N.status,isAnchor:N.isAnchor,isSelf:f?.actor.id===N.userId,...N.profileEntityId?{profileEntityId:N.profileEntityId}:{},passkeys:N.passkeys.map((L)=>({id:L.id,kind:iWr(L),createdAt:L.createdAt})),identities:N.identities.filter(rWr).map((L)=>({id:L.id,type:L.type,displayName:k.get(L.type)??po(L.type),label:L.label??"Connected identity",verified:L.verifiedAt!==void 0})),peers:N.externalPeers.map((L)=>({peerId:L.peerId,verificationStatus:L.verificationStatus}))}]}),activeCount:M.length,activeAdminCount:M.filter((N)=>N.role==="admin").length,suspendedCount:w.length-M.length,channelTypes:A.map((N)=>({type:N.type,displayName:N.displayName}))}}})}});return YA(r,vfe.actions)}var xWr=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(Rh,u.number().int().min(0).max(1e5)).optional(),limit:u.preprocess(Rh,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 gWr(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function yWr(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 bWr(e,t){if(!yWr(e))throw Error(`${t} tab returned invalid workspace data`);return e}function wVe(e,t){let r=[];for(let i of e){if(i.type==="tabs")throw Error(`${t} tab cannot contribute nested tabs`);r.push(i)}return r}function Rfe(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function yP(e,t,r,i){return bWr(await e.dataProvider(t,r,i),e.label)}async function EWr(e,t,r,i){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,r,i)}function vWr(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 SVe(e){return{suspended:e.filter((t)=>t.status==="suspended").length,pendingInvitations:e.filter((t)=>t.invitation!==void 0&&!["claimed","expired","cancelled"].includes(t.invitation.state)).length}}function AWr(e){return[...e.pendingInvitations>0?[{id:"invitations",title:`${e.pendingInvitations} ${e.pendingInvitations===1?"invitation":"invitations"} waiting`,detail:"Not yet accepted.",severity:"info",action:{label:"Review invitations",query:{tab:"invitations"}}}]:[],...e.suspended>0?[{id:"suspended",title:`${e.suspended} ${e.suspended===1?"person":"people"} suspended`,severity:"info",action:{label:"Review people",query:{tab:"people"}}}]:[]]}async function kVe(e){if(!e.studio.isAvailable())return;let t=AVe(e),r=bVe(e),i=EVe(e),n=lVe(e),o=vWr([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:q9,priority:10,permission:"admin",section:"brain",urlQuery:!0,aliases:[{id:"admin:people",query:{tab:"people"}},{id:"admin:invitations",query:{tab:"invitations"}},{id:"admin:peers",query:{tab:"people"}},{id:"admin:audit",query:{tab:"audit"}}],entityTypes:[],accessHandler:(d)=>s.accessHandler(d),dataProvider:async(d,p,m)=>{let h=xWr.parse(p??{}),f,g=Rfe("People"),y=Rfe("Invitations"),b=Rfe("Audit");if(h.tab==="people"){let[A,w]=await Promise.all([yP(s,d,{...h.selected?{selected:h.selected}:{}},m),yP(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),B=yfe(w.view.blocks);g=[...vVe(wVe(A.view.blocks,"People"),{type:"notice",id:"people-peer-note",tone:"neutral",title:"External brain relationships",text:"A peer link records how a locally administered person relates to another brain. It does not grant or change local access."},B.people).blocks]}else if(h.tab==="invitations"){let[A,w]=await Promise.all([yP(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...Hn({offset:h.offset,limit:h.limit})},m),yP(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),B=yfe(w.view.blocks),R=gVe(A.view.blocks,B.invitations);f=A.view.primaryAction,y=[...R.blocks]}else{let A=await yP(l,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...Hn({offset:h.offset,limit:h.limit})},m);b=wVe(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=gWr(d);if(!h)throw new br("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new br("not_found",{publicMessage:`Unknown Administration action: ${h}`});return EWr(f,d,p,m)},badgeProvider:async()=>{let d=SVe(await fm(e).listAdminUsers());return d.suspended+d.pendingInvitations},attentionProvider:async()=>AWr(SVe(await fm(e).listAdminUsers()))})}var wWr=259200000,SWr=u.strictObject({id:u.string(),displayName:u.string(),state:u.string(),reason:u.enum(["expiring","delivery-failed"]),expiresAt:u.number().optional()}),kWr=u.strictObject({invitations:u.array(SWr),expiringCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()}),BVe=ro({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:kWr,digest:({data:e})=>({items:[{label:"Expiring soon",value:String(e.expiringCount),...e.expiringCount>0?{tone:"warn"}:{}},{label:"Delivery failures",value:String(e.failureCount),...e.failureCount>0?{tone:"warn"}:{}}],attention:e.invitations.length}),view:({data:e})=>({blocks:[{type:"stats",items:[{label:"Expiring soon",value:e.expiringCount,tone:e.expiringCount>0?"warn":"good"},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"good"}]},{type:"list",id:"invitation-attention",empty:"No invitation setup links need attention.",items:e.invitations.map((t)=>({id:t.id,title:t.displayName,description:t.reason==="delivery-failed"?"Invitation delivery failed. Resend or cancel it.":"The single-use setup link expires soon.",metadata:[t.state,...t.expiresAt!==void 0?[`Expires ${Fh(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function BWr(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+wWr)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 CVe(e,t){t.throwIfAborted();let r=await fm(e).listAdminUsers();return t.throwIfAborted(),BWr(r,Date.now())}var CWr=u.strictObject({}),DWr=zt({id:"admin",config:CWr},{subscriptions:(e)=>{let t=bt(e);return t.registered(async()=>{await kVe(t)}),[]},dashboardWidgets:(e)=>{let t=bt(e);return[BVe.bind(e,({signal:r})=>CVe(t,r))]}}),Ffe=DWr;var Ki="agent",DVe="agent-network",IVe="agent-proximity",Qfe="agent-discovery:entities",TVe="agent-discovery:proximity-map",Xfe="proximity-map",e0e="agent-list",t0e="agent-detail",Nc="skill",_Ve=30,PVe=120;var dW="skill-derivation",RVe="skill-derivation",r0e="skill:skill-derivation",FVe="skills";var IWr=u.string().trim().min(1).max(PVe),i0e=u.array(IWr).max(_Ve),QA=u.object({name:u.string(),description:u.string(),tags:i0e,examples:u.array(u.string())}),CP=QA,XA=o0.extend({entityType:u.literal(Nc),metadata:CP});var pW=u.object({name:u.string(),description:u.string(),tags:i0e}),Mb=u.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),TWr=s5,s0=u.object({name:u.string(),kind:TWr,organization:u.string().optional(),brainName:u.string().describe("Name of the brain instance"),shownAs:u.string().min(1).optional().describe("The name this brain shows the agent under, in place of its own name"),url:u.string().url().describe("Brain endpoint URL"),repoDid:u.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:u.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:u.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:u.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:u.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:u.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:u.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:u.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:Mb,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"})}),DP=u.object({name:u.string(),shownAs:u.string().min(1).optional(),url:u.string().url(),status:Mb,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()}),On=o0.extend({entityType:u.literal(Ki),metadata:DP}),_Wr=jr.extend({entityType:u.literal(Ki),metadata:DP}),IP=_Wr.extend({frontmatter:s0,about:u.string(),skills:u.array(pW),notes:u.string()}),PWr=IP.extend({url:u.string().optional(),typeLabel:u.string().optional()}),RWr=IP.extend({url:u.string(),typeLabel:u.string()});var FWr=u.record(u.string(),u.unknown());function MWr(e){try{return Mn(e,FWr).content}catch{return e}}function n0e(e){return{name:e.name,...e.shownAs&&{shownAs:e.shownAs},url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:W9(e.url),...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter}}}function MVe(e){return Ws(Ki,e,s0)}function TP(e){return{content:e,metadata:n0e(MVe(e))}}function Z9(e){let t={name:e.name,kind:e.kind,...e.organization&&{organization:e.organization},brainName:e.brainName,...e.shownAs&&{shownAs:e.shownAs},url:e.url,...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter},status:Mb.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},r=tfe({about:e.about,skills:e.skills,notes:e.notes});return dn(r,t)}function bm(e,t={}){return Z9({...e.frontmatter,...e.body,...t})}function _P(e){return gP(MWr(e))}function Zs(e){return{frontmatter:MVe(e.content),body:_P(e.content)}}function o0e(e){return dn("",e)}function NWr(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function OVe(e,t,r={}){let i=r.minCount??1,n=r.topN??12,o=new Map,s=(a)=>{for(let c of mc(a))o.set(c,(o.get(c)??0)+1)};for(let a of e)s(a.metadata.tags);for(let a of t){let c=_P(a.content);s(c.skills.flatMap((l)=>l.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=i).sort(NWr).slice(0,n)}function NVe(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 XZe(a,"Agent call failed");let c=vhe.safeParse(a.data);if(!c.success)throw new br("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(VH,async({request:{userPermissionLevel:i}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:ai(i)}}})).filter((s)=>s.metadata.status==="approved").map((s)=>{let a=s.metadata.name;return{id:s.id,label:typeof a==="string"&&a.length>0?a:s.id}}).sort((s,a)=>s.label.localeCompare(a.label))}})}var tVe={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.819",dependencies:{"@a2a-js/sdk":"^0.3.13","@brains/contracts":"workspace:*","@brains/http-signatures":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*",hono:"^4.13.13"},devDependencies:{"@brains/auth-service":"workspace:*","@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/templates":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};function JH(e,t){let r=new Headers(e.headers);for(let[i,n]of Object.entries(t))r.set(i,n);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}var RHr={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Signature, Signature-Input, Content-Digest, Date","X-Content-Type-Options":"nosniff"},nd=(e)=>JH(e,RHr);function FHr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(Ph(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();await mZe(i,n.privateJwk,n.keyId)}}function MHr(e){let t=e.auth();if(!t)return;let r=t.getIssuer();if(Ph(r)||new URL(r).protocol!=="https:")return;return async(i)=>{let n=await t.getA2ASigningKey();return{keyId:n.keyId,signature:fZe(i,n.privateJwk)}}}function Ahe(e,t,r){let i=FHr(e);return{...i?{requestSigner:i}:{},...r.fetch?{fetch:r.fetch}:{},requestTimeoutMs:t.requestTimeoutMs,streamIdleTimeoutMs:t.streamIdleTimeoutMs,maxNetworkAttempts:t.maxNetworkAttempts,entityService:e.entityReads,isContactApproved:r.isContactApproved??((n)=>e.classRuntimeState.scoped({namespace:QH,schema:XH}).has(n.trim().toLowerCase()))}}async function OHr(e,t,r){if(!r.cardReady)return;return DZe({character:e.identity.get(),profile:e.identity.getProfile(),version:tVe.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 NHr(e,t,r,i){let n=new URL(r.url),o=new URL(`${n.pathname}${n.search}`,Yx(r)),s=await hZe({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 LHr(e,t,r){let i=new iVe,n=e.agent;return i.get("/.well-known/agent-card.json",async(o)=>{let s=await OHr(e,t,r);if(!s)return nd(o.json({error:"Agent Card not ready"},503));return nd(o.json(s))}),i.get("/.well-known/agent-directory.json",async(o)=>{let s=await IZe(e.entityReads);return nd(o.json(s))}),i.get("/a2a",(o)=>nd(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),i.options("/a2a",()=>nd(new Response(null,{status:204}))),i.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return nd(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await NHr(e,r,o.req.raw,s)}catch{return nd(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return nd(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let l=PZe.safeParse(c);if(!l.success)return nd(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(iZe(o.req.raw.headers)){let p=l.data.method==="message/send"?nZe(l.data.params):void 0,m=p?.op==="list"?await aZe(e.entityReads,a.permissionLevel):await sZe(e.entityReads,a.permissionLevel,p,MHr(e));if(!m)return nd(o.json({error:"Not found"},404));return nd(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=LZe.safeParse(l.data.params??{});if(!p.success)return nd(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:l.data.id}));let m=jZe(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 nd(o.json(m));return nd(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await MZe(l.data,{taskManager:r.taskManager,turnSupervisor:r.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:r.publicAsks});return nd(o.json(d))}),i}function whe(e={}){let t=_h({id:"a2a",config:BZe,setup:(o)=>{let{config:s}=o,a=Jo(o),{servesHttp:c}=a,l=Ahe(a,s,e),d={cardReady:!1,servesHttp:c,taskManager:new hhe,turnSupervisor:new fhe,jwksResolver:new nP(e.fetch?{fetch:e.fetch}:{}),clientDeps:l,publicAsks:new mhe(s.publicAsks,a.classRuntimeState)};if(c)a.endpoint({label:"A2A",url:"/a2a",priority:25}),a.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),a.logger.info("A2A interface registered",{domain:a.domain});else a.logger.info("A2A interface registered in tool-only mode",{domain:a.domain});return a.ready(()=>{d.cardReady=!0}),d}}),r=rVe(t,(o)=>{let s=Jo(o);eVe(s,Ahe(s,o.config,e),{networkAskTimeoutMs:o.config.networkAskTimeoutMs,turnTimeoutMs:o.config.turnTimeoutMs})}),i=ko(r,(o)=>{let{config:s,state:a}=o;if(!a.servesHttp)return[];let c=Jo(o),l=LHr(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=Kx(i,(o)=>{let{state:s}=o,{logger:a}=Jo(o);return{id:"a2a",start:async()=>{if(s.servesHttp)a.info("A2A mounted on shared webserver host");else a.info("A2A running without webserver routes")},stop:async()=>{await s.turnSupervisor.close(),a.info("A2A server stopped")}}});return Fn(n,(o)=>{let{config:s}=o,a=Jo(o),c=()=>WZe(Ahe(a,s,e));return[{...c(),handler:(l,d)=>c().handler(l,d)}]})}var jHr=whe(),nVe=jHr;function Rh(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function YA(e,t){return{registration:e,actionIds:t.map((r)=>r.name)}}var zHr=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function Fh(e){return zHr.format(new Date(e))}function fm(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function Oc(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function rW(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function c5(e){if(!e)return"This brain";let t="did:web:";if(!e.startsWith(t))return e;let r=e.slice(t.length);if(r.length===0)return e;return r.split(":").map(decodeURIComponent).join("/")}var UHr={"auth.a2a_peer_trust.granted":"Trusted an A2A peer","auth.a2a_peer_trust.revoked":"Revoked A2A peer trust","auth.access.reinitialized":"Reinitialized access from configuration","auth.external_peer.invited":"Invited a person from an external peer","auth.external_peer.linked":"Linked an external peer","auth.external_peer.unlinked":"Unlinked an external peer","auth.invitation.created":"Person invited","auth.invitation.cancelled":"Invitation cancelled","auth.invitation.manual_delivery_confirmed":"Manual delivery confirmed","auth.invitation.resent":"Invitation resent","auth.identity.attached":"Connected an identity","auth.identity.detached":"Disconnected an identity","auth.identity.delivery_bound":"Bound a verified delivery channel","auth.passkey.authentication_failed":"Recorded a failed passkey sign-in","auth.passkey.migrated":"Migrated a passkey","auth.passkey.registered":"Registered a passkey","auth.passkey.registration_failed":"Recorded a failed passkey registration","auth.passkey.registration_started":"Created a passkey setup link","auth.passkey.revoked":"Revoked a passkey","auth.setup_token.generated":"Generated a setup token","auth.user.created":"Created an account","auth.user.deleted":"Deleted a suspended account","auth.user.grants_revoked":"Revoked account grants","auth.user.role_updated":"Role changed","auth.user.status_updated":"Changed account status"};function nfe(e){let t=UHr[e];if(t)return t;let r=e.replaceAll(/[._-]+/g," ").trim();return r.length===0?e:po(r)}var ofe=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(Rh,u.number().int().min(0).max(1e5)).default(0),limit:u.preprocess(Rh,u.number().int().min(1).max(100)).default(25)}),oVe=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()}),qHr=u.strictObject({userId:u.string().min(1),displayName:u.string().min(1)}),$Hr=u.strictObject({query:ofe,events:u.array(oVe),selectedEvent:oVe.optional(),users:u.array(qHr),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 sVe(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 aVe(e,t){return e?t.get(e)??"Former Admin":"System"}function cVe(e,t){if(e.targetId)return t.get(e.targetId)??(e.targetUserId?t.get(e.targetUserId):void 0)??e.targetType??e.targetId;return e.targetType??"Access"}var ife=Po({id:"audit",label:"Audit",priority:90,permission:"admin",query:ofe,data:$Hr,actions:[],view:({data:e})=>{let t=new Map(e.users.map((o)=>[o.userId,o.displayName])),r=e.selectedEvent,n=[{type:"query",id:"audit-filters",...{controls:[{key:"actorUserId",label:"Actor",value:e.query.actorUserId,allLabel:"All actors",options:e.users.map((o)=>({value:o.userId,label:o.displayName}))},{key:"action",label:"Action",value:e.query.action,allLabel:"All actions",options:e.actions}],...e.total>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.total}}:{}}},{type:"detail",id:"audit-detail",queryKey:"selected",empty:"Select an event to inspect its audit record.",...r?{open:{forId:r.id,title:nfe(r.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:aVe(r.actorUserId,t)},{label:"Action",value:r.action},{label:"Target",value:cVe(r,t)},{label:"Occurred",value:Fh(r.createdAt)},{label:"Event ID",value:r.id},{label:"Action ID",value:r.action},...r.targetId?[{label:"Target ID",value:r.targetId}]:[],...r.actorUserId?[{label:"Actor ID",value:r.actorUserId}]:[]]}]}}:{},master:{type:"list",id:"audit-events",presentation:"standard",empty:"No audit events match these filters.",items:e.events.map((o)=>({id:o.id,title:nfe(o.action),description:`${aVe(o.actorUserId,t)} \u2192 ${cVe(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 lVe(e){let t=e.studio.source({definition:ife,bind:(r)=>ife.bind(r,{load:async({query:i})=>{let n=fm(e),o=i.get(ofe),[s,a]=await Promise.all([n.queryAuditEvents({...o.actorUserId?{actorUserId:o.actorUserId}:{},...o.action?{action:o.action}:{},...o.selected?{selectedId:o.selected}:{},offset:o.offset,limit:o.limit}),n.listUsers()]);return{query:o,events:s.events.map(sVe),...s.selectedEvent?{selectedEvent:sVe(s.selectedEvent)}:{},users:rW(a),actions:s.actions.map(({action:c,count:l})=>({value:c,label:nfe(c),count:l})).sort((c,l)=>c.label.localeCompare(l.label)),total:s.total}},actions:[]})});return YA(t,ife.actions)}var n0=u.strictObject({status:u.string()}),iW=u.strictObject({status:u.string(),setupUrl:u.url(),expiresAt:u.string()});function G9(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var nW=u.strictObject({type:u.string(),displayName:u.string(),subjectLabel:u.string(),deliveryModes:u.array(u.enum(["automatic","manual"]))});function oW(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function sW(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function aW(e,t){return{deliveryType:{label:"Delivery channel",control:"select",options:e.map((r)=>({value:r.type,label:r.displayName}))},deliverySubject:{label:"Delivery destination",labelBy:{field:"deliveryType",values:e.map((r)=>({value:r.type,label:r.subjectLabel}))},control:"text"},deliveryLabel:{label:"Delivery label (optional)",control:"text"},deliveryMode:{label:"Delivery mode",control:"select",options:t.map((r)=>({value:r,label:r==="automatic"?"Automatic":"Manual"}))}}}import{randomUUID as GHr}from"crypto";var uVe=new Set(["claimed","expired","cancelled"]),HHr=new Set(["claimed","cancelled"]),ufe=u.strictObject({state:u.enum(["pending","history"]).optional().default("pending"),selected:u.string().trim().min(1).max(200).optional(),offset:u.preprocess(Rh,u.number().int().min(0)).optional().default(0),limit:u.preprocess(Rh,u.number().int().min(1).max(100)).optional().default(25)}),hVe=u.strictObject({status:u.string(),setupUrl:u.url().nullable(),expiresAt:u.string().nullable()}),WHr=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"])}),fVe=u.strictObject({invitationId:u.string().min(1)}),ZHr=u.strictObject({invitationId:u.string().min(1),deliveryAttemptId:u.string().min(1)}),xVe=u.strictObject({invitationId:u.string(),state:u.string()}),cfe=Vr({name:"create-invitation",label:"Add a person",permission:"admin",input:WHr,output:hVe}),dfe=Vr({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:fVe,output:hVe}),pfe=Vr({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:fVe,output:xVe}),mfe=Vr({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:ZHr,output:xVe}),dVe=u.strictObject({id:u.string(),displayName:u.string(),role:u.string(),state:u.string(),destination:u.string(),updatedAt:u.number(),deliveryAttemptId:u.string().optional()}),VHr=u.strictObject({query:ufe,idempotencyKey:u.string(),channels:u.array(nW),invitations:u.array(dVe),selectedInvitation:dVe.optional(),selectedTotal:u.number().int().nonnegative(),pendingCount:u.number().int().nonnegative(),historyCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()});function lfe(e,t){let r=e.filter((i)=>i.id===t);if(r.length!==1||!r[0])throw Error(`Invitations tab composition requires block "${t}" exactly once`);return r[0]}function sfe(e,t){let r=lfe(e,t);switch(r.type){case"tabs":case"detail":case"columns":throw Error(`Invitations tab composition block "${t}" must be a region`);default:return r}}function gVe(e,t){let r=lfe(e,"invitation-totals");if(r.type!=="stats")throw Error('Invitations tab composition block "invitation-totals" must be stats');let i=e.some((a)=>a.id==="create-invitation-unavailable")?[sfe(e,"create-invitation-unavailable")]:[],n=lfe(e,"invitations");if(n.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=sfe(e,"invitation-delivery");if(o.type!=="card")throw Error("Invitations composition requires delivery capabilities");let s=t.flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[...i,sfe(e,"invitation-filters"),n,{...o,presentation:"disclosure",blocks:[...o.blocks,r,...s]}]}}var yVe=G9("Invitation setup");function KHr(e){if(HHr.has(e.state))return[];return[...e.deliveryAttemptId?[{action:mfe,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:dfe,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:yVe}]:[],...e.state!=="expired"?[{action:pfe,input:{invitationId:e.id}}]:[]]}function pVe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return po(e.state)}var afe=Po({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:ufe,data:VHr,actions:[cfe,dfe,pfe,mfe],badge:({data:e})=>e.pendingCount,view:({data:e})=>{let t=[{type:"stats",id:"invitation-totals",items:[{label:"Pending",value:e.pendingCount},{label:"History",value:e.historyCount},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"neutral"}]}],r=oW(e.channels),i;if(e.channels.length>0&&r.length>0)i={action:cfe,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:sW("Role"),...aW(e.channels,r)}},result:yVe};else t.push({type:"notice",id:"create-invitation-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});let n=e.selectedInvitation;return t.push({type:"query",id:"invitation-filters",controls:[{key:"state",label:"View",value:e.query.state,options:[{value:"pending",label:"Pending",count:e.pendingCount},{value:"history",label:"History",count:e.historyCount}]}],...e.selectedTotal>e.query.limit||e.query.offset>0?{pagination:{offset:e.query.offset,limit:e.query.limit,total:e.selectedTotal}}:{}},{type:"detail",id:"invitations",queryKey:"selected",empty:"Select an invitation to review its delivery.",master:{type:"list",id:"invitation-records",presentation:"standard",empty:e.query.state==="pending"?"No pending invitations.":"No invitation history yet.",items:e.invitations.map((o)=>({id:o.id,title:o.displayName,description:`${po(o.role)} \xB7 ${pVe(o)}`,metadata:[o.destination,`Updated ${new Date(o.updatedAt).toISOString()}`],links:[{label:"Review",target:{detail:{itemId:o.id}}}]}))},...n?{open:{forId:n.id,title:n.displayName,blocks:[{type:"key-values",id:"invitation-fields",items:[{label:"Role",value:po(n.role)},{label:"Delivery",value:pVe(n)},{label:"Destination",value:n.destination},{label:"Updated",value:Fh(n.updatedAt)}]},{type:"actions",id:"invitation-actions",items:KHr(n)}]}}:e.query.selected?{open:{forId:e.query.selected,title:"Invitation unavailable",blocks:[{type:"notice",tone:"neutral",text:"This invitation is no longer available. Return to the list to choose another."}]}}:{}},{type:"card",id:"invitation-delivery",label:"Delivery capabilities",blocks:[{type:"key-values",items:e.channels.map((o)=>({label:o.displayName,value:o.deliveryModes.map(po).join(" \xB7 ")}))}]}),{kicker:"Access administration",title:"Invitations",description:"Create, deliver, retry, and revoke passkey invitations without moving auth authority into Studio.",status:{label:`${e.pendingCount} pending`,tone:e.failureCount>0?"warn":"neutral"},...i?{primaryAction:i}:{},blocks:t}}});function mVe(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 bVe(e){let t=fm(e),r=new Map,i=e.studio.source({definition:afe,bind:(n)=>{let o=cfe.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}},Oc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return mVe(p)}),s=dfe.bind(n,async({input:l,caller:d})=>{let p=await t.resendInvitation(l.invitationId,Oc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)r.set(p.invitation.id,p.registration.deliveryAttemptId);return mVe(p)}),a=pfe.bind(n,async({input:l,caller:d})=>{let p=await t.cancelInvitation(l.invitationId,Oc(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=mfe.bind(n,async({input:l,caller:d})=>{let p=await t.confirmManualInvitationDelivery(l.invitationId,l.deliveryAttemptId,Oc(d));return r.delete(l.invitationId),{invitationId:p.id,state:p.state}});return afe.bind(n,{actions:[o,s,a,c],load:async({query:l})=>{let d=l.get(ufe),[p,m]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),h=m.filter((R)=>R.deliveryModes.length>0),f=p.filter((R)=>R.invitation!==void 0),g=f.filter((R)=>R.invitation&&!uVe.has(R.invitation.state)),y=f.filter((R)=>R.invitation&&uVe.has(R.invitation.state)),b=d.state==="pending"?g:y,A=f.flatMap((R)=>{let M=R.invitation;if(!M)return[];let k=R.identities.find((L)=>L.type!=="passkey")?.label??R.externalPeers[0]?.peerId??"Not recorded",N=r.get(M.id);return[{id:M.id,displayName:R.displayName,role:R.role,state:M.state,destination:k,updatedAt:M.claimedAt??M.cancelledAt??M.expiredAt??M.sentAt??M.updatedAt,...N?{deliveryAttemptId:N}:{}}]}),w=new Map(A.map((R)=>[R.id,R])),B=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:GHr(),channels:h.map((R)=>({type:R.type,displayName:R.displayName,subjectLabel:R.subjectLabel,deliveryModes:R.deliveryModes})),invitations:b.slice(d.offset,d.offset+d.limit).flatMap((R)=>{let M=R.invitation?w.get(R.invitation.id):void 0;return M?[M]:[]}),...B?{selectedInvitation:B}:{},selectedTotal:b.length,pendingCount:g.length,historyCount:y.length,failureCount:g.filter((R)=>R.invitation?.state==="failed").length}}})}});return YA(i,afe.actions)}var gfe=u.strictObject({peerId:u.string().trim().max(2000).optional(),displayName:u.string().trim().max(200).optional()}),YHr=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"])}),JHr=u.strictObject({peerId:u.string().trim().min(1).max(2000),userId:u.string().min(1)}),ffe=Vr({name:"invite-external-peer-person",label:"Invite peer person",permission:"admin",confirmation:{kind:"static",message:"Create this local member and bind them to the external peer?"},input:YHr,output:iW}),xfe=Vr({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:JHr,output:n0}),QHr=u.strictObject({query:gfe,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(nW)});function cW(e,t){let r=e.filter((n)=>n.id===t);if(r.length!==1)throw Error(`Peer tab composition requires block "${t}" exactly once`);let i=r[0];if(!i)throw Error(`Peer tab composition requires block "${t}" exactly once`);switch(i.type){case"tabs":case"detail":case"columns":throw Error(`Peer tab composition block "${t}" must be a region`);default:return i}}function yfe(e){let t=e.some((r)=>r.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[cW(e,"peers"),cW(e,"link-peer"),cW(e,t)],invitations:[cW(e,t)]}}var XHr=G9("Peer invitation setup"),hfe=Po({id:"peers",label:"Peers",priority:12,permission:"admin",query:gfe,data:QHr,actions:[ffe,xfe],view:({data:e})=>{let t=oW(e.channels),r=[{type:"stats",id:"peer-summary",items:[{label:"Linked peers",value:e.peers.length},{label:"Verified",value:e.peers.filter((i)=>i.verificationStatus==="verified").length},{label:"Available people",value:e.people.length}]}];if(e.channels.length>0&&t.length>0)r.push({type:"card",id:"invite-peer",label:"Peer-first invitation",blocks:[{type:"text",text:"Create a local member for a person known first through another brain, then issue their single-use passkey setup link."},{type:"action",action:ffe,input:{...e.query.peerId?{peerId:e.query.peerId}:{},...e.query.displayName?{displayName:e.query.displayName}:{}},form:{presentation:"disclosure",submitLabel:"Invite peer person",fields:{peerId:{label:"External peer ID",control:"text"},displayName:{label:"Display name",control:"text"},role:sW("Local role"),...aW(e.channels,t)}},result:XHr}]});else r.push({type:"notice",id:"invite-peer-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});return r.push({type:"card",id:"link-peer",label:"Link an existing person",blocks:[{type:"action",action:xfe,input:{...e.query.peerId?{peerId:e.query.peerId}:{}},form:{submitLabel:"Link peer",fields:{peerId:{label:"External peer ID",control:"text"},userId:{label:"Local person",control:"select",options:e.people.map((i)=>({value:i.userId,label:i.displayName}))}}}}]},{type:"table",id:"peers",empty:"No external peers linked.",columns:[{key:"peer",label:"Peer"},{key:"person",label:"Local person"},{key:"role",label:"Local role"},{key:"verification",label:"Verification"},{key:"linked",label:"Linked"}],rows:e.peers.map((i)=>({id:`${i.peerId}:${i.displayName}`,cells:{peer:c5(i.peerId),person:i.displayName,role:i.role,verification:i.verificationStatus,linked:Fh(i.createdAt)},compact:{title:c5(i.peerId),metadata:[i.displayName,po(i.role),Fh(i.createdAt)],badges:[{label:po(i.verificationStatus),tone:i.verificationStatus==="verified"?"good":"warn"}]}}))}),{kicker:"Network administration",title:"Peers",description:"List external brain relationships, invite peer-first people, and link known peers to existing members.",status:{label:`${e.peers.length} linked`},blocks:r}}});function EVe(e){let t=fm(e),r=e.studio.source({definition:hfe,bind:(i)=>{let n=ffe.bind(i,async({input:s,caller:a})=>{let c=await t.inviteExternalPeerPerson({peerId:s.peerId,displayName:s.displayName,role:s.role,delivery:{type:s.deliveryType,subject:s.deliverySubject,...s.deliveryLabel?{label:s.deliveryLabel}:{},mode:s.deliveryMode}},Oc(a));return{status:`Created ${c.user.displayName} and linked ${c.peer.peerId}. Deliver only through ${c.registration.delivery.label}.`,setupUrl:c.registration.setupUrl,expiresAt:new Date(c.registration.expiresAt*1000).toISOString()}}),o=xfe.bind(i,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},Oc(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((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 hfe.bind(i,{actions:[n,o],load:async({query:s})=>{let a=s.get(gfe),[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:rW(d),channels:l.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return YA(r,hfe.actions)}function bfe(e,t){let r=e.filter((i)=>i.id===t);if(r.length!==1||!r[0])throw Error(`People tab composition requires block "${t}" exactly once`);return r[0]}function vVe(e,t,r){let i=bfe(e,"people-summary");if(i.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let n=bfe(e,"people");if(n.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=bfe(e,"brain-anchor");if(o.type!=="card")throw Error('People tab composition block "brain-anchor" must be a card');let s=[t,...r].flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[n,{type:"card",id:"people-peers",label:"External brains",presentation:"disclosure",blocks:s},{...o,label:"Access reference",presentation:"disclosure",blocks:[i,...o.blocks]}]}}var Ife=u.strictObject({selected:u.string().trim().min(1).max(200).optional()}),Tfe=u.strictObject({userId:u.string().min(1)}),eWr=u.strictObject({userId:u.string().min(1),role:u.enum(["admin","trusted","public"])}),tWr=u.strictObject({userId:u.string().min(1),status:u.enum(["active","suspended"])});function rWr(e){return e.revokedAt===void 0&&e.type!=="passkey"}function iWr(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var nWr=u.strictObject({userId:u.string().min(1),credentialId:u.string().min(1)}),oWr=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()}),sWr=u.strictObject({userId:u.string().min(1),identityId:u.string().min(1)}),aWr=u.strictObject({userId:u.string().min(1),peerId:u.string().trim().min(1).max(2000)}),Afe=Vr({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:eWr,output:n0}),wfe=Vr({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:tWr,output:n0}),Sfe=Vr({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:Tfe,output:n0}),kfe=Vr({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:nWr,output:n0}),_fe=Vr({name:"start-person-passkey-registration",label:"Create setup link",permission:"admin",confirmation:{kind:"static",message:"Create a single-use passkey setup link for this person?"},input:Tfe,output:iW}),Bfe=Vr({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:Tfe,output:n0}),Pfe=Vr({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:oWr,output:n0}),Cfe=Vr({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:sWr,output:n0}),Dfe=Vr({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:aWr,output:n0}),cWr=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"])}))}),lWr=u.strictObject({query:Ife,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(cWr),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()}))}),uWr=G9("Passkey setup");function dWr(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function Efe(e){return{type:"notice",tone:"warn",text:e}}function pWr(e){return{type:"action",action:_fe,input:{userId:e},result:uWr}}function mWr(e,t){return{type:"action",action:Pfe,input:{userId:e},form:{submitLabel:"Attach channel",fields:{type:{label:"Channel type",control:"select",options:t.map((r)=>({value:r.type,label:r.displayName}))},subject:{label:"Channel subject",control:"text"},issuer:{label:"Issuer (optional)",control:"url"},label:{label:"Display label (optional)",control:"text"}}}}}function hWr(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var vfe=Po({id:"people",label:"People",priority:10,permission:"admin",query:Ife,data:lWr,actions:[Afe,wfe,Sfe,kfe,_fe,Bfe,Pfe,Cfe,Dfe],badge:({data:e})=>e.suspendedCount,view:({data:e})=>{let t=e.people.find((n)=>n.userId===e.query.selected),r=[];if(t){let n=t.role==="admin"&&t.status==="active"&&e.activeAdminCount<=1,o=t.isAnchor?"The protected brain identity must remain an active Admin.":t.status==="suspended"?"Reactivate this person before changing access.":n?"Add another active Admin before changing this role.":void 0,s=t.isAnchor?"The protected brain identity cannot be suspended.":n?"Add another active Admin before suspending this person.":void 0;if(r.push({type:"key-values",id:"person-summary",items:[{label:"Role",value:po(t.role)},{label:"Status",value:po(t.status)},{label:"Protected brain identity",value:t.isAnchor},{label:"Brain relationship",value:t.peers.length>0?"External peer + local member":"Hosted member"}]}),o)r.push({type:"notice",tone:"warn",text:o});else r.push({type:"card",id:"person-role",label:"Permission role",blocks:[{type:"action",action:Afe,input:{userId:t.userId,role:t.role},form:{submitLabel:"Change role",fields:{role:{label:"Role",control:"select",options:[{value:"admin",label:"Admin"},{value:"trusted",label:"Trusted"},{value:"public",label:"Public"}]}}}}]});r.push({type:"card",id:"person-access",label:"Access",blocks:[{type:"actions",items:[{action:wfe,input:{userId:t.userId,status:t.status==="suspended"?"active":"suspended"},capability:{id:t.status==="suspended"?"reactivate-person":"suspend-person",label:t.status==="suspended"?"Reactivate person":"Suspend person"},disabled:t.status==="active"&&s!==void 0},...t.status==="active"&&!t.isSelf?[{action:Bfe,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:Sfe,input:{userId:t.userId}}]:[]]},...t.isSelf?[dWr()]:[],...s&&t.status==="active"?[Efe(s)]:[]]}),r.push({type:"card",id:"person-sign-in",label:"Sign-in",blocks:[{type:"table",id:"person-passkeys",empty:"No passkeys registered.",columns:[{key:"kind",label:"Passkey"},{key:"created",label:"Added"}],rows:t.passkeys.map((a)=>({id:a.id,cells:{kind:a.kind,created:Fh(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${Fh(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:kfe,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[pWr(t.userId)]:[Efe("A verified channel is required for setup delivery.")]:[]]}),r.push({type:"card",id:"person-channels",label:"Linked identities",blocks:[{type:"table",id:"person-identities",empty:"No linked identity.",columns:[{key:"channel",label:"Channel"},{key:"identity",label:"Identity"},{key:"assurance",label:"Assurance"}],rows:t.identities.map((a)=>({id:a.id,cells:{channel:a.displayName,identity:a.label,assurance:a.verified?"Verified":"Asserted"},compact:{title:a.label,metadata:[a.displayName],badges:[{label:a.verified?"Verified":"Asserted",tone:a.verified?"good":"neutral"}]},actions:[{action:Cfe,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[mWr(t.userId,e.channelTypes)]:[Efe("No attachable channel type is configured.")]]}),r.push({type:"notice",tone:"neutral",text:"External peer links record provenance from another brain. They do not grant or change this person's local access."}),r.push({type:"list",id:"person-peers",empty:"No external peer linked; this person is hosted locally.",items:t.peers.map((a)=>({id:a.peerId,title:c5(a.peerId),description:`Vouched in by ${c5(a.peerId)} \xB7 ${a.peerId}`,metadata:[po(a.verificationStatus)],actions:[{action:Dfe,input:{userId:t.userId,peerId:a.peerId}}]}))})}let i=[{type:"stats",id:"people-summary",items:[{label:"Active members",value:e.activeCount},{label:"Active Admins",value:e.activeAdminCount},{label:"Suspended",value:e.suspendedCount,tone:e.suspendedCount>0?"warn":"neutral"}]},{type:"card",id:"brain-anchor",label:"Brain identity",blocks:[{type:"key-values",items:[{label:"Name",value:e.anchor.displayName},{label:"Kind",value:e.anchor.configuredKind},{label:"Ownership",value:e.anchor.kind},{label:"Administered by",value:e.anchor.administeredBy}]}]},{type:"detail",id:"people",queryKey:"selected",empty:"Select a person to inspect their access.",master:{type:"list",id:"people-roster",presentation:"standard",empty:"No people are available.",items:[...e.people].sort((n,o)=>Number(o.isSelf)-Number(n.isSelf)||Number(n.isAnchor)-Number(o.isAnchor)||n.displayName.localeCompare(o.displayName)).map((n)=>({id:n.userId,title:n.displayName,description:[po(n.role),po(n.status),...n.isSelf?["You"]:[],...n.isAnchor?["Protected brain identity"]:[]].join(" \xB7 "),metadata:[n.identities.length===0?"No linked identities":n.identities.length===1?"One linked identity":`${n.identities.length} linked identities`,...n.peers.length>0?[`Arrived via ${c5(n.peers[0]?.peerId)}`]:[]],...n.isSelf?{link:{detail:{itemId:n.userId}}}:{},links:[{label:n.isSelf?"Account \u2192":n.isAnchor?"View protection":"Manage person",target:n.isSelf?{launch:{target:"account-settings"}}:{detail:{itemId:n.userId}}}]}))},...t?{open:{forId:t.userId,title:t.displayName,blocks:r}}:{}}];return{kicker:"Access administration",title:"People",description:"Manage people\u2019s access to this brain, linked identities, and account recovery. Use Account for your own profile and sign-in settings.",status:{label:`${e.activeCount} active`,tone:e.suspendedCount>0?"warn":"neutral"},blocks:i}}});function lW(e,t){return e.find((r)=>r.userId===t)?.displayName??"person"}async function fWr(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function AVe(e){let t=fm(e),r=e.studio.source({definition:vfe,bind:(i)=>{let n=Afe.bind(i,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,Oc(f)),{status:`Role changed to ${po(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${lW(f,h.userId)}\u2019s role to ${po(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=wfe.bind(i,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,Oc(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${lW(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=Sfe.bind(i,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,Oc(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${lW(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=kfe.bind(i,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,Oc(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=_fe.bind(i,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,Oc(f));return{status:`Bound to ${g.delivery.label}. Deliver only through that confirmed private channel.`,setupUrl:g.setupUrl,expiresAt:new Date(g.expiresAt*1000).toISOString()}}),l=Bfe.bind(i,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,Oc(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${lW(f,h.userId)} out everywhere?`,revision:h.userId}}),d=Pfe.bind(i,async({input:h,caller:f})=>(await t.attachIdentity({userId:h.userId,type:h.type,subject:h.subject,...h.issuer?{issuer:h.issuer}:{},...h.label?{label:h.label}:{},verifiedAt:Date.now(),source:{kind:"admin"}},Oc(f)),{status:"Verified channel attached."})),p=Cfe.bind(i,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,Oc(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=Dfe.bind(i,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,Oc(f)),{status:"External peer unlinked from the local person."}),({input:h})=>({summary:`Unlink ${h.peerId}? Local access will not change.`,revision:`${h.peerId}:${h.userId}`}));return vfe.bind(i,{actions:[n,o,s,a,c,l,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(Ife),[y,b,A]=await Promise.all([fWr(t),t.listAdminUsers(),t.listInvitationChannels()]),w=b.filter((N)=>N.status!=="invited"),B=w.find((N)=>N.isAnchor)??w.find((N)=>N.role==="admin"&&N.status==="active"),R=y??hWr(B?.displayName??"Brain owner",w.filter((N)=>N.role==="admin"&&N.status==="active").length),M=w.filter((N)=>N.status==="active"),k=new Map(A.map((N)=>[N.type,N.displayName]));return{query:g,anchor:{kind:R.kind,configuredKind:R.configuredKind,displayName:R.displayName,administeredBy:R.administeredBy},people:w.flatMap((N)=>{if(N.status==="invited")return[];return[{userId:N.userId,displayName:N.displayName,role:N.role,status:N.status,isAnchor:N.isAnchor,isSelf:f?.actor.id===N.userId,...N.profileEntityId?{profileEntityId:N.profileEntityId}:{},passkeys:N.passkeys.map((L)=>({id:L.id,kind:iWr(L),createdAt:L.createdAt})),identities:N.identities.filter(rWr).map((L)=>({id:L.id,type:L.type,displayName:k.get(L.type)??po(L.type),label:L.label??"Connected identity",verified:L.verifiedAt!==void 0})),peers:N.externalPeers.map((L)=>({peerId:L.peerId,verificationStatus:L.verificationStatus}))}]}),activeCount:M.length,activeAdminCount:M.filter((N)=>N.role==="admin").length,suspendedCount:w.length-M.length,channelTypes:A.map((N)=>({type:N.type,displayName:N.displayName}))}}})}});return YA(r,vfe.actions)}var xWr=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(Rh,u.number().int().min(0).max(1e5)).optional(),limit:u.preprocess(Rh,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 gWr(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function yWr(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 bWr(e,t){if(!yWr(e))throw Error(`${t} tab returned invalid workspace data`);return e}function wVe(e,t){let r=[];for(let i of e){if(i.type==="tabs")throw Error(`${t} tab cannot contribute nested tabs`);r.push(i)}return r}function Rfe(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function yP(e,t,r,i){return bWr(await e.dataProvider(t,r,i),e.label)}async function EWr(e,t,r,i){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,r,i)}function vWr(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 SVe(e){return{suspended:e.filter((t)=>t.status==="suspended").length,pendingInvitations:e.filter((t)=>t.invitation!==void 0&&!["claimed","expired","cancelled"].includes(t.invitation.state)).length}}function AWr(e){return[...e.pendingInvitations>0?[{id:"invitations",title:`${e.pendingInvitations} ${e.pendingInvitations===1?"invitation":"invitations"} waiting`,detail:"Not yet accepted.",severity:"info",action:{label:"Review invitations",query:{tab:"invitations"}}}]:[],...e.suspended>0?[{id:"suspended",title:`${e.suspended} ${e.suspended===1?"person":"people"} suspended`,severity:"info",action:{label:"Review people",query:{tab:"people"}}}]:[]]}async function kVe(e){if(!e.studio.isAvailable())return;let t=AVe(e),r=bVe(e),i=EVe(e),n=lVe(e),o=vWr([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:q9,priority:10,permission:"admin",section:"brain",urlQuery:!0,aliases:[{id:"admin:people",query:{tab:"people"}},{id:"admin:invitations",query:{tab:"invitations"}},{id:"admin:peers",query:{tab:"people"}},{id:"admin:audit",query:{tab:"audit"}}],entityTypes:[],accessHandler:(d)=>s.accessHandler(d),dataProvider:async(d,p,m)=>{let h=xWr.parse(p??{}),f,g=Rfe("People"),y=Rfe("Invitations"),b=Rfe("Audit");if(h.tab==="people"){let[A,w]=await Promise.all([yP(s,d,{...h.selected?{selected:h.selected}:{}},m),yP(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),B=yfe(w.view.blocks);g=[...vVe(wVe(A.view.blocks,"People"),{type:"notice",id:"people-peer-note",tone:"neutral",title:"External brain relationships",text:"A peer link records how a locally administered person relates to another brain. It does not grant or change local access."},B.people).blocks]}else if(h.tab==="invitations"){let[A,w]=await Promise.all([yP(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...Hn({offset:h.offset,limit:h.limit})},m),yP(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),B=yfe(w.view.blocks),R=gVe(A.view.blocks,B.invitations);f=A.view.primaryAction,y=[...R.blocks]}else{let A=await yP(l,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...Hn({offset:h.offset,limit:h.limit})},m);b=wVe(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=gWr(d);if(!h)throw new br("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new br("not_found",{publicMessage:`Unknown Administration action: ${h}`});return EWr(f,d,p,m)},badgeProvider:async()=>{let d=SVe(await fm(e).listAdminUsers());return d.suspended+d.pendingInvitations},attentionProvider:async()=>AWr(SVe(await fm(e).listAdminUsers()))})}var wWr=259200000,SWr=u.strictObject({id:u.string(),displayName:u.string(),state:u.string(),reason:u.enum(["expiring","delivery-failed"]),expiresAt:u.number().optional()}),kWr=u.strictObject({invitations:u.array(SWr),expiringCount:u.number().int().nonnegative(),failureCount:u.number().int().nonnegative()}),BVe=ro({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:kWr,digest:({data:e})=>({items:[{label:"Expiring soon",value:String(e.expiringCount),...e.expiringCount>0?{tone:"warn"}:{}},{label:"Delivery failures",value:String(e.failureCount),...e.failureCount>0?{tone:"warn"}:{}}],attention:e.invitations.length}),view:({data:e})=>({blocks:[{type:"stats",items:[{label:"Expiring soon",value:e.expiringCount,tone:e.expiringCount>0?"warn":"good"},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"good"}]},{type:"list",id:"invitation-attention",empty:"No invitation setup links need attention.",items:e.invitations.map((t)=>({id:t.id,title:t.displayName,description:t.reason==="delivery-failed"?"Invitation delivery failed. Resend or cancel it.":"The single-use setup link expires soon.",metadata:[t.state,...t.expiresAt!==void 0?[`Expires ${Fh(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function BWr(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+wWr)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 CVe(e,t){t.throwIfAborted();let r=await fm(e).listAdminUsers();return t.throwIfAborted(),BWr(r,Date.now())}var CWr=u.strictObject({}),DWr=zt({id:"admin",config:CWr},{subscriptions:(e)=>{let t=bt(e);return t.registered(async()=>{await kVe(t)}),[]},dashboardWidgets:(e)=>{let t=bt(e);return[BVe.bind(e,({signal:r})=>CVe(t,r))]}}),Ffe=DWr;var Ki="agent",DVe="agent-network",IVe="agent-proximity",Qfe="agent-discovery:entities",TVe="agent-discovery:proximity-map",Xfe="proximity-map",e0e="agent-list",t0e="agent-detail",Nc="skill",_Ve=30,PVe=120;var dW="skill-derivation",RVe="skill-derivation",r0e="skill:skill-derivation",FVe="skills";var IWr=u.string().trim().min(1).max(PVe),i0e=u.array(IWr).max(_Ve),QA=u.object({name:u.string(),description:u.string(),tags:i0e,examples:u.array(u.string())}),CP=QA,XA=o0.extend({entityType:u.literal(Nc),metadata:CP});var pW=u.object({name:u.string(),description:u.string(),tags:i0e}),Mb=u.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),TWr=s5,s0=u.object({name:u.string(),kind:TWr,organization:u.string().optional(),brainName:u.string().describe("Name of the brain instance"),shownAs:u.string().min(1).optional().describe("The name this brain shows the agent under, in place of its own name"),url:u.string().url().describe("Brain endpoint URL"),repoDid:u.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:u.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:u.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:u.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:u.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:u.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:u.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:u.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:Mb,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"})}),DP=u.object({name:u.string(),shownAs:u.string().min(1).optional(),url:u.string().url(),status:Mb,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()}),On=o0.extend({entityType:u.literal(Ki),metadata:DP}),_Wr=jr.extend({entityType:u.literal(Ki),metadata:DP}),IP=_Wr.extend({frontmatter:s0,about:u.string(),skills:u.array(pW),notes:u.string()}),PWr=IP.extend({url:u.string().optional(),typeLabel:u.string().optional()}),RWr=IP.extend({url:u.string(),typeLabel:u.string()});var FWr=u.record(u.string(),u.unknown());function MWr(e){try{return Mn(e,FWr).content}catch{return e}}function n0e(e){return{name:e.name,...e.shownAs&&{shownAs:e.shownAs},url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:W9(e.url),...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter}}}function MVe(e){return Ws(Ki,e,s0)}function TP(e){return{content:e,metadata:n0e(MVe(e))}}function Z9(e){let t={name:e.name,kind:e.kind,...e.organization&&{organization:e.organization},brainName:e.brainName,...e.shownAs&&{shownAs:e.shownAs},url:e.url,...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter},status:Mb.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},r=tfe({about:e.about,skills:e.skills,notes:e.notes});return dn(r,t)}function bm(e,t={}){return Z9({...e.frontmatter,...e.body,...t})}function _P(e){return gP(MWr(e))}function Zs(e){return{frontmatter:MVe(e.content),body:_P(e.content)}}function o0e(e){return dn("",e)}function NWr(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function OVe(e,t,r={}){let i=r.minCount??1,n=r.topN??12,o=new Map,s=(a)=>{for(let c of mc(a))o.set(c,(o.get(c)??0)+1)};for(let a of e)s(a.metadata.tags);for(let a of t){let c=_P(a.content);s(c.skills.flatMap((l)=>l.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=i).sort(NWr).slice(0,n)}function NVe(e){if(e.length===0)return"";return["Current agent-directory tag vocabulary (reuse existing tags where they fit; propose new only when nothing does):",...e.map(({tag:t,count:r})=>`- ${t} (${r})`)].join(`
|
|
1039
1039
|
`)}function V9(e,t={}){let r=e.anchor?.name??e.brainName,i=e.anchor?.category??"person",n=[];if(e.anchor?.description)n.push(e.anchor.description);if(e.description)n.push(e.description);let o=t.status??"discovered",s=new Date().toISOString();return{content:Z9({name:r,kind:i,...e.anchor?.organization&&{organization:e.anchor.organization},brainName:e.brainName,url:e.url,status:o,discoveredAt:s,...t.provenance&&{introducedBy:t.provenance.introducedBy,hops:t.provenance.hops},about:n.join(`
|
|
1040
1040
|
|
|
1041
1041
|
`),skills:e.skills.map((c)=>({name:c.name,description:c.description,tags:mc(c.tags)})),notes:""}),metadata:{name:r,url:e.url,status:o,discoveredAt:s,slug:W9(e.url)},anchorName:r}}function Xx(e){let t=e.trim();if(t.startsWith("http://")||t.startsWith("https://"))try{return new URL(t).hostname}catch{return t}let r=t.match(/https?:\/\/[^\s]+?(?=[.,;:!?)]*(?:\s|$))/);if(r)try{return new URL(r[0]).hostname}catch{return r[0]}if(/^[^\s]+\.[^\s]+$/.test(t))return t;return""}var LWr=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 LVe(e){return{input:LWr,generate:async({input:t})=>{let r=Xx(t.url??t.prompt??"");if(!r)return{success:!1,error:"No URL or domain provided. Use: system_create agent with a domain like yeehaa.io"};let i=await Th(r,{fetch:e??globalThis.fetch});if(!i.ok)return{success:!1,error:HA(i.reason)?i.error:`Could not fetch Agent Card from ${r}. Make sure the agent is running and accessible.`};let{content:n,metadata:o}=V9(i.card,{...t.status!==void 0?{status:t.status}:{}});return{success:!0,id:r,content:n,metadata:o}}}}var jWr=100,jVe=50000,a0e="connect",zVe="dismiss";function s0e(e){let t=On.parse(e),r=zWr(t);return r?{entity:t,parsed:r}:void 0}function UVe(e){return{sourceId:"agent-sightings",displayName:"Agent sightings",list:async({records:r})=>(await r.list()).flatMap((i)=>{let n=s0e(i);return n?[n]:[]}).sort((i,n)=>n.parsed.frontmatter.discoveredAt.localeCompare(i.parsed.frontmatter.discoveredAt)).slice(0,jWr).map(({entity:i,parsed:n})=>UWr(i,n)),resolveDetail:async(r,{records:i,signal:n})=>{n.throwIfAborted();let o=s0e(await i.get(r));if(n.throwIfAborted(),!o)throw Error("Agent sighting not found");let s=$Wr(o.entity,o.parsed);return{kind:"plain",text:s.slice(0,jVe),truncated:s.length>jVe}},act:async(r,i,{records:n,edits:o})=>{if(i!==a0e&&i!==zVe)throw Error("Invalid agent sighting Inbox action");let s=await n.get(r),a=s?s0e(s):void 0;if(!s||!a)throw Error("Agent sighting not found");let c=i===a0e?"approved":"archived";if(c==="approved")await e.approve(s.id);else await e.revoke(s.id);await o.update(s,{content:bm(a.parsed,{status:c,...c==="approved"?{introducedBy:void 0,hops:void 0}:{}}),metadata:{...s.metadata,status:c}})}}}function zWr(e){let t=Zs(e);return t.frontmatter.status==="discovered"&&(t.frontmatter.introducedBy?.length??0)>0?t:void 0}function UWr(e,t){let r=a0(t.frontmatter.name),i=a0(e.id),n=qVe(r===i?r:`${r} \xB7 ${i}`,160);return{id:e.id,title:n,summary:qWr(t),receivedAt:t.frontmatter.discoveredAt,urgency:"normal",entityRef:{entityType:Ki,entityId:e.id},actions:[{id:a0e,label:"Connect",confirm:!0},{id:zVe,label:"Dismiss",confirm:!0}]}}function qWr(e){let t=e.frontmatter.introducedBy??[],r=`Introduced by ${c0e(t.map(a0))}.`,i=a0(e.body.about),n=e.body.skills.map((s)=>a0(s.name)).filter(Boolean).slice(0,4),o=n.length>0?` Declared skills: ${c0e(n)}.`:"";return qVe(`${r}${i?` ${i}`:""}${o}`,1000)}function $Wr(e,t){let r=[`Agent: ${a0(t.frontmatter.name)}`,`Domain: ${a0(e.id)}`,`Introduced by: ${c0e((t.frontmatter.introducedBy??[]).map(a0))}`],i=a0(t.body.about);if(i)r.push(`About: ${i}`);if(t.body.skills.length>0)r.push("Skills:",...t.body.skills.map((n)=>{let o=a0(n.description);return`- ${a0(n.name)}${o?`: ${o}`:""}`}));return r.join(`
|
|
@@ -9586,7 +9586,7 @@ Guidelines:
|
|
|
9586
9586
|
3. Depth: Provide enough detail to be useful as a reference, but stay focused on the topic.
|
|
9587
9587
|
4. Style: Informative and educational. Write as if explaining to yourself for future reference.
|
|
9588
9588
|
5. Length: Adjust based on topic complexity - concise for simple topics, more detailed for complex ones.
|
|
9589
|
-
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var hpo="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.",H7=Vi(Hfe(dt({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:jue,markdown:zue,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:hpo,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:xUe(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:EUe},generation:gUe,create:{fromUpload:MPr},jobs:{"upload-import":FPr(()=>H7)},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:fUe}),[Gfe(que,async({request:e,entities:t})=>{let{id:r,title:i,body:n}=e;if(await t.get(H7,r))return{noteId:r,created:!1};return await t.create(H7,{id:r,content:n,metadata:{title:i,titleStated:!0},visibility:"restricted"}),{noteId:r,created:!0}})]),G7);var fpo=Pi({id:"note",config:hUe,entities:[H7]}),NPr=fpo;var xpo=u.object({type:u.literal("email"),address:u.string().max(0).optional()}).transform(()=>{return}),gpo=u.looseObject({defaultRecipient:xpo.or(LPr).optional()}),ypo=zt({id:"notifications",config:gpo},{subscriptions:(e)=>{let{config:t}=e,r=bt(e),{logger:i}=r;return r.answer(h3,async({request:n})=>{let o=n.recipient??t.defaultRecipient;if(!o)return i.warn($ue.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=r.deliveryProvider(o.type);if(!s||!await s.isAvailable())return i.warn($ue.transportMissing,{channelType:o.type}),{status:"failed",failure:"transport-missing"};let a=await s.send({recipient:o.address,subject:n.title,text:n.body,...n.html?{html:n.html}:{},...n.replyTo?{replyTo:n.replyTo}:{},sensitivity:n.sensitivity,idempotencyKey:n.idempotencyKey??crypto.randomUUID()});if(a.status!=="sent"){i.warn($ue.deliveryFailed,{transportCode:a.failureCode});let c=jPr.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}),[]}}),zPr=ypo;var qPr=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],bpo=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()}),Epo="https://api.linkedin.com/rest",vpo="202312",UPr=1000,Apo=1000;function wpo(e){return e.toLowerCase().includes("no data found for this memberid")}function Spo(e,t){let r=e.paging?.links?.find((n)=>n.rel==="next")?.href,i=r?Number(new URL(r,"https://api.linkedin.com").searchParams.get("start")):Number.NaN;return Number.isInteger(i)&&i>t?i:t+1}class j${accessToken;fetchFn;constructor(e,t=globalThis.fetch){this.accessToken=e,this.fetchFn=t}fetchProfile(){return this.fetchDomain("PROFILE")}fetchDomain(e){return this.fetchPages(e,0,0)}async fetchPages(e,t,r){if(r===UPr)throw Error(`LinkedIn snapshot exceeded ${UPr} 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,Spo(i,t),r+1)]}async fetchPage(e,t){let r=new URL(`${Epo}/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":vpo}});if(i.ok)return bpo.parse(await i.json());let n=await i.text();if(i.status<500&&wpo(n))return null;throw new Gue(i.status,n.slice(0,Apo))}}class Gue extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var kpo=$Pr({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 vUe{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:kpo})}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 AUe(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var Bpo="https://www.linkedin.com/oauth/v2/authorization",Cpo="https://www.linkedin.com/oauth/v2/accessToken",GPr="r_dma_portability_3rd_party",Dpo=500,Ipo=u.looseObject({access_token:u.string().min(1),expires_in:u.number().int().positive(),scope:u.string().optional()}),Tpo=u.looseObject({error:u.string().optional(),error_description:u.string().optional()});async function _po(e){try{return await e.json()}catch{return null}}class U${config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(Bpo);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",GPr),t}async exchange(e,t){let r=await this.fetchFn(Cpo,{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 _po(r);if(!r.ok){let o=Tpo.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,Dpo)}`:""}`)}let n=Ipo.parse(i);if(n.scope!==void 0&&n.scope!==GPr)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 WPr(e){return new z$({...HPr,now:e})}var Hue="linkedin",Ppo=u.strictObject({accessToken:u.string().min(1),expiresAt:u.iso.datetime()});function wUe(e,t={}){let r=(n)=>new U$({...e,redirectUri:n},t.fetch),i=t.now??Date.now;return{id:Hue,authorizationUrl:({redirectUri:n,state:o})=>r(n).authorizationUrl(o),exchange:async({code:n,redirectUri:o})=>{let s=await r(o).exchange(n,i());return{accessToken:s.accessToken,expiresAt:s.expiresAt}}}}class SUe{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(W7.authorizations,{provider:Hue,brainState:e},"the connection");return new URL(ZPr.parse(t).authorizationUrl)}async redeem(e){let t=VPr.parse(await this.post(W7.redeem,{provider:Hue,grant:e},"grant redemption"));if(t.provider!==Hue)throw Error("OAuth broker redeemed a grant for another provider");return Ppo.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 Rpo(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function MB(e,t){return e.map((r)=>Rpo(r[t])).find(Boolean)}function KPr(e){let t=[MB(e,"First Name"),MB(e,"Last Name")].filter(Boolean).join(" ")||void 0,r=MB(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],i={name:t,headline:MB(e,"Headline"),industry:MB(e,"Industry"),location:MB(e,"Geo Location"),website:r,story:MB(e,"Summary")};return Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))}function YPr(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new br(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new br("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class kUe{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 YPr(await this.messaging.request($$,{fields:t,revision:r}))}async previewFields(e){return YPr(await this.messaging.request(q$,{fields:e}))}async imported(e){let t=new j$(e,this.fetchFn);return KPr(await t.fetchProfile())}}var BUe="/linkedin/oauth/start",H$="/linkedin/oauth/callback",W$="/linkedin/oauth/broker/return";function JPr(e){return e?.permissionLevel==="admin"&&e.isAnchor}function G$(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function XPr(e){let t=(c)=>{let l=e.workspaceUrl(),d=l.includes("?")?"&":"?";return G$(303,`${l}${d}connection=${c}`)},r=async(c,l)=>{let d=e.states.take(l),p=await e.resolveSession(c);return d&&JPr(p)&&p?.userId===d?d:null},i=async(c,l)=>{try{return await e.connections.save(c,await l()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${fe(d)}`),t("failed")}},n=async(c)=>{let l=await e.resolveSession(c);if(!l)return G$(401);if(!JPr(l))return G$(403);let d=e.states.issue(l.userId),{mode:p}=e;if(p.kind==="direct")return G$(302,p.oauth.authorizationUrl(d).toString());try{return G$(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${fe(m)}`),t("failed")}},o=(c)=>async(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=QPr.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:BUe,method:"GET",public:!0,handler:n},a.kind==="direct"?{path:H$,method:"GET",public:!0,handler:o(a.oauth)}:{path:W$,method:"GET",public:!0,handler:s(a.broker)}]}var Fpo=/^(?: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,Mpo=[[/^$/,"<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>"],[Fpo,"<month-year>"]];function rRr(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 eRr(e){if(typeof e!=="string")return`<${rRr(e)}>`;let t=e.trim();return Mpo.find(([r])=>r.test(t))?.[1]??"<string>"}function Opo(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(eRr))].sort();return eRr(e)}function tRr([e],[t]){return e.localeCompare(t)}function Npo(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])=>rRr(a)))].sort(),presentCount:s.length}}),n=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(tRr).map(([a,c])=>[a,Opo(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:i,recordShapes:[...n].sort(tRr).map(([,o])=>o)}}async function iRr(e){let t=await Promise.all(qPr.map(async(r)=>[r,Npo(await e.fetchDomain(r))]));return Object.fromEntries(t)}var lRr={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},Lpo={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},jpo={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."}},nRr=200,TUe=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())})}),Wue=Vr({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:u.object({}),output:u.object({disconnected:u.boolean()})}),_Ue=Vr({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:u.object({}),output:u.object({shapes:u.string()})}),PUe=u.object({connection:u.enum(["connected","declined","failed"]).optional()}),zpo=u.object({field:u.enum(["name","headline","industry","location","website","story"]),current:u.string().nullable(),imported:u.string(),outcome:u.enum(["fill","preserve","unchanged"])}),CUe=PUe.shape.connection,Upo=u.discriminatedUnion("status",[u.object({status:u.literal("disconnected"),expired:u.boolean(),startUrl:u.string(),connection:CUe}),u.object({status:u.literal("unavailable"),message:u.string(),startUrl:u.string(),connection:CUe}),u.object({status:u.literal("ready"),fields:u.array(zpo),connection:CUe})]);function oRr(e){if(e===null)return"\u2014";return e.length>nRr?`${e.slice(0,nRr-1)}\u2026`:e}function sRr(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function aRr(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function DUe(e){let t=e.connection?jpo[e.connection]:null;return t?[{type:"notice",...t}]:[]}var cRr=Po({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",section:"library",query:PUe,data:Upo,actions:[TUe,Wue,_Ue],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:[...DUe(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],aRr(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...DUe(e),{type:"notice",tone:"warn",text:e.message},aRr(e.startUrl,"Connect LinkedIn again"),{type:"action",action:Wue,input:{}}]};let t=e.fields.some((r)=>r.outcome==="fill");return{kicker:"Profile import",title:"LinkedIn",description:"What LinkedIn holds for each profile field, and what an import would do with it.",status:{label:t?"Ready to import":"Profile already complete",tone:t?"good":"neutral"},...t?{primaryAction:{action:TUe,input:{}}}:{},blocks:[...DUe(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:lRr[r.field],current:oRr(r.current),imported:oRr(r.imported),outcome:Lpo[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:_Ue,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:Wue,input:{}}]}}});function IUe(e){if(e?.permission!=="admin"||!e.isAnchor)throw new br("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function qpo(e){if(e instanceof Gue&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${fe(e)}`}async function uRr(e,t){if(!e.isAvailable())return;let r=async(n)=>{let o=await t.connections.get(IUe(n));if(!o||AUe(o))throw new br("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},i=e.source({definition:cRr,bind:(n)=>cRr.bind(n,{load:async({caller:o,query:s})=>{let a=IUe(o),{connection:c}=s.get(PUe),l=await t.connections.get(a);if(!l||AUe(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:qpo(d),startUrl:t.startUrl,connection:c}}},actions:[TUe.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)=>lRr[p.field].toLowerCase()),c=a("fill"),l=a("preserve");if(c.length===0)throw new br("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${sRr(c)} from LinkedIn?${l.length>0?` Your ${sRr(l)} stay as you wrote them.`:""}`,revision:s.revision}}),_Ue.bind(n,async({caller:o})=>{let s=await iRr(t.clientFor((await r(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),Wue.bind(n,async({caller:o})=>(await t.connections.forget(IUe(o)),{disconnected:!0}))]})});return e.register({...i,accessHandler:async(n)=>n.isAnchor&&await i.accessHandler(n)})}var dRr={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.818",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 Gpo="/studio",Hpo=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 ${H$}, registered with the LinkedIn app`)}),Wpo=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 ${W$}, registered with the broker`)}),pRr=u.object({oauth:Hpo.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:Wpo.optional().describe("The managed broker holding the shared LinkedIn app")});function Zpo(e,t){let{oauth:r,broker:i}=e;if(r&&i)throw Error("linkedin-import: configure either oauth (direct) or broker, not both");if(r&&new URL(r.redirectUri).pathname!==H$)throw Error(`linkedin-import: oauth.redirectUri must end at ${H$}`);if(i&&new URL(i.returnUri).pathname!==W$)throw Error(`linkedin-import: broker.returnUri must end at ${W$}`);if(r)return{kind:"direct",oauth:new U$(r,t.fetch)};if(i)return{kind:"broker",broker:new SUe(i,t.fetch)};return null}function mRr(e={}){let t=zt({id:"linkedin-import",config:pRr,setup:(r)=>{let{config:i}=r,n=Zpo(i,e),o=i.oauth?.redirectUri??i.broker?.returnUri;if(!n||!o)return{routes:[]};let s=bt(r),a=new vUe(s.accountSettings,{pluginId:s.pluginId,packageName:dRr.name}),c=Gpo;return s.registered(async()=>{let l=await uRr(s.studio,{profileImport:new kUe(s.messaging,e.fetch),clientFor:(d)=>new j$(d,e.fetch),connections:a,startUrl:new URL(BUe,o).toString()});if(l)c=l}),{routes:XPr({mode:n,states:WPr(),connections:a,resolveSession:async(l)=>s.auth()?.resolveSession(l),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return ko(t,({state:r})=>r.routes)}var RUe=mRr();import{createHash as Vpo,timingSafeEqual as Kpo}from"crypto";function hRr(e){return Vpo("sha256").update(e).digest()}function Ypo(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 FUe{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:hRr(t.secret)}]))}authenticate(e){let t=Ypo(e.headers.get("authorization")),r=t?this.instances.get(t.id):void 0;if(!t||!r)return null;return Kpo(hRr(t.secret),r.secretHash)?{id:r.id,returnUris:r.returnUris}:null}}var Jpo=10,Qpo=600000,OUe={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function C8(e,t=200){return Response.json(e,{status:t,headers:OUe})}function fRr(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...OUe,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function xRr(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function Zue(e,t){let r=new URL(e.returnUri);return r.searchParams.set("provider",e.provider),r.searchParams.set("state",e.brainState),Object.entries(t).forEach(([i,n])=>r.searchParams.set(i,n)),new Response(null,{status:303,headers:{...OUe,Location:r.toString()}})}function bRr(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-Qpo),p=d.length<Jpo;return r.set(c,p?[...d,l]:d),p},n=(c)=>new URL(MUe(c),e.publicUrl).toString(),o=async(c)=>{let l=e.instances.authenticate(c);if(!l)return fRr();let d=gRr.safeParse(await xRr(c));if(!d.success)return C8({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=l.returnUris[d.data.provider];if(!p||!m)return C8({error:"Provider is unavailable for this instance"},400);if(!i(l.id))return C8({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 C8({authorizationUrl:f})},s=async(c)=>{let l=e.instances.authenticate(c);if(!l)return fRr();let d=yRr.safeParse(await xRr(c));if(!d.success)return C8({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,m=e.grants.take(d.data.grant,(h)=>h.provider===p&&h.instanceId===l.id);if(!m)return C8({error:"Invalid or expired grant"},400);return C8({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 C8({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return Zue(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return Zue(p,{error:"authorization_incomplete"});try{let h=await c.exchange({code:m,redirectUri:n(c.id)}),f=e.grants.issue({provider:c.id,instanceId:p.instanceId,credential:h});return Zue(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${fe(h)}`),Zue(p,{error:"credential_exchange_failed"})}};return[{path:W7.authorizations,method:"POST",public:!0,handler:o},{path:W7.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:MUe(c.id),method:"GET",public:!0,handler:a(c)}))]}var Xpo=600000,emo=120000,ERr=1000,tmo=u.object({clientId:u.string().trim().min(1),clientSecret:u.string().trim().min(1)}),rmo=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(NUe,u.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),vRr=u.object({publicUrl:u.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:u.record(NUe,tmo).default({}).describe("Per provider, the shared app the broker holds"),instances:u.array(rmo).default([])});function imo(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 LUe(e){let t=zt({id:"oauth-broker",config:vRr,setup:(r)=>{let{config:i}=r,n=imo(i,e);if(i.instances.length===0||n.length===0)return{routes:[]};return{routes:bRr({publicUrl:i.publicUrl,providers:n,instances:new FUe(i.instances),authorizations:new z$({ttlMs:Xpo,maxPending:ERr,now:e.now}),grants:new z$({ttlMs:emo,maxPending:ERr,now:e.now}),now:e.now??Date.now,logger:bt(r).logger})}}});return ko(t,({state:r})=>r.routes)}var nmo=2592000000,Z$=(e,t)=>Ht(`${e}
|
|
9589
|
+
6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var hpo="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.",H7=Vi(Hfe(dt({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:jue,markdown:zue,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:hpo,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:xUe(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:EUe},generation:gUe,create:{fromUpload:MPr},jobs:{"upload-import":FPr(()=>H7)},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:fUe}),[Gfe(que,async({request:e,entities:t})=>{let{id:r,title:i,body:n}=e;if(await t.get(H7,r))return{noteId:r,created:!1};return await t.create(H7,{id:r,content:n,metadata:{title:i,titleStated:!0},visibility:"restricted"}),{noteId:r,created:!0}})]),G7);var fpo=Pi({id:"note",config:hUe,entities:[H7]}),NPr=fpo;var xpo=u.object({type:u.literal("email"),address:u.string().max(0).optional()}).transform(()=>{return}),gpo=u.looseObject({defaultRecipient:xpo.or(LPr).optional()}),ypo=zt({id:"notifications",config:gpo},{subscriptions:(e)=>{let{config:t}=e,r=bt(e),{logger:i}=r;return r.answer(h3,async({request:n})=>{let o=n.recipient??t.defaultRecipient;if(!o)return i.warn($ue.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=r.deliveryProvider(o.type);if(!s||!await s.isAvailable())return i.warn($ue.transportMissing,{channelType:o.type}),{status:"failed",failure:"transport-missing"};let a=await s.send({recipient:o.address,subject:n.title,text:n.body,...n.html?{html:n.html}:{},...n.replyTo?{replyTo:n.replyTo}:{},sensitivity:n.sensitivity,idempotencyKey:n.idempotencyKey??crypto.randomUUID()});if(a.status!=="sent"){i.warn($ue.deliveryFailed,{transportCode:a.failureCode});let c=jPr.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}),[]}}),zPr=ypo;var qPr=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],bpo=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()}),Epo="https://api.linkedin.com/rest",vpo="202312",UPr=1000,Apo=1000;function wpo(e){return e.toLowerCase().includes("no data found for this memberid")}function Spo(e,t){let r=e.paging?.links?.find((n)=>n.rel==="next")?.href,i=r?Number(new URL(r,"https://api.linkedin.com").searchParams.get("start")):Number.NaN;return Number.isInteger(i)&&i>t?i:t+1}class j${accessToken;fetchFn;constructor(e,t=globalThis.fetch){this.accessToken=e,this.fetchFn=t}fetchProfile(){return this.fetchDomain("PROFILE")}fetchDomain(e){return this.fetchPages(e,0,0)}async fetchPages(e,t,r){if(r===UPr)throw Error(`LinkedIn snapshot exceeded ${UPr} 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,Spo(i,t),r+1)]}async fetchPage(e,t){let r=new URL(`${Epo}/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":vpo}});if(i.ok)return bpo.parse(await i.json());let n=await i.text();if(i.status<500&&wpo(n))return null;throw new Gue(i.status,n.slice(0,Apo))}}class Gue extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var kpo=$Pr({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 vUe{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:kpo})}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 AUe(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var Bpo="https://www.linkedin.com/oauth/v2/authorization",Cpo="https://www.linkedin.com/oauth/v2/accessToken",GPr="r_dma_portability_3rd_party",Dpo=500,Ipo=u.looseObject({access_token:u.string().min(1),expires_in:u.number().int().positive(),scope:u.string().optional()}),Tpo=u.looseObject({error:u.string().optional(),error_description:u.string().optional()});async function _po(e){try{return await e.json()}catch{return null}}class U${config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(Bpo);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",GPr),t}async exchange(e,t){let r=await this.fetchFn(Cpo,{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 _po(r);if(!r.ok){let o=Tpo.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,Dpo)}`:""}`)}let n=Ipo.parse(i);if(n.scope!==void 0&&n.scope!==GPr)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 WPr(e){return new z$({...HPr,now:e})}var Hue="linkedin",Ppo=u.strictObject({accessToken:u.string().min(1),expiresAt:u.iso.datetime()});function wUe(e,t={}){let r=(n)=>new U$({...e,redirectUri:n},t.fetch),i=t.now??Date.now;return{id:Hue,authorizationUrl:({redirectUri:n,state:o})=>r(n).authorizationUrl(o),exchange:async({code:n,redirectUri:o})=>{let s=await r(o).exchange(n,i());return{accessToken:s.accessToken,expiresAt:s.expiresAt}}}}class SUe{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(W7.authorizations,{provider:Hue,brainState:e},"the connection");return new URL(ZPr.parse(t).authorizationUrl)}async redeem(e){let t=VPr.parse(await this.post(W7.redeem,{provider:Hue,grant:e},"grant redemption"));if(t.provider!==Hue)throw Error("OAuth broker redeemed a grant for another provider");return Ppo.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 Rpo(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function MB(e,t){return e.map((r)=>Rpo(r[t])).find(Boolean)}function KPr(e){let t=[MB(e,"First Name"),MB(e,"Last Name")].filter(Boolean).join(" ")||void 0,r=MB(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],i={name:t,headline:MB(e,"Headline"),industry:MB(e,"Industry"),location:MB(e,"Geo Location"),website:r,story:MB(e,"Summary")};return Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))}function YPr(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new br(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new br("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class kUe{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 YPr(await this.messaging.request($$,{fields:t,revision:r}))}async previewFields(e){return YPr(await this.messaging.request(q$,{fields:e}))}async imported(e){let t=new j$(e,this.fetchFn);return KPr(await t.fetchProfile())}}var BUe="/linkedin/oauth/start",H$="/linkedin/oauth/callback",W$="/linkedin/oauth/broker/return";function JPr(e){return e?.permissionLevel==="admin"&&e.isAnchor}function G$(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function XPr(e){let t=(c)=>{let l=e.workspaceUrl(),d=l.includes("?")?"&":"?";return G$(303,`${l}${d}connection=${c}`)},r=async(c,l)=>{let d=e.states.take(l),p=await e.resolveSession(c);return d&&JPr(p)&&p?.userId===d?d:null},i=async(c,l)=>{try{return await e.connections.save(c,await l()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${fe(d)}`),t("failed")}},n=async(c)=>{let l=await e.resolveSession(c);if(!l)return G$(401);if(!JPr(l))return G$(403);let d=e.states.issue(l.userId),{mode:p}=e;if(p.kind==="direct")return G$(302,p.oauth.authorizationUrl(d).toString());try{return G$(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${fe(m)}`),t("failed")}},o=(c)=>async(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=QPr.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:BUe,method:"GET",public:!0,handler:n},a.kind==="direct"?{path:H$,method:"GET",public:!0,handler:o(a.oauth)}:{path:W$,method:"GET",public:!0,handler:s(a.broker)}]}var Fpo=/^(?: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,Mpo=[[/^$/,"<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>"],[Fpo,"<month-year>"]];function rRr(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 eRr(e){if(typeof e!=="string")return`<${rRr(e)}>`;let t=e.trim();return Mpo.find(([r])=>r.test(t))?.[1]??"<string>"}function Opo(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(eRr))].sort();return eRr(e)}function tRr([e],[t]){return e.localeCompare(t)}function Npo(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])=>rRr(a)))].sort(),presentCount:s.length}}),n=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(tRr).map(([a,c])=>[a,Opo(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:i,recordShapes:[...n].sort(tRr).map(([,o])=>o)}}async function iRr(e){let t=await Promise.all(qPr.map(async(r)=>[r,Npo(await e.fetchDomain(r))]));return Object.fromEntries(t)}var lRr={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},Lpo={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},jpo={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."}},nRr=200,TUe=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())})}),Wue=Vr({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:u.object({}),output:u.object({disconnected:u.boolean()})}),_Ue=Vr({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:u.object({}),output:u.object({shapes:u.string()})}),PUe=u.object({connection:u.enum(["connected","declined","failed"]).optional()}),zpo=u.object({field:u.enum(["name","headline","industry","location","website","story"]),current:u.string().nullable(),imported:u.string(),outcome:u.enum(["fill","preserve","unchanged"])}),CUe=PUe.shape.connection,Upo=u.discriminatedUnion("status",[u.object({status:u.literal("disconnected"),expired:u.boolean(),startUrl:u.string(),connection:CUe}),u.object({status:u.literal("unavailable"),message:u.string(),startUrl:u.string(),connection:CUe}),u.object({status:u.literal("ready"),fields:u.array(zpo),connection:CUe})]);function oRr(e){if(e===null)return"\u2014";return e.length>nRr?`${e.slice(0,nRr-1)}\u2026`:e}function sRr(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function aRr(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function DUe(e){let t=e.connection?jpo[e.connection]:null;return t?[{type:"notice",...t}]:[]}var cRr=Po({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",section:"library",query:PUe,data:Upo,actions:[TUe,Wue,_Ue],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:[...DUe(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],aRr(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...DUe(e),{type:"notice",tone:"warn",text:e.message},aRr(e.startUrl,"Connect LinkedIn again"),{type:"action",action:Wue,input:{}}]};let t=e.fields.some((r)=>r.outcome==="fill");return{kicker:"Profile import",title:"LinkedIn",description:"What LinkedIn holds for each profile field, and what an import would do with it.",status:{label:t?"Ready to import":"Profile already complete",tone:t?"good":"neutral"},...t?{primaryAction:{action:TUe,input:{}}}:{},blocks:[...DUe(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:lRr[r.field],current:oRr(r.current),imported:oRr(r.imported),outcome:Lpo[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:_Ue,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:Wue,input:{}}]}}});function IUe(e){if(e?.permission!=="admin"||!e.isAnchor)throw new br("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function qpo(e){if(e instanceof Gue&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${fe(e)}`}async function uRr(e,t){if(!e.isAvailable())return;let r=async(n)=>{let o=await t.connections.get(IUe(n));if(!o||AUe(o))throw new br("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},i=e.source({definition:cRr,bind:(n)=>cRr.bind(n,{load:async({caller:o,query:s})=>{let a=IUe(o),{connection:c}=s.get(PUe),l=await t.connections.get(a);if(!l||AUe(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:qpo(d),startUrl:t.startUrl,connection:c}}},actions:[TUe.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)=>lRr[p.field].toLowerCase()),c=a("fill"),l=a("preserve");if(c.length===0)throw new br("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${sRr(c)} from LinkedIn?${l.length>0?` Your ${sRr(l)} stay as you wrote them.`:""}`,revision:s.revision}}),_Ue.bind(n,async({caller:o})=>{let s=await iRr(t.clientFor((await r(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),Wue.bind(n,async({caller:o})=>(await t.connections.forget(IUe(o)),{disconnected:!0}))]})});return e.register({...i,accessHandler:async(n)=>n.isAnchor&&await i.accessHandler(n)})}var dRr={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.819",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 Gpo="/studio",Hpo=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 ${H$}, registered with the LinkedIn app`)}),Wpo=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 ${W$}, registered with the broker`)}),pRr=u.object({oauth:Hpo.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:Wpo.optional().describe("The managed broker holding the shared LinkedIn app")});function Zpo(e,t){let{oauth:r,broker:i}=e;if(r&&i)throw Error("linkedin-import: configure either oauth (direct) or broker, not both");if(r&&new URL(r.redirectUri).pathname!==H$)throw Error(`linkedin-import: oauth.redirectUri must end at ${H$}`);if(i&&new URL(i.returnUri).pathname!==W$)throw Error(`linkedin-import: broker.returnUri must end at ${W$}`);if(r)return{kind:"direct",oauth:new U$(r,t.fetch)};if(i)return{kind:"broker",broker:new SUe(i,t.fetch)};return null}function mRr(e={}){let t=zt({id:"linkedin-import",config:pRr,setup:(r)=>{let{config:i}=r,n=Zpo(i,e),o=i.oauth?.redirectUri??i.broker?.returnUri;if(!n||!o)return{routes:[]};let s=bt(r),a=new vUe(s.accountSettings,{pluginId:s.pluginId,packageName:dRr.name}),c=Gpo;return s.registered(async()=>{let l=await uRr(s.studio,{profileImport:new kUe(s.messaging,e.fetch),clientFor:(d)=>new j$(d,e.fetch),connections:a,startUrl:new URL(BUe,o).toString()});if(l)c=l}),{routes:XPr({mode:n,states:WPr(),connections:a,resolveSession:async(l)=>s.auth()?.resolveSession(l),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return ko(t,({state:r})=>r.routes)}var RUe=mRr();import{createHash as Vpo,timingSafeEqual as Kpo}from"crypto";function hRr(e){return Vpo("sha256").update(e).digest()}function Ypo(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 FUe{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:hRr(t.secret)}]))}authenticate(e){let t=Ypo(e.headers.get("authorization")),r=t?this.instances.get(t.id):void 0;if(!t||!r)return null;return Kpo(hRr(t.secret),r.secretHash)?{id:r.id,returnUris:r.returnUris}:null}}var Jpo=10,Qpo=600000,OUe={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function C8(e,t=200){return Response.json(e,{status:t,headers:OUe})}function fRr(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...OUe,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function xRr(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function Zue(e,t){let r=new URL(e.returnUri);return r.searchParams.set("provider",e.provider),r.searchParams.set("state",e.brainState),Object.entries(t).forEach(([i,n])=>r.searchParams.set(i,n)),new Response(null,{status:303,headers:{...OUe,Location:r.toString()}})}function bRr(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-Qpo),p=d.length<Jpo;return r.set(c,p?[...d,l]:d),p},n=(c)=>new URL(MUe(c),e.publicUrl).toString(),o=async(c)=>{let l=e.instances.authenticate(c);if(!l)return fRr();let d=gRr.safeParse(await xRr(c));if(!d.success)return C8({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=l.returnUris[d.data.provider];if(!p||!m)return C8({error:"Provider is unavailable for this instance"},400);if(!i(l.id))return C8({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 C8({authorizationUrl:f})},s=async(c)=>{let l=e.instances.authenticate(c);if(!l)return fRr();let d=yRr.safeParse(await xRr(c));if(!d.success)return C8({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,m=e.grants.take(d.data.grant,(h)=>h.provider===p&&h.instanceId===l.id);if(!m)return C8({error:"Invalid or expired grant"},400);return C8({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 C8({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return Zue(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return Zue(p,{error:"authorization_incomplete"});try{let h=await c.exchange({code:m,redirectUri:n(c.id)}),f=e.grants.issue({provider:c.id,instanceId:p.instanceId,credential:h});return Zue(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${fe(h)}`),Zue(p,{error:"credential_exchange_failed"})}};return[{path:W7.authorizations,method:"POST",public:!0,handler:o},{path:W7.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:MUe(c.id),method:"GET",public:!0,handler:a(c)}))]}var Xpo=600000,emo=120000,ERr=1000,tmo=u.object({clientId:u.string().trim().min(1),clientSecret:u.string().trim().min(1)}),rmo=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(NUe,u.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),vRr=u.object({publicUrl:u.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:u.record(NUe,tmo).default({}).describe("Per provider, the shared app the broker holds"),instances:u.array(rmo).default([])});function imo(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 LUe(e){let t=zt({id:"oauth-broker",config:vRr,setup:(r)=>{let{config:i}=r,n=imo(i,e);if(i.instances.length===0||n.length===0)return{routes:[]};return{routes:bRr({publicUrl:i.publicUrl,providers:n,instances:new FUe(i.instances),authorizations:new z$({ttlMs:Xpo,maxPending:ERr,now:e.now}),grants:new z$({ttlMs:emo,maxPending:ERr,now:e.now}),now:e.now??Date.now,logger:bt(r).logger})}}});return ko(t,({state:r})=>r.routes)}var nmo=2592000000,Z$=(e,t)=>Ht(`${e}
|
|
9590
9590
|
${t}`);function ARr(e,t){let r=(i)=>i!==void 0&&t()-i.usedAt<nmo;return{get:async(i,n)=>{let o=await e.get(Z$(i,n));return r(o)?{hash:o.hash,...o.conflictEdit!==void 0&&{conflictEdit:o.conflictEdit},...o.conflictId!==void 0&&{conflictId:o.conflictId}}:void 0},held:async(i,n,o)=>{await e.set(Z$(i,n),{hash:o,usedAt:t()})},conflictKept:async(i,n,o,s)=>{let a=await e.get(Z$(i,n));if(!r(a))return;await e.set(Z$(i,n),{hash:a.hash,conflictEdit:o,...s!==void 0&&{conflictId:s},usedAt:t()})},forget:async(i,n)=>{await e.delete(Z$(i,n))},sweep:async()=>{let i=(await e.keys()).filter(({value:n})=>!r(n));await Promise.all(i.map(({key:n})=>e.delete(n)))}}}function wRr(e=Date.now){let t=new Map;return ARr({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 omo="webdav.mount-base",smo=u.object({hash:u.string().min(1),conflictEdit:u.string().min(1).optional(),conflictId:u.string().min(1).optional(),usedAt:u.number()});function SRr(e,t=Date.now){let r=e.scoped({namespace:omo,schema:smo});return ARr({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 amo=new Set([".obsidian"]),kRr=33554432;function OB(e){let[t]=e;return t!==void 0&&amo.has(t)}function BRr(){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 cmo="webdav.kept",lmo=u.object({path:u.string().min(1),bytes:u.string().optional(),modified:u.number()});function CRr(e){let t=e.scoped({namespace:cmo,schema:lmo}),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 umo}from"crypto";var dmo=500;class jUe{run=umo().slice(0,8);keep;sequence=0;recent=[];waiting=new Set;closed=!1;constructor(e={}){this.keep=e.keep??dmo}cursor(){return`${this.run}:${this.sequence}`}record(e){this.sequence+=1,this.recent=[...this.recent.slice(-(this.keep-1)),{sequence:this.sequence,type:e}];let t=[...this.waiting];this.waiting.clear();for(let r of t)r()}close(){this.closed=!0;let e=[...this.waiting];this.waiting.clear();for(let t of e)t()}since(e){if(e===null)return{cursor:this.cursor(),types:[]};let[t,r]=e.split(":"),i=Number(r),n=this.recent[0]?.sequence??this.sequence+1;if(t!==this.run||!Number.isInteger(i)||i>this.sequence||i<n-1)return{cursor:this.cursor(),reset:!0};return{cursor:this.cursor(),types:[...new Set(this.recent.filter((o)=>o.sequence>i).map((o)=>o.type))]}}async wait(e,t,r){let i=this.since(e);if("reset"in i||i.types.length>0||e===null)return i;if(t<=0||this.closed)return i;return await new Promise((n)=>{let o=()=>{clearTimeout(s),this.waiting.delete(o),r?.removeEventListener("abort",o),n()},s=setTimeout(o,t);this.waiting.add(o),r?.addEventListener("abort",o,{once:!0})}),this.since(e)}}var IRr="obsidian",TRr="Obsidian",pmo=1024,mmo="Your brain could not answer this.",hmo=u.object({question:u.string().min(1).max(8000),conversation:u.string().min(1).max(Vue).optional(),path:u.string().min(1).max(pmo).optional()}),fmo=u.object({conversation:u.string().min(1).max(Vue),approval:u.string().min(1).max(Vue),confirmed:u.boolean()});function _Rr(e){let{principal:t}=e;return{userId:t.userId,personId:t.personId,displayName:t.displayName,permissionLevel:t.permissionLevel,isAnchor:t.isAnchor,...t.canonicalId!==void 0&&{canonicalId:t.canonicalId}}}async function xmo(e,t){let r=await e.entityAt(t.split("/"));if(!r)return;let i=await r.file.open();if(typeof i!=="string")return;let n=r.entity.metadata.title;return{entityType:r.entity.entityType,id:r.entity.id,title:typeof n==="string"&&n!==""?n:r.entity.id,content:i.slice(0,DRr)}}async function PRr(e,t,r){let i=(r.cards??[]).flatMap((a)=>a.kind==="sources"?a.sources:[]),n=await Promise.all(i.map(async(a)=>{let c=a.entityType!==void 0&&a.entityId!==void 0&&a.brain===void 0?await e.pathOf(a.entityType,a.entityId):void 0;return{title:a.title??a.source,...c!==void 0&&{path:c},...a.url!==void 0&&{url:a.url},...a.excerpt!==void 0&&{excerpt:a.excerpt}}})),o=(r.pendingConfirmations??[]).map(({id:a,summary:c,preview:l})=>({id:a,summary:c,...l!==void 0&&{preview:l}})),s={conversation:t,text:r.text,...r.error!==void 0&&{error:mmo},sources:n,confirmations:o};return new Response(JSON.stringify(s),{status:200,headers:{"Content-Type":"application/json; charset=utf-8"}})}var RRr=()=>new Response("Nothing answers questions here right now.",{status:503});async function FRr(e,t){let r=hmo.safeParse(t);if(!r.success)return new Response('Ask with { "question": "\u2026" }',{status:400});let{question:i,conversation:n,path:o}=r.data,s=o===void 0?void 0:await xmo(e.tree,o),a=await e.ask?.({asker:_Rr(e.grant),interfaceType:IRr,channelName:TRr,question:i,...n!==void 0&&{conversationId:n},...s!==void 0&&{entry:s}});if(!a)return RRr();if("message"in a)return new Response(a.message,{status:409});return PRr(e.tree,a.conversationId,a.response)}async function MRr(e,t){let r=fmo.safeParse(t);if(!r.success)return new Response('Answer with { "conversation": "\u2026", "approval": "\u2026", "confirmed": true }',{status:400});let{conversation:i,approval:n,confirmed:o}=r.data,s=await e.confirmAsk?.({asker:_Rr(e.grant),interfaceType:IRr,channelName:TRr,conversationId:i,approvalId:n,confirmed:o});if(!s)return RRr();if("message"in s)return new Response(s.message,{status:409});return PRr(e.tree,i,s.response)}import{createHash as vmo}from"crypto";import{posix as Amo}from"path";var gmo="conflict",V$="note",ymo=100,NRr=new Set(["image","document"]);function UUe(e){return NRr.has(e)}var bmo={".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 qUe{reader;scope;containment;everyType;constructor(e,t,r={}){this.reader=e,this.scope=t,this.containment=Dy(e),this.everyType=r.everyType??!1}async resolve(e){if(e.length===0)return{kind:"folder",segments:e};if(!e.every(zUe))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(ORr).map((i)=>({kind:"folder",segments:[...e,i]})),...r.sort((i,n)=>ORr(i.segments.join("/"),n.segments.join("/")))]}async rootChildren(){let e=new Map((await this.reader.getEntityCounts(this.scope)).map((i)=>[i.entityType,i.count])),t=this.reader.getEntityTypes().filter((i)=>this.isFolderType(i)&&(this.everyType||[i,this.containedIn(i)].some((n)=>n!==void 0&&(e.get(n)??0)>0))),r=this.reader.getEntityTypes().includes(V$)?(await this.hierarchy(V$,[])).entities:[];return{folders:t,files:await this.filesIn([],r)}}async typeFolderChildren(e){let[t,...r]=e;if(t===void 0||!this.isFolderType(t))return{folders:[],files:[]};let i=await Promise.all([t,this.containedIn(t)].filter((n)=>n!==void 0).map((n)=>this.hierarchy(n,r)));return{folders:i.flatMap((n)=>n.folders),files:await this.filesIn(e,i.flatMap((n)=>n.entities))}}async hierarchy(e,t,r=0){let[i,...n]=t,o=await this.reader.queryEntityHierarchy({entityType:e,prefix:i===void 0?null:[i,...n],visibilityScope:this.scope,limit:ymo,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 related(e,t){let r=await this.entityAt(e);if(!r)return;let i=await this.nearestTo(r.entity,t);if(i==="unindexed")return i;return(await Promise.all(i.map(async(o)=>{let s=await this.reader.getEntityRaw({entityType:o.entityType,id:o.entityId,visibilityScope:this.scope,source:!0}),a=s?await this.fileOf(s):void 0;if(!s||!a)return;let c=s.metadata.title;return{path:a.segments.join("/"),title:typeof c==="string"&&c!==""?c:s.id,entityType:s.entityType,distance:o.distance}}))).filter((o)=>o!==void 0)}async nearestTo(e,t){try{return await this.reader.nearestToEntity({origin:{entityType:e.entityType,entityId:e.id},types:this.reader.getEntityTypes().filter((r)=>!UUe(r)&&r!==gmo),limit:t,visibilityScope:this.scope})}catch(r){if(r instanceof U9)return"unindexed";throw r}}async pathOf(e,t){if(!this.reader.getEntityTypes().includes(e))return;let r=await this.reader.getEntityRaw({entityType:e,id:t,visibilityScope:this.scope,source:!0});return(r?await this.fileOf(r):void 0)?.segments.join("/")}async entityAt(e){if(e.length===0||!e.every(zUe))return;let{entityType:t,id:r}=V6(e.join("/"),this.containment);if(!this.reader.getEntityTypes().includes(t))return;let i=await this.reader.getEntityRaw({entityType:t,id:r,visibilityScope:this.scope,source:!0}),n=i?await this.fileOf(i):void 0;return i&&n?.segments.join("/")===e.join("/")?{entity:i,file:n}:void 0}textExtension(e){return this.reader.fileExtension(e)}placementAt(e,t){if(e.length===0||!e.every(zUe))return;let r=e.join("/"),{entityType:i,id:n}=V6(r,this.containment);if(!this.reader.getEntityTypes().includes(i))return;let o=Iy(i,n,t,this.containment);return o.writable&&o.relativePath===r?{entityType:i,id:n}:void 0}async fileOf(e){let t=t8(e,this.reader.fileExtension(e.entityType));if(!Iy(e.entityType,e.id,t,this.containment).writable)return;let i={kind:"file",segments:IT(e.id,e.entityType,t,this.containment).split("/"),contentType:bmo[t]??"application/octet-stream",etag:`"${e.contentHash}"`,modified:new Date(e.updated)};if(!NRr.has(e.entityType)||t===".md"){let a=t===".yaml"?EP(e.content):e.content;return{...i,size:Buffer.byteLength(a),open:async()=>a}}if(e.content==="")return;let n=cp.safeParse(e.content);if(n.success){let a=await this.reader.statAsset(n.data);if(!a)return;return{...i,size:a.sizeBytes,open:async()=>Emo(await this.reader.openAsset(n.data))}}let o=/^data:[a-z0-9.+/-]+;base64,([\s\S]+)$/i.exec(e.content.trim())?.[1];if(!o)return;let s=Buffer.from(o.replace(/\s/g,""),"base64");return{...i,size:s.byteLength,open:async()=>s}}isFolderType(e){return e!==V$&&!this.containment.has(e)&&this.reader.getEntityTypes().includes(e)}folderTypeOf(e){return this.containment.get(e)??e}containedIn(e){return[...this.containment].find(([,t])=>t===e)?.[0]}}function ORr(e,t){return e<t?-1:e>t?1:0}function zUe(e){return e.length>0&&e!=="."&&e!==".."&&!/[/\\\0]/.test(e)}function Emo(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 qRr="image",wmo="document",Smo=".pdf",LRr="note",$Ue="webdav";async function GUe(e,t){let r=Amo.extname(t.segments[t.segments.length-1]??"").toLowerCase();if(Zu.includes(r))return zRr(e,t,r,Imo);if(r===Smo)return zRr(e,t,r,Tmo);let i=r===".yaml"?kmo(e,t):t;if(i===void 0)return await Kue(e,t)?D8("No entry can be stored at this path"):Yue();if(r!==".md"&&r!==".yaml")return await Kue(e,i)?D8("The drive stores notes, entries, images and PDFs"):Yue();if(i.bytes.byteLength>e.writes.maxFileBytes)return ZRr();let n=await e.tree.entityAt(i.segments),o=n?.entity.entityType??e.tree.placementAt(i.segments,r)?.entityType;if(o!==void 0&&UUe(o))return D8(o===qRr?"An image is stored as its image file":"A document is stored as its PDF file");return n?Bmo(e,i,n):Dmo(e,i,r)}function kmo(e,t){let r=e.tree.placementAt(t.segments,".yaml")?.entityType;if(r===void 0||e.tree.textExtension(r)!==".yaml")return;let i=KRr(t.bytes);if(i===void 0)return t;return{...t,bytes:new Uint8Array(Buffer.from(vP(i),"utf8"))}}async function Bmo(e,t,{entity:r,file:i}){let{writes:n}=e,o=t.onlyIfAbsent===!0||!HUe(t.ifMatch,i.etag);if(o&&!t.keepAsConflict)return t.onlyIfAbsent?Jue():I8();let s=HRr(n,t.bytes,r.entityType);if("status"in s)return s;if(Cmo(n,s.parsed,r))return await e.mount.held(r.contentHash),{status:204,etag:await WRr(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 K$(e,t.grant,"update",l,p5(r.entityType,r,l,e.reader));if(d)return d;if(o)return jRr(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 jRr(e,t,{existing:r,base:h,text:s.text,declared:s.parsed.visibility})}let p=await Que(()=>n.updateEntity({entity:l,options:{expectedContentHash:r.contentHash,eventContext:Y$(t.grant)}}));if(!p.ok)return VRr(p.error);if(p.value.skipReason==="content-conflict")return I8();if(!p.value.skipped)await NB(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 Cmo(e,t,r){let i=ZUe(()=>e.deserializeEntity(r.content,r.entityType));return i.ok&&(t.visibility??r.visibility)===r.visibility&&Bun.deepEquals(t,i.value)}async function jRr(e,t,r){let{existing:i,base:n,text:o,declared:s}=r,a=Ht(o);if(n?.conflictEdit===a)return{status:204,conflictId:n.conflictId};let c=await e.recordConflict({entityType:i.entityType,entityId:i.id,origin:"drive",actor:t.grant.principal.userId,...n!==void 0&&{base:n.hash},current:i.contentHash,text:o,targetVisibility:i.visibility,...s!==void 0&&s!==i.visibility&&{declaredVisibility:s}});if(c===void 0)return I8();return await e.mount.conflictKept(a,c),{status:204,conflictId:c}}async function Dmo(e,t,r){let{writes:i,tree:n}=e,{segments:o}=t;if(!await Kue(e,t))return Yue();let s=n.placementAt(o,r);if(!s)return D8("No entry can be stored at this path");let a=HRr(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=Ufe(s.entityType,void 0,l.status,e.reader)!=="non-publish",h=await K$(e,t.grant,"create",p,m?["create","publish"]:["create"]);if(h)return h;let f=await Que(()=>i.createEntity({entity:p,options:{conditionalWrite:{expectedRevision:null},eventContext:Y$(t.grant)}}));if(!f.ok)return WUe(f.error);return await NB(i,t.grant,"create","allowed",p),{status:201,etag:await WRr(e,t,a.text)}}var Imo={entityType:qRr,noun:"image",wrongFolder:"An image can only be stored in the image folder",describe:async({bytes:e,digest:t,extension:r,existing:i})=>{let n=await FT(URr(e));if(!n)return{status:422,message:"The file is not a PNG, JPEG, GIF or WebP image"};let o=DT(n.format);if(o!==r)return{status:422,message:`These bytes are stored as ${o}; save the image under that extension`};let s=i?.status;if(typeof s==="string"&&MT(t,s))return{status:422,message:"These bytes are the old pending placeholder, not this image's bytes"};return{metadata:{...i,...n}}}},Tmo={entityType:wmo,noun:"document",wrongFolder:"A PDF can only be stored in the document folder",describe:async({bytes:e,digest:t,name:r,existing:i})=>{if(!zae(e))return{status:422,message:"The file is not a PDF"};if(Kse(t))return{status:422,message:"These bytes are the old pending placeholder, not a document's bytes"};let{pageCount:n,status:o,processingJobId:s,processingError:a,...c}=i??{},l=Oae(e);return{metadata:{...i?c:{filename:r,attachmentType:"uploaded"},mimeType:"application/pdf",...l>0&&{pageCount:l}}}}};async function zRr(e,t,r,i){let{writes:n,tree:o}=e,{segments:s,bytes:a,grant:c}=t,l=await o.entityAt(s);if(!l&&!await Kue(e,t))return Yue();let d=l?{entityType:l.entity.entityType,id:l.entity.id}:o.placementAt(s,r);if(d?.entityType!==i.entityType)return D8(i.wrongFolder);if(a.byteLength>n.maxAssetBytes)return ZRr();if(l&&t.onlyIfAbsent)return Jue();if(l&&!HUe(t.ifMatch,l.file.etag))return I8();let p=await i.describe({bytes:a,digest:vmo("sha256").update(a).digest("hex"),extension:r,name:s[s.length-1]??"",existing:l?.entity.metadata});if("status"in p)return p;let m=l?"update":"create",h={id:d.id,entityType:i.entityType,visibility:l?.entity.visibility??"public"},f=await K$(e,c,m,h,[m]);if(f)return f;if(l&&t.ifMatch===null){let R=await e.mount.base();if(R!==void 0&&R.hash!==l.entity.contentHash)return{status:409,message:`The ${i.noun} changed since this drive last read it`}}let g=await n.stageAsset(a,{maxBytes:n.maxAssetBytes,expectedSize:a.byteLength}),y={content:g.ref,metadata:{...p.metadata,sizeBytes:g.sizeBytes}},b={eventContext:Y$(c)},A=await Que(async()=>{if(l)return(await n.updateEntity({entity:{...l.entity,...y},stagedAsset:g,options:{...b,expectedContentHash:l.entity.contentHash}})).skipReason==="content-conflict"?I8():void 0;await n.createEntity({entity:{...h,...y},stagedAsset:g,options:{...b,conditionalWrite:{expectedRevision:null}}});return}),w=A.ok?A.value:WUe(A.error);if(w)return await n.discardStagedAsset(g),w;await NB(n,c,m,"allowed",h);let B=await o.entityAt(s);if(B)await e.mount.held(B.entity.contentHash);return{status:l?204:201,etag:B?.file.etag}}async function $Rr(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!==LRr||s?.entityType!==LRr)return D8("The drive renames notes only, to another note's name");if(await i.entityAt(t.to))return Jue();let a=await K$(e,t.grant,"rename",o,["update"]);if(a)return a;let c=await Que(()=>r.renameEntity({entityType:o.entityType,id:o.id,newId:s.id,options:{expectedContentHash:o.contentHash,eventContext:Y$(t.grant)}}));if(!c.ok)return WUe(c.error);if(!c.value.renamed)return I8();return await NB(r,t.grant,"rename","allowed",o),{status:201}}async function GRr(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(!HUe(t.ifMatch,n.etag))return I8();let o=await K$(e,t.grant,"delete",i,["delete"]);if(o)return o;if(t.ifMatch===null){let a=await e.mount.base();if(a!==void 0&&a.hash!==i.contentHash)return{status:409,message:"The file changed since this drive last read it"}}if(!await e.writes.deleteEntity({entityType:i.entityType,id:i.id,options:{expectedContentHash:i.contentHash,eventContext:Y$(t.grant)}}))return I8();return await e.mount.forget(),await NB(e.writes,t.grant,"delete","allowed",i),{status:204}}function HRr(e,t,r){let i=KRr(t);if(i===void 0)return{status:422,message:"The file is not UTF-8 text"};let n=ZUe(()=>e.deserializeEntity(i,r));return n.ok?{text:i,parsed:n.value}:{status:422,message:fe(n.error,"The file cannot be read")}}async function K$(e,t,r,i,n){let o=t.principal.permissionLevel,s=ZUe(()=>n.forEach((a)=>e.writes.permissions.assertEntityActionAllowed(i.entityType,a,{userPermissionLevel:o})));if(!s.ok)return await NB(e.writes,t,r,"denied",i,"entity-action-policy"),D8(fe(s.error,"Not allowed"));if(r!=="delete"&&!xm(o,i.visibility))return await NB(e.writes,t,r,"denied",i,"visibility-policy"),D8(`Cannot set visibility to "${i.visibility}" at ${o} permission`);return}function NB(e,t,r,i,n,o){return e.recordAudit({actorUserId:t.principal.userId,action:`${$Ue}.entity.${r}.${i}`,targetType:"entity",targetId:n.id,metadata:{entityType:n.entityType,interfaceType:$Ue,outcome:i,...o?{reason:o}:{}}})}async function WRr(e,t,r){let i=await e.tree.entityAt(t.segments);return i?.entity.content===r?i.file.etag:void 0}function Y$(e){return{actor:{kind:"user",userId:e.principal.userId},interfaceType:$Ue}}function HUe(e,t){return e===null||e==="*"||e===t}function Kue(e,t){return e.folderExists(t.segments.slice(0,-1))}function Yue(){return{status:409,message:"The folder does not exist"}}function ZRr(){return{status:413,message:"The file is larger than the drive accepts"}}function Jue(){return{status:412,message:"An entry already exists at this path"}}function WUe(e){return e instanceof Error&&e.name==="EntityWriteConflictError"?Jue():VRr(e)}function D8(e){return{status:403,message:e}}function I8(){return{status:412,message:"The file changed since it was opened"}}function VRr(e){if(l5(e))return{status:422,message:fe(e,"The file cannot be saved")};throw e}function KRr(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return}}function ZUe(e){try{return{ok:!0,value:e()}}catch(t){return{ok:!1,error:t}}}async function Que(e){try{return{ok:!0,value:await e()}}catch(t){return{ok:!1,error:t}}}import{posix as _mo}from"path";var Pmo=new Set([".md",".yaml",...Zu,...e8]),Rmo=600000,Fmo=16777216,YRr=(e,t,r)=>!OB(e.split("/"))&&r-t>=Rmo;function JRr(e){return e.startsWith(".")||!Pmo.has(_mo.extname(e).toLowerCase())}class VUe{files=new Map;folders=new Map;now;kept;opened=new Map;pending=Promise.resolve();constructor(e=Date.now,t=BRr()){this.now=e,this.kept=t}open(e){let t=this.opened.get(e)??this.kept.load(e).then((r)=>{r.forEach(({path:i,bytes:n,modified:o})=>{let s=i.split("/");if(n===void 0)this.foldersOf(e).set(i,o);else this.filesOf(e).set(i,{segments:s,bytes:n,modified:new Date(o),touched:o})})});return this.opened.set(e,t),t}settle(){return this.pending}persist(e){this.pending=this.pending.then(e)}get(e,t){let r=this.live(e).get(t.join("/"));if(r)r.touched=this.now();return r}list(e,t){return[...this.live(e).values()].filter((r)=>r.segments.length===t.length+1&&t.every((i,n)=>r.segments[n]===i)).sort((r,i)=>r.segments.join("/")<i.segments.join("/")?-1:1)}put(e,t,r){let i=this.live(e),n=t.join("/"),o=i.get(n),s=OB(t);if([...i.values()].filter((l)=>OB(l.segments)===s).reduce((l,d)=>l+d.bytes.byteLength,0)-(o?.bytes.byteLength??0)+r.byteLength>(s?kRr:Fmo))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&&OB(t))this.persist(()=>this.kept.remove(e,[r]));return i}hasFolder(e,t){let r=this.liveFolders(e),i=t.join("/");if(!r.has(i))return!1;return r.set(i,this.now()),!0}listFolders(e,t){let r=t.length>0?`${t.join("/")}/`:"";return[...this.liveFolders(e).keys()].filter((i)=>i.startsWith(r)&&!i.slice(r.length).includes("/")).map((i)=>i.slice(r.length)).sort()}makeFolder(e,t){let r=this.liveFolders(e),i=t.join("/"),n=r.has(i),o=this.now();if(r.set(i,o),this.folders.set(e,r),!n&&OB(t))this.persist(()=>this.kept.put(e,{path:i,modified:o}))}removeFolder(e,t){let r=t.join("/"),i=(a)=>a===r||a.startsWith(`${r}/`),n=this.liveFolders(e);if(!n.has(r))return!1;let o=this.live(e),s=[...n.keys(),...o.keys()].filter(i);if(s.forEach((a)=>{n.delete(a),o.delete(a)}),OB(t))this.persist(()=>this.kept.remove(e,s));return!0}forgetFolders(e,t){let r=this.liveFolders(e);t.forEach((i,n)=>r.delete(t.slice(0,n+1).join("/")))}rename(e,t,r){let i=this.get(e,t);if(!i)return"missing";let n=this.put(e,r,i.bytes);if(n==="full")return"missing";return this.delete(e,t),n}foldersOf(e){let t=this.folders.get(e)??new Map;return this.folders.set(e,t),t}filesOf(e){let t=this.files.get(e)??new Map;return this.files.set(e,t),t}liveFolders(e){let t=this.folders.get(e)??new Map,r=this.now();if([...t].forEach(([i,n])=>{if(YRr(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(YRr(i,n.touched,r))t.delete(i)}),t.size===0)this.files.delete(e);return t}}class KUe{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(QRr(e,t),r+30000)}take(e,t){let r=QRr(e,t),i=this.expected.get(r);if(i===void 0)return!1;return this.expected.delete(r),i>this.now()}}function QRr(e,t){return`${e}
|
|
9591
9591
|
${t.join("/")}`}import{createHash as Mmo}from"crypto";var Omo=600000,Nmo=16777216;class YUe{held=new Map;now;capBytes;constructor(e=Date.now,t=Nmo){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-${Mmo("sha256").update(r.bytes).digest("hex")}"`,until:o+Omo});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 Lmo}from"crypto";var XRr=600;class JUe{locks=new Map;now;constructor(e=Date.now){this.now=e}acquire(e,t,r){if(this.live(e))return;let i={token:`opaquelocktoken:${Lmo()}`,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||!eFr(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||eFr(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 eFr(e,t,r){return e.userId===t&&r.includes(`<${e.token}>`)}function tFr(e){let t=/Second-(\d+)/i.exec(e??"")?.[1];return Math.min(t?Number(t):XRr,XRr)}function jmo(e){let t=Ane(e);if(t==="enum"){let r=Sne(e);return r?{type:"enum",enumValues:r}:{type:"enum"}}if(t==="literal")return{type:"string",defaultValue:kne(e)};if(t==="string")return{type:"string"};if(t==="number")return{type:"number"};if(t==="boolean")return{type:"boolean"};if(t==="array")return{type:"array"};if(t==="date")return{type:"date"};return{type:"unknown"}}function zmo(e){let t=[];for(let[r,i]of Object.entries(e.shape)){if(S6(i)?.studioWidget==="hidden")continue;let{inner:n,required:o,defaultValue:s}=wne(i),a=jmo(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 QUe(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:zmo(r)}]})}var Umo={"&":"&","<":"<",">":">"};function LB(e){return e.replace(/[&<>]/g,(t)=>Umo[t]??t)}var rFr="<D:lockscope><D:exclusive/></D:lockscope><D:locktype><D:write/></D:locktype>";function qmo(e){return[`<D:supportedlock><D:lockentry>${rFr}</D:lockentry></D:supportedlock>`,`<D:displayname>${LB(e.displayName)}</D:displayname>`,e.collection?"<D:resourcetype><D:collection/></D:resourcetype>":"<D:resourcetype/>",e.contentLength!==void 0?`<D:getcontentlength>${e.contentLength}</D:getcontentlength>`:"",e.contentType?`<D:getcontenttype>${LB(e.contentType)}</D:getcontenttype>`:"",e.etag?`<D:getetag>${LB(e.etag)}</D:getetag>`:"",e.lastModified?`<D:getlastmodified>${e.lastModified.toUTCString()}</D:getlastmodified>`:""].join("")}function iFr(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:">${e.map((r)=>`<D:response><D:href>${LB(r.href)}</D:href><D:propstat><D:prop>${qmo(r)}</D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>`).join("")}</D:multistatus>`}function nFr(e){return`<?xml version="1.0" encoding="utf-8"?><D:error xmlns:D="DAV:"><D:${e}/></D:error>`}function oFr(e){return`<?xml version="1.0" encoding="utf-8"?><D:prop xmlns:D="DAV:"><D:lockdiscovery><D:activelock>${rFr}<D:depth>0</D:depth><D:timeout>Second-${e.seconds}</D:timeout><D:locktoken><D:href>${LB(e.token)}</D:href></D:locktoken><D:lockroot><D:href>${LB(e.href)}</D:href></D:lockroot></D:activelock></D:lockdiscovery></D:prop>`}function sFr(e){return`<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"><D:response><D:href>${LB(e)}</D:href><D:status>HTTP/1.1 200 OK</D:status></D:response></D:multistatus>`}var $mo=[".brain","changes"],Gmo=50,aFr=25,cFr=[".brain","conflicts"],Hmo=".brain",Wmo=65536,Zmo=1024,Vmo=[".brain","publish"],Kmo=u.object({path:u.string().min(1).max(Zmo)}),lFr=".brain/ask",uFr=".brain/ask/confirm",Ymo=[".brain","related"],dFr=10,Jmo=25,Qmo=[".brain","vault-shapes.json"],Xmo=["OPTIONS","GET","HEAD","PROPFIND"],gFr=["POST","PUT","DELETE","MOVE","COPY","PROPPATCH","MKCOL","LOCK","UNLOCK"],yFr=[...Xmo,...gFr],eho=yFr.filter((e)=>e!=="POST").join(", "),tde='application/xml; charset="utf-8"',tho={"X-Content-Type-Options":"nosniff","Content-Security-Policy":"sandbox","Cache-Control":"no-store"};function bFr(e){let t={options:e,mounts:e.mounts??wRr(e.now),scratch:new VUe(e.now,e.kept),locks:new JUe(e.now),cleanups:new KUe(e.now),holds:new YUe(e.now)},r={GET:(i,n)=>hFr(i,n,!0),HEAD:(i,n)=>hFr(i,n,!1),PROPFIND:nho,POST:dho,PUT:oho,DELETE:fho,MOVE:yho,COPY:async()=>V7("The drive does not copy files"),PROPPATCH:xho,MKCOL:gho,LOCK:vho,UNLOCK:Aho};return yFr.map((i)=>({path:e.basePath,match:"prefix",method:i,public:!0,handler:async(n)=>{if(i==="OPTIONS")return J$(kho());let o=await e.resolveAppPassword(n);if(!o)return J$(Bho(e.realm));if(pFr(i)&&o.access!=="write")return J$(V7("This app password is read-only"));let s=n.headers.get("x-brain-sync")?.trim()==="1",a={request:n,grant:o,tree:new qUe(e.reader,ai(o.principal.permissionLevel),{everyType:s}),path:DFr(e.basePath,new URL(n.url).pathname),sync:s};if(pFr(i)&&i!=="LOCK"&&i!=="UNLOCK"&&a.path&&!EFr(t,a,a.path.segments))return J$(nqe());await t.scratch.open(o.principal.userId);let c=await r[i](t,a);return await t.scratch.settle(),J$(c)}}))}function EFr(e,t,r){return e.locks.permits(r,t.grant.principal.userId,t.request.headers.get("if"))}function pFr(e){return gFr.some((t)=>t===e)}function rde(e,t){let{path:r}=t;return r&&!r.asFolder&&Z7(r.segments)?e.scratch.get(t.grant.principal.userId,r.segments):void 0}function Z7(e){let t=e[e.length-1];return t!==void 0&&(vFr(e)||JRr(t))}function vFr(e){return e.some((t)=>t.startsWith("."))}async function ide(e,t){if(!t.path)return;let r=await t.tree.resolve(t.path.segments);if(r)return r.kind==="file"&&t.path.asFolder?void 0:r;return e.scratch.hasFolder(t.grant.principal.userId,t.path.segments)?{kind:"folder",segments:t.path.segments}:void 0}async function rqe(e,t,r){return r.length===0||e.scratch.hasFolder(t.grant.principal.userId,r)||(await t.tree.resolve(r))?.kind==="folder"}async function iqe(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 AFr(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 iqe(e,t,n):void 0)?.etag===i?null:i}async function rho(e,t){let r=new URL(t.request.url).searchParams,i=Number(r.get("wait")??aFr),n=Number.isFinite(i)?Math.min(Math.max(i,0),Gmo):aFr,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 iho(e){let t=new URL(e.request.url).searchParams,r=t.get("path")??"";if(r==="")return new Response("Name the file with ?path=",{status:400});let i=Number(t.get("limit")??dFr),n=Number.isInteger(i)&&i>0?Math.min(i,Jmo):dFr,o=await e.tree.related(r.split("/"),n)??[];return new Response(JSON.stringify(o==="unindexed"?{related:[],indexed:!1}:{related:o,indexed:!0}),{status:200,headers:{"Content-Type":"application/json; charset=utf-8"}})}async function mFr(e,t,r){let i=eqe(r,e.options.basePath),n=await iqe(e,t,r);return n?{...i,contentLength:n.bytes.byteLength,etag:n.etag,lastModified:n.savedAt}:i}function wFr(e,t){let r=t.grant.appPasswordId,i=(t.path?.segments??[]).join("/");return{base:()=>e.mounts.get(r,i),held:(n)=>e.mounts.held(r,i,n),conflictKept:(n,o)=>e.mounts.conflictKept(r,i,n,o),forget:()=>e.mounts.forget(r,i)}}function nde(e,t){return{tree:t.tree,reader:e.options.reader,writes:e.options.writes,mount:wFr(e,t),recordConflict:async(r)=>e.options.recordConflict?.(r),folderExists:(r)=>rqe(e,t,r)}}async function hFr(e,t,r){let{shapes:i,changes:n}=e.options;if(t.sync&&t.path?.segments.join("/")===Ymo.join("/"))return iho(t);if(t.sync&&n!==void 0&&t.path?.segments.join("/")===$mo.join("/"))return rho(n,t);if(t.sync&&i!==void 0&&t.path?.segments.join("/")===Qmo.join("/")){let c=JSON.stringify({shapes:QUe(i).filter((l)=>l.entityType===V$||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=rde(e,t);if(o)return new Response(r?o.bytes:null,{status:200,headers:{"Content-Type":"application/octet-stream","Content-Disposition":"attachment","Content-Length":String(o.bytes.byteLength),ETag:CFr(o),"Last-Modified":o.modified.toUTCString()}});let s=await ide(e,t);if(!s)return Ah();if(s.kind==="folder")return tqe();let a=await iqe(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 wFr(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 nho(e,t){let r=t.request.headers.get("depth");if(r!=="0"&&r!=="1")return new Response(nFr("propfind-finite-depth"),{status:403,headers:{"Content-Type":tde}});let{basePath:i}=e.options,n=rde(e,t);if(n)return XUe([xFr(n,i)]);let o=await ide(e,t);if(!o)return Ah();if(o.kind==="file"||r==="0")return XUe([await mFr(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 XUe([eqe(o,i),...await Promise.all(a.map((l)=>mFr(e,t,l))),...e.scratch.listFolders(s,o.segments).filter((l)=>!c.has(l)).map((l)=>eqe({kind:"folder",segments:[...o.segments,l]},i)),...e.scratch.list(s,o.segments).map((l)=>xFr(l,i))])}async function oho(e,t){let{path:r}=t;if(!r)return Ah();if(r.asFolder||r.segments.length===0)return tqe();let{maxFileBytes:i,maxAssetBytes:n}=e.options.writes,o=await BFr(t.request,Math.max(i,n)),s=t.grant.principal.userId,a=Z7(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 rqe(e,t,r.segments))return tqe();return kFr(e.scratch.put(s,r.segments,o))}let c=await GUe(nde(e,t),{segments:r.segments,bytes:o,ifMatch:await AFr(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 sho(e,t,r.segments,o,c);if("message"in c||c.etag===void 0)e.cleanups.expect(s,r.segments);return await cho(e,t,r.segments,o,c),X$(e,t,r.segments,c)}async function sho(e,t,r,i,n){if("message"in n)return X$(e,t,r,n);e.holds.release(t.grant.appPasswordId,r);let o=await t.tree.entityAt(r),s={};if(o)s.ETag=o.file.etag,s["X-Brain-Stored"]=n.conflictId!==void 0?"conflict":await aho(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 aho(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 cho(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 lho(e){let t=await BFr(e,Wmo);if(!t)return SFr;try{return JSON.parse(new TextDecoder().decode(t))}catch{return}}var SFr=Symbol("too large");function uho(){return new Response("The request is too large",{status:413})}async function dho(e,t){let r=t.sync?t.path?.segments.join("/"):void 0,i=()=>({tree:t.tree,grant:t.grant,ask:e.options.ask,confirmAsk:e.options.confirmAsk}),n=[lFr,uFr,Vmo.join("/")];if(r===void 0||!n.includes(r))return new Response("The drive takes no POST here",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}});let o=await lho(t.request);if(o===SFr)return uho();if(r===lFr)return FRr(i(),o);if(r===uFr)return MRr(i(),o);return pho(e,t,o)}async function pho(e,t,r){let i=Kmo.safeParse(r);if(!i.success)return new Response('Name the file: { "path": "\u2026" }',{status:400});let n=await t.tree.entityAt(i.data.path.split("/"));if(!n)return new Response("There is no entry at this path.",{status:409});let o=await e.options.publish?.({entityType:n.entity.entityType,id:n.entity.id,userId:t.grant.principal.userId,permissionLevel:t.grant.principal.permissionLevel});if(!o)return new Response("Nothing publishes here right now.",{status:503});if("message"in o)return new Response(o.message,{status:409});return new Response(JSON.stringify(o),{status:200,headers:{"Content-Type":"application/json; charset=utf-8"}})}function mho(e){let[t,r,i,...n]=e;return t===cFr[0]&&r===cFr[1]&&i!==void 0&&n.length===0?i:void 0}async function hho(e,t,r){return await e.options.resolveConflict?.({conflictId:r,action:"keep-current",userId:t.grant.principal.userId,permissionLevel:t.grant.principal.permissionLevel})?Xue():new Response("Conflicts cannot be settled here right now.",{status:503})}async function fho(e,t){let{path:r}=t;if(!r)return Ah();let i=t.sync&&!r.asFolder?mho(r.segments):void 0;if(i!==void 0)return hho(e,t,i);let n=t.grant.principal.userId;if(e.scratch.removeFolder(n,r.segments))return Xue();if(!r.asFolder&&Z7(r.segments)){if(e.scratch.delete(n,r.segments))return Xue()}if(r.segments.length===0||(await t.tree.resolve(r.segments))?.kind==="folder")return V7("The drive does not delete folders");if(r.asFolder)return Ah();if(t.request.headers.get("if-match")===null&&e.cleanups.take(n,r.segments))return new Response("The file is kept: the save just before was refused or stored in another form. Delete it again to remove it.",{status:409});let o=await GRr(nde(e,t),{segments:r.segments,ifMatch:await AFr(e,t,r.segments),grant:t.grant});if(!("message"in o))e.holds.release(t.grant.appPasswordId,r.segments);return X$(e,t,r.segments,o)}async function xho(e,t){let r=rde(e,t)??await ide(e,t);if(!r||!t.path)return Ah();let i="kind"in r&&r.kind==="folder",n=Q$(t.path.segments);return new Response(sFr(`${e.options.basePath}/${n}${i&&n?"/":""}`),{status:207,headers:{"Content-Type":tde}})}async function gho(e,t){let{path:r}=t;if(!r)return Ah();if((await t.request.arrayBuffer()).byteLength>0)return new Response("MKCOL takes no body",{status:415});let{segments:i}=r,n=t.grant.principal.userId;if(i.length===0||await t.tree.resolve(i)||e.scratch.hasFolder(n,i)||e.scratch.get(n,i))return new Response("Already exists",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}});if(!await rqe(e,t,i.slice(0,-1)))return new Response("The parent folder does not exist",{status:409});let[o]=i;if(!vFr(i)&&(o===void 0||!t.tree.isFolderType(o)))return V7("Only an entity type can be a folder here");return e.scratch.makeFolder(n,i),new Response(null,{status:201})}async function yho(e,t){let r=t.request.headers.get("destination");if(!r)return new Response("Destination required",{status:400});let i=who(e.options.basePath,t.request,r);if(!i)return new Response("Destination is not on this drive",{status:502});let{path:n}=t;if(!n)return Ah();if(!EFr(e,t,i.segments))return nqe();let o=t.request.headers.get("overwrite")?.toUpperCase()!=="F";if(n.asFolder)return V7("The drive does not rename files");if(!Z7(n.segments))return Z7(i.segments)?Eho(e,t,n.segments,i.segments,o):bho(e,t,n.segments,i.segments);let s=t.grant.principal.userId,a=e.scratch.get(s,n.segments);if(!a)return Ah();if(Z7(i.segments)){if(!o&&e.scratch.get(s,i.segments))return ede("The destination exists");let l=e.scratch.rename(s,n.segments,i.segments);return l==="missing"?Ah():new Response(null,{status:l==="created"?201:204})}if(!o&&await t.tree.entityAt(i.segments))return ede("The destination exists");let c=await GUe(nde(e,t),{segments:i.segments,bytes:a.bytes,ifMatch:null,grant:t.grant});if(c.status<300)e.scratch.delete(s,n.segments),e.holds.release(t.grant.appPasswordId,i.segments);return X$(e,t,i.segments,c)}async function bho(e,t,r,i){let n=await $Rr(nde(e,t),{from:r,to:i,grant:t.grant});if(n.status<300){let o=t.grant.appPasswordId,s=await e.mounts.get(o,r.join("/"));if(await e.mounts.forget(o,r.join("/")),s)await e.mounts.held(o,i.join("/"),s.hash);e.holds.release(o,r)}return X$(e,t,i,n)}async function Eho(e,t,r,i,n){let o=await t.tree.entityAt(r);if(!o)return Ah();let s=t.grant.principal.userId;if(!n&&e.scratch.get(s,i))return ede("The destination exists");let a=new Uint8Array(await new Response(await o.file.open()).arrayBuffer());return kFr(e.scratch.put(s,i,a))}async function vho(e,t){let{path:r}=t;if(!r||r.segments.length===0)return Ah();if(r.segments[0]===Hmo)return V7("There is nothing to lock here");let i=t.grant.principal.userId,n=tFr(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?fFr(e,r.segments,l,200):ede("No such lock to refresh")}let a=e.locks.acquire(r.segments,i,n);if(!a)return nqe();let c=rde(e,t)!==void 0||await ide(e,t)!==void 0;return fFr(e,r.segments,a,c?200:201)}function fFr(e,t,r,i){return new Response(oFr({...r,href:`${e.options.basePath}/${Q$(t)}`}),{status:i,headers:{"Content-Type":tde,"Lock-Token":`<${r.token}>`}})}async function Aho(e,t){let{path:r}=t;if(!r)return Ah();let i=/<([^>]+)>/.exec(t.request.headers.get("lock-token")??"")?.[1];if(!i)return new Response("Lock-Token required",{status:400});return e.locks.release(r.segments,t.grant.principal.userId,i)?Xue():new Response("No such lock",{status:409})}function X$(e,t,r,i){if("message"in i)return new Response(i.message,{status:i.status});if(i.status===201)e.scratch.forgetFolders(t.grant.principal.userId,r.slice(0,-1));return new Response(null,{status:i.status,headers:i.etag?{ETag:i.etag}:{}})}function kFr(e){return e==="full"?new Response("Too many temporary files",{status:507}):new Response(null,{status:e==="created"?201:204})}async function BFr(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 eqe(e,t){let r=e.segments[e.segments.length-1]??"";if(e.kind==="folder"){let i=Q$(e.segments);return{href:i?`${t}/${i}/`:`${t}/`,displayName:r,collection:!0}}return{href:`${t}/${Q$(e.segments)}`,displayName:r,collection:!1,contentLength:e.size,contentType:e.contentType,etag:e.etag,lastModified:e.modified}}function xFr(e,t){return{href:`${t}/${Q$(e.segments)}`,displayName:e.segments[e.segments.length-1]??"",collection:!1,contentLength:e.bytes.byteLength,contentType:"application/octet-stream",etag:CFr(e),lastModified:e.modified}}function CFr(e){return`"scratch-${e.modified.getTime()}-${e.bytes.byteLength}"`}function Q$(e){return e.map(encodeURIComponent).join("/")}function DFr(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(Sho);return o.every((s)=>s!==void 0&&s!==""&&!/[/\\\0]/.test(s))?{segments:o.filter((s)=>s!==void 0),asFolder:i}:void 0}function who(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=DFr(e,n.pathname);return o&&!o.asFolder&&o.segments.length>0?o:void 0}function Sho(e){try{return decodeURIComponent(e)}catch{return}}function XUe(e){return new Response(iFr(e),{status:207,headers:{"Content-Type":tde}})}function kho(){return new Response(null,{status:200,headers:{DAV:"1, 2",Allow:eho,"MS-Author-Via":"DAV"}})}function Bho(e){return new Response("Authentication required",{status:401,headers:{"WWW-Authenticate":`Basic realm="${e.replace(/["\\]/g,"")}", charset="UTF-8"`}})}function tqe(){return new Response("A folder has no content",{status:405,headers:{Allow:"OPTIONS, PROPFIND"}})}function Xue(){return new Response(null,{status:204})}function Ah(){return new Response("Not found",{status:404})}function V7(e){return new Response(e,{status:403})}function nqe(){return new Response("The file is locked",{status:423})}function ede(e){return new Response(e,{status:412})}function J$(e){let t=new Headers(e.headers);return Object.entries(tho).forEach(([r,i])=>t.set(r,i)),new Response(e.body,{status:e.status,headers:t})}var oqe="/dav",Cho=5242880,IFr=u.strictObject({maxFileBytes:u.number().int().positive().describe("Maximum bytes of a file a client may save").default(Cho)}),Dho=zt({id:"webdav",config:IFr,setup:(e)=>{let t=bt(e);if(t.executionOnly)return{routes:[]};t.registered(()=>{if(t.entityReads.getEntityTypes().includes(us))return;throw Error(`webdav needs the "${us}" entity type to keep saves that lose to a newer version. Add "conflict" to this brain, which the core bundle includes.`)});let r=new jUe;for(let n of[ma,fs,lp,Sb])t.listen(n,({payload:o})=>r.record(o.entityType),{mode:"observe"});t.listen(uo.shuttingDown,()=>r.close(),{mode:"observe"});let i=SRr(t.classRuntimeState);return t.ready(()=>i.sweep()),t.interaction({id:Wne,label:"Drive",description:"Mount the brain as a network drive over WebDAV.",href:`${oqe}/`,kind:"protocol",priority:40,visibility:"trusted"}),{routes:bFr({basePath:oqe,realm:t.identity.get().name,reader:t.entityReads,shapes:t.entityShapes,changes:r,writes:{maxFileBytes:e.config.maxFileBytes,maxAssetBytes:kT,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:CRr(t.classRuntimeState),recordConflict:async(n)=>{let o=await t.messaging.request(LS,n);return o.status==="answered"?o.data.conflictId:void 0},ask:async(n)=>{let o=await t.messaging.request(ode,n);if(o.status==="answered")return o.data;return o.status==="failed"?{message:o.error.message}:void 0},confirmAsk:async(n)=>{let o=await t.messaging.request(sde,n);if(o.status==="answered")return o.data;return o.status==="failed"?{message:o.error.message}:void 0},publish:async(n)=>{let o=await t.messaging.request(ooe,n);if(o.status==="answered")return o.data;return o.status==="failed"?{message:o.error.message}:void 0},resolveConflict:async(n)=>{let o=await t.messaging.request(qI,n);if(o.status==="answered")return{resolved:!0};return o.status==="failed"?{message:o.error.message}:void 0},conflictPending:async(n)=>await t.entityReads.getEntityRaw({entityType:us,id:n,visibilityScope:ot("ask only whether a conflict is still waiting to be resolved")})!==null})}}}),sqe=ko(Dho,({state:e})=>e.routes);var TFr=sqe;var Iho=u.object({errcode:u.string()}),Tho=u.object({session:u.string()});async function aqe(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 _Fr(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=Tho.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 _Fr(d)??d.status}`);return"registered"}async function _Fr(e){let t=Iho.safeParse(await e.json().catch(()=>{return}));return t.success?t.data.errcode:void 0}var cqe="matrix-homeserver";function ade(e){return`${e.replace(/\/+$/,"")}/_matrix/client/unstable/login/sso/callback/matrix-homeserver`}function Jy(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`}function lqe(e){let t=e.publicBaseUrl.replace(/\/+$/,"");return`[global]
|
|
9592
9592
|
server_name = ${Jy(e.serverName)}
|
|
@@ -11176,5 +11176,5 @@ ${Xpe}</style><link rel="stylesheet" href="${Swo}"></head><body class="guest-pag
|
|
|
11176
11176
|
`);return{kind:"text",filename:"inbox-source.txt",mediaType:"text/plain",content:l,sizeBytes:new TextEncoder().encode(l).byteLength}}catch{return bWe()}}async readEntryContext(e,t){let r=_$r(e);if(!r)return null;let i=await this.runtime.request(Vne,{...r,visibilityScope:ai(t)}).catch(()=>null);return i?.status==="answered"?i.data:null}async handleContextSessionRequest(e){let t=Ea(e);if(t)return t;return Iqr(e,{conversations:this.runtime.conversations,resolveAccess:(r)=>this.resolveConversationAccess(r),interfaceType:om,authorizeSource:async({sourceId:r,itemId:i,permissionLevel:n,signal:o})=>{if(r===EWe)return await this.readEntryContext(i,n)!==null;let s=this.runtime.inbox.getSource(r);if(!s?.resolveDetail)return!1;return await s.resolveDetail(i,{permissionLevel:n},o),!0}})}async handleSessionsRequest(e){return jqr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:om})}async handleDeleteSessionRequest(e){return zqr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:om})}async handleRenameSessionRequest(e){return Uqr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:om})}async handleArchiveSessionRequest(e){return qqr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:om})}async handleDocumentAttachmentRequest(e){return jUr(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleImageAttachmentRequest(e){return zUr(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleJobStatusRequest(e){return Pqr(e,{resolveAuthSession:this.resolveAuthSession,createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),jobs:this.runtime.jobs})}async handleMessagesRequest(e){return Hqr(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:om})}async resolveConversationAccess(e){let t=await this.resolveBrowserAccess(e);return this.toConversationAccess(t.permissionLevel,t.principal)}toConversationAccess(e,t){return{permissionLevel:e,...t?{personId:t.personId}:{}}}requireExistingWebChatConversation(e,t){return this.requireExistingBrowserConversation(e,om,t)}ensureWebChatConversation(e,t){return this.ensureBrowserConversation(e,om,"Web Chat",t)}async requireExistingBrowserConversation(e,t,r){let i=await this.runtime.conversations.get(e);return ob(i,r,t)?void 0:new Response("Conversation not found",{status:404})}async ensureBrowserConversation(e,t,r,i){let n=await this.runtime.conversations.get(e);if(n)return ob(n,i,t)?void 0:new Response("Conversation not found",{status:404});if(i.permissionLevel==="trusted"&&!i.personId)return new Response("Forbidden",{status:403});await this.runtime.conversations.start({sessionId:e,interfaceType:t,channelId:e,...i.personId?{personId:i.personId}:{},metadata:{channelName:r,interfaceType:t,channelId:e}});let o=await this.runtime.conversations.get(e);return ob(o,i,t)?void 0:new Response("Conversation not found",{status:404})}getActiveStream(e){if(!e)return;return this.activeStreams.get(e)}async resolveBrowserAccess(e){let t=await this.resolveAuthPrincipal(e);if(t){let i=t.status==="active"&&(t.permissionLevel==="admin"||t.permissionLevel==="trusted");return{principal:t,permissionLevel:i?t.permissionLevel:"public",hasChatAccess:i}}if(this.resolveCallerPermissionLevel){let i=await this.resolveCallerPermissionLevel(e);return{permissionLevel:i,hasChatAccess:i==="admin"||i==="trusted"}}let r=this.resolveAuthSessionOverride?await this.resolveAuthSessionOverride(e):!1;return{permissionLevel:r?"admin":"public",hasChatAccess:r}}async resolvePermissionLevel(e){return(await this.resolveBrowserAccess(e)).permissionLevel}async resolveAttachmentPermissionLevel(e){return this.resolvePermissionLevel(e)}createAuthLoginRequiredResponse(e){let t=this.runtime.auth();if(t)return t.createAuthLoginResponse(e);return new Response("Authentication required",{status:401,headers:{"Content-Type":"text/plain; charset=utf-8"}})}writeText(e,t,r){return Ype(e,t,r,(i)=>this.createId(i))}createId(e){return`${e}-${crypto.randomUUID()}`}}function bWe(){return new Response("Inbox context is unavailable",{status:409})}function vWe(e={}){let t=_h({id:om,config:oWe,setup:async(n)=>{let o=Jo(n),s=new F$r(n.config,e,o,n.runtimeState(JT));return await s.register(),o.ready(()=>s.onReady()),s}}),r=ko(t,({state:n})=>n.webRoutes()),i=Kx(r,({state:n})=>{let o=n.maintenanceDaemon();return{id:"guest-maintenance",start:()=>o.start(),stop:()=>o.stop(),healthCheck:()=>o.healthCheck()}});return Ene(i,({state:n})=>n.transport())}var a1o=vWe(),M$r=a1o;var AWe='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 O$r={critical:0,high:1,medium:2,low:3};function N$r(e){return[...e].sort((t,r)=>{let i=r.metadata.requested-t.metadata.requested;if(i!==0)return i;return O$r[t.metadata.priority]-O$r[r.metadata.priority]})}var YG=u.enum(["new","planned","in-progress","done","declined"]),JG=u.enum(["low","medium","high","critical"]),dme=u.object({title:u.string(),status:YG,priority:JG.default("medium"),requested:u.number().int().default(1).meta({studioWidget:"provenance"}),declinedReason:u.string().optional()}),wWe=u.object({title:u.string(),status:YG,priority:JG,requested:u.number().int().meta({studioWidget:"provenance"}),slug:u.string().optional().meta({studioWidget:"hidden"}),declinedReason:u.string().optional()});var c1o=u.object({items:u.array(u.object({id:u.string(),name:u.string(),count:u.number().int().nonnegative(),priority:JG,status:YG}))});function l1o(e){if(e==="critical")return"error";if(e==="high")return"warn";return"neutral"}var SWe=ro({id:"top-wishes",title:"Top Wishes",group:"knowledge",placement:"secondary",priority:30,permission:"public",data:c1o,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:l1o(t.priority)},{label:t.status,tone:t.status==="done"?"good":"neutral"}]}))}]})});function u1o(e){return SWe.bind(e,async({entities:t,signal:r})=>(r.throwIfAborted(),{items:N$r(await t.list(ab,{limit:10})).map((n)=>({id:n.id,name:n.metadata.title,count:n.metadata.requested,priority:n.metadata.priority,status:n.metadata.status}))}))}var ab=Vi(dt({type:"wish",purpose:"A demand record the assistant proactively creates when a user requests a capability or outcome no installed tool can fulfill, unless the user declines.",metadata:wWe,markdown:{decode:({content:e,frontmatter:t})=>{let r=dme.parse(t);return{content:e,metadata:{title:r.title,status:r.status,priority:r.priority,requested:r.requested,slug:Lt(r.title),...r.declinedReason!==void 0&&{declinedReason:r.declinedReason}}}},encode:({content:e,metadata:t})=>({content:e,frontmatter:{title:t.title,status:t.status,priority:t.priority,requested:t.requested,...t.declinedReason!==void 0&&{declinedReason:t.declinedReason}}})},config:{projectionSource:!1,projectionSourceRole:"excluded"},instructions:AWe,dashboardWidgets:(e)=>[u1o(e)]}),dme);var L$r=0.3,d1o="Do these two wishes ask for the same thing?",p1o=u.object({same:u.boolean().describe("True only when delivering one would fulfil the other.")});async function m1o(e,t,r){let{same:i}=await e.generateObject([d1o,"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(`
|
|
11177
11177
|
`),p1o);return i}function pme(e,t,r){return{nearest:(i,n)=>e.nearest(ab,i,{maxDistance:n}),getEntity:(i)=>t.get(ab,i),maxDistance:r,ai:e}}async function mme(e,t){let r=(await e.nearest(t.content,e.maxDistance)).flatMap(({entity:s})=>s.visibility==="public"?[s]:[]),i=async(s)=>{let a=r[s];if(!a)return;return await m1o(e.ai,t.content,h1o(a))?a:i(s+1)},n=await i(0);if(n)return n;let o=await e.getEntity(Lt(t.title));return o?.visibility==="public"?o:null}function h1o(e){let{title:t,status:r,priority:i,requested:n,declinedReason:o}=e.metadata;return QG({title:t,status:r,priority:i,requested:n,declinedReason:o},e.content)}function QG(e,t){let r=Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0&&i!==null));return Object.keys(r).length>0?fi(r,t):t}var j$r=u.object({title:u.string(),description:u.string()}),f1o=u.object({stored:j$r,incoming:j$r}),kWe="eval-stored-wish";function z$r(e){return QG({title:e.title,status:"new",priority:"medium",requested:1},e.description)}function U$r(e){return{sameWish:async(t,r)=>{let{stored:i,incoming:n}=f1o.parse(t),{fixtures:o}=r;await o.reset(),await o.seed({id:kWe,entityType:"wish",content:z$r(i),metadata:{title:i.title,status:"new",priority:"medium",requested:1,slug:Lt(i.title)}}),await o.settleEmbeddings();let s=$t(r),a=z$r(n),c=(await s.nearest(ab,a,{maxDistance:2})).find(({entity:d})=>d.id===kWe)?.distance;if(c===void 0)throw Error("The stored wish was not embedded");let l=await mme(pme(s,r.entities,e),{title:n.title,content:a});return{distance:c,shortlisted:c<=e,sameWish:l?.id===kWe}}}}async function x1o(e,t){let{input:r}=e;if(r.visibility!==void 0&&r.visibility!=="public")return{refuse:"Wish creation currently supports public visibility only; use a note for shared or restricted capture."};let i=r.title??r.prompt??"Untitled wish",n=r.content??r.prompt??"",o={title:i,status:"new",priority:"medium",requested:1},s=await mme(pme($t(e),e.entities,t),{title:i,content:QG(o,n)});if(s)return{update:{id:s.id,content:s.content.trim(),metadata:{...s.metadata,requested:s.metadata.requested+1}}};let a=Lt(i);return{create:{id:a,content:n,metadata:{...o,slug:a}}}}function q$r(e){let t={resolve:(r)=>x1o(r,e)};return{fromPrompt:t,fromContent:t,fromUpload:t}}var BWe=u.object({sameWishDistance:u.number().min(0).max(1).default(L$r)});var g1o=Pi({id:"wishlist",config:BWe,entities:[ab],configure:({config:e})=>({entities:[{entity:ab,create:q$r(e.sameWishDistance),evals:U$r(e.sameWishDistance)}]})}),$$r=g1o;var G$r="gpt-6-luna";var OA={create:"trusted",update:"trusted",delete:"admin",extract:"admin",publish:"admin"},H$r=[{member:"content-pipeline",value:{generationSchedules:{newsletter:"0 9 * * 1","social-post":"0 10 * * *"},generationConditions:{newsletter:{skipIfDraftExists:!0,minSourceEntities:1,sourceEntityType:"post"},"social-post":{skipIfDraftExists:!0,maxUnpublishedDrafts:5}}}},{member:"social-media",value:{autoGenerateOnBlogPublish:!0}}],W$r=["Use the installed publishing capabilities for professional website content, essays, projects, decks, newsletters, and social distribution workflows. Treat publishing requests as production and distribution work rather than generic shared-memory capture.",`When answering questions like "what have I written about X" or "which posts relate to this deck/source", search first and use semantic search results as candidates, not proof. Summarize only clearly relevant entities whose title or content directly matches the asked topic or has substantial overlap with the source's main themes; omit weak/tangential candidates rather than presenting them as definite matches. A match based on only an isolated shared term or pattern is not enough; when one candidate is clearly stronger than the rest, list only the strongest clear match and say the others were tangential rather than naming them as matches.`,'Draft blog posts are only post entities with status draft. If the user asks whether draft blog posts exist, call only system_list for entityType post with status draft; do not also list social-post, newsletter, deck, or other draft entity types. After telling the user there are no draft blog posts, treat follow-ups like "make one draft" or "make one a draft" as requests to change an existing published post back to draft: ask which existing published post they want changed; do not offer to create a brand-new post and do not call system_generate to create a fresh draft from that ambiguous follow-up.'],Z$r=[{member:"topics",value:{extractableStatuses:["published","draft"]}},{member:"conversation-memory",value:{memoryVisibility:"shared"}},{member:"action-board",value:{cardVisibility:"shared"}}],V$r=["This is a collaborative team-memory and synthesis posture. Optimize for capturing shared context, finding what the team already knows, summarizing cross-source evidence with attribution, and coordinating with peer brains.","Do not default to personal publishing, personal branding, blog, newsletter, social-media, portfolio, or marketing workflows unless the installed capabilities and the user's request explicitly support them."];var j8="capability-bundles-v1",CWe="core",DWe="media",IWe="automation",XG="web",TWe="chat",_We="site",PWe="publishing",RWe="federation",FWe="team",y1o="matrix",hme=pm({id:CWe,members:["profile","prompt","conflict","style-guide","directory-sync","note","refined-note","link","topics","unified-inbox","mcp","a2a","agents"],evalDisable:["mcp"]}),fme=pm({id:DWe,members:["document","image"]}),xme=pm({id:IWe,members:["playbooks","onboarding"]}),gme=pm({id:XG,members:["auth-service","admin","dashboard","studio","webdav"],http:!0,config:[{member:"dashboard",value:{routePath:"/"}}],permissions:[{member:"mcp",config:{rules:[{pattern:"mcp:http",level:"public"}]}},{member:"studio",config:{entityActions:{"grouping-definitions":{create:"admin",update:"admin",delete:"admin",publish:"never"}}}}],evalDisable:["dashboard"]}),yme=pm({id:TWe,members:["chat","web-chat","ask-content","email","notifications","conversation-memory","faq"],permissions:[{member:"chat",config:{rules:[{pattern:"discord:*",level:"public"}]}},{member:"web-chat",config:{rules:[{pattern:"web-chat:*",level:"admin"}]}}],evalDisable:["chat","web-chat","email","faq"]}),bme=pm({id:_We,members:["site-info","site-content","site-builder","form","analytics"],config:[{member:"dashboard",value:{routePath:"/dashboard"},overrides:XG}]}),Eme=pm({id:PWe,members:["blog","series","portfolio","decks","content-pipeline","social-media","newsletter","stock-photo"],config:H$r,agentInstructions:W$r}),vme=pm({id:RWe,members:["atproto","references"],evalDisable:["atproto"]}),Ame=pm({id:FWe,members:[],config:Z$r,permissions:[{member:"note",config:{entityActions:{note:OA}}},{member:"refined-note",config:{entityActions:{"refined-note":OA}}},{member:"link",config:{entityActions:{link:OA}}},{member:"image",config:{entityActions:{image:OA}}},{member:"docs",config:{entityActions:{doc:OA}}},{member:"conversation-memory",config:{entityActions:{decision:OA,insight:OA,"action-item":OA}}},{member:"mcp",config:{rules:[{pattern:"mcp:http",level:"admin"}]},overrides:XG}],agentInstructions:V$r}),b1o=pm({id:y1o,members:["matrix-server"],http:!0,permissions:[{member:"chat",config:{rules:[{pattern:"matrix:*",level:"public"}]}}]}),K$r=[hme,fme,xme,gme,yme,bme,Eme,vme,b1o,Ame];function tH(e,t,r){let i={name:e,version:z8.version};return(n)=>mm(t,n,i,r)}function E1o(e){let{entity:t,provider:r}=vPr(e),i={name:"@brains/newsletter",version:z8.version};return[...mm(t.definition,t.config,i,{pluginId:"newsletter"}),...r?mm(r.definition,r.config,i,{pluginId:r.kind}):[]]}function $r(e,t,r,i={},n=void 0){return[e,tH(t,r,i),n]}function eH(e,t,r,i,n={}){return[e,tH(t,r,n),i]}var Y$r=Kme({name:"brain",version:z8.version,bundleContract:j8,model:G$r,reasoningEffort:"low",capabilities:[$r("prompt","@brains/prompt",kOr,{pluginId:"prompt"}),$r("conflict","@brains/conflict",wOr,{pluginId:"conflicts"}),$r("profile","@brains/profile",o$e,{pluginId:"profile"}),$r("style-guide","@brains/style-guide",Bjr,{pluginId:"style-guide"}),$r("ask-content","@brains/ask-content",Djr,{pluginId:"ask-content"}),["image",(e)=>[...tH("@brains/image-plugin",m_r,{pluginId:"image"})(e),...tH("@brains/image-plugin",p_r,{})({})],void 0],$r("document","@brains/document-plugin",PSr,{pluginId:"document"}),$r("note","@brains/note",NPr,{pluginId:"note"}),$r("refined-note","@brains/refined-note",DOr,{pluginId:"refined-note"}),$r("link","@brains/link",I_r,{pluginId:"link"}),$r("references","@brains/reference",W_r,{pluginId:"references",ownedTypePluginId:"reference"}),$r("wishlist","@brains/wishlist",$$r,{pluginId:"wishlist"}),["topics",(e)=>[...mm(Bzr,e,{name:"@brains/topics",version:z8.version},{pluginId:"topics"}),...mm(kHe,{},{name:"@brains/knowledge-map",version:z8.version},{pluginId:"knowledge-map"})],void 0],$r("decks","@brains/decks",WEr,{pluginId:"decks"}),$r("directory-sync","@brains/directory-sync",Bwr,{pluginId:"directory-sync"},{seedContent:!0,seedContentPath:"./seed-content",initialSync:!0}),$r("atproto-registry","@brains/atproto-registry",$ye,{pluginId:"atproto-registry"}),["agents",(e)=>{let{enableSkillDerivation:t,notifyOnNewAgents:r,askAllApproved:i}=vrt.parse(e),n={name:"@brains/agent-discovery",version:z8.version};return[...mm(Gge,{},n,{pluginId:"agent-discovery",ownedTypePluginId:"agent-entity"}),...mm(Hge,{notifyOnNewAgents:r,askAllApproved:i},n,{pluginId:"agent"}),...mm(t?Wge:Vge,{},n,{pluginId:"skill",ownedTypePluginId:"skill-entity"}),...mm(Zge,{},n,{pluginId:"shared-copies",ownedTypePluginId:"shared-copy"})]},void 0],["assessment",(e)=>mm(vye.parse(e).enableSwotDerivation?Aye:wye,{},{name:"@brains/assessment",version:z8.version},{pluginId:"swot"}),void 0],$r("auth-service","@brains/auth-service",VAe,{pluginId:"auth-service"}),$r("notifications","@brains/notifications",zPr,{pluginId:"notifications"}),$r("contact","@brains/contact",bgr,{pluginId:"contact",dependencies:ygr}),$r("quiz","@brains/quiz",Pgr,{pluginId:"quiz",dependencies:_gr}),$r("playbooks","@brains/playbooks",_qe,{pluginId:"playbooks"}),$r("onboarding","@brains/onboarding",POr,{pluginId:"onboarding",dependencies:["playbook","playbooks"]}),$r("studio","@brains/studio",wxr,{pluginId:"studio"}),$r("dashboard","@brains/dashboard",yEr,{pluginId:"dashboard"}),$r("admin","@brains/admin",Ffe,{pluginId:"admin"}),$r("site-info","@brains/site-info",OGe,{pluginId:"site-metadata"}),$r("site-content","@brains/site-content",ijr,{pluginId:"site-content",ownedTypePluginId:"site-content-entity"}),$r("site-builder","@brains/site-builder-plugin",ejr,{pluginId:"site-builder"}),$r("form","@brains/form",vgr,{pluginId:"form"}),$r("analytics","@brains/analytics",Vrt,{pluginId:"analytics"}),$r("blog","@brains/blog",yyt,{pluginId:"blog"}),$r("series","@brains/series",LNr,{pluginId:"series"}),$r("portfolio","@brains/portfolio",$Mr,{pluginId:"portfolio"}),$r("content-pipeline","@brains/content-pipeline",Xxr,{pluginId:"content-pipeline"}),$r("social-media","@brains/social-media",Ejr,{pluginId:"social-media"}),["newsletter",E1o,void 0],$r("stock-photo","@brains/stock-photo",Sjr,{pluginId:"stock-photo"}),["atproto",tH("@brains/atproto",Pit,{pluginId:"atproto"}),(e)=>({...e.ATPROTO_APP_PASSWORD?{appPassword:e.ATPROTO_APP_PASSWORD}:{}})],$r("conversation-memory","@brains/conversation-memory",rPe,{pluginId:"conversation-memory"}),$r("action-board","@brains/action-board",eWe,{pluginId:"action-board"}),$r("faq","@brains/faq",Lbr,{pluginId:"faq",ownedTypePluginId:"faq-entity"}),$r("docs","@brains/doc",Vwr,{pluginId:"docs"}),$r("guides","@brains/guide",y1r,{pluginId:"guides"}),$r("book","@brains/book",vSr,{pluginId:"book",ownedTypePluginId:"book-entity"}),$r("seminar","@brains/seminar",SNr,{pluginId:"seminar",ownedTypePluginId:"seminar-entity"}),$r("email-workflows","@brains/email-workflows",G7r,{pluginId:"email-workflows"}),$r("unified-inbox","@brains/unified-inbox",qHe,{pluginId:"unified-inbox"}),$r("linkedin-import","@brains/linkedin-import",RUe,{pluginId:"linkedin-import"}),$r("oauth-broker","@brains/oauth-broker",LUe({providers:{linkedin:wUe}}),{pluginId:"oauth-broker"}),$r("webdav","@brains/webdav",TFr,{pluginId:"webdav"}),$r("matrix-server","@brains/matrix-server",VFr,{pluginId:"matrix-server"},(e)=>mqe(e))],interfaces:[eH("mcp","@brains/mcp",tPr,(e)=>({...e.MCP_AUTH_TOKEN?{authToken:e.MCP_AUTH_TOKEN}:{}}),{pluginId:"mcp"}),eH("email","@brains/email",D7r,()=>({}),{pluginId:"email"}),eH("web-chat","@brains/web-chat",M$r,()=>({}),{pluginId:"web-chat"}),eH("chat","@brains/chat",$fr,(e)=>jTe(e,{captureUrls:!0}),{pluginId:"chat"}),eH("a2a","@brains/a2a",nVe,()=>({}),{pluginId:"a2a"})],bundles:K$r,permissions:{rules:[{pattern:"cli:*",level:"admin"},{pattern:"mcp:stdio",level:"admin"}]},deployment:{cdn:{enabled:!0,provider:"bunny"},dns:{enabled:!0,provider:"bunny"}}});var v1o=["headless","personal","professional","team"];var A1o={headless:{bundleContract:j8,bundles:["core"]},personal:{bundleContract:j8,anchor:"person",kind:"professional",bundles:["core","media","web","chat"],plugins:{"directory-sync":{seedContentPath:"./seed-content"}}},professional:{bundleContract:j8,anchor:"person",kind:"professional",bundles:["core","media","automation","web","chat","site","publishing","federation"],site:{package:"@brains/site-default",theme:"@rizom/theme-default"},plugins:{"directory-sync":{seedContentPath:"./seed-content"}}},team:{bundleContract:j8,anchor:"team",kind:"team",bundles:["core","media","automation","web","chat","site","team"],add:["docs","action-board"],site:{package:"@brains/site-organization",theme:"@brains/theme-rizom"},plugins:{"directory-sync":{seedContentPath:"./seed-content"}}}};function w1o(e){return structuredClone(e)}function S1o(e){return w1o(A1o[e])}var k1o=Y$r,cpc=hme,lpc=fme,upc=xme,dpc=gme,ppc=yme,mpc=bme,hpc=Eme,fpc=vme,xpc=Ame,ypc=k1o;export{IWe as AUTOMATION_BUNDLE_ID,v1o as BRAIN_RECIPE_NAMES,j8 as CANONICAL_BUNDLE_CONTRACT,TWe as CHAT_BUNDLE_ID,CWe as CORE_BUNDLE_ID,RWe as FEDERATION_BUNDLE_ID,DWe as MEDIA_BUNDLE_ID,PWe as PUBLISHING_BUNDLE_ID,_We as SITE_BUNDLE_ID,FWe as TEAM_BUNDLE_ID,XG as WEB_BUNDLE_ID,upc as automationBundle,k1o as canonicalBrain,ppc as chatBundle,cpc as coreBundle,ypc as default,S1o as expandBrainRecipe,fpc as federationBundle,lpc as mediaBundle,hpc as publishingBundle,mpc as siteBundle,xpc as teamBundle,dpc as webBundle};
|
|
11178
11178
|
|
|
11179
|
-
//# debugId=
|
|
11179
|
+
//# debugId=CE7A097D85A9C70F64756E2164756E21
|
|
11180
11180
|
//# sourceMappingURL=model.js.map
|