@rizom/brain 0.2.0-alpha.725 → 0.2.0-alpha.726

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/model.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import"./chunks/index-wny0hr9a.js";import{C as Z3,D as eoi,F as wni,H as sBe}from"./chunks/index-fpnp8e2n.js";import{J as One,K as bD}from"./chunks/index-mnxx4ztw.js";import{L as aue}from"./chunks/index-9deh2vm3.js";import"./chunks/index-e84v85w3.js";import"./chunks/index-66v76w4h.js";import"./chunks/index-624fhq2j.js";import"./chunks/index-z0k97qgd.js";import"./chunks/index-x8e40qwv.js";import{Q as pw}from"./chunks/index-j46pcyqr.js";import{$ as Tq,Aa as UPe,Ba as i5i,Ca as Iri,Da as PX,Ea as qAi,Fa as lm,Na as vj,S as kMe,T as Sj,V as Na,W as i8,X as tpe,Y as ope,Z as Ey,_ as _q,aa as Pq,ba as O$e,ca as Rq,da as A9,ea as AHe,fa as Ud,ha as fvi,ia as xvi,ka as gOe,la as WW,ma as oai,na as iv,oa as tN,pa as cni,qa as qx,ra as HX,sa as ani,ta as lni,ua as VAi,va as UAi,wa as aD,xa as bst,ya as t5i,za as jPe}from"./chunks/index-vjz32ya5.js";import{Qa as Iae,Ra as yki}from"./chunks/index-cpg3s6b6.js";import"./chunks/index-vbw249qg.js";import{$a as Pt,$b as SI,$c as p5,$d as $E,$e as UO,$f as Fw,$g as wce,$i as Hge,$j as Lg,Ab as NHe,Ac as mce,Ad as jg,Af as PE,Ag as Aae,Ah as Pc,Ai as Zge,Aj as Kg,Bb as LHe,Bc as O2,Bd as hce,Bf as Bw,Bh as OQe,Bi as Vge,Bj as Iw,Cc as ZE,Cf as nae,Ch as du,Ci as Cat,Cj as Bae,Dc as y0,Dd as oc,Df as Cf,Dh as FI,Di as Dat,Dj as _w,Eb as zHe,Ec as Wg,Ed as Ut,Eg as P2i,Eh as wae,Ei as d5,Ej as Oj,Fc as JE,Fd as UQ,Fh as Sae,Gb as jHe,Gc as tv,Gd as L2,Gh as Xt,Gi as ipe,Hc as TAi,Hd as up,Hh as kf,Hj as Tw,Ic as iZe,Id as Pa,Ie as Ug,If as CI,Ig as _Xt,Ih as LJ,Ii as m0,Ij as Pw,Jc as i0e,Jd as px,Jf as oae,Jg as IQ,Jh as zJ,Kd as Zn,Kf as sae,Kg as GJt,Kh as ts,Lc as qJ,Ld as om,Lf as aae,Lg as wj,Lh as Ln,Mc as $J,Md as aQ,Mf as DI,Mh as Avi,Nc as GJ,Nd as NJt,Nf as cae,Nh as es,Nj as ZMe,Oc as HJ,Od as W1i,Oe as C5i,Of as lae,Og as d0,Oj as Cae,Pc as MJt,Pd as N3,Pf as uae,Pi as kae,Pj as qE,Qb as _5i,Qc as OJt,Qd as Uh,Qf as dae,Qg as lp,Qj as Sf,Rc as z6e,Rd as iat,Rf as pae,Rg as xce,Rj as Dae,Sb as T5i,Sc as eO,Sd as XE,Sf as mae,Sg as gce,Sh as nR,Si as kJt,Sj as MI,Tb as wBe,Td as Gp,Tf as hae,Tg as yce,Th as dat,Ti as BJt,Tj as vvi,Ua as cce,Uc as Jn,Ud as ct,Ug as bce,Uh as zW,Ui as jW,Va as lce,Vc as sct,Vd as zl,Ve as TE,Vg as Ece,Vh as zoe,Vi as Aat,Wa as tae,Wc as Ie,Wd as GFe,We as r9i,Wg as Ace,Wh as joe,Wi as vat,Xa as zg,Xc as Ah,Xd as fce,Xe as R9i,Xg as Mw,Xi as D9i,Ya as kw,Yc as Sn,Ye as KFe,Yf as _f,Yg as vce,Yi as I9i,Yj as HE,Za as iae,Zc as YW,Ze as uki,Zf as Hj,Zg as vn,Zh as n9i,Zi as wat,Zj as Sy,_a as wI,_b as Uu,_c as nct,_d as kI,_e as dki,_g as zs,_i as Sat,_j as Bf,ab as Ci,ac as en,ad as RB,ae as QE,af as wm,ah as Mi,aj as pat,ak as EQt,bc as Gg,bd as KW,be as A3,bf as e2,bh as Sce,bj as xat,bk as sc,cb as fe,cc as Pm,cd as Hat,ce as LPe,cf as b9i,ch as kce,cj as sR,db as EA,dc as $i,dd as h5,de as DMe,df as E9i,dg as fae,dh as Rm,dj as kat,eb as bt,ec as uu,ed as Yc,ee as O5i,ef as Toe,eg as GE,eh as Ht,ej as aR,fb as c$,fc as ec,fd as yv,fe as _W,ff as pki,fg as qg,fh as zn,fi as sC,fj as Soe,gb as qc,gc as h0,gd as uR,ge as OQ,gf as mki,gg as Cw,gh as Ho,gi as C4e,gj as gat,hb as LWe,hc as rae,hd as gv,he as Cne,hf as j2i,hg as II,hh as I9,hi as B4e,hj as v2i,ib as w_,id as vh,ie as NQ,if as U2i,ig as xae,ih as PI,ii as iai,ij as yat,jb as S_,jd as wye,je as Fre,jf as q2i,jg as Mj,jh as Vn,ji as aC,jj as eQ,kb as gi,kc as uce,kd as tct,ke as Est,kf as $2i,kg as _I,kh as Ft,ki as Yvi,kj as GW,lb as R9,lc as on,ld as ect,le as aw,lf as G2i,lg as gae,lj as HW,mb as l$,mc as In,md as nJ,me as B3,mf as hki,mg as yae,mj as bat,nb as u_,nc as Sst,nd as act,ne as C3,nf as c9i,ng as F2,nj as K2i,oc as dce,od as Mat,oe as age,of as l9i,og as bae,oh as Lr,oj as Bat,pb as s_,pd as Oat,pe as Dni,pf as m9i,ph as p1i,pj as Rat,qb as lpe,qc as NI,qe as C0,qf as A9i,qg as Eae,qh as GL,qj as Y2i,rb as u$,rc as LI,rd as VW,re as yI,rf as v9i,rh as u1i,ri as ine,rj as V2i,sb as ns,sc as Fj,sd as cct,se as OPe,sf as w9i,sg as Ls,sh as vae,sj as mat,tb as ci,tc as pce,td as Dye,te as cz,tf as _oe,th as qi,tj as MJ,ub as et,uc as Hg,ue as uke,uf as gki,uj as QM,vb as Ro,vc as zI,vd as Mvi,vf as x9i,vg as Dw,vj as mJt,wb as Us,wc as jI,we as gA,wf as T2i,wj as Fm,xb as Ym,xc as UI,xd as ws,xe as IMe,xh as $g,xi as B2i,xj as Ow,yb as ape,yc as qI,ye as HQe,yh as Lt,yi as C2i,yj as Zg,zc as $I,ze as WQe,zg as TI,zh as Df,zi as cR,zj as Vg}from"./chunks/index-r6mr3e4f.js";import{$k as sGe,$m as o1i,$n as cp,Ak as EX,Al as Cti,Am as Bee,An as CS,Bk as fN,Bl as YQ,Bm as Fee,Bn as Ise,Ck as Z7,Cl as fwi,Cm as XJ,Cn as Tc,Dk as vee,Dl as xwi,Dm as iQ,Dn as xri,Ek as t6,El as oH,Em as Er,En as $d,Fk as Aee,Fm as I5i,Fn as sd,Gk as R1,Gl as YHe,Gm as $q,Gn as pu,Hk as Xoi,Hl as JHe,Hm as Em,Hn as nt,Ik as esi,Il as FQe,Jk as m2i,Jl as pn,Jm as Tne,Kk as voe,Kl as Qm,Km as Tee,Kn as BI,Lk as h2i,Ll as X1,Lm as tz,Ln as Im,Mk as nsi,Ml as rre,Mm as une,Mn as _se,Nk as f2i,Nl as fAi,Nm as mPe,Ok as QBe,Ol as nre,Om as WL,On as Rse,Pk as XBe,Pl as Un,Pm as ZL,Qk as xN,Ql as r8,Qm as xz,Rk as e4e,Rl as cr,Rm as u6i,Sk as osi,Sl as upe,Sm as gz,Tk as t4e,Tl as n$,Tm as fQ,Uk as ssi,Um as YQt,Vk as asi,Vl as fv,Vm as QQt,Wk as wee,Wl as be,Wm as nXt,Xk as See,Xm as XQt,Yk as csi,Yl as Rs,Ym as eXt,Zk as kee,Zn as nd,_k as Oh,_m as $re,_n as ap,al as Lh,am as Ni,an as s1i,bl as Fx,bm as Nq,bn as nB,ck as psi,cl as yl,cm as X9i,cn as aoe,co as RI,dk as ESi,dl as Coe,dm as R2,dn as coe,em as tQ,en as qre,fl as G9i,fm as DW,fn as sD,gk as Ia,gl as H9i,gm as kB,gn as TTe,hk as Nx,hn as RTe,ik as pQ,in as L1i,jl as ND,jm as tX,jn as h1i,kk as Cr,km as $ei,kn as z1i,lk as lr,lm as EJt,ln as f1i,mk as x3,mm as NJ,mn as b1i,nk as Gne,nl as vI,nm as OJ,nn as cQ,ok as $ne,ol as dwi,om as aHe,on as oB,pk as q6,pn as sH,qk as TL,qn as aH,rk as qn,rl as lki,rn as ZJ,sk as $6,sm as Ivi,sn as MQe,tk as z_e,tl as Ewi,tm as bA,ul as Xse,um as lO,un as rii,vk as r4e,vl as Tj,vn as rge,wk as Zb,wl as Pj,xk as yee,xl as Rj,xn as Jb,yk as bee,yn as KAi,zk as p2i,zl as lne,zn as M6}from"./chunks/index-2tdttvw4.js";import{eo as X_e,go as Bj}from"./chunks/index-vb4gsj32.js";import{$v as p0,Jt as ZW,Nv as Je,Os as vs,Uv as Fat,Xp as kge,aw as $9,cw as Xa,ew as qd,fw as iei,gw as zr,hw as fki,ls as gl,ns as G9,zs as Ta}from"./chunks/index-126267mh.js";import{zx as l}from"./chunks/index-p6bnaf8r.js";import"./chunks/index-ahe7gn4n.js";import{Dx as vl,Ex as xTi,Fx as E,Gx as ey,Hx as Wo,Ix as ce}from"./chunks/index-f709exx1.js";function WNe(e){return e===0||e>=55296&&e<=57343||e>1114111}function ZNe(e){if(WNe(e))return 65533;if(e>=128&&e<=159)return YCi[e-128]||e;return e}function VNe(e){return WNe(e)?65533:e}var YCi;var KNe=Wo(()=>{YCi=[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 YNe(e,t,i,r,n,o){let a=e.length,c=o*90,u=0,d=()=>{let N=Nm[e.charCodeAt(u++)];return N<o?N:N*91-c+Nm[e.charCodeAt(u++)]},p=i-r,m=i+n,h=new Int32Array(m);h.fill(-1,r,o),h.fill(-1,o+p,m);let f=new Int32Array(m),g=new Int32Array(m);function y(N,q){let K=0,ue=q,G=q+N;while(ue<G){let S=Nm[e.charCodeAt(u++)];if(S<89)K+=S,h[ue++]=K;else if(S===89){let P=Nm[e.charCodeAt(u++)]+2;while(P--)h[ue++]=++K}else{let P=Nm[e.charCodeAt(u++)];K+=89+(P<90?P*91+Nm[e.charCodeAt(u++)]:Nm[e.charCodeAt(u++)]*8281+Nm[e.charCodeAt(u++)]*91+Nm[e.charCodeAt(u++)]),h[ue++]=K}}}y(r,0),y(p,o);let b=new Int32Array(n*2),v=0,w=0;function D(N,q){for(let K=0;K<N;K++){let ue=q+K,G=d(),S=d();b[w*2]=G,b[w*2+1]=S,w+=1,f[ue]=v;let P=(h[G]<0?g[G]:1)+(h[S]<0?g[S]:1);g[ue]=P,v+=P}}D(n-o+r,o+p),D(o-r,r);let R=new Uint16Array(v),O=0;for(let N=0;N<w;N++)for(let q=0;q<2;q++){let K=b[N*2+q],ue=h[K];if(ue<0){let G=f[K],S=G+g[K];while(G<S)R[O++]=R[G++]}else R[O++]=ue}let k=new Uint16Array(t),j=0;while(u<a){let N=Nm[e.charCodeAt(u++)];if(N>=o)N=N*91-c+Nm[e.charCodeAt(u++)];let q=h[N];if(q<0){let K=f[N],ue=K+g[N];while(K<ue)k[j++]=R[K++]}else k[j++]=q}return k}var Nm;var JNe=Wo(()=>{Nm=(()=>{let e=new Uint8Array(127),t=0;for(let i=33;i<=126;i++)if(i!==34&&i!==36&&i!==92)e[i]=t++;return e})()});var Kce;var QNe=Wo(()=>{JNe();Kce=YNe("!}.&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~!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dt%3[xn~<5rLOu!5p@Ku+D#'!t7~GrP~?rNKvlaya7'!h+v-5qMg=t|cd,U#5AAaa5Abb{S@52B5@a[@52B5Gx[iXueu;d<#`a(!/549C;ag>23ExY5@Dah89b^~689Jv)!~2b[~1Lv'w(%*!a#bX|aPrmawRe]keu7uhv-q6rxu,q`xTo]/a5aU!bNaDXbi!b-!ao!b<bwA!#5@B932:aV2G|:d-)Y#hJrL>RhG<7@C5<H|_=Cau:5aj5@B932:bJ|ng>vIbs)#?C2F|9jPv0w.vISh-MKvUaz(.!9ABbb|[5;5<H|Eg>unwfh;9:4E|YjQsBt|vjx'hYq3!(?C2F|J:2<BaY?C2F|GOu!5x,g|p{ah!-(?C2F|c9:4E|OjXuvvNr}:Rh&i[w*t|cd+U#jJvsu)vsSn~Mkfrmu9p}u7vwv]So!McW#Xa!ax5@A5aY:5;5<H|>kJv~vYrquJu3x4ib#T)2@SmZM?C2F|Bj:rmu9@xPhI(a*a#U#`a3-5Abb|L~@:RhK9:4E|0@52B5G|#C::aY?C2F|-:2<BaY?C2F|.5Jvk!a)javYrquJu3x4ia#T)2@SmYM?C2F|HAxPhH(!a#U#`a*-5Abb|4~@:RhJ9:4E|R@52B5G|F:2<BaY?C2F|Sc^#Xa2j=Qq5CJvB!-g<v{z;hhM?C2F|Zi[vrv{z;hiM?C2F|XKsA>!a)-g<v{z;h[eb?C2F|]i[vrv{z;h]eb?C2F|^iZu.vix,hZq3ah!.(?C2F|QOu!5ShXM:2<BaY?C2F|P",13494,2713,49,25,61)});var e7;var Yce=Wo(()=>{e7=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 rc;var XNe=Wo(()=>{(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"})(rc||(rc={}))});function eLe(e){return e-El.ZERO>>>0<=9}function JCi(e){return(e|rU)-El.LOWER_A>>>0<=5}function QCi(e){return(e|rU)-El.LOWER_A>>>0<=25}function XCi(e){return e===El.EQUALS||QCi(e)||eLe(e)}class Jce{decodeTree;emitCodePoint;errors;state=bl.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=Lm.Strict;runConsumed=0;constructor(e,t,i){this.decodeTree=e,this.emitCodePoint=t,this.errors=i}startEntity(e){this.decodeMode=e,this.state=bl.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case bl.EntityStart:{if(e.charCodeAt(t)===El.NUM)return this.state=bl.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=bl.NamedEntity,this.stateNamedEntity(e,t)}case bl.NumericStart:return this.stateNumericStart(e,t);case bl.NumericDecimal:return this.stateNumericDecimal(e,t);case bl.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)|rU)===El.LOWER_X)return this.state=bl.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=bl.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){let i=e.length,{result:r}=this,{consumed:n}=this;while(t<i){let o=e.charCodeAt(t);if(eLe(o)||JCi(o)){let s=o<=El.NINE?o-El.ZERO:(o|rU)-El.LOWER_A+10;r=r*16+s,n+=1,t+=1}else return this.result=r,this.consumed=n,this.emitNumericEntity(o,3)}return this.result=r,this.consumed=n,-1}stateNumericDecimal(e,t){let i=e.length,{result:r}=this,{consumed:n}=this;while(t<i){let o=e.charCodeAt(t)-El.ZERO;if(o>>>0>9)return this.result=r,this.consumed=n,this.emitNumericEntity(o+El.ZERO,2);r=r*10+o,n+=1,t+=1}return this.result=r,this.consumed=n,-1}emitNumericEntity(e,t){if(this.consumed<=t)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===El.SEMI)this.consumed+=1;else if(this.decodeMode===Lm.Strict)return 0;if(this.emitCodePoint((this.decodeTree===e7?VNe:ZNe)(this.result),this.consumed),this.errors){if(e!==El.SEMI)this.errors.missingSemicolonAfterCharacterReference();this.errors.validateNumericCharacterReference(this.result)}return this.consumed}flushAndEmitLegacyOrReject(e,t,i,r){return this.consumed=e,this.excess=t,this.result===0||this.decodeMode===Lm.Attribute&&(r===0||t>1||XCi(i))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:i}=this,r=e.length,n=this.decodeMode===Lm.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=i[o];while(t<r){while((c&(rc.VALUE_LENGTH|rc.FLAG13))===0&&(c&rc.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&rc.JUMP_TABLE,f=(c&rc.BRANCH_LENGTH)>>7;if(f===0){if(m!==h)return this.flushAndEmitLegacyOrReject(a,s,m,0);o+=1}else{let g=m-h;if(g>>>0>=f)return this.flushAndEmitLegacyOrReject(a,s,m,0);let y=i[o+1+g];if(y===0)return this.flushAndEmitLegacyOrReject(a,s,m,0);o=o+f+y&65535}if(c=i[o],t+=1,s+=1,t>=r)break}if(t>=r)break;if((c&(rc.VALUE_LENGTH|rc.FLAG13))===rc.FLAG13){let m=(c&rc.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&rc.JUMP_TABLE))return this.flushAndEmitLegacyOrReject(a,s,f,0);t+=1,s+=1,h=1}while(h<m){if(t>=r)return this.treeIndex=o,this.excess=s,this.consumed=a,this.runConsumed=h,-1;let f=h-1,y=i[o+1+(f>>1)]>>((f&1)<<3)&255,b=e.charCodeAt(t);if(b!==y)return this.runConsumed=0,this.flushAndEmitLegacyOrReject(a,s,b,0);t+=1,s+=1,h+=1}this.runConsumed=0,o+=1+(m>>1),c=i[o];continue}let u=c>>>14,d=e.charCodeAt(t);if(u!==0){if(!n&&(c&rc.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===El.SEMI)return this.emitNamedEntityData(o,u,a+s);if(u===1)return this.flushAndEmitLegacyOrReject(a,s,d,u)}let p=eDi(i,c,o+(u||1),d);if(p<0)return this.flushAndEmitLegacyOrReject(a,s,d,u);o=p,c=i[o],t+=1,s+=1}if(!n&&c>>>14!==0&&(c&rc.FLAG13)===0)this.result=o,a+=s-1,s=1;return this.treeIndex=o,this.excess=s,this.consumed=a,-1}emitNotTerminatedNamedEntity(){let{result:e,decodeTree:t}=this,i=t[e]>>>14;return this.emitNamedEntityData(e,i,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,i){let{decodeTree:r}=this;if(this.emitCodePoint(t===1?r[e]&rc.VALUE_MASK:r[e+1],i),t===3)this.emitCodePoint(r[e+2],i);return i}end(){switch(this.state){case bl.NamedEntity:return this.result!==0&&(this.decodeMode!==Lm.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case bl.NumericDecimal:return this.emitNumericEntity(0,2);case bl.NumericHex:return this.emitNumericEntity(0,3);case bl.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function eDi(e,t,i,r){let n=(t&rc.BRANCH_LENGTH)>>7,o=t&rc.JUMP_TABLE;if(o){if(n===0)return r===o?i:-1;let c=r-o;if(c>>>0>=n)return-1;let u=e[i+c];return u===0?-1:i+n+u-1&65535}if(n===0)return-1;let s=n+1>>1,a=i+s+n;for(let c=0;c<n;c++){let d=e[i+(c>>1)]>>((c&1)<<3)&255;if(d===r){let p=i+s+c;return a+e[p]&65535}if(d>r)return-1}return-1}var El,rU=32,bl,Lm;var tLe=Wo(()=>{KNe();Yce();XNe();QNe();Yce();(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"})(El||(El={}));(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"})(bl||(bl={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(Lm||(Lm={}))});function jw(e){return e===fi.Space||e===fi.NewLine||e===fi.Tab||e===fi.FormFeed||e===fi.CarriageReturn}function G2(e){return e===fi.Slash||e===fi.Gt||jw(e)}function tDi(e){return e>=fi.LowerA&&e<=fi.LowerZ||e>=fi.UpperA&&e<=fi.UpperZ}class H2{cbs;state=He.Text;buffer="";sectionStart=0;index=0;entityStart=0;baseState=He.Text;isSpecial=!1;running=!0;offset=0;xmlMode;decodeEntities;recognizeSelfClosing;entityDecoder;constructor({xmlMode:e=!1,decodeEntities:t=!0,recognizeSelfClosing:i=e},r){this.cbs=r,this.xmlMode=e,this.decodeEntities=t,this.recognizeSelfClosing=i,this.entityDecoder=new Jce(e?e7:Kce,(n,o)=>this.emitCodePoint(n,o))}reset(){this.state=He.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=He.Text,this.isSpecial=!1,this.currentSequence=Xi.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===fi.Lt||!this.decodeEntities&&this.fastForwardTo(fi.Lt)){if(this.index>this.sectionStart)this.cbs.ontext(this.sectionStart,this.index);this.state=He.BeforeTagName,this.sectionStart=this.index}else if(this.decodeEntities&&e===fi.Amp)this.startEntity()}currentSequence=Xi.Empty;sequenceIndex=0;enterTagBody(){if(this.currentSequence===Xi.Plaintext)this.currentSequence=Xi.Empty,this.state=He.InPlainText;else if(this.isSpecial)this.state=He.InSpecialTag,this.sequenceIndex=0;else this.state=He.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===Xi.ScriptEnd&&t===Xi.StyleEnd[3]){this.currentSequence=Xi.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===Xi.TitleEnd&&t===Xi.TextareaEnd[3]){this.currentSequence=Xi.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===Xi.NoembedEnd&&t===Xi.NoframesEnd[4]){this.currentSequence=Xi.NoframesEnd,this.sequenceIndex=5;return}}else if(G2(e)){this.sequenceIndex=0,this.state=He.InTagName,this.stateInTagName(e);return}this.isSpecial=!1,this.currentSequence=Xi.Empty,this.sequenceIndex=0,this.state=He.InTagName,this.stateInTagName(e)}stateCDATASequence(e){if(e===Xi.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===Xi.Cdata.length)this.state=He.InCommentLike,this.currentSequence=Xi.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1}else if(this.sequenceIndex=0,this.xmlMode)this.state=He.InDeclaration,this.stateInDeclaration(e);else this.state=He.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=He.Text}stateInCommentLike(e){if(!this.xmlMode&&this.currentSequence===Xi.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&e===fi.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===Xi.CommentEnd&&this.sequenceIndex===2&&e===fi.Gt)this.emitComment(2);else if(this.currentSequence===Xi.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&e!==fi.Gt)this.sequenceIndex=Number(e===fi.Dash);else if(e===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===Xi.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=He.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?!G2(e):tDi(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(G2(e)){let t=this.index-this.currentSequence.length;if(this.sectionStart<t){let i=this.index;this.index=t,this.cbs.ontext(this.sectionStart,t),this.index=i}this.isSpecial=!1,this.sectionStart=t+2,this.stateInClosingTagName(e);return}this.sequenceIndex=0}if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(this.sequenceIndex===0){if(this.currentSequence===Xi.TitleEnd||this.currentSequence===Xi.TextareaEnd){if(this.decodeEntities&&e===fi.Amp)this.startEntity()}else if(this.fastForwardTo(fi.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(e===fi.Lt)}stateBeforeTagName(e){if(e===fi.ExclamationMark)this.state=He.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===fi.Questionmark)if(this.xmlMode)this.state=He.InProcessingInstruction,this.sequenceIndex=0,this.sectionStart=this.index+1;else this.state=He.InSpecialComment,this.sectionStart=this.index;else if(this.isTagStartChar(e)){this.sectionStart=this.index;let t=this.xmlMode||this.cbs.isInForeignContext?.()?void 0:iDi.get(e|32);if(t===void 0)this.state=He.InTagName;else this.isSpecial=!0,this.currentSequence=t,this.sequenceIndex=3,this.state=He.SpecialStartSequence}else if(e===fi.Slash)this.state=He.BeforeClosingTagName;else this.state=He.Text,this.stateText(e)}stateInTagName(e){if(G2(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(jw(e))if(this.xmlMode);else this.state=He.InSpecialComment,this.sectionStart=this.index;else if(e===fi.Gt){if(this.state=He.Text,!this.xmlMode)this.sectionStart=this.index+1}else this.state=this.isTagStartChar(e)?He.InClosingTagName:He.InSpecialComment,this.sectionStart=this.index}stateInClosingTagName(e){if(G2(e))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=He.AfterClosingTagName,this.stateAfterClosingTagName(e)}stateAfterClosingTagName(e){if(e===fi.Gt||this.fastForwardTo(fi.Gt))this.state=He.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(e){if(e===fi.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(e===fi.Slash)this.state=He.InSelfClosingTag;else if(!jw(e))this.state=He.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(e){if(e===fi.Gt){if(this.cbs.onselfclosingtag(this.index),this.sectionStart=this.index+1,!this.recognizeSelfClosing){this.enterTagBody();return}this.state=He.Text,this.isSpecial=!1,this.currentSequence=Xi.Empty}else if(!jw(e))this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===fi.Eq||G2(e))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=He.AfterAttributeName,this.stateAfterAttributeName(e)}stateAfterAttributeName(e){if(e===fi.Eq)this.state=He.BeforeAttributeValue;else if(e===fi.Slash||e===fi.Gt)this.cbs.onattribend(dp.NoValue,this.sectionStart),this.sectionStart=-1,this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!jw(e))this.cbs.onattribend(dp.NoValue,this.sectionStart),this.state=He.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(e){if(e===fi.DoubleQuote)this.state=He.InAttributeValueDq,this.sectionStart=this.index+1;else if(e===fi.SingleQuote)this.state=He.InAttributeValueSq,this.sectionStart=this.index+1;else if(!jw(e))this.sectionStart=this.index,this.state=He.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===fi.DoubleQuote?dp.Double:dp.Single,this.index+1),this.state=He.BeforeAttributeName;else if(this.decodeEntities&&e===fi.Amp)this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,fi.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,fi.SingleQuote)}stateInAttributeValueNoQuotes(e){if(jw(e)||e===fi.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(dp.Unquoted,this.index),this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(this.decodeEntities&&e===fi.Amp)this.startEntity()}stateBeforeDeclaration(e){if(e===fi.OpeningSquareBracket)this.state=He.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=e===fi.Dash?He.BeforeComment:He.InDeclaration;else if((e|32)===Xi.Doctype[0])this.state=He.DeclarationSequence,this.currentSequence=Xi.Doctype,this.sequenceIndex=1;else if(e===fi.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1;else if(e===fi.Dash)this.state=He.BeforeComment;else this.state=He.InSpecialComment}stateDeclarationSequence(e){if(this.sequenceIndex===this.currentSequence.length)this.state=He.InDeclaration,this.stateInDeclaration(e);else if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(e===fi.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1;else this.state=He.InSpecialComment}stateInDeclaration(e){if(e===fi.Gt||this.fastForwardTo(fi.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=He.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(e){if(e===fi.Questionmark)this.sequenceIndex=1;else if(e===fi.Gt&&this.sequenceIndex===1)this.cbs.onprocessinginstruction(this.sectionStart,this.index-1),this.sequenceIndex=0,this.state=He.Text,this.sectionStart=this.index+1;else this.sequenceIndex=Number(this.fastForwardTo(fi.Questionmark))}stateBeforeComment(e){if(e===fi.Dash)this.state=He.InCommentLike,this.currentSequence=Xi.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=He.InDeclaration;else if(e===fi.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1;else this.state=He.InSpecialComment}stateInSpecialComment(e){if(e===fi.Gt||this.fastForwardTo(fi.Gt))this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1}startEntity(){this.baseState=this.state,this.state=He.InEntity,this.entityStart=this.index,this.entityDecoder.startEntity(this.xmlMode?Lm.Strict:this.baseState===He.Text||this.baseState===He.InSpecialTag?Lm.Legacy:Lm.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)===fi.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===He.Text||this.state===He.InPlainText||this.state===He.InSpecialTag&&this.sequenceIndex===0)this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index;else if(this.state===He.InAttributeValueDq||this.state===He.InAttributeValueSq||this.state===He.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 He.Text:{this.stateText(e);break}case He.InPlainText:{this.index=this.buffer.length+this.offset-1;break}case He.SpecialStartSequence:{this.stateSpecialStartSequence(e);break}case He.InSpecialTag:{this.stateInSpecialTag(e);break}case He.CDATASequence:{this.stateCDATASequence(e);break}case He.DeclarationSequence:{this.stateDeclarationSequence(e);break}case He.InAttributeValueDq:{this.stateInAttributeValueDoubleQuotes(e);break}case He.InAttributeName:{this.stateInAttributeName(e);break}case He.InCommentLike:{this.stateInCommentLike(e);break}case He.InSpecialComment:{this.stateInSpecialComment(e);break}case He.BeforeAttributeName:{this.stateBeforeAttributeName(e);break}case He.InTagName:{this.stateInTagName(e);break}case He.InClosingTagName:{this.stateInClosingTagName(e);break}case He.BeforeTagName:{this.stateBeforeTagName(e);break}case He.AfterAttributeName:{this.stateAfterAttributeName(e);break}case He.InAttributeValueSq:{this.stateInAttributeValueSingleQuotes(e);break}case He.BeforeAttributeValue:{this.stateBeforeAttributeValue(e);break}case He.BeforeClosingTagName:{this.stateBeforeClosingTagName(e);break}case He.AfterClosingTagName:{this.stateAfterClosingTagName(e);break}case He.InAttributeValueNq:{this.stateInAttributeValueNoQuotes(e);break}case He.InSelfClosingTag:{this.stateInSelfClosingTag(e);break}case He.InDeclaration:{this.stateInDeclaration(e);break}case He.BeforeDeclaration:{this.stateBeforeDeclaration(e);break}case He.BeforeComment:{this.stateBeforeComment(e);break}case He.InProcessingInstruction:{this.stateInProcessingInstruction(e);break}case He.InEntity:{this.stateInEntity();break}}this.index++}this.cleanup()}finish(){if(this.state===He.InEntity)this.entityDecoder.end(),this.state=this.baseState;this.handleTrailingData(),this.cbs.onend()}handleTrailingCommentLikeData(e){if(this.state!==He.InCommentLike)return!1;if(this.currentSequence===Xi.CdataEnd)if(this.xmlMode){if(this.sectionStart<e)this.cbs.oncdata(this.sectionStart,e,0)}else{let t=this.sectionStart-Xi.Cdata.length-1;this.cbs.oncomment(t,e,0)}else{let t=this.xmlMode?0:Math.min(this.sequenceIndex,Xi.CommentEnd.length-1);this.cbs.oncomment(this.sectionStart,e,t)}return!0}handleTrailingMarkupDeclaration(e){if(this.xmlMode)switch(this.state){case He.InSpecialComment:case He.BeforeComment:case He.CDATASequence:case He.DeclarationSequence:case He.InDeclaration:return this.cbs.ontext(this.sectionStart,e),!0;default:return!1}switch(this.state){case He.BeforeDeclaration:case He.InSpecialComment:case He.BeforeComment:case He.CDATASequence:return this.cbs.oncomment(this.sectionStart,e,0),!0;case He.DeclarationSequence:{if(this.sequenceIndex!==Xi.Doctype.length)this.cbs.oncomment(this.sectionStart,e,0);return!0}case He.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 He.InTagName:case He.BeforeAttributeName:case He.BeforeAttributeValue:case He.AfterAttributeName:case He.InAttributeName:case He.InAttributeValueSq:case He.InAttributeValueDq:case He.InAttributeValueNq:case He.InClosingTagName:break;default:this.cbs.ontext(this.sectionStart,e)}}emitCodePoint(e,t){if(this.baseState!==He.Text&&this.baseState!==He.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 fi,He,dp,Xi,iDi;var Qce=Wo(()=>{tLe();(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"})(fi||(fi={}));(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"})(He||(He={}));(function(e){e[e.NoValue=0]="NoValue",e[e.Unquoted=1]="Unquoted",e[e.Single=2]="Single",e[e.Double=3]="Double"})(dp||(dp={}));Xi={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])},iDi=new Map([[Xi.IframeEnd[2],Xi.IframeEnd],[Xi.NoembedEnd[2],Xi.NoembedEnd],[Xi.Plaintext[2],Xi.Plaintext],[Xi.ScriptEnd[2],Xi.ScriptEnd],[Xi.TitleEnd[2],Xi.TitleEnd],[Xi.XmpEnd[2],Xi.XmpEnd]])});class V2{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??H2)(this.options,this),this.foreignContext=[Xg.None],this.cbs.onparserinit?.(this)}ontext(e,t){let i=this.getSlice(e,t);this.endIndex=t-1,this.cbs.ontext?.(i),this.startIndex=t}ontextentity(e,t){this.endIndex=t-1,this.cbs.ontext?.(iLe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==Xg.None}isVoidElement(e){return this.htmlMode&&nDi.has(e)}readTagName(e,t){let i=this.lowerCaseTagNames?this.getSlice(e,t).toLowerCase():this.getSlice(e,t);if(!(this.lowerCaseTagNames&&this.htmlMode))return i;if(this.foreignContext[0]===Xg.Svg)return cLe.get(i)??i;if(this.foreignContext.length>1){let r=cLe.get(i);if(r!==void 0&&this.stack.includes(r))return r}if(!this.isInForeignContext())return i==="image"?"img":i;return i}onopentagname(e,t){this.endIndex=t,this.emitOpenTag(this.readTagName(e,t))}emitOpenTag(e){if(this.openTagStart=this.startIndex,this.tagname=e,this.htmlMode&&e==="form"&&this.stack.includes("form")){this.tagname="";return}let t=this.htmlMode&&rDi.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(Xg.Svg);else if(e==="math")this.foreignContext.unshift(Xg.MathML);else if(aLe.has(e))this.foreignContext.unshift(Xg.None)}}if(this.cbs.onopentagname?.(e),this.cbs.onopentag)this.attribs={}}endOpenTag(e){if(this.startIndex=this.openTagStart,this.attribs)this.cbs.onopentag?.(this.tagname,this.attribs,e),this.attribs=null;if(this.cbs.onclosetag&&this.isVoidElement(this.tagname))this.cbs.onclosetag(this.tagname,!0);this.tagname=""}onopentagend(e){this.endIndex=e,this.endOpenTag(!1),this.startIndex=e+1}onclosetag(e,t){this.endIndex=t;let i=this.readTagName(e,t);if(!this.isVoidElement(i)){let r=this.stack.indexOf(i);if(r!==-1){for(let n=0;n<r;n++)this.popElement(!0);this.popElement(!1)}else if(this.htmlMode&&i==="p")this.emitOpenTag("p"),this.closeCurrentTag(!0)}else if(this.htmlMode&&i==="br")this.cbs.onopentagname?.("br"),this.cbs.onopentag?.("br",{},!0),this.cbs.onclosetag?.("br",!1);this.startIndex=t+1}onselfclosingtag(e){if(this.endIndex=e,this.recognizeSelfClosing||this.isInForeignContext())this.closeCurrentTag(!1),this.startIndex=e+1;else this.onopentagend(e)}popElement(e){let t=this.stack.shift();if(this.htmlMode&&(oDi.has(t)||aLe.has(t)))this.foreignContext.shift();this.cbs.onclosetag?.(t,e)}closeCurrentTag(e){let t=this.tagname;if(this.endOpenTag(e),this.stack[0]===t)this.popElement(!e)}onattribname(e,t){this.startIndex=e;let i=this.getSlice(e,t);this.attribname=this.lowerCaseAttributeNames?i.toLowerCase():i}onattribdata(e,t){this.attribvalue+=this.getSlice(e,t)}onattribentity(e){this.attribvalue+=iLe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===dp.Double?'"':e===dp.Single?"'":e===dp.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(sDi),i=t<0?e:e.substr(0,t);if(this.lowerCaseTagNames)i=i.toLowerCase();return i}ondeclaration(e,t){this.endIndex=t;let i=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let r=this.htmlMode?this.lowerCaseTagNames?sLe:i.slice(0,sLe.length):this.getInstructionName(i);this.cbs.onprocessinginstruction(`!${r}`,`!${i}`)}this.startIndex=t+1}onprocessinginstruction(e,t){this.endIndex=t;let i=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let r=this.getInstructionName(i);this.cbs.onprocessinginstruction(`?${r}`,`?${i}`)}this.startIndex=t+1}oncomment(e,t,i){this.endIndex=t,this.cbs.oncomment?.(this.getSlice(e,t-i)),this.cbs.oncommentend?.(),this.startIndex=t+1}oncdata(e,t,i){this.endIndex=t;let r=this.getSlice(e,t-i);if(!this.htmlMode||this.options.recognizeCDATA)this.cbs.oncdatastart?.(),this.cbs.ontext?.(r),this.cbs.oncdataend?.();else if(this.isInForeignContext())this.cbs.ontext?.(r);else this.cbs.oncomment?.(`[CDATA[${r}]]`),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(Xg.None),this.bufferOffset=0,this.writeIndex=0,this.ended=!1}parseComplete(e){this.reset(),this.end(e)}getSlice(e,t){if(e===t)return"";while(e-this.bufferOffset>=this.buffers[0].length)this.shiftBuffer();let i=this.buffers[0].slice(e-this.bufferOffset,t-this.bufferOffset);while(t-this.bufferOffset>this.buffers[0].length)this.shiftBuffer(),i+=this.buffers[0].slice(0,t-this.bufferOffset);return i}shiftBuffer(){this.bufferOffset+=this.buffers[0].length,this.writeIndex--,this.buffers.shift()}write(e){if(this.ended){this.cbs.onerror?.(Error(".write() after done!"));return}if(this.buffers.push(e),this.tokenizer.running)this.tokenizer.write(e),this.writeIndex++}end(e){if(this.ended){this.cbs.onerror?.(Error(".end() after done!"));return}if(e)this.write(e);this.ended=!0,this.tokenizer.end()}pause(){this.tokenizer.pause()}resume(){this.tokenizer.resume();while(this.tokenizer.running&&this.writeIndex<this.buffers.length)this.tokenizer.write(this.buffers[this.writeIndex++]);if(this.ended)this.tokenizer.end()}}var iLe,W2,Ss,Z2,rLe,nLe,oLe,rDi,sLe="doctype",nDi,oDi,aLe,cLe,Xg,sDi;var Xce=Wo(()=>{Qce();({fromCodePoint:iLe}=String),W2=new Set(["input","option","optgroup","select","button","datalist","textarea"]),Ss=new Set(["p"]),Z2=new Set(["h1","h2","h3","h4","h5","h6","p"]),rLe=new Set(["thead","tbody"]),nLe=new Set(["dd","dt"]),oLe=new Set(["rt","rp"]),rDi=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",Ss],["h1",Z2],["h2",Z2],["h3",Z2],["h4",Z2],["h5",Z2],["h6",Z2],["select",W2],["input",W2],["output",W2],["button",W2],["datalist",W2],["textarea",W2],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",nLe],["dt",nLe],["address",Ss],["article",Ss],["aside",Ss],["blockquote",Ss],["details",Ss],["div",Ss],["dl",Ss],["fieldset",Ss],["figcaption",Ss],["figure",Ss],["footer",Ss],["form",Ss],["header",Ss],["hr",Ss],["main",Ss],["nav",Ss],["ol",Ss],["pre",Ss],["section",Ss],["table",Ss],["ul",Ss],["rt",oLe],["rp",oLe],["tbody",rLe],["tfoot",rLe]]),nDi=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),oDi=new Set(["math","svg"]),aLe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),cLe=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"})(Xg||(Xg={}));sDi=/\s|\//});var nU={};ey(nU,{CDATA:()=>cle,Comment:()=>nle,Directive:()=>rle,Doctype:()=>aDi,ElementType:()=>tn,Root:()=>tle,Script:()=>ole,Style:()=>sle,Tag:()=>ale,Text:()=>ile,isTag:()=>ele});function ele(e){return e.type===tn.Tag||e.type===tn.Script||e.type===tn.Style}var tn,tle,ile,rle,nle,ole,sle,ale,cle,aDi;var K2=Wo(()=>{(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"})(tn||(tn={}));tle=tn.Root,ile=tn.Text,rle=tn.Directive,nle=tn.Comment,ole=tn.Script,sle=tn.Style,ale=tn.Tag,cle=tn.CDATA,aDi=tn.Doctype});class ule{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 lLe(this,e)}}function Al(e){return ele(e)}function dU(e){return e.type===tn.CDATA}function rA(e){return e.type===tn.Text}function dle(e){return e.type===tn.Comment}function cDi(e){return e.type===tn.Directive}function lDi(e){return e.type===tn.Root}function ad(e){return Object.hasOwn(e,"children")}function lLe(e,t=!1){let i;if(rA(e))i=new t7(e.data);else if(dle(e))i=new sU(e.data);else if(Al(e)){let r=t?lle(e.children):[],n=new uU(e.name,{...e.attribs},r);for(let o of r)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"]};i=n}else if(dU(e)){let r=t?lle(e.children):[],n=new lU(r);for(let o of r)o.parent=n;i=n}else if(lDi(e)){let r=t?lle(e.children):[],n=new i7(r);for(let o of r)o.parent=n;if(e["x-mode"])n["x-mode"]=e["x-mode"];i=n}else if(cDi(e)){let r=new aU(e.name,e.data);if(e["x-name"]!=null)r["x-name"]=e["x-name"],r["x-publicId"]=e["x-publicId"],r["x-systemId"]=e["x-systemId"];i=r}else throw Error(`Not implemented yet: ${e.type}`);if(i.startIndex=e.startIndex,i.endIndex=e.endIndex,e.sourceCodeLocation!=null)i.sourceCodeLocation=e.sourceCodeLocation;return i}function lle(e){let t=e.map((i)=>lLe(i,!0));for(let i=1;i<t.length;i++)t[i].prev=t[i-1],t[i-1].next=t[i];return t}var oU,t7,sU,aU,cU,lU,i7,uU;var ple=Wo(()=>{K2();oU=class oU extends ule{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};t7=class t7 extends oU{type=tn.Text;get nodeType(){return 3}};sU=class sU extends oU{type=tn.Comment;get nodeType(){return 8}};aU=class aU extends oU{type=tn.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};cU=class cU extends ule{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}};lU=class lU extends cU{type=tn.CDATA;get nodeType(){return 4}};i7=class i7 extends cU{type=tn.Root;get nodeType(){return 9}};uU=class uU extends cU{name;attribs;type;constructor(e,t,i=[],r=e==="script"?tn.Script:e==="style"?tn.Style:tn.Tag){super(i);this.name=e,this.attribs=t,this.type=r}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 Uw{dom=[];root=new i7(this.dom);callback;options;elementCB;done=!1;tagStack=[this.root];lastNode=null;parser=null;constructor(e,t,i){if(typeof t==="function")i=t,t=uLe;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??uLe,this.elementCB=i??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new i7(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){if(this.done)return;this.done=!0,this.parser=null,this.handleCallback(null)}onerror(e){this.handleCallback(e)}onclosetag(){this.lastNode=null;let e=this.tagStack.pop();if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(this.elementCB)this.elementCB(e)}onopentag(e,t){let i=this.options.xmlMode?tn.Tag:void 0,r=new uU(e,t,void 0,i);this.addNode(r),this.tagStack.push(r)}ontext(e){let{lastNode:t}=this;if(t&&t.type===tn.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let i=new t7(e);this.addNode(i),this.lastNode=i}}oncomment(e){if(this.lastNode&&this.lastNode.type===tn.Comment){this.lastNode.data+=e;return}let t=new sU(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new t7(""),t=new lU([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let i=new aU(e,t);this.addNode(i)}handleCallback(e){if(typeof this.callback==="function")this.callback(e,this.dom);else if(e)throw e}addNode(e){let t=this.tagStack[this.tagStack.length-1],i=t.children[t.children.length-1];if(this.options.withStartIndices&&this.parser)e.startIndex=this.parser.startIndex;if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(t.children.push(e),i)e.prev=i,i.next=e;e.parent=t,this.lastNode=null}}var uLe;var nA=Wo(()=>{K2();ple();ple();uLe={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function Y2(e,t,i=!0,r=Number.POSITIVE_INFINITY){return dLe(e,Array.isArray(t)?t:[t],i,r)}function dLe(e,t,i,r){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),--r<=0)return n}if(i&&ad(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function pU(e,t,i=!0){let r=Array.isArray(t)?t:[t];for(let n of r){if(Al(n)&&e(n))return n;if(i&&ad(n)&&n.children.length>0){let o=pU(e,n.children,!0);if(o)return o}}return null}function pLe(e,t){return(Array.isArray(t)?t:[t]).some((i)=>Al(i)&&e(i)||ad(i)&&pLe(e,i.children))}function uDi(e,t){let i=[],r=[Array.isArray(t)?t:[t]],n=[0];for(;;){if(n[0]>=r[0].length){if(r.length===1)return i;r.shift(),n.shift();continue}let o=r[0][n[0]++];if(Al(o)&&e(o))i.push(o);if(ad(o)&&o.children.length>0)n.unshift(0),r.unshift(o.children)}}var mle=Wo(()=>{nA()});function hle(e,t){if(typeof t==="function")return(i)=>Al(i)&&t(i.attribs[e]);return(i)=>Al(i)&&i.attribs[e]===t}function dDi(e,t){return(i)=>e(i)||t(i)}function mLe(e){let t=Object.keys(e).map((i)=>{let r=e[i];return Object.hasOwn(mU,i)?mU[i](r):hle(i,r)});return t.length===0?null:t.reduce(dDi)}function pDi(e,t){let i=mLe(e);return i?i(t):!0}function mDi(e,t,i,r=Number.POSITIVE_INFINITY){let n=mLe(e);return n?Y2(n,t,i,r):[]}function hDi(e,t,i=!0){if(!Array.isArray(t))t=[t];return pU(hle("id",e),t,i)}function qw(e,t,i=!0,r=Number.POSITIVE_INFINITY){return Y2(mU.tag_name(e),t,i,r)}function fDi(e,t,i=!0,r=Number.POSITIVE_INFINITY){return Y2(hle("class",e),t,i,r)}function xDi(e,t,i=!0,r=Number.POSITIVE_INFINITY){return Y2(mU.tag_type(e),t,i,r)}var mU;var fle=Wo(()=>{nA();mle();mU={tag_name(e){if(typeof e==="function")return(t)=>Al(t)&&e(t.name);if(e==="*")return Al;return(t)=>Al(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)=>rA(t)&&e(t.data);return(t)=>rA(t)&&t.data===e}}});function fLe(e){return e===34?"&quot;":e===38?"&amp;":e===39?"&apos;":e===60?"&lt;":e===62?"&gt;":"&nbsp;"}function hLe(e){return e>=128||e>=32&&e<64&&(gDi>>>e&1)===1}function hU(e){let{length:t}=e,i,r=0,n=0;while(n<t){let o=e.charCodeAt(n);if(!hLe(o)){let a=Math.min(n+32,t),c=n+1;while(c<a&&!hLe(e.charCodeAt(c)))c++;if(c<a){n=c;continue}if(c>=t)break;if(xle.lastIndex=c,!xle.test(e))break;n=xle.lastIndex-1;continue}if(i===void 0)i=e.substring(0,n);else if(r!==n)i+=e.substring(r,n);if(o<64){i+=fLe(o),r=n+=1;continue}let s=e.codePointAt(n);if(i+=`&#x${s.toString(16)};`,s!==o)n++;r=n+=1}if(i===void 0)return e;if(r<t)i+=e.substr(r);return i}function xLe(e,t){if(e.lastIndex=0,!e.test(t))return t;let i="",r=0;do{let n=e.lastIndex-1;if(r!==n)i+=t.substring(r,n);let o=t.charCodeAt(n);i+=fLe(o),r=n+1}while(e.test(t));return i+t.substring(r)}function gle(e){return xLe(yDi,e)}function yle(e){return xLe(bDi,e)}var gDi=1342177476,xle,yDi,bDi;var gLe=Wo(()=>{xle=/["&'<>\u0080-\uFFFF]/g;yDi=/["&\u{A0}]/gu;bDi=/[&<>\u{A0}]/gu});var yLe,bLe;var ELe=Wo(()=>{gLe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(yLe||(yLe={}));(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"})(bLe||(bLe={}))});var ALe,vLe;var wLe=Wo(()=>{ALe=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])),vLe=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 SDi(e,t={}){let i="length"in e?e:[e],r=t.xmlMode??!1,n="";for(let o=0;o<i.length;o++)n+=kLe(i[o],t,r);return n}function SLe(e,t,i){let r="";for(let n=0;n<e.length;n++)r+=kLe(e[n],t,i);return r}function kLe(e,t,i){switch(e.type){case tle:return SLe(e.children,t,i);case rle:return`<${e.data}>`;case nle:return`<!--${e.data}-->`;case cle:return`<![CDATA[${e.children[0].data}]]>`;case ole:case sle:case ale:return kDi(e,t,i);case ile:{let r=e,n=r.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!i&&r.parent&&EDi.has(r.parent.name)))return i||t.encodeEntities!=="utf8"?hU(n):yle(n);return n}}}function kDi(e,t,i){if(i==="foreign"){if(e.name=ALe.get(e.name)??e.name,e.parent&&wDi.has(e.parent.name))i=!1}if(!i&&vDi.has(e.name))i="foreign";let{name:r,children:n}=e,o=!i&&ADi.has(r),s=`<${r}${CDi(e.attribs,t,i)}`;if(n.length===0&&(i?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=i?"/>":" />";else{if(s+=">",n.length>0)s+=SLe(n,t,i);if(!o)s+=`</${r}>`}return s}function BDi(e){return e.replaceAll('"',"&quot;")}function CDi(e,t,i){if(!e)return"";let r=(t.encodeEntities??t.decodeEntities)===!1?BDi:i||t.encodeEntities!=="utf8"?hU:gle,n=i==="foreign",o=!!(t.emptyAttrs??i),s="";for(let a in e){if(!Object.hasOwn(e,a))continue;let c=e[a],u=n?vLe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${u}`:` ${u}="${r(c==null?"":String(c))}"`}return s}var EDi,ADi,vDi,wDi,BLe;var CLe=Wo(()=>{K2();ELe();wLe();EDi=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),ADi=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),vDi=new Set(["svg","math"]),wDi=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));BLe=SDi});function DLe(e,t){return BLe(e,t)}function DDi(e,t){return ad(e)?e.children.map((i)=>DLe(i,t)).join(""):""}function fU(e){if(Array.isArray(e))return e.map(fU).join("");if(Al(e))return e.name==="br"?`
2
+ import"./chunks/index-cgg754d1.js";import{C as Z3,D as eoi,F as wni,H as sBe}from"./chunks/index-fpnp8e2n.js";import{J as One,K as bD}from"./chunks/index-mnxx4ztw.js";import{L as aue}from"./chunks/index-9deh2vm3.js";import"./chunks/index-e84v85w3.js";import"./chunks/index-66v76w4h.js";import"./chunks/index-624fhq2j.js";import"./chunks/index-z0k97qgd.js";import"./chunks/index-x8e40qwv.js";import{Q as pw}from"./chunks/index-j0bf565n.js";import{$ as Tq,Aa as UPe,Ba as i5i,Ca as Iri,Da as PX,Ea as qAi,Fa as lm,Na as vj,S as kMe,T as Sj,V as Na,W as i8,X as tpe,Y as ope,Z as Ey,_ as _q,aa as Pq,ba as O$e,ca as Rq,da as A9,ea as AHe,fa as Ud,ha as fvi,ia as xvi,ka as gOe,la as WW,ma as oai,na as iv,oa as tN,pa as cni,qa as qx,ra as HX,sa as ani,ta as lni,ua as VAi,va as UAi,wa as aD,xa as bst,ya as t5i,za as jPe}from"./chunks/index-vjz32ya5.js";import{Qa as Iae,Ra as yki}from"./chunks/index-cpg3s6b6.js";import"./chunks/index-vbw249qg.js";import{$a as Pt,$b as SI,$c as p5,$d as $E,$e as UO,$f as Fw,$g as wce,$i as Hge,$j as Lg,Ab as NHe,Ac as mce,Ad as jg,Af as PE,Ag as Aae,Ah as Pc,Ai as Zge,Aj as Kg,Bb as LHe,Bc as O2,Bd as hce,Bf as Bw,Bh as OQe,Bi as Vge,Bj as Iw,Cc as ZE,Cf as nae,Ch as du,Ci as Cat,Cj as Bae,Dc as y0,Dd as oc,Df as Cf,Dh as FI,Di as Dat,Dj as _w,Eb as zHe,Ec as Wg,Ed as Ut,Eg as P2i,Eh as wae,Ei as d5,Ej as Oj,Fc as JE,Fd as UQ,Fh as Sae,Gb as jHe,Gc as tv,Gd as L2,Gh as Xt,Gi as ipe,Hc as TAi,Hd as up,Hh as kf,Hj as Tw,Ic as iZe,Id as Pa,Ie as Ug,If as CI,Ig as _Xt,Ih as LJ,Ii as m0,Ij as Pw,Jc as i0e,Jd as px,Jf as oae,Jg as IQ,Jh as zJ,Kd as Zn,Kf as sae,Kg as GJt,Kh as ts,Lc as qJ,Ld as om,Lf as aae,Lg as wj,Lh as Ln,Mc as $J,Md as aQ,Mf as DI,Mh as Avi,Nc as GJ,Nd as NJt,Nf as cae,Nh as es,Nj as ZMe,Oc as HJ,Od as W1i,Oe as C5i,Of as lae,Og as d0,Oj as Cae,Pc as MJt,Pd as N3,Pf as uae,Pi as kae,Pj as qE,Qb as _5i,Qc as OJt,Qd as Uh,Qf as dae,Qg as lp,Qj as Sf,Rc as z6e,Rd as iat,Rf as pae,Rg as xce,Rj as Dae,Sb as T5i,Sc as eO,Sd as XE,Sf as mae,Sg as gce,Sh as nR,Si as kJt,Sj as MI,Tb as wBe,Td as Gp,Tf as hae,Tg as yce,Th as dat,Ti as BJt,Tj as vvi,Ua as cce,Uc as Jn,Ud as ct,Ug as bce,Uh as zW,Ui as jW,Va as lce,Vc as sct,Vd as zl,Ve as TE,Vg as Ece,Vh as zoe,Vi as Aat,Wa as tae,Wc as Ie,Wd as GFe,We as r9i,Wg as Ace,Wh as joe,Wi as vat,Xa as zg,Xc as Ah,Xd as fce,Xe as R9i,Xg as Mw,Xi as D9i,Ya as kw,Yc as Sn,Ye as KFe,Yf as _f,Yg as vce,Yi as I9i,Yj as HE,Za as iae,Zc as YW,Ze as uki,Zf as Hj,Zg as vn,Zh as n9i,Zi as wat,Zj as Sy,_a as wI,_b as Uu,_c as nct,_d as kI,_e as dki,_g as zs,_i as Sat,_j as Bf,ab as Ci,ac as en,ad as RB,ae as QE,af as wm,ah as Mi,aj as pat,ak as EQt,bc as Gg,bd as KW,be as A3,bf as e2,bh as Sce,bj as xat,bk as sc,cb as fe,cc as Pm,cd as Hat,ce as LPe,cf as b9i,ch as kce,cj as sR,db as EA,dc as $i,dd as h5,de as DMe,df as E9i,dg as fae,dh as Rm,dj as kat,eb as bt,ec as uu,ed as Yc,ee as O5i,ef as Toe,eg as GE,eh as Ht,ej as aR,fb as c$,fc as ec,fd as yv,fe as _W,ff as pki,fg as qg,fh as zn,fi as sC,fj as Soe,gb as qc,gc as h0,gd as uR,ge as OQ,gf as mki,gg as Cw,gh as Ho,gi as C4e,gj as gat,hb as LWe,hc as rae,hd as gv,he as Cne,hf as j2i,hg as II,hh as I9,hi as B4e,hj as v2i,ib as w_,id as vh,ie as NQ,if as U2i,ig as xae,ih as PI,ii as iai,ij as yat,jb as S_,jd as wye,je as Fre,jf as q2i,jg as Mj,jh as Vn,ji as aC,jj as eQ,kb as gi,kc as uce,kd as tct,ke as Est,kf as $2i,kg as _I,kh as Ft,ki as Yvi,kj as GW,lb as R9,lc as on,ld as ect,le as aw,lf as G2i,lg as gae,lj as HW,mb as l$,mc as In,md as nJ,me as B3,mf as hki,mg as yae,mj as bat,nb as u_,nc as Sst,nd as act,ne as C3,nf as c9i,ng as F2,nj as K2i,oc as dce,od as Mat,oe as age,of as l9i,og as bae,oh as Lr,oj as Bat,pb as s_,pd as Oat,pe as Dni,pf as m9i,ph as p1i,pj as Rat,qb as lpe,qc as NI,qe as C0,qf as A9i,qg as Eae,qh as GL,qj as Y2i,rb as u$,rc as LI,rd as VW,re as yI,rf as v9i,rh as u1i,ri as ine,rj as V2i,sb as ns,sc as Fj,sd as cct,se as OPe,sf as w9i,sg as Ls,sh as vae,sj as mat,tb as ci,tc as pce,td as Dye,te as cz,tf as _oe,th as qi,tj as MJ,ub as et,uc as Hg,ue as uke,uf as gki,uj as QM,vb as Ro,vc as zI,vd as Mvi,vf as x9i,vg as Dw,vj as mJt,wb as Us,wc as jI,we as gA,wf as T2i,wj as Fm,xb as Ym,xc as UI,xd as ws,xe as IMe,xh as $g,xi as B2i,xj as Ow,yb as ape,yc as qI,ye as HQe,yh as Lt,yi as C2i,yj as Zg,zc as $I,ze as WQe,zg as TI,zh as Df,zi as cR,zj as Vg}from"./chunks/index-r6mr3e4f.js";import{$k as sGe,$m as o1i,$n as cp,Ak as EX,Al as Cti,Am as Bee,An as CS,Bk as fN,Bl as YQ,Bm as Fee,Bn as Ise,Ck as Z7,Cl as fwi,Cm as XJ,Cn as Tc,Dk as vee,Dl as xwi,Dm as iQ,Dn as xri,Ek as t6,El as oH,Em as Er,En as $d,Fk as Aee,Fm as I5i,Fn as sd,Gk as R1,Gl as YHe,Gm as $q,Gn as pu,Hk as Xoi,Hl as JHe,Hm as Em,Hn as nt,Ik as esi,Il as FQe,Jk as m2i,Jl as pn,Jm as Tne,Kk as voe,Kl as Qm,Km as Tee,Kn as BI,Lk as h2i,Ll as X1,Lm as tz,Ln as Im,Mk as nsi,Ml as rre,Mm as une,Mn as _se,Nk as f2i,Nl as fAi,Nm as mPe,Ok as QBe,Ol as nre,Om as WL,On as Rse,Pk as XBe,Pl as Un,Pm as ZL,Qk as xN,Ql as r8,Qm as xz,Rk as e4e,Rl as cr,Rm as u6i,Sk as osi,Sl as upe,Sm as gz,Tk as t4e,Tl as n$,Tm as fQ,Uk as ssi,Um as YQt,Vk as asi,Vl as fv,Vm as QQt,Wk as wee,Wl as be,Wm as nXt,Xk as See,Xm as XQt,Yk as csi,Yl as Rs,Ym as eXt,Zk as kee,Zn as nd,_k as Oh,_m as $re,_n as ap,al as Lh,am as Ni,an as s1i,bl as Fx,bm as Nq,bn as nB,ck as psi,cl as yl,cm as X9i,cn as aoe,co as RI,dk as ESi,dl as Coe,dm as R2,dn as coe,em as tQ,en as qre,fl as G9i,fm as DW,fn as sD,gk as Ia,gl as H9i,gm as kB,gn as TTe,hk as Nx,hn as RTe,ik as pQ,in as L1i,jl as ND,jm as tX,jn as h1i,kk as Cr,km as $ei,kn as z1i,lk as lr,lm as EJt,ln as f1i,mk as x3,mm as NJ,mn as b1i,nk as Gne,nl as vI,nm as OJ,nn as cQ,ok as $ne,ol as dwi,om as aHe,on as oB,pk as q6,pn as sH,qk as TL,qn as aH,rk as qn,rl as lki,rn as ZJ,sk as $6,sm as Ivi,sn as MQe,tk as z_e,tl as Ewi,tm as bA,ul as Xse,um as lO,un as rii,vk as r4e,vl as Tj,vn as rge,wk as Zb,wl as Pj,xk as yee,xl as Rj,xn as Jb,yk as bee,yn as KAi,zk as p2i,zl as lne,zn as M6}from"./chunks/index-2tdttvw4.js";import{eo as X_e,go as Bj}from"./chunks/index-vb4gsj32.js";import{$v as p0,Jt as ZW,Nv as Je,Os as vs,Uv as Fat,Xp as kge,aw as $9,cw as Xa,ew as qd,fw as iei,gw as zr,hw as fki,ls as gl,ns as G9,zs as Ta}from"./chunks/index-126267mh.js";import{zx as l}from"./chunks/index-p6bnaf8r.js";import"./chunks/index-ahe7gn4n.js";import{Dx as vl,Ex as xTi,Fx as E,Gx as ey,Hx as Wo,Ix as ce}from"./chunks/index-f709exx1.js";function WNe(e){return e===0||e>=55296&&e<=57343||e>1114111}function ZNe(e){if(WNe(e))return 65533;if(e>=128&&e<=159)return YCi[e-128]||e;return e}function VNe(e){return WNe(e)?65533:e}var YCi;var KNe=Wo(()=>{YCi=[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 YNe(e,t,i,r,n,o){let a=e.length,c=o*90,u=0,d=()=>{let N=Nm[e.charCodeAt(u++)];return N<o?N:N*91-c+Nm[e.charCodeAt(u++)]},p=i-r,m=i+n,h=new Int32Array(m);h.fill(-1,r,o),h.fill(-1,o+p,m);let f=new Int32Array(m),g=new Int32Array(m);function y(N,q){let K=0,ue=q,G=q+N;while(ue<G){let S=Nm[e.charCodeAt(u++)];if(S<89)K+=S,h[ue++]=K;else if(S===89){let P=Nm[e.charCodeAt(u++)]+2;while(P--)h[ue++]=++K}else{let P=Nm[e.charCodeAt(u++)];K+=89+(P<90?P*91+Nm[e.charCodeAt(u++)]:Nm[e.charCodeAt(u++)]*8281+Nm[e.charCodeAt(u++)]*91+Nm[e.charCodeAt(u++)]),h[ue++]=K}}}y(r,0),y(p,o);let b=new Int32Array(n*2),v=0,w=0;function D(N,q){for(let K=0;K<N;K++){let ue=q+K,G=d(),S=d();b[w*2]=G,b[w*2+1]=S,w+=1,f[ue]=v;let P=(h[G]<0?g[G]:1)+(h[S]<0?g[S]:1);g[ue]=P,v+=P}}D(n-o+r,o+p),D(o-r,r);let R=new Uint16Array(v),O=0;for(let N=0;N<w;N++)for(let q=0;q<2;q++){let K=b[N*2+q],ue=h[K];if(ue<0){let G=f[K],S=G+g[K];while(G<S)R[O++]=R[G++]}else R[O++]=ue}let k=new Uint16Array(t),j=0;while(u<a){let N=Nm[e.charCodeAt(u++)];if(N>=o)N=N*91-c+Nm[e.charCodeAt(u++)];let q=h[N];if(q<0){let K=f[N],ue=K+g[N];while(K<ue)k[j++]=R[K++]}else k[j++]=q}return k}var Nm;var JNe=Wo(()=>{Nm=(()=>{let e=new Uint8Array(127),t=0;for(let i=33;i<=126;i++)if(i!==34&&i!==36&&i!==92)e[i]=t++;return e})()});var Kce;var QNe=Wo(()=>{JNe();Kce=YNe("!}.&u%}'&}*'~!6*)%&,~!J~!J~%L~y<~!R,~~%Lu~~#GD~~#|)1#%}^%}2%+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?C2F|]i[vrv{z;h]eb?C2F|^iZu.vix,hZq3ah!.(?C2F|QOu!5ShXM:2<BaY?C2F|P",13494,2713,49,25,61)});var e7;var Yce=Wo(()=>{e7=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 rc;var XNe=Wo(()=>{(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"})(rc||(rc={}))});function eLe(e){return e-El.ZERO>>>0<=9}function JCi(e){return(e|rU)-El.LOWER_A>>>0<=5}function QCi(e){return(e|rU)-El.LOWER_A>>>0<=25}function XCi(e){return e===El.EQUALS||QCi(e)||eLe(e)}class Jce{decodeTree;emitCodePoint;errors;state=bl.EntityStart;consumed=1;result=0;treeIndex=0;excess=1;decodeMode=Lm.Strict;runConsumed=0;constructor(e,t,i){this.decodeTree=e,this.emitCodePoint=t,this.errors=i}startEntity(e){this.decodeMode=e,this.state=bl.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(e,t){switch(this.state){case bl.EntityStart:{if(e.charCodeAt(t)===El.NUM)return this.state=bl.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1);return this.state=bl.NamedEntity,this.stateNamedEntity(e,t)}case bl.NumericStart:return this.stateNumericStart(e,t);case bl.NumericDecimal:return this.stateNumericDecimal(e,t);case bl.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)|rU)===El.LOWER_X)return this.state=bl.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1);return this.state=bl.NumericDecimal,this.stateNumericDecimal(e,t)}stateNumericHex(e,t){let i=e.length,{result:r}=this,{consumed:n}=this;while(t<i){let o=e.charCodeAt(t);if(eLe(o)||JCi(o)){let s=o<=El.NINE?o-El.ZERO:(o|rU)-El.LOWER_A+10;r=r*16+s,n+=1,t+=1}else return this.result=r,this.consumed=n,this.emitNumericEntity(o,3)}return this.result=r,this.consumed=n,-1}stateNumericDecimal(e,t){let i=e.length,{result:r}=this,{consumed:n}=this;while(t<i){let o=e.charCodeAt(t)-El.ZERO;if(o>>>0>9)return this.result=r,this.consumed=n,this.emitNumericEntity(o+El.ZERO,2);r=r*10+o,n+=1,t+=1}return this.result=r,this.consumed=n,-1}emitNumericEntity(e,t){if(this.consumed<=t)return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===El.SEMI)this.consumed+=1;else if(this.decodeMode===Lm.Strict)return 0;if(this.emitCodePoint((this.decodeTree===e7?VNe:ZNe)(this.result),this.consumed),this.errors){if(e!==El.SEMI)this.errors.missingSemicolonAfterCharacterReference();this.errors.validateNumericCharacterReference(this.result)}return this.consumed}flushAndEmitLegacyOrReject(e,t,i,r){return this.consumed=e,this.excess=t,this.result===0||this.decodeMode===Lm.Attribute&&(r===0||t>1||XCi(i))?0:this.emitNotTerminatedNamedEntity()}stateNamedEntity(e,t){let{decodeTree:i}=this,r=e.length,n=this.decodeMode===Lm.Strict,{treeIndex:o}=this,{excess:s}=this,{consumed:a}=this,c=i[o];while(t<r){while((c&(rc.VALUE_LENGTH|rc.FLAG13))===0&&(c&rc.JUMP_TABLE)!==0){let m=e.charCodeAt(t),h=c&rc.JUMP_TABLE,f=(c&rc.BRANCH_LENGTH)>>7;if(f===0){if(m!==h)return this.flushAndEmitLegacyOrReject(a,s,m,0);o+=1}else{let g=m-h;if(g>>>0>=f)return this.flushAndEmitLegacyOrReject(a,s,m,0);let y=i[o+1+g];if(y===0)return this.flushAndEmitLegacyOrReject(a,s,m,0);o=o+f+y&65535}if(c=i[o],t+=1,s+=1,t>=r)break}if(t>=r)break;if((c&(rc.VALUE_LENGTH|rc.FLAG13))===rc.FLAG13){let m=(c&rc.BRANCH_LENGTH)>>7,{runConsumed:h}=this;if(h===0){let f=e.charCodeAt(t);if(f!==(c&rc.JUMP_TABLE))return this.flushAndEmitLegacyOrReject(a,s,f,0);t+=1,s+=1,h=1}while(h<m){if(t>=r)return this.treeIndex=o,this.excess=s,this.consumed=a,this.runConsumed=h,-1;let f=h-1,y=i[o+1+(f>>1)]>>((f&1)<<3)&255,b=e.charCodeAt(t);if(b!==y)return this.runConsumed=0,this.flushAndEmitLegacyOrReject(a,s,b,0);t+=1,s+=1,h+=1}this.runConsumed=0,o+=1+(m>>1),c=i[o];continue}let u=c>>>14,d=e.charCodeAt(t);if(u!==0){if(!n&&(c&rc.FLAG13)===0)this.result=o,a+=s-1,s=1;if(d===El.SEMI)return this.emitNamedEntityData(o,u,a+s);if(u===1)return this.flushAndEmitLegacyOrReject(a,s,d,u)}let p=eDi(i,c,o+(u||1),d);if(p<0)return this.flushAndEmitLegacyOrReject(a,s,d,u);o=p,c=i[o],t+=1,s+=1}if(!n&&c>>>14!==0&&(c&rc.FLAG13)===0)this.result=o,a+=s-1,s=1;return this.treeIndex=o,this.excess=s,this.consumed=a,-1}emitNotTerminatedNamedEntity(){let{result:e,decodeTree:t}=this,i=t[e]>>>14;return this.emitNamedEntityData(e,i,this.consumed),this.errors?.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,i){let{decodeTree:r}=this;if(this.emitCodePoint(t===1?r[e]&rc.VALUE_MASK:r[e+1],i),t===3)this.emitCodePoint(r[e+2],i);return i}end(){switch(this.state){case bl.NamedEntity:return this.result!==0&&(this.decodeMode!==Lm.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case bl.NumericDecimal:return this.emitNumericEntity(0,2);case bl.NumericHex:return this.emitNumericEntity(0,3);case bl.NumericStart:return this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed),0;default:return 0}}}function eDi(e,t,i,r){let n=(t&rc.BRANCH_LENGTH)>>7,o=t&rc.JUMP_TABLE;if(o){if(n===0)return r===o?i:-1;let c=r-o;if(c>>>0>=n)return-1;let u=e[i+c];return u===0?-1:i+n+u-1&65535}if(n===0)return-1;let s=n+1>>1,a=i+s+n;for(let c=0;c<n;c++){let d=e[i+(c>>1)]>>((c&1)<<3)&255;if(d===r){let p=i+s+c;return a+e[p]&65535}if(d>r)return-1}return-1}var El,rU=32,bl,Lm;var tLe=Wo(()=>{KNe();Yce();XNe();QNe();Yce();(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"})(El||(El={}));(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"})(bl||(bl={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(Lm||(Lm={}))});function jw(e){return e===fi.Space||e===fi.NewLine||e===fi.Tab||e===fi.FormFeed||e===fi.CarriageReturn}function G2(e){return e===fi.Slash||e===fi.Gt||jw(e)}function tDi(e){return e>=fi.LowerA&&e<=fi.LowerZ||e>=fi.UpperA&&e<=fi.UpperZ}class H2{cbs;state=He.Text;buffer="";sectionStart=0;index=0;entityStart=0;baseState=He.Text;isSpecial=!1;running=!0;offset=0;xmlMode;decodeEntities;recognizeSelfClosing;entityDecoder;constructor({xmlMode:e=!1,decodeEntities:t=!0,recognizeSelfClosing:i=e},r){this.cbs=r,this.xmlMode=e,this.decodeEntities=t,this.recognizeSelfClosing=i,this.entityDecoder=new Jce(e?e7:Kce,(n,o)=>this.emitCodePoint(n,o))}reset(){this.state=He.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=He.Text,this.isSpecial=!1,this.currentSequence=Xi.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===fi.Lt||!this.decodeEntities&&this.fastForwardTo(fi.Lt)){if(this.index>this.sectionStart)this.cbs.ontext(this.sectionStart,this.index);this.state=He.BeforeTagName,this.sectionStart=this.index}else if(this.decodeEntities&&e===fi.Amp)this.startEntity()}currentSequence=Xi.Empty;sequenceIndex=0;enterTagBody(){if(this.currentSequence===Xi.Plaintext)this.currentSequence=Xi.Empty,this.state=He.InPlainText;else if(this.isSpecial)this.state=He.InSpecialTag,this.sequenceIndex=0;else this.state=He.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===Xi.ScriptEnd&&t===Xi.StyleEnd[3]){this.currentSequence=Xi.StyleEnd,this.sequenceIndex=4;return}if(this.currentSequence===Xi.TitleEnd&&t===Xi.TextareaEnd[3]){this.currentSequence=Xi.TextareaEnd,this.sequenceIndex=4;return}}else if(this.sequenceIndex===4&&this.currentSequence===Xi.NoembedEnd&&t===Xi.NoframesEnd[4]){this.currentSequence=Xi.NoframesEnd,this.sequenceIndex=5;return}}else if(G2(e)){this.sequenceIndex=0,this.state=He.InTagName,this.stateInTagName(e);return}this.isSpecial=!1,this.currentSequence=Xi.Empty,this.sequenceIndex=0,this.state=He.InTagName,this.stateInTagName(e)}stateCDATASequence(e){if(e===Xi.Cdata[this.sequenceIndex]){if(++this.sequenceIndex===Xi.Cdata.length)this.state=He.InCommentLike,this.currentSequence=Xi.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1}else if(this.sequenceIndex=0,this.xmlMode)this.state=He.InDeclaration,this.stateInDeclaration(e);else this.state=He.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=He.Text}stateInCommentLike(e){if(!this.xmlMode&&this.currentSequence===Xi.CommentEnd&&this.sequenceIndex<=1&&this.index===this.sectionStart+this.sequenceIndex&&e===fi.Gt)this.emitComment(this.sequenceIndex);else if(this.currentSequence===Xi.CommentEnd&&this.sequenceIndex===2&&e===fi.Gt)this.emitComment(2);else if(this.currentSequence===Xi.CommentEnd&&this.sequenceIndex===this.currentSequence.length-1&&e!==fi.Gt)this.sequenceIndex=Number(e===fi.Dash);else if(e===this.currentSequence[this.sequenceIndex]){if(++this.sequenceIndex===this.currentSequence.length){if(this.currentSequence===Xi.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=He.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?!G2(e):tDi(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(G2(e)){let t=this.index-this.currentSequence.length;if(this.sectionStart<t){let i=this.index;this.index=t,this.cbs.ontext(this.sectionStart,t),this.index=i}this.isSpecial=!1,this.sectionStart=t+2,this.stateInClosingTagName(e);return}this.sequenceIndex=0}if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(this.sequenceIndex===0){if(this.currentSequence===Xi.TitleEnd||this.currentSequence===Xi.TextareaEnd){if(this.decodeEntities&&e===fi.Amp)this.startEntity()}else if(this.fastForwardTo(fi.Lt))this.sequenceIndex=1}else this.sequenceIndex=Number(e===fi.Lt)}stateBeforeTagName(e){if(e===fi.ExclamationMark)this.state=He.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===fi.Questionmark)if(this.xmlMode)this.state=He.InProcessingInstruction,this.sequenceIndex=0,this.sectionStart=this.index+1;else this.state=He.InSpecialComment,this.sectionStart=this.index;else if(this.isTagStartChar(e)){this.sectionStart=this.index;let t=this.xmlMode||this.cbs.isInForeignContext?.()?void 0:iDi.get(e|32);if(t===void 0)this.state=He.InTagName;else this.isSpecial=!0,this.currentSequence=t,this.sequenceIndex=3,this.state=He.SpecialStartSequence}else if(e===fi.Slash)this.state=He.BeforeClosingTagName;else this.state=He.Text,this.stateText(e)}stateInTagName(e){if(G2(e))this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateBeforeClosingTagName(e){if(jw(e))if(this.xmlMode);else this.state=He.InSpecialComment,this.sectionStart=this.index;else if(e===fi.Gt){if(this.state=He.Text,!this.xmlMode)this.sectionStart=this.index+1}else this.state=this.isTagStartChar(e)?He.InClosingTagName:He.InSpecialComment,this.sectionStart=this.index}stateInClosingTagName(e){if(G2(e))this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=He.AfterClosingTagName,this.stateAfterClosingTagName(e)}stateAfterClosingTagName(e){if(e===fi.Gt||this.fastForwardTo(fi.Gt))this.state=He.Text,this.sectionStart=this.index+1}stateBeforeAttributeName(e){if(e===fi.Gt)this.cbs.onopentagend(this.index),this.enterTagBody(),this.sectionStart=this.index+1;else if(e===fi.Slash)this.state=He.InSelfClosingTag;else if(!jw(e))this.state=He.InAttributeName,this.sectionStart=this.index}stateInSelfClosingTag(e){if(e===fi.Gt){if(this.cbs.onselfclosingtag(this.index),this.sectionStart=this.index+1,!this.recognizeSelfClosing){this.enterTagBody();return}this.state=He.Text,this.isSpecial=!1,this.currentSequence=Xi.Empty}else if(!jw(e))this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e)}stateInAttributeName(e){if(e===fi.Eq||G2(e))this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=He.AfterAttributeName,this.stateAfterAttributeName(e)}stateAfterAttributeName(e){if(e===fi.Eq)this.state=He.BeforeAttributeValue;else if(e===fi.Slash||e===fi.Gt)this.cbs.onattribend(dp.NoValue,this.sectionStart),this.sectionStart=-1,this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(!jw(e))this.cbs.onattribend(dp.NoValue,this.sectionStart),this.state=He.InAttributeName,this.sectionStart=this.index}stateBeforeAttributeValue(e){if(e===fi.DoubleQuote)this.state=He.InAttributeValueDq,this.sectionStart=this.index+1;else if(e===fi.SingleQuote)this.state=He.InAttributeValueSq,this.sectionStart=this.index+1;else if(!jw(e))this.sectionStart=this.index,this.state=He.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===fi.DoubleQuote?dp.Double:dp.Single,this.index+1),this.state=He.BeforeAttributeName;else if(this.decodeEntities&&e===fi.Amp)this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,fi.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,fi.SingleQuote)}stateInAttributeValueNoQuotes(e){if(jw(e)||e===fi.Gt)this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(dp.Unquoted,this.index),this.state=He.BeforeAttributeName,this.stateBeforeAttributeName(e);else if(this.decodeEntities&&e===fi.Amp)this.startEntity()}stateBeforeDeclaration(e){if(e===fi.OpeningSquareBracket)this.state=He.CDATASequence,this.sequenceIndex=0;else if(this.xmlMode)this.state=e===fi.Dash?He.BeforeComment:He.InDeclaration;else if((e|32)===Xi.Doctype[0])this.state=He.DeclarationSequence,this.currentSequence=Xi.Doctype,this.sequenceIndex=1;else if(e===fi.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1;else if(e===fi.Dash)this.state=He.BeforeComment;else this.state=He.InSpecialComment}stateDeclarationSequence(e){if(this.sequenceIndex===this.currentSequence.length)this.state=He.InDeclaration,this.stateInDeclaration(e);else if((e|32)===this.currentSequence[this.sequenceIndex])this.sequenceIndex+=1;else if(e===fi.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1;else this.state=He.InSpecialComment}stateInDeclaration(e){if(e===fi.Gt||this.fastForwardTo(fi.Gt))this.cbs.ondeclaration(this.sectionStart,this.index),this.state=He.Text,this.sectionStart=this.index+1}stateInProcessingInstruction(e){if(e===fi.Questionmark)this.sequenceIndex=1;else if(e===fi.Gt&&this.sequenceIndex===1)this.cbs.onprocessinginstruction(this.sectionStart,this.index-1),this.sequenceIndex=0,this.state=He.Text,this.sectionStart=this.index+1;else this.sequenceIndex=Number(this.fastForwardTo(fi.Questionmark))}stateBeforeComment(e){if(e===fi.Dash)this.state=He.InCommentLike,this.currentSequence=Xi.CommentEnd,this.sequenceIndex=0,this.sectionStart=this.index+1;else if(this.xmlMode)this.state=He.InDeclaration;else if(e===fi.Gt)this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1;else this.state=He.InSpecialComment}stateInSpecialComment(e){if(e===fi.Gt||this.fastForwardTo(fi.Gt))this.cbs.oncomment(this.sectionStart,this.index,0),this.state=He.Text,this.sectionStart=this.index+1}startEntity(){this.baseState=this.state,this.state=He.InEntity,this.entityStart=this.index,this.entityDecoder.startEntity(this.xmlMode?Lm.Strict:this.baseState===He.Text||this.baseState===He.InSpecialTag?Lm.Legacy:Lm.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)===fi.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===He.Text||this.state===He.InPlainText||this.state===He.InSpecialTag&&this.sequenceIndex===0)this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index;else if(this.state===He.InAttributeValueDq||this.state===He.InAttributeValueSq||this.state===He.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 He.Text:{this.stateText(e);break}case He.InPlainText:{this.index=this.buffer.length+this.offset-1;break}case He.SpecialStartSequence:{this.stateSpecialStartSequence(e);break}case He.InSpecialTag:{this.stateInSpecialTag(e);break}case He.CDATASequence:{this.stateCDATASequence(e);break}case He.DeclarationSequence:{this.stateDeclarationSequence(e);break}case He.InAttributeValueDq:{this.stateInAttributeValueDoubleQuotes(e);break}case He.InAttributeName:{this.stateInAttributeName(e);break}case He.InCommentLike:{this.stateInCommentLike(e);break}case He.InSpecialComment:{this.stateInSpecialComment(e);break}case He.BeforeAttributeName:{this.stateBeforeAttributeName(e);break}case He.InTagName:{this.stateInTagName(e);break}case He.InClosingTagName:{this.stateInClosingTagName(e);break}case He.BeforeTagName:{this.stateBeforeTagName(e);break}case He.AfterAttributeName:{this.stateAfterAttributeName(e);break}case He.InAttributeValueSq:{this.stateInAttributeValueSingleQuotes(e);break}case He.BeforeAttributeValue:{this.stateBeforeAttributeValue(e);break}case He.BeforeClosingTagName:{this.stateBeforeClosingTagName(e);break}case He.AfterClosingTagName:{this.stateAfterClosingTagName(e);break}case He.InAttributeValueNq:{this.stateInAttributeValueNoQuotes(e);break}case He.InSelfClosingTag:{this.stateInSelfClosingTag(e);break}case He.InDeclaration:{this.stateInDeclaration(e);break}case He.BeforeDeclaration:{this.stateBeforeDeclaration(e);break}case He.BeforeComment:{this.stateBeforeComment(e);break}case He.InProcessingInstruction:{this.stateInProcessingInstruction(e);break}case He.InEntity:{this.stateInEntity();break}}this.index++}this.cleanup()}finish(){if(this.state===He.InEntity)this.entityDecoder.end(),this.state=this.baseState;this.handleTrailingData(),this.cbs.onend()}handleTrailingCommentLikeData(e){if(this.state!==He.InCommentLike)return!1;if(this.currentSequence===Xi.CdataEnd)if(this.xmlMode){if(this.sectionStart<e)this.cbs.oncdata(this.sectionStart,e,0)}else{let t=this.sectionStart-Xi.Cdata.length-1;this.cbs.oncomment(t,e,0)}else{let t=this.xmlMode?0:Math.min(this.sequenceIndex,Xi.CommentEnd.length-1);this.cbs.oncomment(this.sectionStart,e,t)}return!0}handleTrailingMarkupDeclaration(e){if(this.xmlMode)switch(this.state){case He.InSpecialComment:case He.BeforeComment:case He.CDATASequence:case He.DeclarationSequence:case He.InDeclaration:return this.cbs.ontext(this.sectionStart,e),!0;default:return!1}switch(this.state){case He.BeforeDeclaration:case He.InSpecialComment:case He.BeforeComment:case He.CDATASequence:return this.cbs.oncomment(this.sectionStart,e,0),!0;case He.DeclarationSequence:{if(this.sequenceIndex!==Xi.Doctype.length)this.cbs.oncomment(this.sectionStart,e,0);return!0}case He.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 He.InTagName:case He.BeforeAttributeName:case He.BeforeAttributeValue:case He.AfterAttributeName:case He.InAttributeName:case He.InAttributeValueSq:case He.InAttributeValueDq:case He.InAttributeValueNq:case He.InClosingTagName:break;default:this.cbs.ontext(this.sectionStart,e)}}emitCodePoint(e,t){if(this.baseState!==He.Text&&this.baseState!==He.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 fi,He,dp,Xi,iDi;var Qce=Wo(()=>{tLe();(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"})(fi||(fi={}));(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"})(He||(He={}));(function(e){e[e.NoValue=0]="NoValue",e[e.Unquoted=1]="Unquoted",e[e.Single=2]="Single",e[e.Double=3]="Double"})(dp||(dp={}));Xi={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])},iDi=new Map([[Xi.IframeEnd[2],Xi.IframeEnd],[Xi.NoembedEnd[2],Xi.NoembedEnd],[Xi.Plaintext[2],Xi.Plaintext],[Xi.ScriptEnd[2],Xi.ScriptEnd],[Xi.TitleEnd[2],Xi.TitleEnd],[Xi.XmpEnd[2],Xi.XmpEnd]])});class V2{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??H2)(this.options,this),this.foreignContext=[Xg.None],this.cbs.onparserinit?.(this)}ontext(e,t){let i=this.getSlice(e,t);this.endIndex=t-1,this.cbs.ontext?.(i),this.startIndex=t}ontextentity(e,t){this.endIndex=t-1,this.cbs.ontext?.(iLe(e)),this.startIndex=t}isInForeignContext(){return this.foreignContext[0]!==Xg.None}isVoidElement(e){return this.htmlMode&&nDi.has(e)}readTagName(e,t){let i=this.lowerCaseTagNames?this.getSlice(e,t).toLowerCase():this.getSlice(e,t);if(!(this.lowerCaseTagNames&&this.htmlMode))return i;if(this.foreignContext[0]===Xg.Svg)return cLe.get(i)??i;if(this.foreignContext.length>1){let r=cLe.get(i);if(r!==void 0&&this.stack.includes(r))return r}if(!this.isInForeignContext())return i==="image"?"img":i;return i}onopentagname(e,t){this.endIndex=t,this.emitOpenTag(this.readTagName(e,t))}emitOpenTag(e){if(this.openTagStart=this.startIndex,this.tagname=e,this.htmlMode&&e==="form"&&this.stack.includes("form")){this.tagname="";return}let t=this.htmlMode&&rDi.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(Xg.Svg);else if(e==="math")this.foreignContext.unshift(Xg.MathML);else if(aLe.has(e))this.foreignContext.unshift(Xg.None)}}if(this.cbs.onopentagname?.(e),this.cbs.onopentag)this.attribs={}}endOpenTag(e){if(this.startIndex=this.openTagStart,this.attribs)this.cbs.onopentag?.(this.tagname,this.attribs,e),this.attribs=null;if(this.cbs.onclosetag&&this.isVoidElement(this.tagname))this.cbs.onclosetag(this.tagname,!0);this.tagname=""}onopentagend(e){this.endIndex=e,this.endOpenTag(!1),this.startIndex=e+1}onclosetag(e,t){this.endIndex=t;let i=this.readTagName(e,t);if(!this.isVoidElement(i)){let r=this.stack.indexOf(i);if(r!==-1){for(let n=0;n<r;n++)this.popElement(!0);this.popElement(!1)}else if(this.htmlMode&&i==="p")this.emitOpenTag("p"),this.closeCurrentTag(!0)}else if(this.htmlMode&&i==="br")this.cbs.onopentagname?.("br"),this.cbs.onopentag?.("br",{},!0),this.cbs.onclosetag?.("br",!1);this.startIndex=t+1}onselfclosingtag(e){if(this.endIndex=e,this.recognizeSelfClosing||this.isInForeignContext())this.closeCurrentTag(!1),this.startIndex=e+1;else this.onopentagend(e)}popElement(e){let t=this.stack.shift();if(this.htmlMode&&(oDi.has(t)||aLe.has(t)))this.foreignContext.shift();this.cbs.onclosetag?.(t,e)}closeCurrentTag(e){let t=this.tagname;if(this.endOpenTag(e),this.stack[0]===t)this.popElement(!e)}onattribname(e,t){this.startIndex=e;let i=this.getSlice(e,t);this.attribname=this.lowerCaseAttributeNames?i.toLowerCase():i}onattribdata(e,t){this.attribvalue+=this.getSlice(e,t)}onattribentity(e){this.attribvalue+=iLe(e)}onattribend(e,t){if(this.endIndex=t,this.cbs.onattribute?.(this.attribname,this.attribvalue,e===dp.Double?'"':e===dp.Single?"'":e===dp.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(sDi),i=t<0?e:e.substr(0,t);if(this.lowerCaseTagNames)i=i.toLowerCase();return i}ondeclaration(e,t){this.endIndex=t;let i=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let r=this.htmlMode?this.lowerCaseTagNames?sLe:i.slice(0,sLe.length):this.getInstructionName(i);this.cbs.onprocessinginstruction(`!${r}`,`!${i}`)}this.startIndex=t+1}onprocessinginstruction(e,t){this.endIndex=t;let i=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){let r=this.getInstructionName(i);this.cbs.onprocessinginstruction(`?${r}`,`?${i}`)}this.startIndex=t+1}oncomment(e,t,i){this.endIndex=t,this.cbs.oncomment?.(this.getSlice(e,t-i)),this.cbs.oncommentend?.(),this.startIndex=t+1}oncdata(e,t,i){this.endIndex=t;let r=this.getSlice(e,t-i);if(!this.htmlMode||this.options.recognizeCDATA)this.cbs.oncdatastart?.(),this.cbs.ontext?.(r),this.cbs.oncdataend?.();else if(this.isInForeignContext())this.cbs.ontext?.(r);else this.cbs.oncomment?.(`[CDATA[${r}]]`),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(Xg.None),this.bufferOffset=0,this.writeIndex=0,this.ended=!1}parseComplete(e){this.reset(),this.end(e)}getSlice(e,t){if(e===t)return"";while(e-this.bufferOffset>=this.buffers[0].length)this.shiftBuffer();let i=this.buffers[0].slice(e-this.bufferOffset,t-this.bufferOffset);while(t-this.bufferOffset>this.buffers[0].length)this.shiftBuffer(),i+=this.buffers[0].slice(0,t-this.bufferOffset);return i}shiftBuffer(){this.bufferOffset+=this.buffers[0].length,this.writeIndex--,this.buffers.shift()}write(e){if(this.ended){this.cbs.onerror?.(Error(".write() after done!"));return}if(this.buffers.push(e),this.tokenizer.running)this.tokenizer.write(e),this.writeIndex++}end(e){if(this.ended){this.cbs.onerror?.(Error(".end() after done!"));return}if(e)this.write(e);this.ended=!0,this.tokenizer.end()}pause(){this.tokenizer.pause()}resume(){this.tokenizer.resume();while(this.tokenizer.running&&this.writeIndex<this.buffers.length)this.tokenizer.write(this.buffers[this.writeIndex++]);if(this.ended)this.tokenizer.end()}}var iLe,W2,Ss,Z2,rLe,nLe,oLe,rDi,sLe="doctype",nDi,oDi,aLe,cLe,Xg,sDi;var Xce=Wo(()=>{Qce();({fromCodePoint:iLe}=String),W2=new Set(["input","option","optgroup","select","button","datalist","textarea"]),Ss=new Set(["p"]),Z2=new Set(["h1","h2","h3","h4","h5","h6","p"]),rLe=new Set(["thead","tbody"]),nLe=new Set(["dd","dt"]),oLe=new Set(["rt","rp"]),rDi=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",Ss],["h1",Z2],["h2",Z2],["h3",Z2],["h4",Z2],["h5",Z2],["h6",Z2],["select",W2],["input",W2],["output",W2],["button",W2],["datalist",W2],["textarea",W2],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",nLe],["dt",nLe],["address",Ss],["article",Ss],["aside",Ss],["blockquote",Ss],["details",Ss],["div",Ss],["dl",Ss],["fieldset",Ss],["figcaption",Ss],["figure",Ss],["footer",Ss],["form",Ss],["header",Ss],["hr",Ss],["main",Ss],["nav",Ss],["ol",Ss],["pre",Ss],["section",Ss],["table",Ss],["ul",Ss],["rt",oLe],["rp",oLe],["tbody",rLe],["tfoot",rLe]]),nDi=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),oDi=new Set(["math","svg"]),aLe=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),cLe=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"})(Xg||(Xg={}));sDi=/\s|\//});var nU={};ey(nU,{CDATA:()=>cle,Comment:()=>nle,Directive:()=>rle,Doctype:()=>aDi,ElementType:()=>tn,Root:()=>tle,Script:()=>ole,Style:()=>sle,Tag:()=>ale,Text:()=>ile,isTag:()=>ele});function ele(e){return e.type===tn.Tag||e.type===tn.Script||e.type===tn.Style}var tn,tle,ile,rle,nle,ole,sle,ale,cle,aDi;var K2=Wo(()=>{(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"})(tn||(tn={}));tle=tn.Root,ile=tn.Text,rle=tn.Directive,nle=tn.Comment,ole=tn.Script,sle=tn.Style,ale=tn.Tag,cle=tn.CDATA,aDi=tn.Doctype});class ule{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 lLe(this,e)}}function Al(e){return ele(e)}function dU(e){return e.type===tn.CDATA}function rA(e){return e.type===tn.Text}function dle(e){return e.type===tn.Comment}function cDi(e){return e.type===tn.Directive}function lDi(e){return e.type===tn.Root}function ad(e){return Object.hasOwn(e,"children")}function lLe(e,t=!1){let i;if(rA(e))i=new t7(e.data);else if(dle(e))i=new sU(e.data);else if(Al(e)){let r=t?lle(e.children):[],n=new uU(e.name,{...e.attribs},r);for(let o of r)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"]};i=n}else if(dU(e)){let r=t?lle(e.children):[],n=new lU(r);for(let o of r)o.parent=n;i=n}else if(lDi(e)){let r=t?lle(e.children):[],n=new i7(r);for(let o of r)o.parent=n;if(e["x-mode"])n["x-mode"]=e["x-mode"];i=n}else if(cDi(e)){let r=new aU(e.name,e.data);if(e["x-name"]!=null)r["x-name"]=e["x-name"],r["x-publicId"]=e["x-publicId"],r["x-systemId"]=e["x-systemId"];i=r}else throw Error(`Not implemented yet: ${e.type}`);if(i.startIndex=e.startIndex,i.endIndex=e.endIndex,e.sourceCodeLocation!=null)i.sourceCodeLocation=e.sourceCodeLocation;return i}function lle(e){let t=e.map((i)=>lLe(i,!0));for(let i=1;i<t.length;i++)t[i].prev=t[i-1],t[i-1].next=t[i];return t}var oU,t7,sU,aU,cU,lU,i7,uU;var ple=Wo(()=>{K2();oU=class oU extends ule{data;constructor(e){super();this.data=e}get nodeValue(){return this.data}set nodeValue(e){this.data=e}};t7=class t7 extends oU{type=tn.Text;get nodeType(){return 3}};sU=class sU extends oU{type=tn.Comment;get nodeType(){return 8}};aU=class aU extends oU{type=tn.Directive;name;constructor(e,t){super(t);this.name=e}get nodeType(){return 1}"x-name";"x-publicId";"x-systemId"};cU=class cU extends ule{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}};lU=class lU extends cU{type=tn.CDATA;get nodeType(){return 4}};i7=class i7 extends cU{type=tn.Root;get nodeType(){return 9}};uU=class uU extends cU{name;attribs;type;constructor(e,t,i=[],r=e==="script"?tn.Script:e==="style"?tn.Style:tn.Tag){super(i);this.name=e,this.attribs=t,this.type=r}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 Uw{dom=[];root=new i7(this.dom);callback;options;elementCB;done=!1;tagStack=[this.root];lastNode=null;parser=null;constructor(e,t,i){if(typeof t==="function")i=t,t=uLe;if(typeof e==="object")t=e,e=void 0;this.callback=e??null,this.options=t??uLe,this.elementCB=i??null}onparserinit(e){this.parser=e}onreset(){this.dom=[],this.root=new i7(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){if(this.done)return;this.done=!0,this.parser=null,this.handleCallback(null)}onerror(e){this.handleCallback(e)}onclosetag(){this.lastNode=null;let e=this.tagStack.pop();if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(this.elementCB)this.elementCB(e)}onopentag(e,t){let i=this.options.xmlMode?tn.Tag:void 0,r=new uU(e,t,void 0,i);this.addNode(r),this.tagStack.push(r)}ontext(e){let{lastNode:t}=this;if(t&&t.type===tn.Text){if(t.data+=e,this.options.withEndIndices&&this.parser)t.endIndex=this.parser.endIndex}else{let i=new t7(e);this.addNode(i),this.lastNode=i}}oncomment(e){if(this.lastNode&&this.lastNode.type===tn.Comment){this.lastNode.data+=e;return}let t=new sU(e);this.addNode(t),this.lastNode=t}oncommentend(){this.lastNode=null}oncdatastart(){let e=new t7(""),t=new lU([e]);this.addNode(t),e.parent=t,this.lastNode=e}oncdataend(){this.lastNode=null}onprocessinginstruction(e,t){let i=new aU(e,t);this.addNode(i)}handleCallback(e){if(typeof this.callback==="function")this.callback(e,this.dom);else if(e)throw e}addNode(e){let t=this.tagStack[this.tagStack.length-1],i=t.children[t.children.length-1];if(this.options.withStartIndices&&this.parser)e.startIndex=this.parser.startIndex;if(this.options.withEndIndices&&this.parser)e.endIndex=this.parser.endIndex;if(t.children.push(e),i)e.prev=i,i.next=e;e.parent=t,this.lastNode=null}}var uLe;var nA=Wo(()=>{K2();ple();ple();uLe={withStartIndices:!1,withEndIndices:!1,xmlMode:!1}});function Y2(e,t,i=!0,r=Number.POSITIVE_INFINITY){return dLe(e,Array.isArray(t)?t:[t],i,r)}function dLe(e,t,i,r){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),--r<=0)return n}if(i&&ad(a)&&a.children.length>0)s.unshift(0),o.unshift(a.children)}}function pU(e,t,i=!0){let r=Array.isArray(t)?t:[t];for(let n of r){if(Al(n)&&e(n))return n;if(i&&ad(n)&&n.children.length>0){let o=pU(e,n.children,!0);if(o)return o}}return null}function pLe(e,t){return(Array.isArray(t)?t:[t]).some((i)=>Al(i)&&e(i)||ad(i)&&pLe(e,i.children))}function uDi(e,t){let i=[],r=[Array.isArray(t)?t:[t]],n=[0];for(;;){if(n[0]>=r[0].length){if(r.length===1)return i;r.shift(),n.shift();continue}let o=r[0][n[0]++];if(Al(o)&&e(o))i.push(o);if(ad(o)&&o.children.length>0)n.unshift(0),r.unshift(o.children)}}var mle=Wo(()=>{nA()});function hle(e,t){if(typeof t==="function")return(i)=>Al(i)&&t(i.attribs[e]);return(i)=>Al(i)&&i.attribs[e]===t}function dDi(e,t){return(i)=>e(i)||t(i)}function mLe(e){let t=Object.keys(e).map((i)=>{let r=e[i];return Object.hasOwn(mU,i)?mU[i](r):hle(i,r)});return t.length===0?null:t.reduce(dDi)}function pDi(e,t){let i=mLe(e);return i?i(t):!0}function mDi(e,t,i,r=Number.POSITIVE_INFINITY){let n=mLe(e);return n?Y2(n,t,i,r):[]}function hDi(e,t,i=!0){if(!Array.isArray(t))t=[t];return pU(hle("id",e),t,i)}function qw(e,t,i=!0,r=Number.POSITIVE_INFINITY){return Y2(mU.tag_name(e),t,i,r)}function fDi(e,t,i=!0,r=Number.POSITIVE_INFINITY){return Y2(hle("class",e),t,i,r)}function xDi(e,t,i=!0,r=Number.POSITIVE_INFINITY){return Y2(mU.tag_type(e),t,i,r)}var mU;var fle=Wo(()=>{nA();mle();mU={tag_name(e){if(typeof e==="function")return(t)=>Al(t)&&e(t.name);if(e==="*")return Al;return(t)=>Al(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)=>rA(t)&&e(t.data);return(t)=>rA(t)&&t.data===e}}});function fLe(e){return e===34?"&quot;":e===38?"&amp;":e===39?"&apos;":e===60?"&lt;":e===62?"&gt;":"&nbsp;"}function hLe(e){return e>=128||e>=32&&e<64&&(gDi>>>e&1)===1}function hU(e){let{length:t}=e,i,r=0,n=0;while(n<t){let o=e.charCodeAt(n);if(!hLe(o)){let a=Math.min(n+32,t),c=n+1;while(c<a&&!hLe(e.charCodeAt(c)))c++;if(c<a){n=c;continue}if(c>=t)break;if(xle.lastIndex=c,!xle.test(e))break;n=xle.lastIndex-1;continue}if(i===void 0)i=e.substring(0,n);else if(r!==n)i+=e.substring(r,n);if(o<64){i+=fLe(o),r=n+=1;continue}let s=e.codePointAt(n);if(i+=`&#x${s.toString(16)};`,s!==o)n++;r=n+=1}if(i===void 0)return e;if(r<t)i+=e.substr(r);return i}function xLe(e,t){if(e.lastIndex=0,!e.test(t))return t;let i="",r=0;do{let n=e.lastIndex-1;if(r!==n)i+=t.substring(r,n);let o=t.charCodeAt(n);i+=fLe(o),r=n+1}while(e.test(t));return i+t.substring(r)}function gle(e){return xLe(yDi,e)}function yle(e){return xLe(bDi,e)}var gDi=1342177476,xle,yDi,bDi;var gLe=Wo(()=>{xle=/["&'<>\u0080-\uFFFF]/g;yDi=/["&\u{A0}]/gu;bDi=/[&<>\u{A0}]/gu});var yLe,bLe;var ELe=Wo(()=>{gLe();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(yLe||(yLe={}));(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"})(bLe||(bLe={}))});var ALe,vLe;var wLe=Wo(()=>{ALe=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])),vLe=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 SDi(e,t={}){let i="length"in e?e:[e],r=t.xmlMode??!1,n="";for(let o=0;o<i.length;o++)n+=kLe(i[o],t,r);return n}function SLe(e,t,i){let r="";for(let n=0;n<e.length;n++)r+=kLe(e[n],t,i);return r}function kLe(e,t,i){switch(e.type){case tle:return SLe(e.children,t,i);case rle:return`<${e.data}>`;case nle:return`<!--${e.data}-->`;case cle:return`<![CDATA[${e.children[0].data}]]>`;case ole:case sle:case ale:return kDi(e,t,i);case ile:{let r=e,n=r.data||"";if((t.encodeEntities??t.decodeEntities)!==!1&&!(!i&&r.parent&&EDi.has(r.parent.name)))return i||t.encodeEntities!=="utf8"?hU(n):yle(n);return n}}}function kDi(e,t,i){if(i==="foreign"){if(e.name=ALe.get(e.name)??e.name,e.parent&&wDi.has(e.parent.name))i=!1}if(!i&&vDi.has(e.name))i="foreign";let{name:r,children:n}=e,o=!i&&ADi.has(r),s=`<${r}${CDi(e.attribs,t,i)}`;if(n.length===0&&(i?t.selfClosingTags!==!1:t.selfClosingTags&&o))s+=i?"/>":" />";else{if(s+=">",n.length>0)s+=SLe(n,t,i);if(!o)s+=`</${r}>`}return s}function BDi(e){return e.replaceAll('"',"&quot;")}function CDi(e,t,i){if(!e)return"";let r=(t.encodeEntities??t.decodeEntities)===!1?BDi:i||t.encodeEntities!=="utf8"?hU:gle,n=i==="foreign",o=!!(t.emptyAttrs??i),s="";for(let a in e){if(!Object.hasOwn(e,a))continue;let c=e[a],u=n?vLe.get(a)??a:a;s+=!o&&(c==null||c==="")?` ${u}`:` ${u}="${r(c==null?"":String(c))}"`}return s}var EDi,ADi,vDi,wDi,BLe;var CLe=Wo(()=>{K2();ELe();wLe();EDi=new Set("style script xmp iframe noembed noframes plaintext noscript".split(" ")),ADi=new Set("area base basefont br col command embed frame hr img input isindex keygen link meta param source track wbr".split(" ")),vDi=new Set(["svg","math"]),wDi=new Set("mi mo mn ms mtext annotation-xml foreignObject desc title".split(" "));BLe=SDi});function DLe(e,t){return BLe(e,t)}function DDi(e,t){return ad(e)?e.children.map((i)=>DLe(i,t)).join(""):""}function fU(e){if(Array.isArray(e))return e.map(fU).join("");if(Al(e))return e.name==="br"?`
3
3
  `:fU(e.children);if(dU(e))return fU(e.children);if(rA(e))return e.data;return""}function r7(e){if(Array.isArray(e))return e.map(r7).join("");if(ad(e)&&!dle(e))return r7(e.children);if(rA(e))return e.data;return""}function ble(e){if(Array.isArray(e))return e.map(ble).join("");if(ad(e)&&(e.type===tn.Tag||dU(e)))return ble(e.children);if(rA(e))return e.data;return""}var Ele=Wo(()=>{CLe();K2();nA()});function n7(e){let t=xU(RDi,e);return t?t.name==="feed"?IDi(t):_Di(t):null}function IDi(e){let t=e.children,i={type:"atom",items:qw("entry",t).map((o)=>{let{children:s}=o,a={media:ILe(s)};cd(a,"id","id",s),cd(a,"title","title",s);let c=xU("link",s)?.attribs.href;if(c)a.link=c;let u=oA("summary",s)||oA("content",s);if(u)a.description=u;let d=oA("updated",s);if(d)a.pubDate=new Date(d);return a})};cd(i,"id","id",t),cd(i,"title","title",t);let r=xU("link",t)?.attribs.href;if(r)i.link=r;cd(i,"description","subtitle",t);let n=oA("updated",t);if(n)i.updated=new Date(n);return cd(i,"author","email",t,!0),i}function _Di(e){let t=xU("channel",e.children)?.children??[],i={type:e.name.substr(0,3),id:"",items:qw("item",e.children).map((n)=>{let{children:o}=n,s={media:ILe(o)};cd(s,"id","guid",o),cd(s,"title","title",o),cd(s,"link","link",o),cd(s,"description","description",o);let a=oA("pubDate",o)||oA("dc:date",o);if(a)s.pubDate=new Date(a);return s})};cd(i,"title","title",t),cd(i,"link","link",t),cd(i,"description","description",t);let r=oA("lastBuildDate",t);if(r)i.updated=new Date(r);return cd(i,"author","managingEditor",t,!0),i}function ILe(e){return qw("media:content",e).map((t)=>{let{attribs:i}=t,r={medium:i.medium,isDefault:!!i.isDefault};for(let n of TDi)if(i[n])r[n]=i[n];for(let n of PDi)if(i[n])r[n]=Number.parseInt(i[n],10);if(i.expression)r.expression=i.expression;return r})}function xU(e,t){return qw(e,t,!0,1)[0]}function oA(e,t,i=!1){return r7(qw(e,t,i,1)).trim()}function cd(e,t,i,r,n=!1){let o=oA(i,r,n);if(o)e[t]=o}function RDi(e){return e==="rss"||e==="feed"||e==="rdf:RDF"}var TDi,PDi;var _Le=Wo(()=>{fle();Ele();TDi=["url","type","lang"],PDi=["fileSize","bitrate","framerate","samplingrate","channels","duration","height","width"]});function FDi(e){let t=e.length;while(--t>=0){let i=e[t];if(t>0&&e.lastIndexOf(i,t-1)>=0){e.splice(t,1);continue}for(let r=i.parent;r;r=r.parent)if(e.includes(r)){e.splice(t,1);break}}return e}function TLe(e,t){let i=[],r=[];if(e===t)return 0;let n=ad(e)?e:e.parent;while(n)i.unshift(n),n=n.parent;n=ad(t)?t:t.parent;while(n)r.unshift(n),n=n.parent;let o=Math.min(i.length,r.length),s=0;while(s<o&&i[s]===r[s])s++;if(s===0)return b0.DISCONNECTED;let a=i[s-1],c=a.children,u=i[s],d=r[s];if(c.indexOf(u)>c.indexOf(d)){if(a===t)return b0.FOLLOWING|b0.CONTAINED_BY;return b0.FOLLOWING}if(a===e)return b0.PRECEDING|b0.CONTAINS;return b0.PRECEDING}function MDi(e){return e=e.filter((t,i,r)=>!r.includes(t,i+1)),e.sort((t,i)=>{let r=TLe(t,i);if(r&b0.PRECEDING)return-1;if(r&b0.FOLLOWING)return 1;return 0}),e}var b0;var PLe=Wo(()=>{nA();(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"})(b0||(b0={}))});function o7(e){if(e.prev)e.prev.next=e.next;if(e.next)e.next.prev=e.prev;if(e.parent){let t=e.parent.children,i=t.lastIndexOf(e);if(i!==-1)t.splice(i,1)}e.next=null,e.prev=null,e.parent=null}function ODi(e,t){if(t.prev=e.prev,t.prev)t.prev.next=t;if(t.next=e.next,t.next)t.next.prev=t;if(t.parent=e.parent,t.parent){let{children:i}=t.parent,r=i.lastIndexOf(e);if(r===-1)return;i[r]=t,e.parent=null}}function NDi(e,t){if(o7(t),t.next=null,t.parent=e,e.children.push(t)>1){let i=e.children[e.children.length-2];i.next=t,t.prev=i}else t.prev=null}function LDi(e,t){o7(t);let{parent:i}=e,r=e.next;if(t.next=r,t.prev=e,e.next=t,t.parent=i,r){if(r.prev=t,i){let n=i.children;n.splice(n.lastIndexOf(r),0,t)}}else if(i)i.children.push(t)}function zDi(e,t){if(o7(t),t.parent=e,t.prev=null,e.children.unshift(t)===1)t.next=null;else{let i=e.children[1];i.prev=t,t.next=i}}function jDi(e,t){o7(t);let{parent:i}=e;if(i){let r=i.children;r.splice(r.indexOf(e),0,t)}if(e.prev)e.prev.next=t;t.parent=i,t.prev=e.prev,t.next=e,e.prev=t}var RLe=()=>{};function FLe(e){return ad(e)?e.children:[]}function MLe(e){return e.parent||null}function UDi(e){let t=MLe(e);if(t!=null)return FLe(t);let i=[e],{prev:r,next:n}=e;while(r!=null)i.unshift(r),{prev:r}=r;while(n!=null)i.push(n),{next:n}=n;return i}function qDi(e,t){let{attribs:i}=e;return i?.[t]}function $Di(e,t){let{attribs:i}=e;return i!=null&&Object.hasOwn(i,t)&&i[t]!=null}function GDi(e){return e.name}function HDi(e){let{next:t}=e;while(t!==null&&!Al(t))({next:t}=t);return t}function WDi(e){let{prev:t}=e;while(t!==null&&!Al(t))({prev:t}=t);return t}var OLe=Wo(()=>{nA()});var Ale={};ey(Ale,{DocumentPosition:()=>b0,append:()=>LDi,appendChild:()=>NDi,compareDocumentPosition:()=>TLe,existsOne:()=>pLe,filter:()=>Y2,find:()=>dLe,findAll:()=>uDi,findOne:()=>pU,getAttributeValue:()=>qDi,getChildren:()=>FLe,getElementById:()=>hDi,getElements:()=>mDi,getElementsByClassName:()=>fDi,getElementsByTagName:()=>qw,getElementsByTagType:()=>xDi,getFeed:()=>n7,getInnerHTML:()=>DDi,getName:()=>GDi,getOuterHTML:()=>DLe,getParent:()=>MLe,getSiblings:()=>UDi,getText:()=>fU,hasAttrib:()=>$Di,innerText:()=>ble,nextElementSibling:()=>HDi,prepend:()=>jDi,prependChild:()=>zDi,prevElementSibling:()=>WDi,removeElement:()=>o7,removeSubsets:()=>FDi,replaceElement:()=>ODi,testElement:()=>pDi,textContent:()=>r7,uniqueSort:()=>MDi});var gU=Wo(()=>{_Le();PLe();fle();RLe();mle();Ele();OLe()});var LLe={};ey(LLe,{DefaultHandler:()=>Uw,DomHandler:()=>Uw,DomUtils:()=>Ale,ElementType:()=>nU,Parser:()=>V2,QuoteType:()=>dp,Tokenizer:()=>H2,createDocumentStream:()=>ZDi,getFeed:()=>n7,parseDocument:()=>NLe,parseFeed:()=>KDi});function NLe(e,t){let i=new Uw(void 0,t);return new V2(i,t).end(e),i.root}function ZDi(e,t,i){let r=new Uw((n)=>e(n,r.root),t,i);return new V2(r,t)}function KDi(e,t=VDi){return n7(NLe(e,t).children)}var VDi;var zLe=Wo(()=>{Xce();Xce();nA();nA();K2();Qce();gU();gU();gU();VDi={xmlMode:!0}});var ULe=E(function(Keo,jLe){jLe.exports=(e)=>{if(typeof e!=="string")throw TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}});var $Le=E(function(JDi){/*!
4
4
  * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
5
5
  *
@@ -1021,7 +1021,7 @@ ${mE(e.cont)}`}}function i3n(e,t){return t.map((i,r,{length:n})=>r3n(e,i,r===n-1
1021
1021
  `).find((b)=>b.startsWith("data: "));if(!d)continue;let p;try{let b=o4i.safeParse(JSON.parse(d.slice(6)));if(!b.success)continue;p=b.data}catch{return await Yse(r),{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 Yse(r);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(`
1022
1022
  `)||"No response text";return{success:!0,data:{state:f,response:y,sources:r4i(a)}}}s=await uOe(r,t,i)}return{success:!1,error:"Stream ended without a terminal event"}}class Qse extends Error{timeoutMs;constructor(e){super(`request timed out after ${e}ms`);this.timeoutMs=e,this.name="A2ARequestTimeoutError"}}class AI extends Error{timeoutMs;constructor(e){super(`A2A stream stalled waiting for final event after ${e}ms`);this.timeoutMs=e,this.name="A2AStreamIdleTimeoutError"}}async function m4i(e,t,i,r,n){return Vse((o)=>e(t,{...i,signal:o}),{timeoutMs:r,onTimeout:()=>new Qse(r),signal:n})}async function uOe(e,t,i){try{return await Vse(()=>e.read(),{timeoutMs:t,onTimeout:()=>new AI(t),signal:i})}catch(r){if(r instanceof AI||i?.aborted)await Yse(e,r);throw r}}async function Yse(e,t){try{await e.cancel(t)}catch{}}function h4i(e){if(e instanceof Qse||e instanceof AI)return!1;return e instanceof Error}function Kse(e,t){let i=t>1?` after ${t} attempts`:"";if(e instanceof AI)return`${e.message}${i}`;let r=be(e,"Unknown network error");return`Failed to reach remote agent${i}: ${r}`}async function _j(e,t={},i={}){let r=t.fetch??globalThis.fetch,n=i.signal;n?.throwIfAborted();let o={requestTimeoutMs:t.requestTimeoutMs??s4i,streamIdleTimeoutMs:t.streamIdleTimeoutMs??a4i,maxNetworkAttempts:t.maxNetworkAttempts??c4i},s=d4i(e.agent),a=en(i.userPermissionLevel);if(!s.ok){let p=t.entityService?await aOe(t.entityService,e.agent,a):void 0;if(typeof p==="string")return{success:!1,error:p};if(!p)return{success:!1,error:s.error}}if(!t.entityService)return{success:!1,error:"Agent directory is unavailable. Add the agent first, then try again."};let c=s.ok?s.agentId:e.agent.trim(),u=s.ok?await t.entityService.getEntity({entityType:"agent",id:c,visibilityScope:a}):null;if(n?.throwIfAborted(),!u&&!cOe(c)){let p=await aOe(t.entityService,e.agent,a);if(n?.throwIfAborted(),typeof p==="string")return{success:!1,error:p};if(p)u=p,c=p.id}if(!u){if(i.requireSaved)return{success:!1,error:`Agent ${c} is not saved or approved.`,code:"agent_not_saved"};if(!cOe(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 Sf(c,{fetch:r,timeoutMs:o.requestTimeoutMs,signal:n});if(!p.ok){if(qE(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 lOe(p.card.url,e.message,r,t.requestSigner,o,n);if("success"in m&&m.success===!0){let h=typeof m.data==="object"&&m.data!==null?m.data:{};return{...m,data:{...h,agentCall:{mode:"one-shot",agent:c},agentContactCandidate:{source:{kind:"url",url:(s.ok?s.sourceUrl:void 0)??c}}}}}return m}if(u.metadata.status==="archived")return{success:!1,error:`Agent ${c} is archived and cannot be contacted until it is restored and approved.`,code:"agent_archived"};if(u.metadata.status!=="approved")return{success:!1,error:`Agent ${c} is discovered but not approved yet. Approve it first.`,code:"agent_not_approved"};let d=await Sf(c,{fetch:r,timeoutMs:o.requestTimeoutMs,signal:n});if(!d.ok){if(qE(d.reason))return{success:!1,error:d.error};return{success:!1,error:`Could not fetch Agent Card from https://${c}`}}return lOe(d.card.url,e.message,r,t.requestSigner,o,n)}function pOe(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:l4i,visibility:"trusted",sideEffects:"external",handler:async(t,i)=>{let r=u4i.safeParse(t);if(!r.success)return{success:!1,error:`Invalid input: ${r.error.message}`};return _j(r.data,e,{userPermissionLevel:i.userPermissionLevel,...i.signal?{signal:i.signal}:{}})}}}var f4i=new Set(["agent_not_saved","agent_not_approved","agent_archived"]);function mOe(e,t){let i="code"in e&&f4i.has(e.code??"")?"permission_denied":"handler_failed",r="error"in e?e.error:t;return new Ni(i,{publicMessage:R2(r)})}function x4i(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(`
1023
1023
  `)}function hOe(e,t,i={networkAskTimeoutMs:30000}){e.answer(Tj,async({request:{agent:r,question:n}})=>{let o=i.networkAskTimeoutMs,s=AbortSignal.timeout(o),a=(d)=>new Ni("deadline_exceeded",{publicMessage:`${r} did not answer within ${o} ms`,cause:d}),c;try{c=await _j({agent:r,message:x4i(n)},{...t,maxNetworkAttempts:1},{requireSaved:!0,signal:s})}catch(d){if(s.aborted)throw a(d);throw new Ni("handler_failed",{message:be(d,`${r} did not answer`),publicMessage:`${r} did not answer`,cause:d})}if(s.aborted)throw a();if(!("success"in c)||c.success!==!0)throw mOe(c,`${r} did not answer`);let u=Xse.safeParse(c.data);if(!u.success)throw new Ni("handler_failed",{publicMessage:`${r} gave no readable answer`});if(u.data.state!=="completed")throw new Ni("handler_failed",{publicMessage:R2(`${r} did not answer: ${u.data.response}`)});return u.data}),e.answer(Pj,async({request:{agent:r,instruction:n,selection:o,userPermissionLevel:s}})=>{let a=await _j({agent:r,message:["A Studio author is asking about selected markdown.",`Instruction: ${n}`,"","Selected markdown:",o].join(`
1024
- `)},t,{requireSaved:!0,userPermissionLevel:s});if(!("success"in a)||a.success!==!0)throw mOe(a,"Agent call failed");let c=Xse.safeParse(a.data);if(!c.success)throw new Ni("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(Rj,async({request:{userPermissionLevel:r}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:en(r)}}})).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 fOe={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.725",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"};var y4i={"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"};function sp(e){let t=new Headers(e.headers);for(let[i,r]of Object.entries(y4i))t.set(i,r);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function b4i(e){let t=e.auth();if(!t)return;let i=t.getIssuer();if(Bf(i)||new URL(i).protocol!=="https:")return;return async(r)=>{let n=await t.getA2ASigningKey();await NMe(r,n.privateJwk,n.keyId)}}function xOe(e,t,i){let r=b4i(e);return{...r?{requestSigner:r}:{},...i.fetch?{fetch:i.fetch}:{},requestTimeoutMs:t.requestTimeoutMs,streamIdleTimeoutMs:t.streamIdleTimeoutMs,maxNetworkAttempts:t.maxNetworkAttempts,entityService:e.entityReads}}async function E4i(e,t,i){if(!i.cardReady)return;return VMe({character:e.identity.get(),profile:e.identity.getProfile(),version:fOe.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 A4i(e,t,i,r){let n=new URL(i.url),o=new URL(`${n.pathname}${n.search}`,Lg(i)),s=await LMe({method:i.method,url:o.toString(),headers:i.headers,body:r},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 v4i(e,t,i){let r=new gOe,n=e.agent;return r.get("/.well-known/agent-card.json",async(o)=>{let s=await E4i(e,t,i);if(!s)return sp(o.json({error:"Agent Card not ready"},503));return sp(o.json(s))}),r.get("/.well-known/agent-directory.json",async(o)=>{let s=await KMe(e.entityReads);return sp(o.json(s))}),r.get("/a2a",(o)=>sp(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),r.options("/a2a",()=>sp(new Response(null,{status:204}))),r.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return sp(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await A4i(e,i,o.req.raw,s)}catch{return sp(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return sp(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let u=QMe.safeParse(c);if(!u.success)return sp(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(u.data.method==="message/stream"){let p=nOe.safeParse(u.data.params??{});if(!p.success)return sp(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:u.data.id}));let m=oOe(u.data.id,p.data.message,{taskManager:i.taskManager,turnSupervisor:i.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:i.publicAsks});if("error"in m)return sp(o.json(m));return sp(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await tOe(u.data,{taskManager:i.taskManager,turnSupervisor:i.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:i.publicAsks});return sp(o.json(d))}),r}function eae(e={}){let t=m0({id:"a2a",config:WMe,setup:(n)=>{let{config:o}=n,s=es(n),{servesHttp:a}=s,c=xOe(s,o,e),u={cardReady:!1,servesHttp:a,taskManager:new Wse,turnSupervisor:new Zse,jwksResolver:new qse(e.fetch?{fetch:e.fetch}:{}),clientDeps:c,publicAsks:new Hse(o.publicAsks,s.classRuntimeState)};if(hOe(s,c,{networkAskTimeoutMs:o.networkAskTimeoutMs}),a)s.endpoint({label:"A2A",url:"/a2a",priority:25}),s.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),s.logger.info("A2A interface registered",{domain:s.domain});else s.logger.info("A2A interface registered in tool-only mode",{domain:s.domain});return s.ready(()=>{u.cardReady=!0}),u}}),i=ts(t,(n)=>{let{config:o,state:s}=n;if(!s.servesHttp)return[];let a=es(n),c=v4i(a,o,s),u=(p)=>Promise.resolve(c.fetch(p)),d=(p,m)=>({path:p,method:m,public:!0,handler:u});return[d("/.well-known/agent-card.json","GET"),d("/.well-known/agent-directory.json","GET"),d("/a2a","GET"),d("/a2a","POST"),d("/a2a","OPTIONS")]}),r=kf(i,(n)=>{let{state:o}=n,{logger:s}=es(n);return{id:"a2a",start:async()=>{if(o.servesHttp)s.info("A2A mounted on shared webserver host");else s.info("A2A running without webserver routes")},stop:async()=>{await o.turnSupervisor.close(),s.info("A2A server stopped")}}});return Ln(r,(n)=>{let{config:o}=n,s=es(n),a=()=>pOe(xOe(s,o,e));return[{...a(),handler:(c,u)=>a().handler(c,u)}]})}var w4i=eae(),yOe=w4i;function f0(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function WE(e,t){return{registration:e,actionIds:t.map((i)=>i.name)}}var S4i=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function x0(e){return S4i.format(new Date(e))}function g0(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function tc(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function Nj(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function Rw(e){if(!e)return"This brain";let t="did:web:";if(!e.startsWith(t))return e;let i=e.slice(t.length);if(i.length===0)return e;return i.split(":").map(decodeURIComponent).join("/")}var k4i={"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 Tae(e){let t=k4i[e];if(t)return t;let i=e.replaceAll(/[._-]+/g," ").trim();return i.length===0?e:Zn(i)}var Pae=l.strictObject({actorUserId:l.string().trim().min(1).max(120).optional(),action:l.string().trim().min(1).max(200).optional(),selected:l.string().trim().min(1).max(120).optional(),offset:l.preprocess(f0,l.number().int().min(0).max(1e5)).default(0),limit:l.preprocess(f0,l.number().int().min(1).max(100)).default(25)}),bOe=l.strictObject({id:l.string().min(1),actorUserId:l.string().min(1).optional(),action:l.string().min(1),targetType:l.string().min(1).optional(),targetId:l.string().min(1).optional(),targetUserId:l.string().min(1).optional(),createdAt:l.number().int().nonnegative()}),B4i=l.strictObject({userId:l.string().min(1),displayName:l.string().min(1)}),C4i=l.strictObject({query:Pae,events:l.array(bOe),selectedEvent:bOe.optional(),users:l.array(B4i),actions:l.array(l.strictObject({value:l.string().min(1),label:l.string().min(1),count:l.number().int().nonnegative()})),total:l.number().int().nonnegative()});function EOe(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 AOe(e,t){return e?t.get(e)??"Former Admin":"System"}function vOe(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 _ae=Ho({id:"audit",label:"Audit",priority:90,permission:"admin",query:Pae,data:C4i,actions:[],view:({data:e})=>{let t=new Map(e.users.map((o)=>[o.userId,o.displayName])),i=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.",...i?{open:{forId:i.id,title:Tae(i.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:AOe(i.actorUserId,t)},{label:"Action",value:i.action},{label:"Target",value:vOe(i,t)},{label:"Occurred",value:x0(i.createdAt)},{label:"Event ID",value:i.id},{label:"Action ID",value:i.action},...i.targetId?[{label:"Target ID",value:i.targetId}]:[],...i.actorUserId?[{label:"Actor ID",value:i.actorUserId}]:[]]}]}}:{},master:{type:"list",id:"audit-events",presentation:"standard",empty:"No audit events match these filters.",items:e.events.map((o)=>({id:o.id,title:Tae(o.action),description:`${AOe(o.actorUserId,t)} \u2192 ${vOe(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 wOe(e){let t=e.studio.source({definition:_ae,bind:(i)=>_ae.bind(i,{load:async({query:r})=>{let n=g0(e),o=r.get(Pae),[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(EOe),...s.selectedEvent?{selectedEvent:EOe(s.selectedEvent)}:{},users:Nj(a),actions:s.actions.map(({action:c,count:u})=>({value:c,label:Tae(c),count:u})).sort((c,u)=>c.label.localeCompare(u.label)),total:s.total}},actions:[]})});return WE(t,_ae.actions)}var Tm=l.strictObject({status:l.string()}),Lj=l.strictObject({status:l.string(),setupUrl:l.url(),expiresAt:l.string()});function M2(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var zj=l.strictObject({type:l.string(),displayName:l.string(),subjectLabel:l.string(),deliveryModes:l.array(l.enum(["automatic","manual"]))});function jj(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function Uj(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function qj(e,t){return{deliveryType:{label:"Delivery channel",control:"select",options:e.map((i)=>({value:i.type,label:i.displayName}))},deliverySubject:{label:"Delivery destination",labelBy:{field:"deliveryType",values:e.map((i)=>({value:i.type,label:i.subjectLabel}))},control:"text"},deliveryLabel:{label:"Delivery label (optional)",control:"text"},deliveryMode:{label:"Delivery mode",control:"select",options:t.map((i)=>({value:i,label:i==="automatic"?"Automatic":"Manual"}))}}}import{randomUUID as D4i}from"crypto";var SOe=new Set(["claimed","expired","cancelled"]),I4i=new Set(["claimed","cancelled"]),Nae=l.strictObject({state:l.enum(["pending","history"]).optional().default("pending"),selected:l.string().trim().min(1).max(200).optional(),offset:l.preprocess(f0,l.number().int().min(0)).optional().default(0),limit:l.preprocess(f0,l.number().int().min(1).max(100)).optional().default(25)}),DOe=l.strictObject({status:l.string(),setupUrl:l.url().nullable(),expiresAt:l.string().nullable()}),_4i=l.strictObject({idempotencyKey:l.string().min(1),displayName:l.string().trim().min(1).max(200),role:l.enum(["admin","trusted"]),deliveryType:l.string().trim().min(1).max(100),deliverySubject:l.string().trim().min(1).max(500),deliveryLabel:l.string().trim().max(200).optional(),deliveryMode:l.enum(["automatic","manual"])}),IOe=l.strictObject({invitationId:l.string().min(1)}),T4i=l.strictObject({invitationId:l.string().min(1),deliveryAttemptId:l.string().min(1)}),_Oe=l.strictObject({invitationId:l.string(),state:l.string()}),Mae=qi({name:"create-invitation",label:"Add a person",permission:"admin",input:_4i,output:DOe}),Lae=qi({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:IOe,output:DOe}),zae=qi({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:IOe,output:_Oe}),jae=qi({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:T4i,output:_Oe}),kOe=l.strictObject({id:l.string(),displayName:l.string(),role:l.string(),state:l.string(),destination:l.string(),updatedAt:l.number(),deliveryAttemptId:l.string().optional()}),P4i=l.strictObject({query:Nae,idempotencyKey:l.string(),channels:l.array(zj),invitations:l.array(kOe),selectedInvitation:kOe.optional(),selectedTotal:l.number().int().nonnegative(),pendingCount:l.number().int().nonnegative(),historyCount:l.number().int().nonnegative(),failureCount:l.number().int().nonnegative()});function Oae(e,t){let i=e.filter((r)=>r.id===t);if(i.length!==1||!i[0])throw Error(`Invitations tab composition requires block "${t}" exactly once`);return i[0]}function Rae(e,t){let i=Oae(e,t);switch(i.type){case"tabs":case"detail":case"columns":throw Error(`Invitations tab composition block "${t}" must be a region`);default:return i}}function TOe(e,t){let i=Oae(e,"invitation-totals");if(i.type!=="stats")throw Error('Invitations tab composition block "invitation-totals" must be stats');let r=e.some((a)=>a.id==="create-invitation-unavailable")?[Rae(e,"create-invitation-unavailable")]:[],n=Oae(e,"invitations");if(n.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=Rae(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:[...r,Rae(e,"invitation-filters"),n,{...o,presentation:"disclosure",blocks:[...o.blocks,i,...s]}]}}var POe=M2("Invitation setup");function R4i(e){if(I4i.has(e.state))return[];return[...e.deliveryAttemptId?[{action:jae,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:Lae,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:POe}]:[],...e.state!=="expired"?[{action:zae,input:{invitationId:e.id}}]:[]]}function BOe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return Zn(e.state)}var Fae=Ho({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:Nae,data:P4i,actions:[Mae,Lae,zae,jae],badge:({data:e})=>e.pendingCount,view:({data:e})=>{let t=[{type:"stats",id:"invitation-totals",items:[{label:"Pending",value:e.pendingCount},{label:"History",value:e.historyCount},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"neutral"}]}],i=jj(e.channels),r;if(e.channels.length>0&&i.length>0)r={action:Mae,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:Uj("Role"),...qj(e.channels,i)}},result:POe};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:`${Zn(o.role)} \xB7 ${BOe(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:Zn(n.role)},{label:"Delivery",value:BOe(n)},{label:"Destination",value:n.destination},{label:"Updated",value:x0(n.updatedAt)}]},{type:"actions",id:"invitation-actions",items:R4i(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(Zn).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"},...r?{primaryAction:r}:{},blocks:t}}});function COe(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 ROe(e){let t=g0(e),i=new Map,r=e.studio.source({definition:Fae,bind:(n)=>{let o=Mae.bind(n,async({input:u,caller:d})=>{let p=await t.createInvitation({idempotencyKey:u.idempotencyKey,displayName:u.displayName,role:u.role,delivery:{type:u.deliveryType,subject:u.deliverySubject,...u.deliveryLabel?{label:u.deliveryLabel}:{},mode:u.deliveryMode}},tc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)i.set(p.invitation.id,p.registration.deliveryAttemptId);return COe(p)}),s=Lae.bind(n,async({input:u,caller:d})=>{let p=await t.resendInvitation(u.invitationId,tc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)i.set(p.invitation.id,p.registration.deliveryAttemptId);return COe(p)}),a=zae.bind(n,async({input:u,caller:d})=>{let p=await t.cancelInvitation(u.invitationId,tc(d));return i.delete(u.invitationId),{invitationId:p.id,state:p.state}},({input:u})=>({summary:"Cancel this invitation and revoke its pending setup link?",revision:u.invitationId})),c=jae.bind(n,async({input:u,caller:d})=>{let p=await t.confirmManualInvitationDelivery(u.invitationId,u.deliveryAttemptId,tc(d));return i.delete(u.invitationId),{invitationId:p.id,state:p.state}});return Fae.bind(n,{actions:[o,s,a,c],load:async({query:u})=>{let d=u.get(Nae),[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&&!SOe.has(R.invitation.state)),y=f.filter((R)=>R.invitation&&SOe.has(R.invitation.state)),b=d.state==="pending"?g:y,v=f.flatMap((R)=>{let O=R.invitation;if(!O)return[];let k=R.identities.find((N)=>N.type!=="passkey")?.label??R.externalPeers[0]?.peerId??"Not recorded",j=i.get(O.id);return[{id:O.id,displayName:R.displayName,role:R.role,state:O.state,destination:k,updatedAt:O.claimedAt??O.cancelledAt??O.expiredAt??O.sentAt??O.updatedAt,...j?{deliveryAttemptId:j}:{}}]}),w=new Map(v.map((R)=>[R.id,R])),D=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:D4i(),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 O=R.invitation?w.get(R.invitation.id):void 0;return O?[O]:[]}),...D?{selectedInvitation:D}:{},selectedTotal:b.length,pendingCount:g.length,historyCount:y.length,failureCount:g.filter((R)=>R.invitation?.state==="failed").length}}})}});return WE(r,Fae.actions)}var Gae=l.strictObject({peerId:l.string().trim().max(2000).optional(),displayName:l.string().trim().max(200).optional()}),F4i=l.strictObject({peerId:l.string().trim().min(1).max(2000),displayName:l.string().trim().min(1).max(200),role:l.enum(["admin","trusted"]),deliveryType:l.string().trim().min(1).max(64),deliverySubject:l.string().trim().min(1).max(1000),deliveryLabel:l.string().trim().min(1).max(200).optional(),deliveryMode:l.enum(["automatic","manual"])}),M4i=l.strictObject({peerId:l.string().trim().min(1).max(2000),userId:l.string().min(1)}),qae=qi({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:F4i,output:Lj}),$ae=qi({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:M4i,output:Tm}),O4i=l.strictObject({query:Gae,peers:l.array(l.strictObject({peerId:l.string(),displayName:l.string(),role:l.enum(["admin","trusted","public"]),verificationStatus:l.enum(["unverified","verified"]),createdAt:l.number()})),people:l.array(l.strictObject({userId:l.string(),displayName:l.string()})),channels:l.array(zj)});function $j(e,t){let i=e.filter((n)=>n.id===t);if(i.length!==1)throw Error(`Peer tab composition requires block "${t}" exactly once`);let r=i[0];if(!r)throw Error(`Peer tab composition requires block "${t}" exactly once`);switch(r.type){case"tabs":case"detail":case"columns":throw Error(`Peer tab composition block "${t}" must be a region`);default:return r}}function Hae(e){let t=e.some((i)=>i.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[$j(e,"peers"),$j(e,"link-peer"),$j(e,t)],invitations:[$j(e,t)]}}var N4i=M2("Peer invitation setup"),Uae=Ho({id:"peers",label:"Peers",priority:12,permission:"admin",query:Gae,data:O4i,actions:[qae,$ae],view:({data:e})=>{let t=jj(e.channels),i=[{type:"stats",id:"peer-summary",items:[{label:"Linked peers",value:e.peers.length},{label:"Verified",value:e.peers.filter((r)=>r.verificationStatus==="verified").length},{label:"Available people",value:e.people.length}]}];if(e.channels.length>0&&t.length>0)i.push({type:"card",id:"invite-peer",label:"Peer-first invitation",blocks:[{type:"text",text:"Create a local member for a person known first through another brain, then issue their single-use passkey setup link."},{type:"action",action:qae,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:Uj("Local role"),...qj(e.channels,t)}},result:N4i}]});else i.push({type:"notice",id:"invite-peer-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});return i.push({type:"card",id:"link-peer",label:"Link an existing person",blocks:[{type:"action",action:$ae,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((r)=>({value:r.userId,label:r.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((r)=>({id:`${r.peerId}:${r.displayName}`,cells:{peer:Rw(r.peerId),person:r.displayName,role:r.role,verification:r.verificationStatus,linked:x0(r.createdAt)},compact:{title:Rw(r.peerId),metadata:[r.displayName,Zn(r.role),x0(r.createdAt)],badges:[{label:Zn(r.verificationStatus),tone:r.verificationStatus==="verified"?"good":"warn"}]}}))}),{kicker:"Network administration",title:"Peers",description:"List external brain relationships, invite peer-first people, and link known peers to existing members.",status:{label:`${e.peers.length} linked`},blocks:i}}});function FOe(e){let t=g0(e),i=e.studio.source({definition:Uae,bind:(r)=>{let n=qae.bind(r,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}},tc(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=$ae.bind(r,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},tc(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((u)=>u.userId===s.userId)?.displayName??"person";return{summary:`Link ${s.peerId} to ${c}? Local access does not change.`,revision:`${s.peerId}:${s.userId}`}});return Uae.bind(r,{actions:[n,o],load:async({query:s})=>{let a=s.get(Gae),[c,u]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),d=c.filter((p)=>p.status!=="invited");return{query:a,peers:c.flatMap((p)=>p.externalPeers.map((m)=>({peerId:m.peerId,displayName:p.displayName,role:p.role,verificationStatus:m.verificationStatus,createdAt:m.createdAt}))),people:Nj(d),channels:u.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return WE(i,Uae.actions)}function Wae(e,t){let i=e.filter((r)=>r.id===t);if(i.length!==1||!i[0])throw Error(`People tab composition requires block "${t}" exactly once`);return i[0]}function MOe(e,t,i){let r=Wae(e,"people-summary");if(r.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let n=Wae(e,"people");if(n.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=Wae(e,"brain-anchor");if(o.type!=="card")throw Error('People tab composition block "brain-anchor" must be a card');let s=[t,...i].flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[n,{type:"card",id:"people-peers",label:"External brains",presentation:"disclosure",blocks:s},{...o,label:"Access reference",presentation:"disclosure",blocks:[r,...o.blocks]}]}}var ice=l.strictObject({selected:l.string().trim().min(1).max(200).optional()}),rce=l.strictObject({userId:l.string().min(1)}),L4i=l.strictObject({userId:l.string().min(1),role:l.enum(["admin","trusted","public"])}),z4i=l.strictObject({userId:l.string().min(1),status:l.enum(["active","suspended"])});function j4i(e){return e.revokedAt===void 0&&e.type!=="passkey"}function U4i(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var q4i=l.strictObject({userId:l.string().min(1),credentialId:l.string().min(1)}),$4i=l.strictObject({userId:l.string().min(1),type:l.string().trim().min(1).max(64),subject:l.string().trim().min(1).max(2000),issuer:l.string().trim().min(1).max(2000).optional(),label:l.string().trim().min(1).max(200).optional()}),G4i=l.strictObject({userId:l.string().min(1),identityId:l.string().min(1)}),H4i=l.strictObject({userId:l.string().min(1),peerId:l.string().trim().min(1).max(2000)}),Kae=qi({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:L4i,output:Tm}),Yae=qi({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:z4i,output:Tm}),Jae=qi({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:rce,output:Tm}),Qae=qi({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:q4i,output:Tm}),nce=qi({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:rce,output:Lj}),Xae=qi({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:rce,output:Tm}),oce=qi({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:$4i,output:Tm}),ece=qi({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:G4i,output:Tm}),tce=qi({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:H4i,output:Tm}),W4i=l.strictObject({userId:l.string(),displayName:l.string(),role:l.enum(["admin","trusted","public"]),status:l.enum(["active","suspended"]),isAnchor:l.boolean(),isSelf:l.boolean(),profileEntityId:l.string().optional(),passkeys:l.array(l.strictObject({id:l.string(),kind:l.string(),createdAt:l.number()})),identities:l.array(l.strictObject({id:l.string(),type:l.string(),displayName:l.string(),label:l.string(),verified:l.boolean()})),peers:l.array(l.strictObject({peerId:l.string(),verificationStatus:l.enum(["unverified","verified"])}))}),Z4i=l.strictObject({query:ice,anchor:l.strictObject({kind:l.enum(["person","collective"]),configuredKind:l.enum(["person","team","organization"]),displayName:l.string(),administeredBy:l.number().int().nonnegative()}),people:l.array(W4i),activeCount:l.number().int().nonnegative(),activeAdminCount:l.number().int().nonnegative(),suspendedCount:l.number().int().nonnegative(),channelTypes:l.array(l.strictObject({type:l.string(),displayName:l.string()}))}),V4i=M2("Passkey setup");function K4i(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function Zae(e){return{type:"notice",tone:"warn",text:e}}function Y4i(e){return{type:"action",action:nce,input:{userId:e},result:V4i}}function J4i(e,t){return{type:"action",action:oce,input:{userId:e},form:{submitLabel:"Attach channel",fields:{type:{label:"Channel type",control:"select",options:t.map((i)=>({value:i.type,label:i.displayName}))},subject:{label:"Channel subject",control:"text"},issuer:{label:"Issuer (optional)",control:"url"},label:{label:"Display label (optional)",control:"text"}}}}}function Q4i(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var Vae=Ho({id:"people",label:"People",priority:10,permission:"admin",query:ice,data:Z4i,actions:[Kae,Yae,Jae,Qae,nce,Xae,oce,ece,tce],badge:({data:e})=>e.suspendedCount,view:({data:e})=>{let t=e.people.find((n)=>n.userId===e.query.selected),i=[];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(i.push({type:"key-values",id:"person-summary",items:[{label:"Role",value:Zn(t.role)},{label:"Status",value:Zn(t.status)},{label:"Protected brain identity",value:t.isAnchor},{label:"Brain relationship",value:t.peers.length>0?"External peer + local member":"Hosted member"}]}),o)i.push({type:"notice",tone:"warn",text:o});else i.push({type:"card",id:"person-role",label:"Permission role",blocks:[{type:"action",action:Kae,input:{userId:t.userId,role:t.role},form:{submitLabel:"Change role",fields:{role:{label:"Role",control:"select",options:[{value:"admin",label:"Admin"},{value:"trusted",label:"Trusted"},{value:"public",label:"Public"}]}}}}]});i.push({type:"card",id:"person-access",label:"Access",blocks:[{type:"actions",items:[{action:Yae,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:Xae,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:Jae,input:{userId:t.userId}}]:[]]},...t.isSelf?[K4i()]:[],...s&&t.status==="active"?[Zae(s)]:[]]}),i.push({type:"card",id:"person-sign-in",label:"Sign-in",blocks:[{type:"table",id:"person-passkeys",empty:"No passkeys registered.",columns:[{key:"kind",label:"Passkey"},{key:"created",label:"Added"}],rows:t.passkeys.map((a)=>({id:a.id,cells:{kind:a.kind,created:x0(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${x0(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:Qae,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[Y4i(t.userId)]:[Zae("A verified channel is required for setup delivery.")]:[]]}),i.push({type:"card",id:"person-channels",label:"Linked identities",blocks:[{type:"table",id:"person-identities",empty:"No linked identity.",columns:[{key:"channel",label:"Channel"},{key:"identity",label:"Identity"},{key:"assurance",label:"Assurance"}],rows:t.identities.map((a)=>({id:a.id,cells:{channel:a.displayName,identity:a.label,assurance:a.verified?"Verified":"Asserted"},compact:{title:a.label,metadata:[a.displayName],badges:[{label:a.verified?"Verified":"Asserted",tone:a.verified?"good":"neutral"}]},actions:[{action:ece,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[J4i(t.userId,e.channelTypes)]:[Zae("No attachable channel type is configured.")]]}),i.push({type:"notice",tone:"neutral",text:"External peer links record provenance from another brain. They do not grant or change this person's local access."}),i.push({type:"list",id:"person-peers",empty:"No external peer linked; this person is hosted locally.",items:t.peers.map((a)=>({id:a.peerId,title:Rw(a.peerId),description:`Vouched in by ${Rw(a.peerId)} \xB7 ${a.peerId}`,metadata:[Zn(a.verificationStatus)],actions:[{action:tce,input:{userId:t.userId,peerId:a.peerId}}]}))})}let r=[{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:[Zn(n.role),Zn(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 ${Rw(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:i}}:{}}];return{kicker:"Access administration",title:"People",description:"Manage people\u2019s access to this brain, linked identities, and account recovery. Use Account for your own profile and sign-in settings.",status:{label:`${e.activeCount} active`,tone:e.suspendedCount>0?"warn":"neutral"},blocks:r}}});function Gj(e,t){return e.find((i)=>i.userId===t)?.displayName??"person"}async function X4i(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function OOe(e){let t=g0(e),i=e.studio.source({definition:Vae,bind:(r)=>{let n=Kae.bind(r,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,tc(f)),{status:`Role changed to ${Zn(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${Gj(f,h.userId)}\u2019s role to ${Zn(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=Yae.bind(r,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,tc(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${Gj(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=Jae.bind(r,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,tc(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${Gj(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=Qae.bind(r,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,tc(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=nce.bind(r,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,tc(f));return{status:`Bound to ${g.delivery.label}. Deliver only through that confirmed private channel.`,setupUrl:g.setupUrl,expiresAt:new Date(g.expiresAt*1000).toISOString()}}),u=Xae.bind(r,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,tc(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${Gj(f,h.userId)} out everywhere?`,revision:h.userId}}),d=oce.bind(r,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"}},tc(f)),{status:"Verified channel attached."})),p=ece.bind(r,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,tc(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=tce.bind(r,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,tc(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 Vae.bind(r,{actions:[n,o,s,a,c,u,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(ice),[y,b,v]=await Promise.all([X4i(t),t.listAdminUsers(),t.listInvitationChannels()]),w=b.filter((j)=>j.status!=="invited"),D=w.find((j)=>j.isAnchor)??w.find((j)=>j.role==="admin"&&j.status==="active"),R=y??Q4i(D?.displayName??"Brain owner",w.filter((j)=>j.role==="admin"&&j.status==="active").length),O=w.filter((j)=>j.status==="active"),k=new Map(v.map((j)=>[j.type,j.displayName]));return{query:g,anchor:{kind:R.kind,configuredKind:R.configuredKind,displayName:R.displayName,administeredBy:R.administeredBy},people:w.flatMap((j)=>{if(j.status==="invited")return[];return[{userId:j.userId,displayName:j.displayName,role:j.role,status:j.status,isAnchor:j.isAnchor,isSelf:f?.actor.id===j.userId,...j.profileEntityId?{profileEntityId:j.profileEntityId}:{},passkeys:j.passkeys.map((N)=>({id:N.id,kind:U4i(N),createdAt:N.createdAt})),identities:j.identities.filter(j4i).map((N)=>({id:N.id,type:N.type,displayName:k.get(N.type)??Zn(N.type),label:N.label??"Connected identity",verified:N.verifiedAt!==void 0})),peers:j.externalPeers.map((N)=>({peerId:N.peerId,verificationStatus:N.verificationStatus}))}]}),activeCount:O.length,activeAdminCount:O.filter((j)=>j.role==="admin").length,suspendedCount:w.length-O.length,channelTypes:v.map((j)=>({type:j.type,displayName:j.displayName}))}}})}});return WE(i,Vae.actions)}var e3i=l.strictObject({tab:l.enum(["people","invitations","audit"]).default("people"),selected:l.string().trim().min(1).max(200).optional(),state:l.enum(["pending","history"]).optional(),offset:l.preprocess(f0,l.number().int().min(0).max(1e5)).optional(),limit:l.preprocess(f0,l.number().int().min(1).max(100)).optional(),peerId:l.string().trim().max(2000).optional(),displayName:l.string().trim().max(200).optional(),actorUserId:l.string().trim().min(1).max(120).optional(),action:l.string().trim().min(1).max(200).optional()});function t3i(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function i3i(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 r3i(e,t){if(!i3i(e))throw Error(`${t} tab returned invalid workspace data`);return e}function NOe(e,t){let i=[];for(let r of e){if(r.type==="tabs")throw Error(`${t} tab cannot contribute nested tabs`);i.push(r)}return i}function sce(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function OI(e,t,i,r){return r3i(await e.dataProvider(t,i,r),e.label)}async function n3i(e,t,i,r){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,i,r)}function o3i(e){let t=new Map;for(let i of e)for(let r of i.actionIds){if(t.has(r))throw Error(`Administration action "${r}" is declared by more than one source`);if(!i.registration.actionHandler)throw Error(`Administration source "${i.registration.label}" declares actions without a handler`);t.set(r,i.registration)}return t}function s3i(e){let t=e.filter((r)=>r.status==="suspended").length,i=e.filter((r)=>r.invitation!==void 0&&!["claimed","expired","cancelled"].includes(r.invitation.state)).length;return t+i}async function LOe(e){if(!e.studio.isAvailable())return;let t=OOe(e),i=ROe(e),r=FOe(e),n=wOe(e),o=o3i([t,i,r,n]),s=t.registration,a=i.registration,c=r.registration,u=n.registration;return e.studio.register({id:"admin:administration",label:"Administration",rendererName:CI,priority:10,permission:"admin",urlQuery:!0,aliases:[{id:"admin:people",query:{tab:"people"}},{id:"admin:invitations",query:{tab:"invitations"}},{id:"admin:peers",query:{tab:"people"}},{id:"admin:audit",query:{tab:"audit"}}],entityTypes:[],accessHandler:(d)=>s.accessHandler(d),dataProvider:async(d,p,m)=>{let h=e3i.parse(p??{}),f,g=sce("People"),y=sce("Invitations"),b=sce("Audit");if(h.tab==="people"){let[v,w]=await Promise.all([OI(s,d,{...h.selected?{selected:h.selected}:{}},m),OI(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),D=Hae(w.view.blocks);g=[...MOe(NOe(v.view.blocks,"People"),{type:"notice",id:"people-peer-note",tone:"neutral",title:"External brain relationships",text:"A peer link records how a locally administered person relates to another brain. It does not grant or change local access."},D.people).blocks]}else if(h.tab==="invitations"){let[v,w]=await Promise.all([OI(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...yl({offset:h.offset,limit:h.limit})},m),OI(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),D=Hae(w.view.blocks),R=TOe(v.view.blocks,D.invitations);f=v.view.primaryAction,y=[...R.blocks]}else{let v=await OI(u,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...yl({offset:h.offset,limit:h.limit})},m);b=NOe(v.view.blocks,"Audit")}return{view:{kicker:"Access administration",title:"Administration",description:"Manage people, invitations, and access to this brain. Use Account for your own profile, sign-in security, and personal settings.",...f?{primaryAction:f}:{},blocks:[{type:"tabs",id:"administration-tabs",label:"Administration sections",defaultTab:h.tab,queryKey:"tab",tabs:[{id:"people",label:"People",blocks:g},{id:"invitations",label:"Invitations",blocks:y},{id:"audit",label:"Access activity",blocks:b}]}]}}},actionHandler:async(d,p,m)=>{let h=t3i(d);if(!h)throw new Ni("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new Ni("not_found",{publicMessage:`Unknown Administration action: ${h}`});return n3i(f,d,p,m)},badgeProvider:async()=>s3i(await g0(e).listAdminUsers())})}var a3i=259200000,c3i=l.strictObject({id:l.string(),displayName:l.string(),state:l.string(),reason:l.enum(["expiring","delivery-failed"]),expiresAt:l.number().optional()}),l3i=l.strictObject({invitations:l.array(c3i),expiringCount:l.number().int().nonnegative(),failureCount:l.number().int().nonnegative()}),zOe=zn({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:l3i,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 ${x0(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function u3i(e,t){let i=e.flatMap((r)=>{let n=r.invitation;if(!n)return[];if(n.state==="failed")return[{id:n.id,displayName:r.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+a3i)return[];return[{id:n.id,displayName:r.displayName,state:n.state,reason:"expiring",expiresAt:n.expiresAt}]});return i.sort((r,n)=>(r.expiresAt??Number.MAX_SAFE_INTEGER)-(n.expiresAt??Number.MAX_SAFE_INTEGER)||r.displayName.localeCompare(n.displayName)),{invitations:i,expiringCount:i.filter((r)=>r.reason==="expiring").length,failureCount:i.filter((r)=>r.reason==="delivery-failed").length}}async function jOe(e,t){t.throwIfAborted();let i=await g0(e).listAdminUsers();return t.throwIfAborted(),u3i(i,Date.now())}var d3i=l.strictObject({}),p3i=Xt({id:"admin",config:d3i},{subscriptions:(e)=>{let t=Lt(e);return t.registered(async()=>{await LOe(t)}),[]},dashboardWidgets:(e)=>{let t=Lt(e);return[zOe.bind(e,({signal:i})=>jOe(t,i))]}}),ace=p3i;var sn="agent";var UOe="agent-network",qOe="agent-proximity",Bce="agent-discovery:entities",$Oe="agent-discovery:proximity-map",Cce="proximity-map",Dce="agent-list",Ice="agent-detail",ic="skill",GOe=30,HOe=120;var Wj="skill-derivation",WOe="skill-derivation",_ce="skill:skill-derivation",ZOe="skills";var m3i=l.string().trim().min(1).max(HOe),Tce=l.array(m3i).max(GOe),VE=l.object({name:l.string(),description:l.string(),tags:Tce,examples:l.array(l.string())}),N2=VE,KE=Pm.extend({entityType:l.literal(ic),metadata:N2});var Zj=l.object({name:l.string(),description:l.string(),tags:Tce}),Yg=l.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),h3i=Tw,Mm=l.object({name:l.string(),kind:h3i,organization:l.string().optional(),brainName:l.string().describe("Name of the brain instance"),url:l.string().url().describe("Brain endpoint URL"),repoDid:l.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:l.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:l.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:l.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:l.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:l.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:l.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:l.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:Yg,discoveredAt:l.string().datetime().meta({description:"When this agent was first discovered",studioWidget:"provenance"}),introducedBy:l.array(l.string()).optional().meta({description:"Agent ids of the peers whose directories reported this agent",studioWidget:"provenance"}),hops:l.number().int().min(2).optional().meta({description:"Discovery order: 2 = sighted through a first-order peer",studioWidget:"provenance"})}),GI=l.object({name:l.string(),url:l.string().url(),status:Yg,discoveredAt:l.string().datetime().optional(),slug:l.string(),repoDid:l.string().optional(),brainDid:l.string().optional(),cardUri:l.string().optional(),cardCid:l.string().optional(),cardLastError:l.string().optional(),cardFailureCount:l.number().int().nonnegative().optional(),cardUnavailableAt:l.string().datetime().optional(),cardStaleAfter:l.string().datetime().optional()}),Io=Pm.extend({entityType:l.literal(sn),metadata:GI}),f3i=$i.extend({entityType:l.literal(sn),metadata:GI}),HI=f3i.extend({frontmatter:Mm,about:l.string(),skills:l.array(Zj),notes:l.string()}),x3i=HI.extend({url:l.string().optional(),typeLabel:l.string().optional()}),g3i=HI.extend({url:l.string(),typeLabel:l.string()});var y3i=l.record(l.string(),l.unknown());function b3i(e){try{return In(e,y3i).content}catch{return e}}function Pce(e){return{name:e.name,url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:L2(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 VOe(e){return ws(sn,e,Mm)}function WI(e){return{content:e,metadata:Pce(VOe(e))}}function z2(e){let t={name:e.name,kind:e.kind,...e.organization&&{organization:e.organization},brainName:e.brainName,url:e.url,...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter},status:Yg.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},i=Dae({about:e.about,skills:e.skills,notes:e.notes});return on(i,t)}function Nw(e,t={}){return z2({...e.frontmatter,...e.body,...t})}function ZI(e){return MI(b3i(e))}function od(e){return{frontmatter:VOe(e.content),body:ZI(e.content)}}function Rce(e){return on("",e)}function A3i(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function KOe(e,t,i={}){let r=i.minCount??1,n=i.topN??12,o=new Map,s=(a)=>{for(let c of Pa(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=ZI(a.content);s(c.skills.flatMap((u)=>u.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=r).sort(A3i).slice(0,n)}function YOe(e){if(e.length===0)return"";return["Current agent-directory tag vocabulary (reuse existing tags where they fit; propose new only when nothing does):",...e.map(({tag:t,count:i})=>`- ${t} (${i})`)].join(`
1024
+ `)},t,{requireSaved:!0,userPermissionLevel:s});if(!("success"in a)||a.success!==!0)throw mOe(a,"Agent call failed");let c=Xse.safeParse(a.data);if(!c.success)throw new Ni("handler_failed",{publicMessage:"Invalid response from agent"});return c.data}),e.answer(Rj,async({request:{userPermissionLevel:r}})=>{if(!e.entityReads.hasEntityType("agent"))return{agents:[]};return{agents:(await e.entityReads.listEntities({entityType:"agent",options:{filter:{visibilityScope:en(r)}}})).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 fOe={name:"@brains/a2a",license:"AGPL-3.0-only",version:"0.2.0-alpha.726",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"};var y4i={"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"};function sp(e){let t=new Headers(e.headers);for(let[i,r]of Object.entries(y4i))t.set(i,r);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function b4i(e){let t=e.auth();if(!t)return;let i=t.getIssuer();if(Bf(i)||new URL(i).protocol!=="https:")return;return async(r)=>{let n=await t.getA2ASigningKey();await NMe(r,n.privateJwk,n.keyId)}}function xOe(e,t,i){let r=b4i(e);return{...r?{requestSigner:r}:{},...i.fetch?{fetch:i.fetch}:{},requestTimeoutMs:t.requestTimeoutMs,streamIdleTimeoutMs:t.streamIdleTimeoutMs,maxNetworkAttempts:t.maxNetworkAttempts,entityService:e.entityReads}}async function E4i(e,t,i){if(!i.cardReady)return;return VMe({character:e.identity.get(),profile:e.identity.getProfile(),version:fOe.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 A4i(e,t,i,r){let n=new URL(i.url),o=new URL(`${n.pathname}${n.search}`,Lg(i)),s=await LMe({method:i.method,url:o.toString(),headers:i.headers,body:r},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 v4i(e,t,i){let r=new gOe,n=e.agent;return r.get("/.well-known/agent-card.json",async(o)=>{let s=await E4i(e,t,i);if(!s)return sp(o.json({error:"Agent Card not ready"},503));return sp(o.json(s))}),r.get("/.well-known/agent-directory.json",async(o)=>{let s=await KMe(e.entityReads);return sp(o.json(s))}),r.get("/a2a",(o)=>sp(o.json({error:"Use POST with JSON-RPC 2.0 requests.",agentCard:"/.well-known/agent-card.json"},405))),r.options("/a2a",()=>sp(new Response(null,{status:204}))),r.post("/a2a",async(o)=>{let s=await o.req.text().catch(()=>{return});if(s===void 0)return sp(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Request body could not be read"},id:null},400));let a;try{a=await A4i(e,i,o.req.raw,s)}catch{return sp(o.json({error:"Invalid HTTP signature"},401))}let c;try{c=JSON.parse(s)}catch{return sp(o.json({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}))}let u=QMe.safeParse(c);if(!u.success)return sp(o.json({jsonrpc:"2.0",error:{code:-32600,message:"Invalid request"},id:null}));if(u.data.method==="message/stream"){let p=nOe.safeParse(u.data.params??{});if(!p.success)return sp(o.json({jsonrpc:"2.0",error:{code:-32602,message:`Invalid params: ${p.error.message}`},id:u.data.id}));let m=oOe(u.data.id,p.data.message,{taskManager:i.taskManager,turnSupervisor:i.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:i.publicAsks});if("error"in m)return sp(o.json(m));return sp(new Response(m.stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}}))}let d=await tOe(u.data,{taskManager:i.taskManager,turnSupervisor:i.turnSupervisor,agentService:n,callerPermissionLevel:a.permissionLevel,callerIsAnchor:a.isAnchor,callerDomain:a.callerDomain,publicAsks:i.publicAsks});return sp(o.json(d))}),r}function eae(e={}){let t=m0({id:"a2a",config:WMe,setup:(n)=>{let{config:o}=n,s=es(n),{servesHttp:a}=s,c=xOe(s,o,e),u={cardReady:!1,servesHttp:a,taskManager:new Wse,turnSupervisor:new Zse,jwksResolver:new qse(e.fetch?{fetch:e.fetch}:{}),clientDeps:c,publicAsks:new Hse(o.publicAsks,s.classRuntimeState)};if(hOe(s,c,{networkAskTimeoutMs:o.networkAskTimeoutMs}),a)s.endpoint({label:"A2A",url:"/a2a",priority:25}),s.interaction({id:"a2a",label:"A2A",description:"Let other agents discover and talk to this brain.",href:"/a2a",kind:"agent",priority:25}),s.logger.info("A2A interface registered",{domain:s.domain});else s.logger.info("A2A interface registered in tool-only mode",{domain:s.domain});return s.ready(()=>{u.cardReady=!0}),u}}),i=ts(t,(n)=>{let{config:o,state:s}=n;if(!s.servesHttp)return[];let a=es(n),c=v4i(a,o,s),u=(p)=>Promise.resolve(c.fetch(p)),d=(p,m)=>({path:p,method:m,public:!0,handler:u});return[d("/.well-known/agent-card.json","GET"),d("/.well-known/agent-directory.json","GET"),d("/a2a","GET"),d("/a2a","POST"),d("/a2a","OPTIONS")]}),r=kf(i,(n)=>{let{state:o}=n,{logger:s}=es(n);return{id:"a2a",start:async()=>{if(o.servesHttp)s.info("A2A mounted on shared webserver host");else s.info("A2A running without webserver routes")},stop:async()=>{await o.turnSupervisor.close(),s.info("A2A server stopped")}}});return Ln(r,(n)=>{let{config:o}=n,s=es(n),a=()=>pOe(xOe(s,o,e));return[{...a(),handler:(c,u)=>a().handler(c,u)}]})}var w4i=eae(),yOe=w4i;function f0(e){if(typeof e!=="string"||!/^\d+$/u.test(e))return e;return Number(e)}function WE(e,t){return{registration:e,actionIds:t.map((i)=>i.name)}}var S4i=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"});function x0(e){return S4i.format(new Date(e))}function g0(e){let t=e.auth();if(!t)throw Error("Administration workspace requires auth-service");return t}function tc(e){if(!e)throw Error("Administration action requires a signed-in actor");return{actorUserId:e.actor.id}}function Nj(e){return e.flatMap((t)=>t.status==="invited"?[]:[{userId:t.userId,displayName:t.displayName}])}function Rw(e){if(!e)return"This brain";let t="did:web:";if(!e.startsWith(t))return e;let i=e.slice(t.length);if(i.length===0)return e;return i.split(":").map(decodeURIComponent).join("/")}var k4i={"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 Tae(e){let t=k4i[e];if(t)return t;let i=e.replaceAll(/[._-]+/g," ").trim();return i.length===0?e:Zn(i)}var Pae=l.strictObject({actorUserId:l.string().trim().min(1).max(120).optional(),action:l.string().trim().min(1).max(200).optional(),selected:l.string().trim().min(1).max(120).optional(),offset:l.preprocess(f0,l.number().int().min(0).max(1e5)).default(0),limit:l.preprocess(f0,l.number().int().min(1).max(100)).default(25)}),bOe=l.strictObject({id:l.string().min(1),actorUserId:l.string().min(1).optional(),action:l.string().min(1),targetType:l.string().min(1).optional(),targetId:l.string().min(1).optional(),targetUserId:l.string().min(1).optional(),createdAt:l.number().int().nonnegative()}),B4i=l.strictObject({userId:l.string().min(1),displayName:l.string().min(1)}),C4i=l.strictObject({query:Pae,events:l.array(bOe),selectedEvent:bOe.optional(),users:l.array(B4i),actions:l.array(l.strictObject({value:l.string().min(1),label:l.string().min(1),count:l.number().int().nonnegative()})),total:l.number().int().nonnegative()});function EOe(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 AOe(e,t){return e?t.get(e)??"Former Admin":"System"}function vOe(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 _ae=Ho({id:"audit",label:"Audit",priority:90,permission:"admin",query:Pae,data:C4i,actions:[],view:({data:e})=>{let t=new Map(e.users.map((o)=>[o.userId,o.displayName])),i=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.",...i?{open:{forId:i.id,title:Tae(i.action),blocks:[{type:"key-values",id:"audit-event-fields",items:[{label:"Actor",value:AOe(i.actorUserId,t)},{label:"Action",value:i.action},{label:"Target",value:vOe(i,t)},{label:"Occurred",value:x0(i.createdAt)},{label:"Event ID",value:i.id},{label:"Action ID",value:i.action},...i.targetId?[{label:"Target ID",value:i.targetId}]:[],...i.actorUserId?[{label:"Actor ID",value:i.actorUserId}]:[]]}]}}:{},master:{type:"list",id:"audit-events",presentation:"standard",empty:"No audit events match these filters.",items:e.events.map((o)=>({id:o.id,title:Tae(o.action),description:`${AOe(o.actorUserId,t)} \u2192 ${vOe(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 wOe(e){let t=e.studio.source({definition:_ae,bind:(i)=>_ae.bind(i,{load:async({query:r})=>{let n=g0(e),o=r.get(Pae),[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(EOe),...s.selectedEvent?{selectedEvent:EOe(s.selectedEvent)}:{},users:Nj(a),actions:s.actions.map(({action:c,count:u})=>({value:c,label:Tae(c),count:u})).sort((c,u)=>c.label.localeCompare(u.label)),total:s.total}},actions:[]})});return WE(t,_ae.actions)}var Tm=l.strictObject({status:l.string()}),Lj=l.strictObject({status:l.string(),setupUrl:l.url(),expiresAt:l.string()});function M2(e){return{title:e,fields:{status:{label:"Status"},setupUrl:{label:"Single-use setup URL",copyable:!0,sensitive:!0},expiresAt:{label:"Expires"}}}}var zj=l.strictObject({type:l.string(),displayName:l.string(),subjectLabel:l.string(),deliveryModes:l.array(l.enum(["automatic","manual"]))});function jj(e){return Array.from(new Set(e.flatMap((t)=>t.deliveryModes)))}function Uj(e){return{label:e,control:"select",options:[{value:"trusted",label:"Trusted"},{value:"admin",label:"Admin"}]}}function qj(e,t){return{deliveryType:{label:"Delivery channel",control:"select",options:e.map((i)=>({value:i.type,label:i.displayName}))},deliverySubject:{label:"Delivery destination",labelBy:{field:"deliveryType",values:e.map((i)=>({value:i.type,label:i.subjectLabel}))},control:"text"},deliveryLabel:{label:"Delivery label (optional)",control:"text"},deliveryMode:{label:"Delivery mode",control:"select",options:t.map((i)=>({value:i,label:i==="automatic"?"Automatic":"Manual"}))}}}import{randomUUID as D4i}from"crypto";var SOe=new Set(["claimed","expired","cancelled"]),I4i=new Set(["claimed","cancelled"]),Nae=l.strictObject({state:l.enum(["pending","history"]).optional().default("pending"),selected:l.string().trim().min(1).max(200).optional(),offset:l.preprocess(f0,l.number().int().min(0)).optional().default(0),limit:l.preprocess(f0,l.number().int().min(1).max(100)).optional().default(25)}),DOe=l.strictObject({status:l.string(),setupUrl:l.url().nullable(),expiresAt:l.string().nullable()}),_4i=l.strictObject({idempotencyKey:l.string().min(1),displayName:l.string().trim().min(1).max(200),role:l.enum(["admin","trusted"]),deliveryType:l.string().trim().min(1).max(100),deliverySubject:l.string().trim().min(1).max(500),deliveryLabel:l.string().trim().max(200).optional(),deliveryMode:l.enum(["automatic","manual"])}),IOe=l.strictObject({invitationId:l.string().min(1)}),T4i=l.strictObject({invitationId:l.string().min(1),deliveryAttemptId:l.string().min(1)}),_Oe=l.strictObject({invitationId:l.string(),state:l.string()}),Mae=qi({name:"create-invitation",label:"Add a person",permission:"admin",input:_4i,output:DOe}),Lae=qi({name:"resend-invitation",label:"Resend",permission:"admin",catalog:!0,confirmation:{kind:"static",message:"Create a new single-use setup link for this invitation?"},input:IOe,output:DOe}),zae=qi({name:"cancel-invitation",label:"Cancel",permission:"admin",confirmation:{kind:"prepared"},input:IOe,output:_Oe}),jae=qi({name:"confirm-manual-delivery",label:"Confirm delivered",permission:"admin",input:T4i,output:_Oe}),kOe=l.strictObject({id:l.string(),displayName:l.string(),role:l.string(),state:l.string(),destination:l.string(),updatedAt:l.number(),deliveryAttemptId:l.string().optional()}),P4i=l.strictObject({query:Nae,idempotencyKey:l.string(),channels:l.array(zj),invitations:l.array(kOe),selectedInvitation:kOe.optional(),selectedTotal:l.number().int().nonnegative(),pendingCount:l.number().int().nonnegative(),historyCount:l.number().int().nonnegative(),failureCount:l.number().int().nonnegative()});function Oae(e,t){let i=e.filter((r)=>r.id===t);if(i.length!==1||!i[0])throw Error(`Invitations tab composition requires block "${t}" exactly once`);return i[0]}function Rae(e,t){let i=Oae(e,t);switch(i.type){case"tabs":case"detail":case"columns":throw Error(`Invitations tab composition block "${t}" must be a region`);default:return i}}function TOe(e,t){let i=Oae(e,"invitation-totals");if(i.type!=="stats")throw Error('Invitations tab composition block "invitation-totals" must be stats');let r=e.some((a)=>a.id==="create-invitation-unavailable")?[Rae(e,"create-invitation-unavailable")]:[],n=Oae(e,"invitations");if(n.type!=="detail")throw Error("Invitations composition requires a detail collection");let o=Rae(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:[...r,Rae(e,"invitation-filters"),n,{...o,presentation:"disclosure",blocks:[...o.blocks,i,...s]}]}}var POe=M2("Invitation setup");function R4i(e){if(I4i.has(e.state))return[];return[...e.deliveryAttemptId?[{action:jae,input:{invitationId:e.id,deliveryAttemptId:e.deliveryAttemptId}}]:[],...e.state!=="sending"?[{action:Lae,input:{invitationId:e.id},capability:{id:e.state==="failed"?"retry-invitation":"resend-invitation",label:e.state==="failed"?"Retry":"Resend"},result:POe}]:[],...e.state!=="expired"?[{action:zae,input:{invitationId:e.id}}]:[]]}function BOe(e){if(e.state==="pending"&&e.deliveryAttemptId)return"Manual delivery pending";if(e.state==="failed")return"Delivery failed";return Zn(e.state)}var Fae=Ho({id:"invitations",label:"Invitations",priority:11,permission:"admin",query:Nae,data:P4i,actions:[Mae,Lae,zae,jae],badge:({data:e})=>e.pendingCount,view:({data:e})=>{let t=[{type:"stats",id:"invitation-totals",items:[{label:"Pending",value:e.pendingCount},{label:"History",value:e.historyCount},{label:"Delivery failures",value:e.failureCount,tone:e.failureCount>0?"warn":"neutral"}]}],i=jj(e.channels),r;if(e.channels.length>0&&i.length>0)r={action:Mae,input:{idempotencyKey:e.idempotencyKey},form:{presentation:"disclosure",submitLabel:"Create invitation",fields:{displayName:{label:"Display name",control:"text"},role:Uj("Role"),...qj(e.channels,i)}},result:POe};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:`${Zn(o.role)} \xB7 ${BOe(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:Zn(n.role)},{label:"Delivery",value:BOe(n)},{label:"Destination",value:n.destination},{label:"Updated",value:x0(n.updatedAt)}]},{type:"actions",id:"invitation-actions",items:R4i(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(Zn).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"},...r?{primaryAction:r}:{},blocks:t}}});function COe(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 ROe(e){let t=g0(e),i=new Map,r=e.studio.source({definition:Fae,bind:(n)=>{let o=Mae.bind(n,async({input:u,caller:d})=>{let p=await t.createInvitation({idempotencyKey:u.idempotencyKey,displayName:u.displayName,role:u.role,delivery:{type:u.deliveryType,subject:u.deliverySubject,...u.deliveryLabel?{label:u.deliveryLabel}:{},mode:u.deliveryMode}},tc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)i.set(p.invitation.id,p.registration.deliveryAttemptId);return COe(p)}),s=Lae.bind(n,async({input:u,caller:d})=>{let p=await t.resendInvitation(u.invitationId,tc(d));if(p.invitation.state==="pending"&&p.registration?.deliveryAttemptId)i.set(p.invitation.id,p.registration.deliveryAttemptId);return COe(p)}),a=zae.bind(n,async({input:u,caller:d})=>{let p=await t.cancelInvitation(u.invitationId,tc(d));return i.delete(u.invitationId),{invitationId:p.id,state:p.state}},({input:u})=>({summary:"Cancel this invitation and revoke its pending setup link?",revision:u.invitationId})),c=jae.bind(n,async({input:u,caller:d})=>{let p=await t.confirmManualInvitationDelivery(u.invitationId,u.deliveryAttemptId,tc(d));return i.delete(u.invitationId),{invitationId:p.id,state:p.state}});return Fae.bind(n,{actions:[o,s,a,c],load:async({query:u})=>{let d=u.get(Nae),[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&&!SOe.has(R.invitation.state)),y=f.filter((R)=>R.invitation&&SOe.has(R.invitation.state)),b=d.state==="pending"?g:y,v=f.flatMap((R)=>{let O=R.invitation;if(!O)return[];let k=R.identities.find((N)=>N.type!=="passkey")?.label??R.externalPeers[0]?.peerId??"Not recorded",j=i.get(O.id);return[{id:O.id,displayName:R.displayName,role:R.role,state:O.state,destination:k,updatedAt:O.claimedAt??O.cancelledAt??O.expiredAt??O.sentAt??O.updatedAt,...j?{deliveryAttemptId:j}:{}}]}),w=new Map(v.map((R)=>[R.id,R])),D=d.selected?w.get(d.selected):void 0;return{query:d,idempotencyKey:D4i(),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 O=R.invitation?w.get(R.invitation.id):void 0;return O?[O]:[]}),...D?{selectedInvitation:D}:{},selectedTotal:b.length,pendingCount:g.length,historyCount:y.length,failureCount:g.filter((R)=>R.invitation?.state==="failed").length}}})}});return WE(r,Fae.actions)}var Gae=l.strictObject({peerId:l.string().trim().max(2000).optional(),displayName:l.string().trim().max(200).optional()}),F4i=l.strictObject({peerId:l.string().trim().min(1).max(2000),displayName:l.string().trim().min(1).max(200),role:l.enum(["admin","trusted"]),deliveryType:l.string().trim().min(1).max(64),deliverySubject:l.string().trim().min(1).max(1000),deliveryLabel:l.string().trim().min(1).max(200).optional(),deliveryMode:l.enum(["automatic","manual"])}),M4i=l.strictObject({peerId:l.string().trim().min(1).max(2000),userId:l.string().min(1)}),qae=qi({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:F4i,output:Lj}),$ae=qi({name:"link-external-peer",label:"Link an existing person",permission:"admin",confirmation:{kind:"prepared"},input:M4i,output:Tm}),O4i=l.strictObject({query:Gae,peers:l.array(l.strictObject({peerId:l.string(),displayName:l.string(),role:l.enum(["admin","trusted","public"]),verificationStatus:l.enum(["unverified","verified"]),createdAt:l.number()})),people:l.array(l.strictObject({userId:l.string(),displayName:l.string()})),channels:l.array(zj)});function $j(e,t){let i=e.filter((n)=>n.id===t);if(i.length!==1)throw Error(`Peer tab composition requires block "${t}" exactly once`);let r=i[0];if(!r)throw Error(`Peer tab composition requires block "${t}" exactly once`);switch(r.type){case"tabs":case"detail":case"columns":throw Error(`Peer tab composition block "${t}" must be a region`);default:return r}}function Hae(e){let t=e.some((i)=>i.id==="invite-peer")?"invite-peer":"invite-peer-unavailable";return{people:[$j(e,"peers"),$j(e,"link-peer"),$j(e,t)],invitations:[$j(e,t)]}}var N4i=M2("Peer invitation setup"),Uae=Ho({id:"peers",label:"Peers",priority:12,permission:"admin",query:Gae,data:O4i,actions:[qae,$ae],view:({data:e})=>{let t=jj(e.channels),i=[{type:"stats",id:"peer-summary",items:[{label:"Linked peers",value:e.peers.length},{label:"Verified",value:e.peers.filter((r)=>r.verificationStatus==="verified").length},{label:"Available people",value:e.people.length}]}];if(e.channels.length>0&&t.length>0)i.push({type:"card",id:"invite-peer",label:"Peer-first invitation",blocks:[{type:"text",text:"Create a local member for a person known first through another brain, then issue their single-use passkey setup link."},{type:"action",action:qae,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:Uj("Local role"),...qj(e.channels,t)}},result:N4i}]});else i.push({type:"notice",id:"invite-peer-unavailable",tone:"warn",text:"No invitation delivery channel is currently available."});return i.push({type:"card",id:"link-peer",label:"Link an existing person",blocks:[{type:"action",action:$ae,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((r)=>({value:r.userId,label:r.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((r)=>({id:`${r.peerId}:${r.displayName}`,cells:{peer:Rw(r.peerId),person:r.displayName,role:r.role,verification:r.verificationStatus,linked:x0(r.createdAt)},compact:{title:Rw(r.peerId),metadata:[r.displayName,Zn(r.role),x0(r.createdAt)],badges:[{label:Zn(r.verificationStatus),tone:r.verificationStatus==="verified"?"good":"warn"}]}}))}),{kicker:"Network administration",title:"Peers",description:"List external brain relationships, invite peer-first people, and link known peers to existing members.",status:{label:`${e.peers.length} linked`},blocks:i}}});function FOe(e){let t=g0(e),i=e.studio.source({definition:Uae,bind:(r)=>{let n=qae.bind(r,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}},tc(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=$ae.bind(r,async({input:s,caller:a})=>(await t.linkExternalPeer({peerId:s.peerId,userId:s.userId},tc(a)),{status:"External peer linked to the local person."}),async({input:s})=>{let c=(await t.listAdminUsers()).find((u)=>u.userId===s.userId)?.displayName??"person";return{summary:`Link ${s.peerId} to ${c}? Local access does not change.`,revision:`${s.peerId}:${s.userId}`}});return Uae.bind(r,{actions:[n,o],load:async({query:s})=>{let a=s.get(Gae),[c,u]=await Promise.all([t.listAdminUsers(),t.listInvitationChannels()]),d=c.filter((p)=>p.status!=="invited");return{query:a,peers:c.flatMap((p)=>p.externalPeers.map((m)=>({peerId:m.peerId,displayName:p.displayName,role:p.role,verificationStatus:m.verificationStatus,createdAt:m.createdAt}))),people:Nj(d),channels:u.filter((p)=>p.deliveryModes.length>0).map((p)=>({type:p.type,displayName:p.displayName,subjectLabel:p.subjectLabel,deliveryModes:p.deliveryModes}))}}})}});return WE(i,Uae.actions)}function Wae(e,t){let i=e.filter((r)=>r.id===t);if(i.length!==1||!i[0])throw Error(`People tab composition requires block "${t}" exactly once`);return i[0]}function MOe(e,t,i){let r=Wae(e,"people-summary");if(r.type!=="stats")throw Error('People tab composition block "people-summary" must be stats');let n=Wae(e,"people");if(n.type!=="detail")throw Error('People tab composition block "people" must be a detail');let o=Wae(e,"brain-anchor");if(o.type!=="card")throw Error('People tab composition block "brain-anchor" must be a card');let s=[t,...i].flatMap((a)=>a.type==="card"?[...a.blocks]:[a]);return{blocks:[n,{type:"card",id:"people-peers",label:"External brains",presentation:"disclosure",blocks:s},{...o,label:"Access reference",presentation:"disclosure",blocks:[r,...o.blocks]}]}}var ice=l.strictObject({selected:l.string().trim().min(1).max(200).optional()}),rce=l.strictObject({userId:l.string().min(1)}),L4i=l.strictObject({userId:l.string().min(1),role:l.enum(["admin","trusted","public"])}),z4i=l.strictObject({userId:l.string().min(1),status:l.enum(["active","suspended"])});function j4i(e){return e.revokedAt===void 0&&e.type!=="passkey"}function U4i(e){return e.credentialBackedUp?"Synced passkey":"Device passkey"}var q4i=l.strictObject({userId:l.string().min(1),credentialId:l.string().min(1)}),$4i=l.strictObject({userId:l.string().min(1),type:l.string().trim().min(1).max(64),subject:l.string().trim().min(1).max(2000),issuer:l.string().trim().min(1).max(2000).optional(),label:l.string().trim().min(1).max(200).optional()}),G4i=l.strictObject({userId:l.string().min(1),identityId:l.string().min(1)}),H4i=l.strictObject({userId:l.string().min(1),peerId:l.string().trim().min(1).max(2000)}),Kae=qi({name:"update-person-role",label:"Change role",permission:"admin",confirmation:{kind:"prepared"},input:L4i,output:Tm}),Yae=qi({name:"update-person-status",label:"Suspend person",permission:"admin",catalog:!0,confirmation:{kind:"prepared"},input:z4i,output:Tm}),Jae=qi({name:"delete-person",label:"Delete person",permission:"admin",confirmation:{kind:"prepared"},input:rce,output:Tm}),Qae=qi({name:"revoke-person-passkey",label:"Revoke passkey",permission:"admin",confirmation:{kind:"prepared"},input:q4i,output:Tm}),nce=qi({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:rce,output:Lj}),Xae=qi({name:"revoke-person-sessions",label:"Revoke all sessions",permission:"admin",confirmation:{kind:"prepared"},input:rce,output:Tm}),oce=qi({name:"attach-person-identity",label:"Attach channel",permission:"admin",confirmation:{kind:"static",message:"Attach this verified channel identity to the selected person?"},input:$4i,output:Tm}),ece=qi({name:"detach-person-identity",label:"Detach channel",permission:"admin",confirmation:{kind:"prepared"},input:G4i,output:Tm}),tce=qi({name:"unlink-external-peer",label:"Unlink peer",permission:"admin",confirmation:{kind:"prepared"},input:H4i,output:Tm}),W4i=l.strictObject({userId:l.string(),displayName:l.string(),role:l.enum(["admin","trusted","public"]),status:l.enum(["active","suspended"]),isAnchor:l.boolean(),isSelf:l.boolean(),profileEntityId:l.string().optional(),passkeys:l.array(l.strictObject({id:l.string(),kind:l.string(),createdAt:l.number()})),identities:l.array(l.strictObject({id:l.string(),type:l.string(),displayName:l.string(),label:l.string(),verified:l.boolean()})),peers:l.array(l.strictObject({peerId:l.string(),verificationStatus:l.enum(["unverified","verified"])}))}),Z4i=l.strictObject({query:ice,anchor:l.strictObject({kind:l.enum(["person","collective"]),configuredKind:l.enum(["person","team","organization"]),displayName:l.string(),administeredBy:l.number().int().nonnegative()}),people:l.array(W4i),activeCount:l.number().int().nonnegative(),activeAdminCount:l.number().int().nonnegative(),suspendedCount:l.number().int().nonnegative(),channelTypes:l.array(l.strictObject({type:l.string(),displayName:l.string()}))}),V4i=M2("Passkey setup");function K4i(){return{type:"links",items:[{label:"Manage your own credentials and sessions",target:{launch:{target:"account-settings"}}}]}}function Zae(e){return{type:"notice",tone:"warn",text:e}}function Y4i(e){return{type:"action",action:nce,input:{userId:e},result:V4i}}function J4i(e,t){return{type:"action",action:oce,input:{userId:e},form:{submitLabel:"Attach channel",fields:{type:{label:"Channel type",control:"select",options:t.map((i)=>({value:i.type,label:i.displayName}))},subject:{label:"Channel subject",control:"text"},issuer:{label:"Issuer (optional)",control:"url"},label:{label:"Display label (optional)",control:"text"}}}}}function Q4i(e,t){return{kind:"person",configuredKind:"person",displayName:e,administeredBy:t}}var Vae=Ho({id:"people",label:"People",priority:10,permission:"admin",query:ice,data:Z4i,actions:[Kae,Yae,Jae,Qae,nce,Xae,oce,ece,tce],badge:({data:e})=>e.suspendedCount,view:({data:e})=>{let t=e.people.find((n)=>n.userId===e.query.selected),i=[];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(i.push({type:"key-values",id:"person-summary",items:[{label:"Role",value:Zn(t.role)},{label:"Status",value:Zn(t.status)},{label:"Protected brain identity",value:t.isAnchor},{label:"Brain relationship",value:t.peers.length>0?"External peer + local member":"Hosted member"}]}),o)i.push({type:"notice",tone:"warn",text:o});else i.push({type:"card",id:"person-role",label:"Permission role",blocks:[{type:"action",action:Kae,input:{userId:t.userId,role:t.role},form:{submitLabel:"Change role",fields:{role:{label:"Role",control:"select",options:[{value:"admin",label:"Admin"},{value:"trusted",label:"Trusted"},{value:"public",label:"Public"}]}}}}]});i.push({type:"card",id:"person-access",label:"Access",blocks:[{type:"actions",items:[{action:Yae,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:Xae,input:{userId:t.userId}}]:[],...t.status==="suspended"?[{action:Jae,input:{userId:t.userId}}]:[]]},...t.isSelf?[K4i()]:[],...s&&t.status==="active"?[Zae(s)]:[]]}),i.push({type:"card",id:"person-sign-in",label:"Sign-in",blocks:[{type:"table",id:"person-passkeys",empty:"No passkeys registered.",columns:[{key:"kind",label:"Passkey"},{key:"created",label:"Added"}],rows:t.passkeys.map((a)=>({id:a.id,cells:{kind:a.kind,created:x0(a.createdAt)},compact:{title:a.kind,metadata:[`Added ${x0(a.createdAt)}`]},actions:t.status==="active"&&!t.isSelf?[{action:Qae,input:{userId:t.userId,credentialId:a.id}}]:[]}))},...t.status==="active"&&!t.isSelf?t.identities.some((a)=>a.verified)?[Y4i(t.userId)]:[Zae("A verified channel is required for setup delivery.")]:[]]}),i.push({type:"card",id:"person-channels",label:"Linked identities",blocks:[{type:"table",id:"person-identities",empty:"No linked identity.",columns:[{key:"channel",label:"Channel"},{key:"identity",label:"Identity"},{key:"assurance",label:"Assurance"}],rows:t.identities.map((a)=>({id:a.id,cells:{channel:a.displayName,identity:a.label,assurance:a.verified?"Verified":"Asserted"},compact:{title:a.label,metadata:[a.displayName],badges:[{label:a.verified?"Verified":"Asserted",tone:a.verified?"good":"neutral"}]},actions:[{action:ece,input:{userId:t.userId,identityId:a.id}}]}))},...e.channelTypes.length>0?[J4i(t.userId,e.channelTypes)]:[Zae("No attachable channel type is configured.")]]}),i.push({type:"notice",tone:"neutral",text:"External peer links record provenance from another brain. They do not grant or change this person's local access."}),i.push({type:"list",id:"person-peers",empty:"No external peer linked; this person is hosted locally.",items:t.peers.map((a)=>({id:a.peerId,title:Rw(a.peerId),description:`Vouched in by ${Rw(a.peerId)} \xB7 ${a.peerId}`,metadata:[Zn(a.verificationStatus)],actions:[{action:tce,input:{userId:t.userId,peerId:a.peerId}}]}))})}let r=[{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:[Zn(n.role),Zn(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 ${Rw(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:i}}:{}}];return{kicker:"Access administration",title:"People",description:"Manage people\u2019s access to this brain, linked identities, and account recovery. Use Account for your own profile and sign-in settings.",status:{label:`${e.activeCount} active`,tone:e.suspendedCount>0?"warn":"neutral"},blocks:r}}});function Gj(e,t){return e.find((i)=>i.userId===t)?.displayName??"person"}async function X4i(e){try{return await e.getBrainAnchor()}catch(t){if(t instanceof Error&&t.message==="Brain anchor is not configured")return;throw t}}function OOe(e){let t=g0(e),i=e.studio.source({definition:Vae,bind:(r)=>{let n=Kae.bind(r,async({input:h,caller:f})=>(await t.updateUserRole(h.userId,h.role,tc(f)),{status:`Role changed to ${Zn(h.role)}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Change ${Gj(f,h.userId)}\u2019s role to ${Zn(h.role)}?`,revision:`${h.userId}:${h.role}`}}),o=Yae.bind(r,async({input:h,caller:f})=>(await t.updateUserStatus(h.userId,h.status,tc(f)),{status:`Person ${h.status}.`}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`${h.status==="active"?"Reactivate":"Suspend"} ${Gj(f,h.userId)}?`,revision:`${h.userId}:${h.status}`}}),s=Jae.bind(r,async({input:h,caller:f})=>(await t.deleteSuspendedUser(h.userId,tc(f)),{status:"Suspended person permanently deleted."}),async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Permanently delete ${Gj(f,h.userId)}? Audit history is retained.`,revision:h.userId}}),a=Qae.bind(r,async({input:h,caller:f})=>(await t.revokePasskey(h.credentialId,tc(f)),{status:"Passkey revoked."}),({input:h})=>({summary:"Revoke this passkey immediately?",revision:`${h.userId}:${h.credentialId}`})),c=nce.bind(r,async({input:h,caller:f})=>{let g=await t.startPasskeyRegistrationForUser(h.userId,tc(f));return{status:`Bound to ${g.delivery.label}. Deliver only through that confirmed private channel.`,setupUrl:g.setupUrl,expiresAt:new Date(g.expiresAt*1000).toISOString()}}),u=Xae.bind(r,async({input:h,caller:f})=>{let g=await t.revokeUserSessionsAndRefreshTokens(h.userId,tc(f));return{status:`Revoked ${g.sessions} sessions and ${g.refreshTokens} refresh tokens.`}},async({input:h})=>{let f=await t.listAdminUsers();return{summary:`Sign ${Gj(f,h.userId)} out everywhere?`,revision:h.userId}}),d=oce.bind(r,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"}},tc(f)),{status:"Verified channel attached."})),p=ece.bind(r,async({input:h,caller:f})=>(await t.detachIdentity(h.identityId,tc(f)),{status:"Channel detached."}),({input:h})=>({summary:"Detach this channel identity?",revision:`${h.userId}:${h.identityId}`})),m=tce.bind(r,async({input:h,caller:f})=>(await t.unlinkExternalPeer(h,tc(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 Vae.bind(r,{actions:[n,o,s,a,c,u,d,p,m],load:async({query:h,caller:f})=>{let g=h.get(ice),[y,b,v]=await Promise.all([X4i(t),t.listAdminUsers(),t.listInvitationChannels()]),w=b.filter((j)=>j.status!=="invited"),D=w.find((j)=>j.isAnchor)??w.find((j)=>j.role==="admin"&&j.status==="active"),R=y??Q4i(D?.displayName??"Brain owner",w.filter((j)=>j.role==="admin"&&j.status==="active").length),O=w.filter((j)=>j.status==="active"),k=new Map(v.map((j)=>[j.type,j.displayName]));return{query:g,anchor:{kind:R.kind,configuredKind:R.configuredKind,displayName:R.displayName,administeredBy:R.administeredBy},people:w.flatMap((j)=>{if(j.status==="invited")return[];return[{userId:j.userId,displayName:j.displayName,role:j.role,status:j.status,isAnchor:j.isAnchor,isSelf:f?.actor.id===j.userId,...j.profileEntityId?{profileEntityId:j.profileEntityId}:{},passkeys:j.passkeys.map((N)=>({id:N.id,kind:U4i(N),createdAt:N.createdAt})),identities:j.identities.filter(j4i).map((N)=>({id:N.id,type:N.type,displayName:k.get(N.type)??Zn(N.type),label:N.label??"Connected identity",verified:N.verifiedAt!==void 0})),peers:j.externalPeers.map((N)=>({peerId:N.peerId,verificationStatus:N.verificationStatus}))}]}),activeCount:O.length,activeAdminCount:O.filter((j)=>j.role==="admin").length,suspendedCount:w.length-O.length,channelTypes:v.map((j)=>({type:j.type,displayName:j.displayName}))}}})}});return WE(i,Vae.actions)}var e3i=l.strictObject({tab:l.enum(["people","invitations","audit"]).default("people"),selected:l.string().trim().min(1).max(200).optional(),state:l.enum(["pending","history"]).optional(),offset:l.preprocess(f0,l.number().int().min(0).max(1e5)).optional(),limit:l.preprocess(f0,l.number().int().min(1).max(100)).optional(),peerId:l.string().trim().max(2000).optional(),displayName:l.string().trim().max(200).optional(),actorUserId:l.string().trim().min(1).max(120).optional(),action:l.string().trim().min(1).max(200).optional()});function t3i(e){if(e===null||typeof e!=="object")return;let t=Reflect.get(e,"actionId");return typeof t==="string"?t:void 0}function i3i(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 r3i(e,t){if(!i3i(e))throw Error(`${t} tab returned invalid workspace data`);return e}function NOe(e,t){let i=[];for(let r of e){if(r.type==="tabs")throw Error(`${t} tab cannot contribute nested tabs`);i.push(r)}return i}function sce(e){return[{type:"text",text:`${e} loads when this tab is opened.`}]}async function OI(e,t,i,r){return r3i(await e.dataProvider(t,i,r),e.label)}async function n3i(e,t,i,r){if(!e.actionHandler)throw Error(`${e.label} does not provide actions`);return e.actionHandler(t,i,r)}function o3i(e){let t=new Map;for(let i of e)for(let r of i.actionIds){if(t.has(r))throw Error(`Administration action "${r}" is declared by more than one source`);if(!i.registration.actionHandler)throw Error(`Administration source "${i.registration.label}" declares actions without a handler`);t.set(r,i.registration)}return t}function s3i(e){let t=e.filter((r)=>r.status==="suspended").length,i=e.filter((r)=>r.invitation!==void 0&&!["claimed","expired","cancelled"].includes(r.invitation.state)).length;return t+i}async function LOe(e){if(!e.studio.isAvailable())return;let t=OOe(e),i=ROe(e),r=FOe(e),n=wOe(e),o=o3i([t,i,r,n]),s=t.registration,a=i.registration,c=r.registration,u=n.registration;return e.studio.register({id:"admin:administration",label:"Administration",rendererName:CI,priority:10,permission:"admin",urlQuery:!0,aliases:[{id:"admin:people",query:{tab:"people"}},{id:"admin:invitations",query:{tab:"invitations"}},{id:"admin:peers",query:{tab:"people"}},{id:"admin:audit",query:{tab:"audit"}}],entityTypes:[],accessHandler:(d)=>s.accessHandler(d),dataProvider:async(d,p,m)=>{let h=e3i.parse(p??{}),f,g=sce("People"),y=sce("Invitations"),b=sce("Audit");if(h.tab==="people"){let[v,w]=await Promise.all([OI(s,d,{...h.selected?{selected:h.selected}:{}},m),OI(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),D=Hae(w.view.blocks);g=[...MOe(NOe(v.view.blocks,"People"),{type:"notice",id:"people-peer-note",tone:"neutral",title:"External brain relationships",text:"A peer link records how a locally administered person relates to another brain. It does not grant or change local access."},D.people).blocks]}else if(h.tab==="invitations"){let[v,w]=await Promise.all([OI(a,d,{...h.state?{state:h.state}:{},...h.selected?{selected:h.selected}:{},...yl({offset:h.offset,limit:h.limit})},m),OI(c,d,{...h.peerId?{peerId:h.peerId}:{},...h.displayName?{displayName:h.displayName}:{}},m)]),D=Hae(w.view.blocks),R=TOe(v.view.blocks,D.invitations);f=v.view.primaryAction,y=[...R.blocks]}else{let v=await OI(u,d,{...h.actorUserId?{actorUserId:h.actorUserId}:{},...h.action?{action:h.action}:{},...h.selected?{selected:h.selected}:{},...yl({offset:h.offset,limit:h.limit})},m);b=NOe(v.view.blocks,"Audit")}return{view:{kicker:"Access administration",title:"Administration",description:"Manage people, invitations, and access to this brain. Use Account for your own profile, sign-in security, and personal settings.",...f?{primaryAction:f}:{},blocks:[{type:"tabs",id:"administration-tabs",label:"Administration sections",defaultTab:h.tab,queryKey:"tab",tabs:[{id:"people",label:"People",blocks:g},{id:"invitations",label:"Invitations",blocks:y},{id:"audit",label:"Access activity",blocks:b}]}]}}},actionHandler:async(d,p,m)=>{let h=t3i(d);if(!h)throw new Ni("invalid_input",{publicMessage:"Administration action id is required"});let f=o.get(h);if(!f)throw new Ni("not_found",{publicMessage:`Unknown Administration action: ${h}`});return n3i(f,d,p,m)},badgeProvider:async()=>s3i(await g0(e).listAdminUsers())})}var a3i=259200000,c3i=l.strictObject({id:l.string(),displayName:l.string(),state:l.string(),reason:l.enum(["expiring","delivery-failed"]),expiresAt:l.number().optional()}),l3i=l.strictObject({invitations:l.array(c3i),expiringCount:l.number().int().nonnegative(),failureCount:l.number().int().nonnegative()}),zOe=zn({id:"expiring-invitations",title:"Invitations",description:"Setup links that expire soon or need delivery attention",group:"access",placement:"primary",priority:5,permission:"admin",data:l3i,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 ${x0(t.expiresAt)}`]:[]],tone:t.reason==="delivery-failed"?"error":"warn",link:{launch:{target:"invitations"}}}))},{type:"links",items:[{label:"Open Invitations",target:{launch:{target:"invitations"}}}]}]})});function u3i(e,t){let i=e.flatMap((r)=>{let n=r.invitation;if(!n)return[];if(n.state==="failed")return[{id:n.id,displayName:r.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+a3i)return[];return[{id:n.id,displayName:r.displayName,state:n.state,reason:"expiring",expiresAt:n.expiresAt}]});return i.sort((r,n)=>(r.expiresAt??Number.MAX_SAFE_INTEGER)-(n.expiresAt??Number.MAX_SAFE_INTEGER)||r.displayName.localeCompare(n.displayName)),{invitations:i,expiringCount:i.filter((r)=>r.reason==="expiring").length,failureCount:i.filter((r)=>r.reason==="delivery-failed").length}}async function jOe(e,t){t.throwIfAborted();let i=await g0(e).listAdminUsers();return t.throwIfAborted(),u3i(i,Date.now())}var d3i=l.strictObject({}),p3i=Xt({id:"admin",config:d3i},{subscriptions:(e)=>{let t=Lt(e);return t.registered(async()=>{await LOe(t)}),[]},dashboardWidgets:(e)=>{let t=Lt(e);return[zOe.bind(e,({signal:i})=>jOe(t,i))]}}),ace=p3i;var sn="agent";var UOe="agent-network",qOe="agent-proximity",Bce="agent-discovery:entities",$Oe="agent-discovery:proximity-map",Cce="proximity-map",Dce="agent-list",Ice="agent-detail",ic="skill",GOe=30,HOe=120;var Wj="skill-derivation",WOe="skill-derivation",_ce="skill:skill-derivation",ZOe="skills";var m3i=l.string().trim().min(1).max(HOe),Tce=l.array(m3i).max(GOe),VE=l.object({name:l.string(),description:l.string(),tags:Tce,examples:l.array(l.string())}),N2=VE,KE=Pm.extend({entityType:l.literal(ic),metadata:N2});var Zj=l.object({name:l.string(),description:l.string(),tags:Tce}),Yg=l.enum(["discovered","approved","archived"]).describe("Discovered for review, approved for calling, or archived"),h3i=Tw,Mm=l.object({name:l.string(),kind:h3i,organization:l.string().optional(),brainName:l.string().describe("Name of the brain instance"),url:l.string().url().describe("Brain endpoint URL"),repoDid:l.string().optional().meta({description:"ATProto repo DID",studioWidget:"provenance"}),brainDid:l.string().optional().meta({description:"ATProto brain DID",studioWidget:"provenance"}),cardUri:l.string().optional().meta({description:"ATProto brain card URI",studioWidget:"provenance"}),cardCid:l.string().optional().meta({description:"ATProto brain card CID",studioWidget:"provenance"}),cardLastError:l.string().optional().meta({description:"Last ATProto brain card refresh error",studioWidget:"hidden"}),cardFailureCount:l.number().int().nonnegative().optional().meta({description:"Consecutive ATProto brain card refresh failures",studioWidget:"hidden"}),cardUnavailableAt:l.string().datetime().optional().meta({description:"When the remote ATProto brain card became unavailable",studioWidget:"hidden"}),cardStaleAfter:l.string().datetime().optional().meta({description:"When a never-approved unavailable card may be archived",studioWidget:"hidden"}),status:Yg,discoveredAt:l.string().datetime().meta({description:"When this agent was first discovered",studioWidget:"provenance"}),introducedBy:l.array(l.string()).optional().meta({description:"Agent ids of the peers whose directories reported this agent",studioWidget:"provenance"}),hops:l.number().int().min(2).optional().meta({description:"Discovery order: 2 = sighted through a first-order peer",studioWidget:"provenance"})}),GI=l.object({name:l.string(),url:l.string().url(),status:Yg,discoveredAt:l.string().datetime().optional(),slug:l.string(),repoDid:l.string().optional(),brainDid:l.string().optional(),cardUri:l.string().optional(),cardCid:l.string().optional(),cardLastError:l.string().optional(),cardFailureCount:l.number().int().nonnegative().optional(),cardUnavailableAt:l.string().datetime().optional(),cardStaleAfter:l.string().datetime().optional()}),Io=Pm.extend({entityType:l.literal(sn),metadata:GI}),f3i=$i.extend({entityType:l.literal(sn),metadata:GI}),HI=f3i.extend({frontmatter:Mm,about:l.string(),skills:l.array(Zj),notes:l.string()}),x3i=HI.extend({url:l.string().optional(),typeLabel:l.string().optional()}),g3i=HI.extend({url:l.string(),typeLabel:l.string()});var y3i=l.record(l.string(),l.unknown());function b3i(e){try{return In(e,y3i).content}catch{return e}}function Pce(e){return{name:e.name,url:e.url,status:e.status,discoveredAt:e.discoveredAt,slug:L2(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 VOe(e){return ws(sn,e,Mm)}function WI(e){return{content:e,metadata:Pce(VOe(e))}}function z2(e){let t={name:e.name,kind:e.kind,...e.organization&&{organization:e.organization},brainName:e.brainName,url:e.url,...e.repoDid&&{repoDid:e.repoDid},...e.brainDid&&{brainDid:e.brainDid},...e.cardUri&&{cardUri:e.cardUri},...e.cardCid&&{cardCid:e.cardCid},...e.cardLastError&&{cardLastError:e.cardLastError},...e.cardFailureCount!==void 0&&{cardFailureCount:e.cardFailureCount},...e.cardUnavailableAt&&{cardUnavailableAt:e.cardUnavailableAt},...e.cardStaleAfter&&{cardStaleAfter:e.cardStaleAfter},status:Yg.parse(e.status),discoveredAt:e.discoveredAt,...e.introducedBy?.length&&{introducedBy:e.introducedBy},...e.hops!==void 0&&{hops:e.hops}},i=Dae({about:e.about,skills:e.skills,notes:e.notes});return on(i,t)}function Nw(e,t={}){return z2({...e.frontmatter,...e.body,...t})}function ZI(e){return MI(b3i(e))}function od(e){return{frontmatter:VOe(e.content),body:ZI(e.content)}}function Rce(e){return on("",e)}function A3i(e,t){if(t.count!==e.count)return t.count-e.count;return e.tag.localeCompare(t.tag)}function KOe(e,t,i={}){let r=i.minCount??1,n=i.topN??12,o=new Map,s=(a)=>{for(let c of Pa(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=ZI(a.content);s(c.skills.flatMap((u)=>u.tags))}return Array.from(o.entries()).map(([a,c])=>({tag:a,count:c})).filter((a)=>a.count>=r).sort(A3i).slice(0,n)}function YOe(e){if(e.length===0)return"";return["Current agent-directory tag vocabulary (reuse existing tags where they fit; propose new only when nothing does):",...e.map(({tag:t,count:i})=>`- ${t} (${i})`)].join(`
1025
1025
  `)}function j2(e,t={}){let i=e.anchor?.name??e.brainName,r=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:z2({name:i,kind:r,...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(`
1026
1026
 
1027
1027
  `),skills:e.skills.map((c)=>({name:c.name,description:c.description,tags:Pa(c.tags)})),notes:""}),metadata:{name:i,url:e.url,status:o,discoveredAt:s,slug:L2(e.url)},anchorName:i}}function YE(e){let t=e.trim();if(t.startsWith("http://")||t.startsWith("https://"))try{return new URL(t).hostname}catch{return t}let i=t.match(/https?:\/\/[^\s]+?(?=[.,;:!?)]*(?:\s|$))/);if(i)try{return new URL(i[0]).hostname}catch{return i[0]}if(/^[^\s]+\.[^\s]+$/.test(t))return t;return""}var v3i=l.object({prompt:l.string().optional(),url:l.string().optional(),content:l.string().optional(),skipAi:l.boolean().optional(),status:l.enum(["discovered","approved","archived"]).optional()});function JOe(e){return{input:v3i,generate:async({input:t})=>{let i=YE(t.url??t.prompt??"");if(!i)return{success:!1,error:"No URL or domain provided. Use: system_create agent with a domain like yeehaa.io"};let r=await Sf(i,{fetch:e??globalThis.fetch});if(!r.ok)return{success:!1,error:qE(r.reason)?r.error:`Could not fetch Agent Card from ${i}. Make sure the agent is running and accessible.`};let{content:n,metadata:o}=j2(r.card,{...t.status!==void 0?{status:t.status}:{}});return{success:!0,id:i,content:n,metadata:o}}}}var Fce=zs({header:Mm,deriveMetadata:Pce,readAsWritten:!0}),w3i=Fce.decode;Object.assign(Fce,{decode:(e)=>w3i({...e,content:e.content.replace(/^\n+/u,"")})});function Mce(e){return vn(wce(Mi(Ft({type:sn,classification:"system",purpose:"A saved remote peer-brain contact in the local agent directory.",metadata:GI,markdown:Fce,config:{projectionSourceRole:"supporting",retiredFields:["cardObservedAt","cardLastCheckedAt","a2aEndpoint","did","anchorDid"]},generation:JOe(e)}),Mm),["approved"]))}var S3i=l.object({skills:l.array(VE).max(8)}),Vj=nt({name:"skill:skill-derivation",description:"Derive skills from topic titles and brain capabilities",dataSourceId:"shell:ai-content",schema:S3i,useKnowledgeContext:!0,basePrompt:`You are analyzing a brain's content to identify its high-level capabilities.
@@ -6805,7 +6805,7 @@ When to use directives:
6805
6805
  `;await _ri(s,u),this.logger.warn("Quarantined invalid entity file",{originalPath:e,quarantinePath:`${e}.invalid`,error:c})}catch(s){this.logger.error("Failed to quarantine invalid file",{path:e,error:s}),i.failed++,i.errors.push({path:e,error:"Failed to quarantine invalid file"})}}async markAsRecoveredIfNeeded(e){try{let i=`${hs(this.syncPath,e)}.invalid`;await dsn(i,{force:!0})}catch(i){this.logger.debug("Could not retire recovered quarantine artifact",{path:e,error:i})}let t=Tri(this.syncPath,".import-errors.log");try{let i=await lsn(t,"utf-8"),r=` - ${e}:`,n=` - [RECOVERED] ${e}`;if(i.lastIndexOf(r)<=i.lastIndexOf(n))return;let o=new Date().toISOString();await _ri(t,`${o} - [RECOVERED] ${e}
6806
6806
  `),this.logger.debug("Marked file as recovered in error log",{path:e})}catch(i){if($d(i))return;this.logger.debug("Could not update error log for recovered file",{path:e,error:i})}}}function Pri(e,t,i,r){let n=new Vke(i,t);return{fileOperations:n,batchQueue:new jke({logger:e,syncPath:i,fileOperations:n,deleteOnFileRemoval:r}),progressOperations:new Yke(e,t,n),coverImageConverter:new Kke(t,e),inlineImageConverter:new iN(t,e),quarantine:new Jke(e,i)}}function Rri(e,t,i,r,n,o,s){return new Uke({entityService:t,logger:e,syncPath:i,fileOperations:r.fileOperations,quarantine:r.quarantine,coverImageConverter:r.coverImageConverter,inlineImageConverter:r.inlineImageConverter,...n,pendingDeletes:o,getJobQueueCallback:s})}class rN{targets=new Map;record(e){this.targets.set(this.key(e.entityType,e.entityId),e)}has(e,t){return this.targets.has(this.key(e,t))}complete(e,t,i){let r=this.key(e,t);if(this.targets.get(r)?.filePath!==i)return;this.targets.delete(r)}key(e,t){return`${e}\x00${t}`}}import{readFile as psn}from"fs/promises";async function Fri(e,t){return(await Promise.all(t.map(async(r)=>await msn(e,r)?[]:[r]))).flat()}async function msn(e,t){if(!t.endsWith(".md"))return!1;try{let i=e.fileOperations.parseEntityFromPath(t);if(!e.entityService.hasEntityType(i.entityType))return!1;let r=await psn(hs(e.syncPath,t),"utf8");return(await e.entityService.getEntityWriteSnapshot({...i,visibilityScope:Pt("compare a changed file with its entity")}))?.entity.contentHash===cr(r)}catch{return!1}}async function Mri(e){return e.getAllMarkdownFiles()}async function Ori(e,t,i){let r=i??t.getEntityTypes();await e.ensureDirectoryStructure(r)}import{mkdir as hsn}from"fs/promises";import{isAbsolute as fsn,resolve as xsn}from"path";function Nri(e){return fsn(e)?e:xsn(process.cwd(),e)}async function Qke(e){await hsn(e,{recursive:!0})}async function Lri(e,t,i,r){if(e.debug("Initializing directory sync",{path:t}),await Qke(t),i)await r()}async function zri(e,t){e.debug("Initializing directory structure",{path:t}),await Qke(t)}async function jri(e,t,i,r){let{files:n,stats:o}=await e.gatherFileStatus();return{syncPath:t,exists:await e.syncDirectoryExists(),watching:i?.isWatching()??!1,lastSync:r,files:n,stats:o}}function Xke(){return{deleted:0,errors:[]}}function Uri(e,t,i){t.deleted++,e.debug("Deleted orphaned entity (file missing)",{entityType:i.entityType,id:i.id})}function qri(e,t,i,r){let n=be(r);t.errors.push({entityId:i.id,entityType:i.entityType,error:n}),e.error("Failed to delete orphaned entity",{entityType:i.entityType,id:i.id,error:n})}async function Gri(e){if(!e.deleteOnFileRemoval)return Xke();let t=e.entityTypes??e.entityService.getEntityTypes(),i=Xke();for(let r of t){let n=await Hri(e,r,0);for(let o of n)try{await e.entityService.deleteEntity({entityType:o.entityType,id:o.id,options:{persistenceOrigin:"directory-sync"}}),e.onEntityDeleted?.(o),Uri(e.logger,i,o)}catch(s){qri(e.logger,i,o,s)}}return i}var eBe=1000;async function Hri(e,t,i){let r=await e.entityService.listEntities({entityType:t,options:{limit:eBe,offset:i,binaryContent:"reference",filter:{visibilityScope:Pt("directory sync cleanup spans all visibility tiers")}}}),n=await r.reduce(async(o,s)=>{let a=await o;return await gsn(e,t,s)?[...a,s]:a},Promise.resolve([]));if(r.length<eBe)return n;return[...n,...await Hri(e,t,i+eBe)]}async function gsn(e,t,i){try{e.fileOperations.assertEntityPlacement(i)}catch(n){if(!(n instanceof qb))throw n;return e.logger.info("Keeping entity with refused placement",{entityType:t,entityId:i.id}),!1}let r=e.fileOperations.getEntityFileCandidates(i);if(await $ri(e,r))return!1;if(await $ri(e,r.map((n)=>`${n}.invalid`)))return e.logger.info("Entity file is quarantined, keeping entity",{entityType:i.entityType,entityId:i.id}),!1;return!0}async function $ri(e,t){return(await Promise.all(t.map((r)=>e.fileOperations.fileExists(r)))).includes(!0)}function Wri(){return{exported:0,failed:0,errors:[]}}function Zri(e,t,i,r){if(r.success){if(t.exported++,r.deleted)e.debug("Deleted entity from DB (file missing)",{entityType:i.entityType,id:i.id});return}t.failed++,t.errors.push({entityId:i.id,entityType:i.entityType,error:r.error??"Unknown error"}),e.error("Failed to export entity",{entityType:i.entityType,id:i.id,error:r.error})}function Vri(e,t){e.debug("Export completed",t)}async function Kri(e,t){let i=t??e.entityTypes??e.entityService.getEntityTypes();e.logger.debug("Exporting entities to directory",{entityTypes:i});let r=Wri();for(let n of i){let o=await e.entityService.listEntities({entityType:n,options:{limit:1000,source:!0,binaryContent:"reference",filter:{visibilityScope:Pt("directory sync exports entities across all visibility tiers")}}});e.logger.debug("Processing entity type for export",{entityType:n,count:o.length});for(let s of o){let a=await tBe(e,s);Zri(e.logger,r,s,a)}}return Vri(e.logger,r),r}async function tBe(e,t){try{e.fileOperations.assertEntityPlacement(t);let i=await e.fileOperations.resolveEntityFilePath(t);if(!await e.fileOperations.fileExists(i)){if(e.deleteOnFileRemoval)return e.logger.debug("File missing, deleting entity from DB",{entityId:t.id,entityType:t.entityType}),await e.entityService.deleteEntity({entityType:t.entityType,id:t.id}),{success:!0,deleted:!0}}return await e.fileOperations.writeEntity(t),{success:!0}}catch(i){return{success:!1,error:be(i)}}}function Yri(e){if(!e.content||e.content.trim().length===0)return"empty-content";let t=e.content.trim();if(t==="---"||t===`---
6807
6807
  ---`||t===`---\r
6808
- ---`)return"empty-frontmatter";return}function Jri(e){switch(e){case"empty-content":return"Skipping file with empty content (likely mid-write)";case"empty-frontmatter":return"Skipping file with empty frontmatter (likely mid-write)"}}async function Qri(e,t,i,r){try{return e.entityService.deserializeEntity(t.content,t.entityType)}catch(n){if(e.quarantine.isValidationError(n)){await e.quarantine.quarantineInvalidFile(i,n,r,(o)=>hs(e.imageJobQueue.syncPath,o));return}r.failed++,r.errors.push({path:i,error:n instanceof Error?`Deserialization error (file not quarantined): ${n.message}`:String(n)}),e.logger.warn("Failed to deserialize entity (transient error, not quarantined)",{path:i,entityType:t.entityType,id:t.id,error:be(n)});return}}function Xri(e,t,i,r){if(!e.jobQueueCallback)return;e.jobQueueCallback(t).catch((n)=>{e.logger.warn(`Failed to queue ${r} job`,{filePath:i,error:be(n)})})}function eni(e,t,i){if(!e.jobQueueCallback)return;let r=e.coverImageConverter.detectCoverImageUrl(t);if(!r)return;Xri(e,{type:"cover-image-convert",data:{filePath:hs(e.syncPath,i),sourceUrl:r.sourceUrl,postTitle:r.postTitle,postSlug:r.postSlug,customAlt:r.customAlt}},i,"cover image conversion"),e.logger.debug("Queued cover image conversion job",{filePath:i,sourceUrl:r.sourceUrl})}function tni(e,t,i,r){if(!e.jobQueueCallback)return;let n=e.inlineImageConverter.detectInlineImages(t,r);if(n.length===0)return;Xri(e,{type:"inline-image-convert",data:{filePath:hs(e.syncPath,i),postSlug:r}},i,"inline image conversion"),e.logger.debug("Queued inline image conversion job",{filePath:i,imageCount:n.length})}function ini(e,t,i,r){if(r.binaryStorage)return;eni(e,t.content,i),tni(e,t.content,i,t.id)}function iBe(e,t){if(t.endsWith(".invalid"))return{skip:!0,countSkipped:!1};if(t.includes("{"))return{skip:!0,countSkipped:!0};let{entityType:i}=e.fileOperations.parseEntityFromPath(t);if(e.entityTypes&&!e.entityTypes.includes(i))return{skip:!0,countSkipped:!0};if(!e.entityService.hasEntityType(i))return{skip:!0,countSkipped:!0};return{skip:!1,countSkipped:!1}}import{createHash as vsn}from"crypto";import{basename as nBe,dirname as wsn,extname as uni,join as Ssn}from"path";function rni(){return{imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],issues:[],jobIds:[]}}function Gd(e){e.skipped++}function Gb(e,t,i){(e.issues??=[]).push({path:t,message:i})}function nni(e,t,i,r){if($d(i)){e.debug("File disappeared before import, skipping",{path:t}),Gd(r);return}r.failed++,r.errors.push({path:t,error:be(i,"Failed to import entity")}),e.error("Failed to import entity",{path:t,error:i})}function oni(e,t,i){if(t>1)e.debug("Import completed",{filesProcessed:t,imported:i.imported,skipped:i.skipped,failed:i.failed,quarantined:i.quarantined});else e.debug("Import completed",i)}function ysn(e,t){if(e.visibility)return{visibility:e.visibility};let i=t?.visibility;if(i&&i!=="public")return{visibility:i,retainedFrom:i};return{visibility:i??"public"}}function sni(e){let{data:t}=Nx(e);return rBe(t)?t:{}}function rBe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function bsn(e,t){let i=sni(t);return Object.entries(sni(e)).some(([r,n])=>{if(r==="visibility")return!1;if(!Object.hasOwn(i,r))return!0;let o=i[r];return rBe(n)&&rBe(o)&&Object.keys(n).some((s)=>!Object.hasOwn(o,s))})}async function WX(e,t,i,r,n,o,s){let a=s;try{let c=o?.entity??null,u=t.metadata??{},d=i.metadata??{},{visibility:p,retainedFrom:m}=ysn(i,c);if(m)e.logger.debug("Retained stored visibility; imported file declared none",{path:r,entityType:t.entityType,id:t.id,retained:m});let h={...i,id:i.id??t.id,entityType:i.entityType??t.entityType,content:t.content,visibility:p,metadata:{...d,...u},created:c?.created??t.created.toISOString(),updated:t.updated.toISOString(),contentHash:""},{entity:f,stagedAsset:g}=s?{entity:h,stagedAsset:s}:await Asn(e,h);a=g;let y=e.entityService.serializeEntity(f);f.contentHash=cr(y);let b=m!==void 0||bsn(t.content,y);if(f.entityType!==t.entityType||f.id!==t.id)throw Error("Directory import adapter changed the admitted destination");if(!b&&c?.contentHash===f.contentHash&&c.visibility===f.visibility&&Bun.deepEquals(c.metadata,f.metadata)){Gd(n);return}let v={persistenceOrigin:b?"ordinary":"directory-sync",conditionalWrite:{expectedRevision:o?.revision??null}};a=void 0;let w=await e.entityService.upsertEntity({entity:f,...g&&{stagedAsset:g},options:v});n.imported++,n.jobIds.push(w.jobId),e.logger.debug("Imported entity from directory",{path:r,entityType:t.entityType,id:t.id,jobId:w.jobId}),await e.quarantine.markAsRecoveredIfNeeded(r)}catch(c){if(c instanceof Wg){n.skipped++,Gb(n,r,"Skipped stale import: entity changed while reading the file.");return}if(e.quarantine.isValidationError(c)){await e.quarantine.quarantineInvalidFile(r,c,n,(u)=>hs(e.imageJobQueue.syncPath,u));return}n.failed++,n.errors.push({path:r,error:c instanceof Error?`Transient error (file not quarantined): ${c.message}`:String(c)}),e.logger.warn("Failed to import entity (transient error, not quarantined)",{path:r,entityType:t.entityType,id:t.id,error:be(c)})}finally{if(a)await e.entityService.discardStagedAsset(a).catch(()=>{return})}}var Esn=/^data:[^;,]+;base64,([\s\S]*)$/;async function Asn(e,t){if(e.entityService.getEntityTypeConfig(t.entityType).binaryStorage!=="asset")return{entity:t};let i=Nx(t.content).content.trim(),r=Esn.exec(i)?.[1]?.replace(/\s/g,"");if(!r)return{entity:t};let n=await HX(ani(r));if(!n)return{entity:t};let o=await e.entityService.stageAsset(wI(r),{maxBytes:e.maxAssetImportBytes});return{stagedAsset:o,entity:{...t,content:o.ref,metadata:{...t.metadata,...n,sizeBytes:o.sizeBytes}}}}async function dni(e,t,i,r,n){let o=await e.fileOperations.statEntityFile(t,e.maxAssetImportBytes);if(o.entityType!==i.entityType||o.id!==i.id)throw Error("Directory import destination changed after admission");let s=ksn(r?.entity.content);if(s!==void 0){if(s===await $X(o.fullPath)){Gd(n);return}let d=await Bsn(o.fullPath,s);if(d){Gd(n),Gb(n,t,`Skipped: ${nBe(d)} holds the stored image; ${nBe(o.fullPath)} is a stale copy.`);return}}let a=await HX(lni(o.fullPath));if(!a){Gd(n),Gb(n,t,uni(o.fullPath).toLowerCase()===".svg"?"Skipped: images store PNG, JPEG, GIF or WebP only; rasterize this SVG to PNG or WebP to import it.":"Skipped: the file is not a PNG, JPEG, GIF or WebP image.");return}let c=await e.entityService.stageAsset(Bun.file(o.fullPath).stream(),{maxBytes:e.maxAssetImportBytes,expectedSize:o.sizeBytes}),u={entityType:o.entityType,id:o.id,content:c.ref,created:o.created,updated:o.updated};await WX(e,u,{entityType:o.entityType,id:o.id,content:c.ref,metadata:{...a,sizeBytes:c.sizeBytes}},t,n,r,c)}function ksn(e){let t=zg.safeParse(e);if(t.success)return kw(t.data);let i=e===void 0?void 0:cni(e);if(!i)return;let r=vsn("sha256");try{for(let n of wI(i.base64))r.update(n)}catch{return}return r.digest("hex")}async function Bsn(e,t){let i=Ssn(wsn(e),nBe(e,uni(e))),r=Ux.map((o)=>`${i}${o}`).filter((o)=>o!==e),n=await Promise.all(r.map(async(o)=>await Bun.file(o).exists()?$X(o):void 0));return r.find((o,s)=>n[s]===t)}async function pni(e,t,i){e.logger.debug("Importing entities from directory");let r=rni(),n=t??await e.fileOperations.getAllSyncFiles(),o=i??await $3(e.entityService,e.fileOperations,n.filter((s)=>!iBe(e,s).skip));for(let s of n)await Csn(e,s,r,o);return oni(e.logger,n.length,r),r}async function Csn(e,t,i,r){let n=iBe(e,t);if(n.skip){if(n.countSkipped)Gd(i);return}try{let o=r.find((d)=>d.path===t);if(!o)throw Error("Missing directory import precondition");let s=await e.entityService.getEntityWriteSnapshot({entityType:o.entityType,id:o.id,visibilityScope:Pt("check directory import write preconditions")});if((s?.revision??null)!==o.expectedRevision){Gd(i),Gb(i,t,"Skipped stale import: entity changed after this sync was queued.");return}let a=await Dsn(e,t,i);if(a===void 0)return;let c=e.entityService.getEntityTypeConfig(o.entityType).binaryStorage==="asset";if(c&&Wh(a)){await dni(e,a,o,s,i);return}let u=await e.fileOperations.readEntity(a,c?e.maxAssetImportBytes:e.maxImportFileBytes);if(u.entityType!==o.entityType||u.id!==o.id)throw Error("Directory import destination changed after admission");await Isn(e,u,a,i,s)}catch(o){if(o instanceof VO){Gd(i),Gb(i,t,o.message);return}nni(e.logger,t,o,i)}}async function Dsn(e,t,i){let r=e.fileOperations.getMisplacedContainedPath(t);if(r===void 0)return t;if(await e.fileOperations.moveEntityFile(t,r))return e.logger.info("Moved a contained entity's file into its container",{path:t,canonicalPath:r}),r;e.logger.warn("Kept a misplaced file: its placement already holds one",{path:t,canonicalPath:r}),Gd(i),Gb(i,t,`Not imported: this file belongs at ${r}, which already holds one.`);return}async function Isn(e,t,i,r,n){let o=Yri(t);if(o){e.logger.debug(Jri(o),{path:i,entityType:t.entityType}),Gd(r);return}let s=n?.entity??null;if(s&&_sn(e,s,t)){Gd(r);return}let a=await Qri(e,t,i,r);if(!a)return;let c=r.imported;if(await WX(e,t,a,i,r,n),r.imported>c)ini(e.imageJobQueue,t,i,e.entityService.getEntityTypeConfig(t.entityType))}function _sn(e,t,i){if(e.fileOperations.shouldUpdateEntity(t,i))return!1;return i.entityType!=="document"||Bun.deepEquals(t.metadata,i.metadata??{})}async function mni(e,t,i,r){return tBe(e.createExportDeps(t,i),r)}async function hni(e,t,i,r){return Kri(e.createExportDeps(t,i),r)}async function fni(e,t,i,r){return pni(e.createImportDeps(t),i,r)}async function xni(e,t,i,r){let n=await Gri(e.createCleanupDeps(i,r));if(n.deleted>0)t.info("Cleaned up orphaned entities",{deleted:n.deleted});return n}async function gni(e,t,i,r,n){return e.importEntitiesWithProgress(t,i,r,n)}async function yni(e,t,i,r,n,o){let s=i??t;return e.exportEntitiesWithProgress(s,r,n,o)}var bni=l.object({syncPath:l.string(),autoSync:l.boolean().optional(),watchInterval:l.number().optional(),includeMetadata:l.boolean().optional(),entityTypes:l.array(l.string()).optional(),deleteOnFileRemoval:l.boolean().optional(),maxImportFileBytes:l.number().int().positive().optional(),maxAssetImportBytes:l.number().int().positive().optional()});function Eni(e){let{entityService:t,logger:i,...r}=e;return bni.parse(r),{originalSyncPath:e.syncPath,syncPath:Nri(e.syncPath),autoSync:e.autoSync??!0,watchInterval:e.watchInterval??5000,deleteOnFileRemoval:e.deleteOnFileRemoval??!0,maxImportFileBytes:e.maxImportFileBytes??TX,maxAssetImportBytes:e.maxAssetImportBytes??PX,entityTypes:e.entityTypes}}class ZX{entityService;logger;syncPath;autoSync;watchInterval;deleteOnFileRemoval;entityTypes;fileWatcher;lastSync;batchQueue;fileOperations;progressOperations;operationDeps;jobQueueCallback;pendingDeletes;cleanupAdmission;constructor(e,t=new rN){let i=Eni(e);this.entityService=e.entityService,this.logger=e.logger.child("DirectorySync"),this.pendingDeletes=t,this.syncPath=i.syncPath,this.autoSync=i.autoSync,this.watchInterval=i.watchInterval,this.deleteOnFileRemoval=i.deleteOnFileRemoval,this.entityTypes=i.entityTypes;let r=Pri(this.logger,this.entityService,this.syncPath,this.deleteOnFileRemoval);this.fileOperations=r.fileOperations,this.batchQueue=r.batchQueue,this.progressOperations=r.progressOperations,this.operationDeps=Rri(this.logger,this.entityService,this.syncPath,r,{maxImportFileBytes:i.maxImportFileBytes,maxAssetImportBytes:i.maxAssetImportBytes},this.pendingDeletes,()=>this.jobQueueCallback),this.logger.debug("Initialized with path",{originalPath:i.originalSyncPath,resolvedPath:this.syncPath})}async initialize(){await Lri(this.logger,this.syncPath,this.autoSync,this.startWatching.bind(this))}async initializeDirectory(){await zri(this.logger,this.syncPath)}setJobQueueCallback(e){this.jobQueueCallback=e}setCleanupAdmission(e){this.cleanupAdmission=e}async sync(){return this.runBulkMutation("sync",()=>mri({logger:this.logger,importEntities:this.importEntitiesUnbatched.bind(this),removeOrphanedEntities:this.removeOrphanedEntitiesUnbatched.bind(this),markSynced:(e)=>{this.lastSync=e}}))}async processEntityExport(e){return mni(this.operationDeps,this.deleteOnFileRemoval,this.entityTypes,e)}async exportEntities(e){return hni(this.operationDeps,this.deleteOnFileRemoval,this.entityTypes,e)}async importEntitiesWithProgress(e,t,i,r,n){return this.runBulkMutation("import",async()=>{let o=e??await this.fileOperations.getAllSyncFiles(),s=n??await $3(this.entityService,this.fileOperations,o);return gni(this.progressOperations,o,t,i,(a)=>this.importEntitiesUnbatched(a,s))},r)}async exportEntitiesWithProgress(e,t,i){return yni(this.progressOperations,this.entityTypes,e,t,i,this.exportEntities.bind(this))}async importEntities(e){return this.runBulkMutation("import",()=>this.importEntitiesUnbatched(e))}async removeOrphanedEntities(e){return this.runBulkMutation("cleanup",()=>this.removeOrphanedEntitiesUnbatched(),e)}importEntitiesUnbatched(e,t){return fni(this.operationDeps,this.entityTypes,e,t)}async removeOrphanedEntitiesUnbatched(){return await this.cleanupAdmission?.(),xni(this.operationDeps,this.logger,this.deleteOnFileRemoval,this.entityTypes)}runBulkMutation(e,t,i){return this.entityService.runBulkMutation({source:"directory-sync",operationId:i?.operationId??`${e}:${qd()}`},t)}get fileOps(){return this.fileOperations}get shouldDeleteOnFileRemoval(){return this.deleteOnFileRemoval}async getAllMarkdownFiles(){return Mri(this.fileOperations)}async ensureDirectoryStructure(){await Ori(this.fileOperations,this.entityService,this.entityTypes)}async getStatus(){return jri(this.fileOperations,this.syncPath,this.fileWatcher,this.lastSync)}async queueSyncBatch(e,t,i,r,n){return this.batchQueue.queueSyncBatch(e,t,i,r,n)}async startWatching(){this.fileWatcher=await uri(this.fileWatcher,{logger:this.logger,syncPath:this.syncPath,watchInterval:this.watchInterval,importEntities:this.importEntities.bind(this),jobQueueCallback:this.jobQueueCallback,fileOperations:this.fileOperations,deleteOnFileRemoval:this.deleteOnFileRemoval})}async stopWatching(){let e=this.fileWatcher;this.fileWatcher=void 0,await dri(e)}suppressWatchPaths(e){this.fileWatcher?.suppressPaths(e)}ignorePulledWatchPaths(e,t){this.fileWatcher?.ignorePulledPaths(e,t)}withoutStoredEchoes(e){return Fri({syncPath:this.syncPath,entityService:this.entityService,fileOperations:this.fileOperations},e)}async recordPendingPullDeletes(e){if(!this.deleteOnFileRemoval)return;for(let t of e){let i=this.fileOperations.getPendingDeleteTarget(t);if(!i)continue;if(Zh(t)&&await this.fileOperations.fileExists(i.filePath))continue;this.pendingDeletes.record(i)}}isPendingDelete(e,t){return this.pendingDeletes.has(e,t)}completePendingDelete(e,t,i){let r=this.fileOperations.getPendingDeleteTarget(i);if(r?.entityType!==e||r.entityId!==t)return;this.pendingDeletes.complete(e,t,r.filePath)}setWatchCallback(e){pri(this.fileWatcher,e)}}var Ani=120000;function Tsn(e){let t;try{t=new URL(e)}catch{return{remoteUrl:e,token:void 0}}if(!t.username&&!t.password)return{remoteUrl:e,token:void 0};let i=t.password||t.username;return t.username="",t.password="",{remoteUrl:t.toString(),token:i||void 0}}function vni(e){let t=e.gitUrl??(e.repo?`https://github.com/${e.repo}.git`:"");return Tsn(t).remoteUrl}function oBe(e){let t=e;try{let i=new URL(e);i.username="",i.password="",t=i.toString()}catch{}return Un(t)}async function VX(e){let{BrokerConnection:t}=await import("./chunks/client-pjmxw0x9.js");return t.connect(e)}class aBe{#e;#t=null;#i=null;#n=!1;constructor(e){this.#e=e}async attach(){await this.#o()}async#o(){if(this.#n)throw new sBe(this.#e.checkoutPath,"this client has been cleaned up");if(this.#t)return this.#t;let e=await this.#e.connect(),t;try{t=await e.registerCheckout({checkoutPath:this.#e.checkoutPath,branch:this.#e.branch,remoteFingerprint:this.#e.remoteFingerprint})}catch(r){throw e.close(),r}this.#t=e,e.onUnavailable(()=>{if(this.#t!==e||this.#n)return;this.#t=null,this.#e.onOwnerUnavailable?.()});let i=this.#i;if(this.#i=t.brokerId,i!==null&&i!==t.brokerId)this.#e.onOwnerReplaced?.(t.brokerId);return e}async#r(e,t={}){let i=await this.#o();try{return await i.execute(this.#e.checkoutPath,e,t)}catch(r){if(!(r instanceof sBe))throw r;if(this.#t=null,wni(e))throw r;return(await this.#o()).execute(this.#e.checkoutPath,e,t)}}async admitsMutations(){return(await(await this.#o()).status()).admitsMutations}async openAdmission(){await(await this.#o()).openAdmission()}hasRemote(){return this.#e.remoteUrl.length>0}initialize(){return this.#r({name:"initialize"})}getStatus(){return this.#r({name:"get-status"})}hasLocalChanges(){return this.#r({name:"has-local-changes"})}commit(e){return this.#r({name:"commit",...e===void 0?{}:{message:e}})}push(e){return this.#r({name:"push"},{...e?{signal:e}:{}})}commitAndPush(){return this.#r({name:"commit-and-push"})}pull(e,t){return this.#r({name:"pull"},{...t?{onProgress:t}:{},...e?{signal:e}:{}})}getReconciliationDelta(e){return this.#r({name:"get-reconciliation-delta",...e===void 0?{}:{checkpoint:e}})}getCheckpoint(){return this.#r({name:"get-checkpoint"})}log(e,t){return this.#r({name:"log-file",filePath:e,...t===void 0?{}:{limit:t}})}show(e,t){return this.#r({name:"show-file",sha:e,filePath:t})}async cleanup(){this.#n=!0,this.#t?.close(),this.#t=null}}var Sni="BRAIN_GIT_BROKER_SOCKET";async function kni(e){let{socketPath:t}=e;if(!t)throw Error(`Git sync is configured but ${Sni} is unset: this role has no checkout owner to work through`);let i=new aBe({connect:()=>VX(t),checkoutPath:e.checkoutPath,branch:e.branch,remoteFingerprint:oBe(e.remoteUrl),remoteUrl:e.remoteUrl,...e.onOwnerReplaced?{onOwnerReplaced:e.onOwnerReplaced}:{},...e.onOwnerUnavailable?{onOwnerUnavailable:e.onOwnerUnavailable}:{}});return await i.attach(),e.logger.debug("Connected to the Git broker",{socketPath:t}),i}function cBe(e){return async()=>{let t=await VX(e);try{let i=await t.status();return{ambiguousRequestIds:i.ambiguousRequestIds,evidenceComplete:i.evidenceComplete,recoveryPending:i.recoveryPending}}finally{t.close()}}}function lBe(e){return async()=>{let t=await e.probe().then((i)=>i,(i)=>i);if(!Psn(t))return{status:"unhealthy",message:"No Git checkout owner answered",details:{error:be(t)}};if(t.recoveryPending)return{status:"degraded",message:t.evidenceComplete?`Previous Git owner left ${t.ambiguousRequestIds.length} request(s) unaccounted for`:"Previous Git owner's record could not be read whole",details:{ambiguousRequestIds:t.ambiguousRequestIds,evidenceComplete:t.evidenceComplete}};return{status:"healthy"}}}function Psn(e){return typeof e==="object"&&e!==null&&"ambiguousRequestIds"in e&&"evidenceComplete"in e&&"recoveryPending"in e}function Bni(e){return async()=>{let t=e.client();if(!t)throw Error("Git broker client is unavailable");if(await t.admitsMutations())return;await e.replay(t),await t.openAdmission()}}function Cni(e){let t=0,i=(r)=>{e.scheduler.scheduleTrailing("git-owner-replacement",r,async()=>{try{await e.replay(),t=0}catch(n){t+=1,e.logger.error("Reconciling a replaced Git broker failed",{error:be(n),consecutiveFailures:t});let o=Math.min(1000*2**(t-1),30000);i(o)}})};return(r)=>{e.logger.warn("Git broker was replaced; reconciling from the checkout",{brokerId:r}),i(0)}}class KX extends Dni{canFormat(e){return Z3.safeParse(e).success}format(e){let t=[];if(t.push(`# Directory Sync Status
6808
+ ---`)return"empty-frontmatter";return}function Jri(e){switch(e){case"empty-content":return"Skipping file with empty content (likely mid-write)";case"empty-frontmatter":return"Skipping file with empty frontmatter (likely mid-write)"}}async function Qri(e,t,i,r){try{return e.entityService.deserializeEntity(t.content,t.entityType)}catch(n){if(e.quarantine.isValidationError(n)){await e.quarantine.quarantineInvalidFile(i,n,r,(o)=>hs(e.imageJobQueue.syncPath,o));return}r.failed++,r.errors.push({path:i,error:n instanceof Error?`Deserialization error (file not quarantined): ${n.message}`:String(n)}),e.logger.warn("Failed to deserialize entity (transient error, not quarantined)",{path:i,entityType:t.entityType,id:t.id,error:be(n)});return}}function Xri(e,t,i,r){if(!e.jobQueueCallback)return;e.jobQueueCallback(t).catch((n)=>{e.logger.warn(`Failed to queue ${r} job`,{filePath:i,error:be(n)})})}function eni(e,t,i){if(!e.jobQueueCallback)return;let r=e.coverImageConverter.detectCoverImageUrl(t);if(!r)return;Xri(e,{type:"cover-image-convert",data:{filePath:hs(e.syncPath,i),sourceUrl:r.sourceUrl,postTitle:r.postTitle,postSlug:r.postSlug,customAlt:r.customAlt}},i,"cover image conversion"),e.logger.debug("Queued cover image conversion job",{filePath:i,sourceUrl:r.sourceUrl})}function tni(e,t,i,r){if(!e.jobQueueCallback)return;let n=e.inlineImageConverter.detectInlineImages(t,r);if(n.length===0)return;Xri(e,{type:"inline-image-convert",data:{filePath:hs(e.syncPath,i),postSlug:r}},i,"inline image conversion"),e.logger.debug("Queued inline image conversion job",{filePath:i,imageCount:n.length})}function ini(e,t,i,r){if(r.binaryStorage)return;eni(e,t.content,i),tni(e,t.content,i,t.id)}function iBe(e,t){if(t.endsWith(".invalid"))return{skip:!0,countSkipped:!1};if(t.includes("{"))return{skip:!0,countSkipped:!0};let{entityType:i}=e.fileOperations.parseEntityFromPath(t);if(e.entityTypes&&!e.entityTypes.includes(i))return{skip:!0,countSkipped:!0};if(!e.entityService.hasEntityType(i))return{skip:!0,countSkipped:!0};return{skip:!1,countSkipped:!1}}import{createHash as vsn}from"crypto";import{basename as nBe,dirname as wsn,extname as uni,join as Ssn}from"path";function rni(){return{imported:0,skipped:0,failed:0,quarantined:0,quarantinedFiles:[],errors:[],issues:[],jobIds:[]}}function Gd(e){e.skipped++}function Gb(e,t,i){(e.issues??=[]).push({path:t,message:i})}function nni(e,t,i,r){if($d(i)){e.debug("File disappeared before import, skipping",{path:t}),Gd(r);return}r.failed++,r.errors.push({path:t,error:be(i,"Failed to import entity")}),e.error("Failed to import entity",{path:t,error:i})}function oni(e,t,i){if(t>1)e.debug("Import completed",{filesProcessed:t,imported:i.imported,skipped:i.skipped,failed:i.failed,quarantined:i.quarantined});else e.debug("Import completed",i)}function ysn(e,t){if(e.visibility)return{visibility:e.visibility};let i=t?.visibility;if(i&&i!=="public")return{visibility:i,retainedFrom:i};return{visibility:i??"public"}}function sni(e){let{data:t}=Nx(e);return rBe(t)?t:{}}function rBe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function bsn(e,t){let i=sni(t);return Object.entries(sni(e)).some(([r,n])=>{if(r==="visibility")return!1;if(!Object.hasOwn(i,r))return!0;let o=i[r];return rBe(n)&&rBe(o)&&Object.keys(n).some((s)=>!Object.hasOwn(o,s))})}async function WX(e,t,i,r,n,o,s){let a=s;try{let c=o?.entity??null,u=t.metadata??{},d=i.metadata??{},{visibility:p,retainedFrom:m}=ysn(i,c);if(m)e.logger.debug("Retained stored visibility; imported file declared none",{path:r,entityType:t.entityType,id:t.id,retained:m});let h={...i,id:i.id??t.id,entityType:i.entityType??t.entityType,content:t.content,visibility:p,metadata:{...d,...u},created:c?.created??t.created.toISOString(),updated:t.updated.toISOString(),contentHash:""},{entity:f,stagedAsset:g}=s?{entity:h,stagedAsset:s}:await Asn(e,h);a=g;let y=e.entityService.serializeEntity(f);f.contentHash=cr(y);let b=m!==void 0||bsn(t.content,y);if(f.entityType!==t.entityType||f.id!==t.id)throw Error("Directory import adapter changed the admitted destination");if(!b&&c?.contentHash===f.contentHash&&c.visibility===f.visibility&&Bun.deepEquals(c.metadata,f.metadata)){Gd(n);return}let v={persistenceOrigin:b?"ordinary":"directory-sync",conditionalWrite:{expectedRevision:o?.revision??null}};a=void 0;let w=await e.entityService.upsertEntity({entity:f,...g&&{stagedAsset:g},options:v});n.imported++,n.jobIds.push(w.jobId),e.logger.debug("Imported entity from directory",{path:r,entityType:t.entityType,id:t.id,jobId:w.jobId}),await e.quarantine.markAsRecoveredIfNeeded(r)}catch(c){if(c instanceof Wg){n.skipped++,Gb(n,r,"Skipped stale import: entity changed while reading the file.");return}if(e.quarantine.isValidationError(c)){await e.quarantine.quarantineInvalidFile(r,c,n,(u)=>hs(e.imageJobQueue.syncPath,u));return}n.failed++,n.errors.push({path:r,error:c instanceof Error?`Transient error (file not quarantined): ${c.message}`:String(c)}),e.logger.warn("Failed to import entity (transient error, not quarantined)",{path:r,entityType:t.entityType,id:t.id,error:be(c)})}finally{if(a)await e.entityService.discardStagedAsset(a).catch(()=>{return})}}var Esn=/^data:[^;,]+;base64,([\s\S]*)$/;async function Asn(e,t){if(e.entityService.getEntityTypeConfig(t.entityType).binaryStorage!=="asset")return{entity:t};let i=Nx(t.content).content.trim(),r=Esn.exec(i)?.[1]?.replace(/\s/g,"");if(!r)return{entity:t};let n=await HX(ani(r));if(!n)return{entity:t};let o=await e.entityService.stageAsset(wI(r),{maxBytes:e.maxAssetImportBytes});return{stagedAsset:o,entity:{...t,content:o.ref,metadata:{...t.metadata,...n,sizeBytes:o.sizeBytes}}}}async function dni(e,t,i,r,n){let o=await e.fileOperations.statEntityFile(t,e.maxAssetImportBytes);if(o.entityType!==i.entityType||o.id!==i.id)throw Error("Directory import destination changed after admission");let s=ksn(r?.entity.content);if(s!==void 0){if(s===await $X(o.fullPath)){Gd(n);return}let d=await Bsn(o.fullPath,s);if(d){Gd(n),Gb(n,t,`Skipped: ${nBe(d)} holds the stored image; ${nBe(o.fullPath)} is a stale copy.`);return}}let a=await HX(lni(o.fullPath));if(!a){Gd(n),Gb(n,t,uni(o.fullPath).toLowerCase()===".svg"?"Skipped: images store PNG, JPEG, GIF or WebP only; rasterize this SVG to PNG or WebP to import it.":"Skipped: the file is not a PNG, JPEG, GIF or WebP image.");return}let c=await e.entityService.stageAsset(Bun.file(o.fullPath).stream(),{maxBytes:e.maxAssetImportBytes,expectedSize:o.sizeBytes}),u={entityType:o.entityType,id:o.id,content:c.ref,created:o.created,updated:o.updated};await WX(e,u,{entityType:o.entityType,id:o.id,content:c.ref,metadata:{...a,sizeBytes:c.sizeBytes}},t,n,r,c)}function ksn(e){let t=zg.safeParse(e);if(t.success)return kw(t.data);let i=e===void 0?void 0:cni(e);if(!i)return;let r=vsn("sha256");try{for(let n of wI(i.base64))r.update(n)}catch{return}return r.digest("hex")}async function Bsn(e,t){let i=Ssn(wsn(e),nBe(e,uni(e))),r=Ux.map((o)=>`${i}${o}`).filter((o)=>o!==e),n=await Promise.all(r.map(async(o)=>await Bun.file(o).exists()?$X(o):void 0));return r.find((o,s)=>n[s]===t)}async function pni(e,t,i){e.logger.debug("Importing entities from directory");let r=rni(),n=t??await e.fileOperations.getAllSyncFiles(),o=i??await $3(e.entityService,e.fileOperations,n.filter((s)=>!iBe(e,s).skip));for(let s of n)await Csn(e,s,r,o);return oni(e.logger,n.length,r),r}async function Csn(e,t,i,r){let n=iBe(e,t);if(n.skip){if(n.countSkipped)Gd(i);return}try{let o=r.find((d)=>d.path===t);if(!o)throw Error("Missing directory import precondition");let s=await e.entityService.getEntityWriteSnapshot({entityType:o.entityType,id:o.id,visibilityScope:Pt("check directory import write preconditions")});if((s?.revision??null)!==o.expectedRevision){Gd(i),Gb(i,t,"Skipped stale import: entity changed after this sync was queued.");return}let a=await Dsn(e,t,i);if(a===void 0)return;let c=e.entityService.getEntityTypeConfig(o.entityType).binaryStorage==="asset";if(c&&Wh(a)){await dni(e,a,o,s,i);return}let u=await e.fileOperations.readEntity(a,c?e.maxAssetImportBytes:e.maxImportFileBytes);if(u.entityType!==o.entityType||u.id!==o.id)throw Error("Directory import destination changed after admission");await Isn(e,u,a,i,s)}catch(o){if(o instanceof VO){Gd(i),Gb(i,t,o.message);return}nni(e.logger,t,o,i)}}async function Dsn(e,t,i){let r=e.fileOperations.getMisplacedContainedPath(t);if(r===void 0)return t;if(await e.fileOperations.moveEntityFile(t,r))return e.logger.info("Moved a contained entity's file into its container",{path:t,canonicalPath:r}),r;e.logger.warn("Kept a misplaced file: its placement already holds one",{path:t,canonicalPath:r}),Gd(i),Gb(i,t,`Not imported: this file belongs at ${r}, which already holds one.`);return}async function Isn(e,t,i,r,n){let o=Yri(t);if(o){e.logger.debug(Jri(o),{path:i,entityType:t.entityType}),Gd(r);return}let s=n?.entity??null;if(s&&_sn(e,s,t)){Gd(r);return}let a=await Qri(e,t,i,r);if(!a)return;let c=r.imported;if(await WX(e,t,a,i,r,n),r.imported>c)ini(e.imageJobQueue,t,i,e.entityService.getEntityTypeConfig(t.entityType))}function _sn(e,t,i){if(e.fileOperations.shouldUpdateEntity(t,i))return!1;return i.entityType!=="document"||Bun.deepEquals(t.metadata,i.metadata??{})}async function mni(e,t,i,r){return tBe(e.createExportDeps(t,i),r)}async function hni(e,t,i,r){return Kri(e.createExportDeps(t,i),r)}async function fni(e,t,i,r){return pni(e.createImportDeps(t),i,r)}async function xni(e,t,i,r){let n=await Gri(e.createCleanupDeps(i,r));if(n.deleted>0)t.info("Cleaned up orphaned entities",{deleted:n.deleted});return n}async function gni(e,t,i,r,n){return e.importEntitiesWithProgress(t,i,r,n)}async function yni(e,t,i,r,n,o){let s=i??t;return e.exportEntitiesWithProgress(s,r,n,o)}var bni=l.object({syncPath:l.string(),autoSync:l.boolean().optional(),watchInterval:l.number().optional(),includeMetadata:l.boolean().optional(),entityTypes:l.array(l.string()).optional(),deleteOnFileRemoval:l.boolean().optional(),maxImportFileBytes:l.number().int().positive().optional(),maxAssetImportBytes:l.number().int().positive().optional()});function Eni(e){let{entityService:t,logger:i,...r}=e;return bni.parse(r),{originalSyncPath:e.syncPath,syncPath:Nri(e.syncPath),autoSync:e.autoSync??!0,watchInterval:e.watchInterval??5000,deleteOnFileRemoval:e.deleteOnFileRemoval??!0,maxImportFileBytes:e.maxImportFileBytes??TX,maxAssetImportBytes:e.maxAssetImportBytes??PX,entityTypes:e.entityTypes}}class ZX{entityService;logger;syncPath;autoSync;watchInterval;deleteOnFileRemoval;entityTypes;fileWatcher;lastSync;batchQueue;fileOperations;progressOperations;operationDeps;jobQueueCallback;pendingDeletes;cleanupAdmission;constructor(e,t=new rN){let i=Eni(e);this.entityService=e.entityService,this.logger=e.logger.child("DirectorySync"),this.pendingDeletes=t,this.syncPath=i.syncPath,this.autoSync=i.autoSync,this.watchInterval=i.watchInterval,this.deleteOnFileRemoval=i.deleteOnFileRemoval,this.entityTypes=i.entityTypes;let r=Pri(this.logger,this.entityService,this.syncPath,this.deleteOnFileRemoval);this.fileOperations=r.fileOperations,this.batchQueue=r.batchQueue,this.progressOperations=r.progressOperations,this.operationDeps=Rri(this.logger,this.entityService,this.syncPath,r,{maxImportFileBytes:i.maxImportFileBytes,maxAssetImportBytes:i.maxAssetImportBytes},this.pendingDeletes,()=>this.jobQueueCallback),this.logger.debug("Initialized with path",{originalPath:i.originalSyncPath,resolvedPath:this.syncPath})}async initialize(){await Lri(this.logger,this.syncPath,this.autoSync,this.startWatching.bind(this))}async initializeDirectory(){await zri(this.logger,this.syncPath)}setJobQueueCallback(e){this.jobQueueCallback=e}setCleanupAdmission(e){this.cleanupAdmission=e}async sync(){return this.runBulkMutation("sync",()=>mri({logger:this.logger,importEntities:this.importEntitiesUnbatched.bind(this),removeOrphanedEntities:this.removeOrphanedEntitiesUnbatched.bind(this),markSynced:(e)=>{this.lastSync=e}}))}async processEntityExport(e){return mni(this.operationDeps,this.deleteOnFileRemoval,this.entityTypes,e)}async exportEntities(e){return hni(this.operationDeps,this.deleteOnFileRemoval,this.entityTypes,e)}async importEntitiesWithProgress(e,t,i,r,n){return this.runBulkMutation("import",async()=>{let o=e??await this.fileOperations.getAllSyncFiles(),s=n??await $3(this.entityService,this.fileOperations,o);return gni(this.progressOperations,o,t,i,(a)=>this.importEntitiesUnbatched(a,s))},r)}async exportEntitiesWithProgress(e,t,i){return yni(this.progressOperations,this.entityTypes,e,t,i,this.exportEntities.bind(this))}async importEntities(e){return this.runBulkMutation("import",()=>this.importEntitiesUnbatched(e))}async removeOrphanedEntities(e){return this.runBulkMutation("cleanup",()=>this.removeOrphanedEntitiesUnbatched(),e)}importEntitiesUnbatched(e,t){return fni(this.operationDeps,this.entityTypes,e,t)}async removeOrphanedEntitiesUnbatched(){return await this.cleanupAdmission?.(),xni(this.operationDeps,this.logger,this.deleteOnFileRemoval,this.entityTypes)}runBulkMutation(e,t,i){return this.entityService.runBulkMutation({source:"directory-sync",operationId:i?.operationId??`${e}:${qd()}`},t)}get fileOps(){return this.fileOperations}get shouldDeleteOnFileRemoval(){return this.deleteOnFileRemoval}async getAllMarkdownFiles(){return Mri(this.fileOperations)}async ensureDirectoryStructure(){await Ori(this.fileOperations,this.entityService,this.entityTypes)}async getStatus(){return jri(this.fileOperations,this.syncPath,this.fileWatcher,this.lastSync)}async queueSyncBatch(e,t,i,r,n){return this.batchQueue.queueSyncBatch(e,t,i,r,n)}async startWatching(){this.fileWatcher=await uri(this.fileWatcher,{logger:this.logger,syncPath:this.syncPath,watchInterval:this.watchInterval,importEntities:this.importEntities.bind(this),jobQueueCallback:this.jobQueueCallback,fileOperations:this.fileOperations,deleteOnFileRemoval:this.deleteOnFileRemoval})}async stopWatching(){let e=this.fileWatcher;this.fileWatcher=void 0,await dri(e)}suppressWatchPaths(e){this.fileWatcher?.suppressPaths(e)}ignorePulledWatchPaths(e,t){this.fileWatcher?.ignorePulledPaths(e,t)}withoutStoredEchoes(e){return Fri({syncPath:this.syncPath,entityService:this.entityService,fileOperations:this.fileOperations},e)}async recordPendingPullDeletes(e){if(!this.deleteOnFileRemoval)return;for(let t of e){let i=this.fileOperations.getPendingDeleteTarget(t);if(!i)continue;if(Zh(t)&&await this.fileOperations.fileExists(i.filePath))continue;this.pendingDeletes.record(i)}}isPendingDelete(e,t){return this.pendingDeletes.has(e,t)}completePendingDelete(e,t,i){let r=this.fileOperations.getPendingDeleteTarget(i);if(r?.entityType!==e||r.entityId!==t)return;this.pendingDeletes.complete(e,t,r.filePath)}setWatchCallback(e){pri(this.fileWatcher,e)}}var Ani=120000;function Tsn(e){let t;try{t=new URL(e)}catch{return{remoteUrl:e,token:void 0}}if(!t.username&&!t.password)return{remoteUrl:e,token:void 0};let i=t.password||t.username;return t.username="",t.password="",{remoteUrl:t.toString(),token:i||void 0}}function vni(e){let t=e.gitUrl??(e.repo?`https://github.com/${e.repo}.git`:"");return Tsn(t).remoteUrl}function oBe(e){let t=e;try{let i=new URL(e);i.username="",i.password="",t=i.toString()}catch{}return Un(t)}async function VX(e){let{BrokerConnection:t}=await import("./chunks/client-5jh7znhw.js");return t.connect(e)}class aBe{#e;#t=null;#i=null;#n=!1;constructor(e){this.#e=e}async attach(){await this.#o()}async#o(){if(this.#n)throw new sBe(this.#e.checkoutPath,"this client has been cleaned up");if(this.#t)return this.#t;let e=await this.#e.connect(),t;try{t=await e.registerCheckout({checkoutPath:this.#e.checkoutPath,branch:this.#e.branch,remoteFingerprint:this.#e.remoteFingerprint})}catch(r){throw e.close(),r}this.#t=e,e.onUnavailable(()=>{if(this.#t!==e||this.#n)return;this.#t=null,this.#e.onOwnerUnavailable?.()});let i=this.#i;if(this.#i=t.brokerId,i!==null&&i!==t.brokerId)this.#e.onOwnerReplaced?.(t.brokerId);return e}async#r(e,t={}){let i=await this.#o();try{return await i.execute(this.#e.checkoutPath,e,t)}catch(r){if(!(r instanceof sBe))throw r;if(this.#t=null,wni(e))throw r;return(await this.#o()).execute(this.#e.checkoutPath,e,t)}}async admitsMutations(){return(await(await this.#o()).status()).admitsMutations}async openAdmission(){await(await this.#o()).openAdmission()}hasRemote(){return this.#e.remoteUrl.length>0}initialize(){return this.#r({name:"initialize"})}getStatus(){return this.#r({name:"get-status"})}hasLocalChanges(){return this.#r({name:"has-local-changes"})}commit(e){return this.#r({name:"commit",...e===void 0?{}:{message:e}})}push(e){return this.#r({name:"push"},{...e?{signal:e}:{}})}commitAndPush(){return this.#r({name:"commit-and-push"})}pull(e,t){return this.#r({name:"pull"},{...t?{onProgress:t}:{},...e?{signal:e}:{}})}getReconciliationDelta(e){return this.#r({name:"get-reconciliation-delta",...e===void 0?{}:{checkpoint:e}})}getCheckpoint(){return this.#r({name:"get-checkpoint"})}log(e,t){return this.#r({name:"log-file",filePath:e,...t===void 0?{}:{limit:t}})}show(e,t){return this.#r({name:"show-file",sha:e,filePath:t})}async cleanup(){this.#n=!0,this.#t?.close(),this.#t=null}}var Sni="BRAIN_GIT_BROKER_SOCKET";async function kni(e){let{socketPath:t}=e;if(!t)throw Error(`Git sync is configured but ${Sni} is unset: this role has no checkout owner to work through`);let i=new aBe({connect:()=>VX(t),checkoutPath:e.checkoutPath,branch:e.branch,remoteFingerprint:oBe(e.remoteUrl),remoteUrl:e.remoteUrl,...e.onOwnerReplaced?{onOwnerReplaced:e.onOwnerReplaced}:{},...e.onOwnerUnavailable?{onOwnerUnavailable:e.onOwnerUnavailable}:{}});return await i.attach(),e.logger.debug("Connected to the Git broker",{socketPath:t}),i}function cBe(e){return async()=>{let t=await VX(e);try{let i=await t.status();return{ambiguousRequestIds:i.ambiguousRequestIds,evidenceComplete:i.evidenceComplete,recoveryPending:i.recoveryPending}}finally{t.close()}}}function lBe(e){return async()=>{let t=await e.probe().then((i)=>i,(i)=>i);if(!Psn(t))return{status:"unhealthy",message:"No Git checkout owner answered",details:{error:be(t)}};if(t.recoveryPending)return{status:"degraded",message:t.evidenceComplete?`Previous Git owner left ${t.ambiguousRequestIds.length} request(s) unaccounted for`:"Previous Git owner's record could not be read whole",details:{ambiguousRequestIds:t.ambiguousRequestIds,evidenceComplete:t.evidenceComplete}};return{status:"healthy"}}}function Psn(e){return typeof e==="object"&&e!==null&&"ambiguousRequestIds"in e&&"evidenceComplete"in e&&"recoveryPending"in e}function Bni(e){return async()=>{let t=e.client();if(!t)throw Error("Git broker client is unavailable");if(await t.admitsMutations())return;await e.replay(t),await t.openAdmission()}}function Cni(e){let t=0,i=(r)=>{e.scheduler.scheduleTrailing("git-owner-replacement",r,async()=>{try{await e.replay(),t=0}catch(n){t+=1,e.logger.error("Reconciling a replaced Git broker failed",{error:be(n),consecutiveFailures:t});let o=Math.min(1000*2**(t-1),30000);i(o)}})};return(r)=>{e.logger.warn("Git broker was replaced; reconciling from the checkout",{brokerId:r}),i(0)}}class KX extends Dni{canFormat(e){return Z3.safeParse(e).success}format(e){let t=[];if(t.push(`# Directory Sync Status
6809
6809
  `),t.push(`**Sync Path:** ${e.syncPath}`),t.push(`**Directory Exists:** ${e.exists?"\u2705 Yes":"\u274C No"}`),t.push(`**File Watching:** ${e.watching?"\u2705 Active":"\u23F8\uFE0F Inactive"}`),e.lastSync)t.push(`**Last Sync:** ${e.lastSync.toLocaleString()}`);if(t.push(""),t.push(`## Statistics
6810
6810
  `),t.push(`**Total Files:** ${e.stats.totalFiles}`),Object.keys(e.stats.byEntityType).length>0){t.push(`
6811
6811
  ### Files by Entity Type
@@ -9383,7 +9383,7 @@ Guidelines:
9383
9383
  3. Depth: Provide enough detail to be useful as a reference, but stay focused on the topic.
9384
9384
  4. Style: Informative and educational. Write as if explaining to yourself for future reference.
9385
9385
  5. Length: Adjust based on topic complexity - concise for simple topics, more detailed for complex ones.
9386
- 6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var sFn="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.",oD=Mi(gce(Ft({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:zre,markdown:jre,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:sFn,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:pTe(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:xTe},generation:mTe,create:{fromUpload:i1i},jobs:{"upload-import":t1i(()=>oD)},evals:{generateNote:async(e,{ai:t})=>t.generate({template:"generation",prompt:l.object({prompt:l.string()}).parse(e).prompt,representedIdentity:"none"},l.object({title:l.string(),body:l.string()}))},atproto:dTe}),[xce(qre,async({request:e,entities:t})=>{let{id:i,title:r,body:n}=e;if(await t.get(oD,i))return{noteId:i,created:!1};return await t.create(oD,{id:i,content:n,metadata:{title:r,titleStated:!0},visibility:"restricted"}),{noteId:i,created:!0}})]),nD);var aFn=Lr({id:"note",config:uTe,entities:[oD]}),n1i=aFn;var cFn=l.object({type:l.literal("email"),address:l.string().max(0).optional()}).transform(()=>{return}),lFn=l.looseObject({defaultRecipient:cFn.or(o1i).optional()}),uFn=Xt({id:"notifications",config:lFn},{subscriptions:(e)=>{let{config:t}=e,i=Lt(e),{logger:r}=i;return i.answer(nB,async({request:n})=>{let o=n.recipient??t.defaultRecipient;if(!o)return r.warn($re.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=i.deliveryProvider(o.type);if(!s||!await s.isAvailable())return r.warn($re.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"){r.warn($re.deliveryFailed,{transportCode:a.failureCode});let c=s1i.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}),[]}}),a1i=uFn;var l1i=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],dFn=l.looseObject({elements:l.array(l.looseObject({snapshotDomain:l.string(),snapshotData:l.array(l.record(l.string(),l.unknown()))})),paging:l.looseObject({links:l.array(l.looseObject({rel:l.string().optional(),href:l.string().optional()})).optional()}).optional()}),pFn="https://api.linkedin.com/rest",mFn="202312",c1i=1000,hFn=1000;function fFn(e){return e.toLowerCase().includes("no data found for this memberid")}function xFn(e,t){let i=e.paging?.links?.find((n)=>n.rel==="next")?.href,r=i?Number(new URL(i,"https://api.linkedin.com").searchParams.get("start")):Number.NaN;return Number.isInteger(r)&&r>t?r:t+1}class $L{accessToken;fetchFn;constructor(e,t=globalThis.fetch){this.accessToken=e,this.fetchFn=t}fetchProfile(){return this.fetchDomain("PROFILE")}fetchDomain(e){return this.fetchPages(e,0,0)}async fetchPages(e,t,i){if(i===c1i)throw Error(`LinkedIn snapshot exceeded ${c1i} pages`);let r=await this.fetchPage(e,t),n=(r?.elements??[]).filter((o)=>o.snapshotDomain===e).flatMap((o)=>o.snapshotData);if(!r||n.length===0)return n;return[...n,...await this.fetchPages(e,xFn(r,t),i+1)]}async fetchPage(e,t){let i=new URL(`${pFn}/memberSnapshotData`);i.searchParams.set("q","criteria"),i.searchParams.set("domain",e),i.searchParams.set("start",String(t));let r=await this.fetchFn(i,{headers:{Authorization:`Bearer ${this.accessToken}`,"Linkedin-Version":mFn}});if(r.ok)return dFn.parse(await r.json());let n=await r.text();if(r.status<500&&fFn(n))return null;throw new Gre(r.status,n.slice(0,hFn))}}class Gre extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var gFn=u1i({title:"LinkedIn",description:"The LinkedIn connection the LinkedIn import reads your profile with. Connect from the LinkedIn workspace, or paste a member token with the r_dma_portability_3rd_party scope.",schema:l.object({accessToken:l.string().trim().min(1),expiresAt:l.iso.datetime().optional()}),fields:{accessToken:{label:"Access token",secret:!0},expiresAt:{label:"Expires (ISO date and time)"}}});class gTe{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:gFn})}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 yTe(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var yFn="https://www.linkedin.com/oauth/v2/authorization",bFn="https://www.linkedin.com/oauth/v2/accessToken",d1i="r_dma_portability_3rd_party",EFn=500,AFn=l.looseObject({access_token:l.string().min(1),expires_in:l.number().int().positive(),scope:l.string().optional()}),vFn=l.looseObject({error:l.string().optional(),error_description:l.string().optional()});async function wFn(e){try{return await e.json()}catch{return null}}class HL{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(yFn);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",d1i),t}async exchange(e,t){let i=await this.fetchFn(bFn,{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()}),r=await wFn(i);if(!i.ok){let o=vFn.safeParse(r),s=o.success?[o.data.error,o.data.error_description].filter(Boolean).join(": "):"";throw Error(`LinkedIn refused the code (${i.status})${s?`: ${s.slice(0,EFn)}`:""}`)}let n=AFn.parse(r);if(n.scope!==void 0&&n.scope!==d1i)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 m1i(e){return new GL({...p1i,now:e})}var Hre="linkedin",SFn=l.strictObject({accessToken:l.string().min(1),expiresAt:l.iso.datetime()});function bTe(e,t={}){let i=(n)=>new HL({...e,redirectUri:n},t.fetch),r=t.now??Date.now;return{id:Hre,authorizationUrl:({redirectUri:n,state:o})=>i(n).authorizationUrl(o),exchange:async({code:n,redirectUri:o})=>{let s=await i(o).exchange(n,r());return{accessToken:s.accessToken,expiresAt:s.expiresAt}}}}class ETe{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(sD.authorizations,{provider:Hre,brainState:e},"the connection");return new URL(h1i.parse(t).authorizationUrl)}async redeem(e){let t=f1i.parse(await this.post(sD.redeem,{provider:Hre,grant:e},"grant redemption"));if(t.provider!==Hre)throw Error("OAuth broker redeemed a grant for another provider");return SFn.parse(t.credential)}async post(e,t,i){let{instanceId:r,secret:n}=this.config,o=await this.fetchFn(new URL(e,this.config.url),{method:"POST",headers:{Accept:"application/json",Authorization:`Basic ${Buffer.from(`${r}:${n}`).toString("base64")}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)throw Error(`OAuth broker refused ${i} (${o.status})`);return o.json()}}function kFn(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function O6(e,t){return e.map((i)=>kFn(i[t])).find(Boolean)}function x1i(e){let t=[O6(e,"First Name"),O6(e,"Last Name")].filter(Boolean).join(" ")||void 0,i=O6(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],r={name:t,headline:O6(e,"Headline"),industry:O6(e,"Industry"),location:O6(e,"Geo Location"),website:i,story:O6(e,"Summary")};return Object.fromEntries(Object.entries(r).filter(([,n])=>n!==void 0))}function g1i(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new Ni(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new Ni("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class ATe{messaging;fetchFn;constructor(e,t){this.messaging=e,this.fetchFn=t}async preview(e){return this.previewFields(await this.imported(e))}async apply(e){let t=await this.imported(e),{revision:i}=await this.previewFields(t);return g1i(await this.messaging.request(ZL,{fields:t,revision:i}))}async previewFields(e){return g1i(await this.messaging.request(WL,{fields:e}))}async imported(e){let t=new $L(e,this.fetchFn);return x1i(await t.fetchProfile())}}var vTe="/linkedin/oauth/start",KL="/linkedin/oauth/callback",YL="/linkedin/oauth/broker/return";function y1i(e){return e?.permissionLevel==="admin"&&e.isAnchor}function VL(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function E1i(e){let t=(c)=>{let u=e.workspaceUrl(),d=u.includes("?")?"&":"?";return VL(303,`${u}${d}connection=${c}`)},i=async(c,u)=>{let d=e.states.take(u),p=await e.resolveSession(c);return d&&y1i(p)&&p?.userId===d?d:null},r=async(c,u)=>{try{return await e.connections.save(c,await u()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${be(d)}`),t("failed")}},n=async(c)=>{let u=await e.resolveSession(c);if(!u)return VL(401);if(!y1i(u))return VL(403);let d=e.states.issue(u.userId),{mode:p}=e;if(p.kind==="direct")return VL(302,p.oauth.authorizationUrl(d).toString());try{return VL(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${be(m)}`),t("failed")}},o=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=await i(u,d.get("state")??"");if(!p)return t("failed");if(d.has("error"))return t("declined");let m=d.get("code");if(!m)return t("failed");return r(p,()=>c.exchange(m,e.now()))},s=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=await i(u,d.get("state")??""),m=b1i.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 r(p,()=>c.redeem(h))},{mode:a}=e;return[{path:vTe,method:"GET",public:!0,handler:n},a.kind==="direct"?{path:KL,method:"GET",public:!0,handler:o(a.oauth)}:{path:YL,method:"GET",public:!0,handler:s(a.broker)}]}var BFn=/^(?: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,CFn=[[/^$/,"<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>"],[BFn,"<month-year>"]];function w1i(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 A1i(e){if(typeof e!=="string")return`<${w1i(e)}>`;let t=e.trim();return CFn.find(([i])=>i.test(t))?.[1]??"<string>"}function DFn(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(A1i))].sort();return A1i(e)}function v1i([e],[t]){return e.localeCompare(t)}function IFn(e){let t=e.flatMap((o)=>Object.entries(o)),r=[...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])=>w1i(a)))].sort(),presentCount:s.length}}),n=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(v1i).map(([a,c])=>[a,DFn(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:r,recordShapes:[...n].sort(v1i).map(([,o])=>o)}}async function S1i(e){let t=await Promise.all(l1i.map(async(i)=>[i,IFn(await e.fetchDomain(i))]));return Object.fromEntries(t)}var _1i={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},_Fn={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},TFn={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."}},k1i=200,BTe=qi({name:"import-profile",label:"Import from LinkedIn",permission:"admin",confirmation:{kind:"prepared"},input:l.object({}),output:l.object({filled:l.array(l.string()),kept:l.array(l.string())})}),Wre=qi({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:l.object({}),output:l.object({disconnected:l.boolean()})}),CTe=qi({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:l.object({}),output:l.object({shapes:l.string()})}),DTe=l.object({connection:l.enum(["connected","declined","failed"]).optional()}),PFn=l.object({field:l.enum(["name","headline","industry","location","website","story"]),current:l.string().nullable(),imported:l.string(),outcome:l.enum(["fill","preserve","unchanged"])}),wTe=DTe.shape.connection,RFn=l.discriminatedUnion("status",[l.object({status:l.literal("disconnected"),expired:l.boolean(),startUrl:l.string(),connection:wTe}),l.object({status:l.literal("unavailable"),message:l.string(),startUrl:l.string(),connection:wTe}),l.object({status:l.literal("ready"),fields:l.array(PFn),connection:wTe})]);function B1i(e){if(e===null)return"\u2014";return e.length>k1i?`${e.slice(0,k1i-1)}\u2026`:e}function C1i(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function D1i(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function STe(e){let t=e.connection?TFn[e.connection]:null;return t?[{type:"notice",...t}]:[]}var I1i=Ho({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",query:DTe,data:RFn,actions:[BTe,Wre,CTe],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:[...STe(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],D1i(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...STe(e),{type:"notice",tone:"warn",text:e.message},D1i(e.startUrl,"Connect LinkedIn again"),{type:"action",action:Wre,input:{}}]};let t=e.fields.some((i)=>i.outcome==="fill");return{kicker:"Profile import",title:"LinkedIn",description:"What LinkedIn holds for each profile field, and what an import would do with it.",status:{label:t?"Ready to import":"Profile already complete",tone:t?"good":"neutral"},...t?{primaryAction:{action:BTe,input:{}}}:{},blocks:[...STe(e),{type:"table",id:"linkedin-fields",empty:"LinkedIn holds no profile fields for this account.",columns:[{key:"field",label:"Field"},{key:"current",label:"Your profile"},{key:"imported",label:"LinkedIn"},{key:"outcome",label:"Import"}],rows:e.fields.map((i)=>({id:i.field,cells:{field:_1i[i.field],current:B1i(i.current),imported:B1i(i.imported),outcome:_Fn[i.outcome]}}))},{type:"card",id:"linkedin-shapes",label:"Data shapes",blocks:[{type:"text",text:"Field names, value types and record forms of your skills, positions, education and certifications on LinkedIn, with every value replaced, for writing import fixtures."},{type:"action",action:CTe,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:Wre,input:{}}]}}});function kTe(e){if(e?.permission!=="admin"||!e.isAnchor)throw new Ni("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function FFn(e){if(e instanceof Gre&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${be(e)}`}async function T1i(e,t){if(!e.isAvailable())return;let i=async(n)=>{let o=await t.connections.get(kTe(n));if(!o||yTe(o))throw new Ni("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},r=e.source({definition:I1i,bind:(n)=>I1i.bind(n,{load:async({caller:o,query:s})=>{let a=kTe(o),{connection:c}=s.get(DTe),u=await t.connections.get(a);if(!u||yTe(u))return{status:"disconnected",expired:u!==null,startUrl:t.startUrl,connection:c};try{return{status:"ready",fields:(await t.profileImport.preview(u.accessToken)).fields,connection:c}}catch(d){return{status:"unavailable",message:FFn(d),startUrl:t.startUrl,connection:c}}},actions:[BTe.bind(n,async({caller:o})=>t.profileImport.apply((await i(o)).accessToken),async({caller:o})=>{let s=await t.profileImport.preview((await i(o)).accessToken),a=(d)=>s.fields.filter((p)=>p.outcome===d).map((p)=>_1i[p.field].toLowerCase()),c=a("fill"),u=a("preserve");if(c.length===0)throw new Ni("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${C1i(c)} from LinkedIn?${u.length>0?` Your ${C1i(u)} stay as you wrote them.`:""}`,revision:s.revision}}),CTe.bind(n,async({caller:o})=>{let s=await S1i(t.clientFor((await i(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),Wre.bind(n,async({caller:o})=>(await t.connections.forget(kTe(o)),{disconnected:!0}))]})});return e.register({...r,accessHandler:async(n)=>n.isAnchor&&await r.accessHandler(n)})}var P1i={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.725",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 OFn="/studio",NFn=l.object({clientId:l.string().trim().min(1).describe("LinkedIn app client ID"),clientSecret:l.string().trim().min(1).describe("LinkedIn app client secret"),redirectUri:l.url({protocol:/^https?$/}).describe(`This brain's callback URL ending at ${KL}, registered with the LinkedIn app`)}),LFn=l.object({url:l.url({protocol:/^https$/}).describe("The managed broker's origin"),instanceId:l.string().trim().min(1).describe("This brain's broker instance"),secret:l.string().min(32).describe("This brain's broker instance secret"),returnUri:l.url({protocol:/^https?$/}).describe(`This brain's return URL ending at ${YL}, registered with the broker`)}),R1i=l.object({oauth:NFn.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:LFn.optional().describe("The managed broker holding the shared LinkedIn app")});function zFn(e,t){let{oauth:i,broker:r}=e;if(i&&r)throw Error("linkedin-import: configure either oauth (direct) or broker, not both");if(i&&new URL(i.redirectUri).pathname!==KL)throw Error(`linkedin-import: oauth.redirectUri must end at ${KL}`);if(r&&new URL(r.returnUri).pathname!==YL)throw Error(`linkedin-import: broker.returnUri must end at ${YL}`);if(i)return{kind:"direct",oauth:new HL(i,t.fetch)};if(r)return{kind:"broker",broker:new ETe(r,t.fetch)};return null}function F1i(e={}){let t=Xt({id:"linkedin-import",config:R1i,setup:(i)=>{let{config:r}=i,n=zFn(r,e),o=r.oauth?.redirectUri??r.broker?.returnUri;if(!n||!o)return{routes:[]};let s=Lt(i),a=new gTe(s.accountSettings,{pluginId:s.pluginId,packageName:P1i.name}),c=OFn;return s.registered(async()=>{let u=await T1i(s.studio,{profileImport:new ATe(s.messaging,e.fetch),clientFor:(d)=>new $L(d,e.fetch),connections:a,startUrl:new URL(vTe,o).toString()});if(u)c=u}),{routes:E1i({mode:n,states:m1i(),connections:a,resolveSession:async(u)=>s.auth()?.resolveSession(u),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return ts(t,({state:i})=>i.routes)}var ITe=F1i();import{createHash as jFn,timingSafeEqual as UFn}from"crypto";function M1i(e){return jFn("sha256").update(e).digest()}function qFn(e){if(!e?.startsWith("Basic "))return null;let t=Buffer.from(e.slice(6),"base64").toString("utf8"),i=t.indexOf(":");if(i<=0||i===t.length-1)return null;return{id:t.slice(0,i),secret:t.slice(i+1)}}class _Te{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:M1i(t.secret)}]))}authenticate(e){let t=qFn(e.headers.get("authorization")),i=t?this.instances.get(t.id):void 0;if(!t||!i)return null;return UFn(M1i(t.secret),i.secretHash)?{id:i.id,returnUris:i.returnUris}:null}}var $Fn=10,GFn=600000,PTe={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function nw(e,t=200){return Response.json(e,{status:t,headers:PTe})}function O1i(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...PTe,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function N1i(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function Zre(e,t){let i=new URL(e.returnUri);return i.searchParams.set("provider",e.provider),i.searchParams.set("state",e.brainState),Object.entries(t).forEach(([r,n])=>i.searchParams.set(r,n)),new Response(null,{status:303,headers:{...PTe,Location:i.toString()}})}function j1i(e){let t=new Map(e.providers.map((c)=>[c.id,c])),i=new Map,r=(c)=>{let u=e.now(),d=(i.get(c)??[]).filter((m)=>m>u-GFn),p=d.length<$Fn;return i.set(c,p?[...d,u]:d),p},n=(c)=>new URL(TTe(c),e.publicUrl).toString(),o=async(c)=>{let u=e.instances.authenticate(c);if(!u)return O1i();let d=L1i.safeParse(await N1i(c));if(!d.success)return nw({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=u.returnUris[d.data.provider];if(!p||!m)return nw({error:"Provider is unavailable for this instance"},400);if(!r(u.id))return nw({error:"Too many connections started; try later"},429);let h=e.authorizations.issue({provider:p.id,instanceId:u.id,returnUri:m,brainState:d.data.brainState}),f=p.authorizationUrl({redirectUri:n(p.id),state:h}).toString();return nw({authorizationUrl:f})},s=async(c)=>{let u=e.instances.authenticate(c);if(!u)return O1i();let d=z1i.safeParse(await N1i(c));if(!d.success)return nw({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,m=e.grants.take(d.data.grant,(h)=>h.provider===p&&h.instanceId===u.id);if(!m)return nw({error:"Invalid or expired grant"},400);return nw({provider:p,credential:m.credential})},a=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=e.authorizations.take(d.get("state")??"",(h)=>h.provider===c.id);if(!p)return nw({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return Zre(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return Zre(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 Zre(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${be(h)}`),Zre(p,{error:"credential_exchange_failed"})}};return[{path:sD.authorizations,method:"POST",public:!0,handler:o},{path:sD.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:TTe(c.id),method:"GET",public:!0,handler:a(c)}))]}var HFn=600000,WFn=120000,U1i=1000,ZFn=l.object({clientId:l.string().trim().min(1),clientSecret:l.string().trim().min(1)}),VFn=l.object({id:l.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/),secret:l.string().min(32).describe("Revocable instance secret"),returnUris:l.record(RTe,l.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),q1i=l.object({publicUrl:l.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:l.record(RTe,ZFn).default({}).describe("Per provider, the shared app the broker holds"),instances:l.array(VFn).default([])});function KFn(e,t){return Object.entries(e.providers).map(([i,r])=>{let n=t.providers[i];if(!n)throw Error(`oauth-broker: no adapter for provider "${i}"`);let o=n(r);if(o.id!==i)throw Error(`oauth-broker: adapter for "${i}" reports provider "${o.id}"`);return o})}function FTe(e){let t=Xt({id:"oauth-broker",config:q1i,setup:(i)=>{let{config:r}=i,n=KFn(r,e);if(r.instances.length===0||n.length===0)return{routes:[]};return{routes:j1i({publicUrl:r.publicUrl,providers:n,instances:new _Te(r.instances),authorizations:new GL({ttlMs:HFn,maxPending:U1i,now:e.now}),grants:new GL({ttlMs:WFn,maxPending:U1i,now:e.now}),now:e.now??Date.now,logger:Lt(i).logger})}}});return ts(t,({state:i})=>i.routes)}import{existsSync as oMn,mkdirSync as sMn,readFileSync as aMn,renameSync as cMn,rmSync as lMn,writeFileSync as uMn}from"fs";import{join as mg}from"path";var MTe=l.object({baseFolder:l.string().default("_obsidian")});function YFn(e){let t=qJ(e);if(t==="enum"){let i=GJ(e);return i?{type:"enum",enumValues:i}:{type:"enum"}}if(t==="literal")return{type:"string",defaultValue:HJ(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 $1i(e){let t=[];for(let[i,r]of Object.entries(e.shape)){if(eO(r)?.studioWidget==="hidden")continue;let{inner:n,required:o,defaultValue:s}=$J(r),a=YFn(n),c={name:i,type:a.type,required:o},u=s!==void 0?s:a.defaultValue;if(u!==void 0)c.defaultValue=u;if(a.enumValues)c.enumValues=a.enumValues;t.push(c)}return t}function JFn(e,t){if(e.name==="entityType")return String(e.defaultValue??t);if(e.name==="title")return'"{{title}}"';if(e.type==="date"&&(e.name==="created"||e.name==="updated"))return'"{{date}}"';if(e.defaultValue!==void 0){if(Array.isArray(e.defaultValue))return"[]";if(typeof e.defaultValue==="boolean")return String(e.defaultValue);if(typeof e.defaultValue==="number")return String(e.defaultValue);return String(e.defaultValue)}if(e.type==="enum"&&e.enumValues&&e.enumValues.length>0)return e.enumValues[0]??"";switch(e.type){case"string":return'""';case"number":return"";case"boolean":return"false";case"array":return"[]";case"date":return'""';default:return'""'}}function G1i(e,t,i=""){let r=["---"];for(let n of t){let o=JFn(n,e);if(o==="")r.push(`${n.name}:`);else r.push(`${n.name}: ${o}`)}if(r.push("---"),r.push(""),i)r.push(i);else r.push("<!-- Write your content here -->"),r.push("");return r.join(`
9386
+ 6. No meta-commentary: Just provide the content directly without phrases like "Here is..." or "This note covers..."`});var sFn="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.",oD=Mi(gce(Ft({type:"note",purpose:"A short, free-form captured thought, reference, or snippet the user wants to keep.",metadata:zre,markdown:jre,config:{projectionSourceRole:"primary",markdownImport:!0},instructions:sFn,displayTitle:({content:e,metadata:t})=>t.titleStated===!0||t.title.trim()&&t.title!=="Untitled"?t.title:pTe(void 0,e),stub:({title:e})=>({content:"",metadata:{title:e,status:"generating",titleStated:!0}}),templates:{generation:xTe},generation:mTe,create:{fromUpload:i1i},jobs:{"upload-import":t1i(()=>oD)},evals:{generateNote:async(e,{ai:t})=>t.generate({template:"generation",prompt:l.object({prompt:l.string()}).parse(e).prompt,representedIdentity:"none"},l.object({title:l.string(),body:l.string()}))},atproto:dTe}),[xce(qre,async({request:e,entities:t})=>{let{id:i,title:r,body:n}=e;if(await t.get(oD,i))return{noteId:i,created:!1};return await t.create(oD,{id:i,content:n,metadata:{title:r,titleStated:!0},visibility:"restricted"}),{noteId:i,created:!0}})]),nD);var aFn=Lr({id:"note",config:uTe,entities:[oD]}),n1i=aFn;var cFn=l.object({type:l.literal("email"),address:l.string().max(0).optional()}).transform(()=>{return}),lFn=l.looseObject({defaultRecipient:cFn.or(o1i).optional()}),uFn=Xt({id:"notifications",config:lFn},{subscriptions:(e)=>{let{config:t}=e,i=Lt(e),{logger:r}=i;return i.answer(nB,async({request:n})=>{let o=n.recipient??t.defaultRecipient;if(!o)return r.warn($re.recipientMissing),{status:"failed",failure:"recipient-missing"};let s=i.deliveryProvider(o.type);if(!s||!await s.isAvailable())return r.warn($re.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"){r.warn($re.deliveryFailed,{transportCode:a.failureCode});let c=s1i.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}),[]}}),a1i=uFn;var l1i=["SKILLS","POSITIONS","EDUCATION","CERTIFICATIONS"],dFn=l.looseObject({elements:l.array(l.looseObject({snapshotDomain:l.string(),snapshotData:l.array(l.record(l.string(),l.unknown()))})),paging:l.looseObject({links:l.array(l.looseObject({rel:l.string().optional(),href:l.string().optional()})).optional()}).optional()}),pFn="https://api.linkedin.com/rest",mFn="202312",c1i=1000,hFn=1000;function fFn(e){return e.toLowerCase().includes("no data found for this memberid")}function xFn(e,t){let i=e.paging?.links?.find((n)=>n.rel==="next")?.href,r=i?Number(new URL(i,"https://api.linkedin.com").searchParams.get("start")):Number.NaN;return Number.isInteger(r)&&r>t?r:t+1}class $L{accessToken;fetchFn;constructor(e,t=globalThis.fetch){this.accessToken=e,this.fetchFn=t}fetchProfile(){return this.fetchDomain("PROFILE")}fetchDomain(e){return this.fetchPages(e,0,0)}async fetchPages(e,t,i){if(i===c1i)throw Error(`LinkedIn snapshot exceeded ${c1i} pages`);let r=await this.fetchPage(e,t),n=(r?.elements??[]).filter((o)=>o.snapshotDomain===e).flatMap((o)=>o.snapshotData);if(!r||n.length===0)return n;return[...n,...await this.fetchPages(e,xFn(r,t),i+1)]}async fetchPage(e,t){let i=new URL(`${pFn}/memberSnapshotData`);i.searchParams.set("q","criteria"),i.searchParams.set("domain",e),i.searchParams.set("start",String(t));let r=await this.fetchFn(i,{headers:{Authorization:`Bearer ${this.accessToken}`,"Linkedin-Version":mFn}});if(r.ok)return dFn.parse(await r.json());let n=await r.text();if(r.status<500&&fFn(n))return null;throw new Gre(r.status,n.slice(0,hFn))}}class Gre extends Error{status;constructor(e,t){super(`LinkedIn snapshot API error: ${e} - ${t}`);this.status=e,this.name="LinkedInApiError"}}var gFn=u1i({title:"LinkedIn",description:"The LinkedIn connection the LinkedIn import reads your profile with. Connect from the LinkedIn workspace, or paste a member token with the r_dma_portability_3rd_party scope.",schema:l.object({accessToken:l.string().trim().min(1),expiresAt:l.iso.datetime().optional()}),fields:{accessToken:{label:"Access token",secret:!0},expiresAt:{label:"Expires (ISO date and time)"}}});class gTe{registry;registration;constructor(e,t){this.registry=e,this.registration=e.register({ownerPluginId:t.pluginId,packageName:t.packageName,definitionId:"linkedin",definition:gFn})}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 yTe(e,t=Date.now()){return e.expiresAt!==void 0&&Date.parse(e.expiresAt)<=t}var yFn="https://www.linkedin.com/oauth/v2/authorization",bFn="https://www.linkedin.com/oauth/v2/accessToken",d1i="r_dma_portability_3rd_party",EFn=500,AFn=l.looseObject({access_token:l.string().min(1),expires_in:l.number().int().positive(),scope:l.string().optional()}),vFn=l.looseObject({error:l.string().optional(),error_description:l.string().optional()});async function wFn(e){try{return await e.json()}catch{return null}}class HL{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}authorizationUrl(e){let t=new URL(yFn);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",d1i),t}async exchange(e,t){let i=await this.fetchFn(bFn,{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()}),r=await wFn(i);if(!i.ok){let o=vFn.safeParse(r),s=o.success?[o.data.error,o.data.error_description].filter(Boolean).join(": "):"";throw Error(`LinkedIn refused the code (${i.status})${s?`: ${s.slice(0,EFn)}`:""}`)}let n=AFn.parse(r);if(n.scope!==void 0&&n.scope!==d1i)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 m1i(e){return new GL({...p1i,now:e})}var Hre="linkedin",SFn=l.strictObject({accessToken:l.string().min(1),expiresAt:l.iso.datetime()});function bTe(e,t={}){let i=(n)=>new HL({...e,redirectUri:n},t.fetch),r=t.now??Date.now;return{id:Hre,authorizationUrl:({redirectUri:n,state:o})=>i(n).authorizationUrl(o),exchange:async({code:n,redirectUri:o})=>{let s=await i(o).exchange(n,r());return{accessToken:s.accessToken,expiresAt:s.expiresAt}}}}class ETe{config;fetchFn;constructor(e,t=globalThis.fetch){this.config=e,this.fetchFn=t}async authorize(e){let t=await this.post(sD.authorizations,{provider:Hre,brainState:e},"the connection");return new URL(h1i.parse(t).authorizationUrl)}async redeem(e){let t=f1i.parse(await this.post(sD.redeem,{provider:Hre,grant:e},"grant redemption"));if(t.provider!==Hre)throw Error("OAuth broker redeemed a grant for another provider");return SFn.parse(t.credential)}async post(e,t,i){let{instanceId:r,secret:n}=this.config,o=await this.fetchFn(new URL(e,this.config.url),{method:"POST",headers:{Accept:"application/json",Authorization:`Basic ${Buffer.from(`${r}:${n}`).toString("base64")}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)throw Error(`OAuth broker refused ${i} (${o.status})`);return o.json()}}function kFn(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function O6(e,t){return e.map((i)=>kFn(i[t])).find(Boolean)}function x1i(e){let t=[O6(e,"First Name"),O6(e,"Last Name")].filter(Boolean).join(" ")||void 0,i=O6(e,"Websites")?.match(/https?:\/\/[^\s,;]+/)?.[0],r={name:t,headline:O6(e,"Headline"),industry:O6(e,"Industry"),location:O6(e,"Geo Location"),website:i,story:O6(e,"Summary")};return Object.fromEntries(Object.entries(r).filter(([,n])=>n!==void 0))}function g1i(e){if(e.status==="answered")return e.data;if(e.status==="failed")throw new Ni(e.error.code,{message:e.error.message,publicMessage:e.error.message});throw new Ni("no_handler",{message:"No package keeps the anchor profile",publicMessage:"This brain keeps no anchor profile to import into."})}class ATe{messaging;fetchFn;constructor(e,t){this.messaging=e,this.fetchFn=t}async preview(e){return this.previewFields(await this.imported(e))}async apply(e){let t=await this.imported(e),{revision:i}=await this.previewFields(t);return g1i(await this.messaging.request(ZL,{fields:t,revision:i}))}async previewFields(e){return g1i(await this.messaging.request(WL,{fields:e}))}async imported(e){let t=new $L(e,this.fetchFn);return x1i(await t.fetchProfile())}}var vTe="/linkedin/oauth/start",KL="/linkedin/oauth/callback",YL="/linkedin/oauth/broker/return";function y1i(e){return e?.permissionLevel==="admin"&&e.isAnchor}function VL(e,t){return new Response(null,{status:e,headers:{"Cache-Control":"no-store",...t?{Location:t}:{}}})}function E1i(e){let t=(c)=>{let u=e.workspaceUrl(),d=u.includes("?")?"&":"?";return VL(303,`${u}${d}connection=${c}`)},i=async(c,u)=>{let d=e.states.take(u),p=await e.resolveSession(c);return d&&y1i(p)&&p?.userId===d?d:null},r=async(c,u)=>{try{return await e.connections.save(c,await u()),t("connected")}catch(d){return e.logger.warn(`LinkedIn connection failed: ${be(d)}`),t("failed")}},n=async(c)=>{let u=await e.resolveSession(c);if(!u)return VL(401);if(!y1i(u))return VL(403);let d=e.states.issue(u.userId),{mode:p}=e;if(p.kind==="direct")return VL(302,p.oauth.authorizationUrl(d).toString());try{return VL(302,(await p.broker.authorize(d)).toString())}catch(m){return e.logger.warn(`LinkedIn broker connection failed: ${be(m)}`),t("failed")}},o=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=await i(u,d.get("state")??"");if(!p)return t("failed");if(d.has("error"))return t("declined");let m=d.get("code");if(!m)return t("failed");return r(p,()=>c.exchange(m,e.now()))},s=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=await i(u,d.get("state")??""),m=b1i.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 r(p,()=>c.redeem(h))},{mode:a}=e;return[{path:vTe,method:"GET",public:!0,handler:n},a.kind==="direct"?{path:KL,method:"GET",public:!0,handler:o(a.oauth)}:{path:YL,method:"GET",public:!0,handler:s(a.broker)}]}var BFn=/^(?: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,CFn=[[/^$/,"<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>"],[BFn,"<month-year>"]];function w1i(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 A1i(e){if(typeof e!=="string")return`<${w1i(e)}>`;let t=e.trim();return CFn.find(([i])=>i.test(t))?.[1]??"<string>"}function DFn(e){if(e===null)return null;if(Array.isArray(e))return[...new Set(e.map(A1i))].sort();return A1i(e)}function v1i([e],[t]){return e.localeCompare(t)}function IFn(e){let t=e.flatMap((o)=>Object.entries(o)),r=[...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])=>w1i(a)))].sort(),presentCount:s.length}}),n=new Map(e.map((o)=>{let s=Object.fromEntries(Object.entries(o).sort(v1i).map(([a,c])=>[a,DFn(c)]));return[JSON.stringify(s),s]}));return{recordsRead:e.length,fields:r,recordShapes:[...n].sort(v1i).map(([,o])=>o)}}async function S1i(e){let t=await Promise.all(l1i.map(async(i)=>[i,IFn(await e.fetchDomain(i))]));return Object.fromEntries(t)}var _1i={name:"Name",headline:"Headline",industry:"Industry",location:"Location",website:"Website",story:"Story"},_Fn={fill:"Fill",preserve:"Keep yours",unchanged:"Same"},TFn={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."}},k1i=200,BTe=qi({name:"import-profile",label:"Import from LinkedIn",permission:"admin",confirmation:{kind:"prepared"},input:l.object({}),output:l.object({filled:l.array(l.string()),kept:l.array(l.string())})}),Wre=qi({name:"disconnect",label:"Disconnect LinkedIn",permission:"admin",confirmation:{kind:"static",message:"Forget the LinkedIn token? Imported profile values stay; importing again needs a new connection."},input:l.object({}),output:l.object({disconnected:l.boolean()})}),CTe=qi({name:"inspect-shapes",label:"Inspect LinkedIn data shapes",permission:"admin",input:l.object({}),output:l.object({shapes:l.string()})}),DTe=l.object({connection:l.enum(["connected","declined","failed"]).optional()}),PFn=l.object({field:l.enum(["name","headline","industry","location","website","story"]),current:l.string().nullable(),imported:l.string(),outcome:l.enum(["fill","preserve","unchanged"])}),wTe=DTe.shape.connection,RFn=l.discriminatedUnion("status",[l.object({status:l.literal("disconnected"),expired:l.boolean(),startUrl:l.string(),connection:wTe}),l.object({status:l.literal("unavailable"),message:l.string(),startUrl:l.string(),connection:wTe}),l.object({status:l.literal("ready"),fields:l.array(PFn),connection:wTe})]);function B1i(e){if(e===null)return"\u2014";return e.length>k1i?`${e.slice(0,k1i-1)}\u2026`:e}function C1i(e){return e.length<2?e.join(""):`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`}function D1i(e,t){return{type:"links",items:[{label:t,target:{external:e}}]}}function STe(e){let t=e.connection?TFn[e.connection]:null;return t?[{type:"notice",...t}]:[]}var I1i=Ho({id:"linkedin",label:"LinkedIn",description:"Fill your profile from LinkedIn without touching what you wrote.",priority:70,permission:"admin",query:DTe,data:RFn,actions:[BTe,Wre,CTe],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:[...STe(e),...e.expired?[{type:"notice",tone:"warn",text:"Your LinkedIn connection expired. Connect again to import."}]:[],D1i(e.startUrl,"Connect LinkedIn")]};if(e.status==="unavailable")return{kicker:"Profile import",title:"LinkedIn",status:{label:"Connection needs attention",tone:"warn"},blocks:[...STe(e),{type:"notice",tone:"warn",text:e.message},D1i(e.startUrl,"Connect LinkedIn again"),{type:"action",action:Wre,input:{}}]};let t=e.fields.some((i)=>i.outcome==="fill");return{kicker:"Profile import",title:"LinkedIn",description:"What LinkedIn holds for each profile field, and what an import would do with it.",status:{label:t?"Ready to import":"Profile already complete",tone:t?"good":"neutral"},...t?{primaryAction:{action:BTe,input:{}}}:{},blocks:[...STe(e),{type:"table",id:"linkedin-fields",empty:"LinkedIn holds no profile fields for this account.",columns:[{key:"field",label:"Field"},{key:"current",label:"Your profile"},{key:"imported",label:"LinkedIn"},{key:"outcome",label:"Import"}],rows:e.fields.map((i)=>({id:i.field,cells:{field:_1i[i.field],current:B1i(i.current),imported:B1i(i.imported),outcome:_Fn[i.outcome]}}))},{type:"card",id:"linkedin-shapes",label:"Data shapes",blocks:[{type:"text",text:"Field names, value types and record forms of your skills, positions, education and certifications on LinkedIn, with every value replaced, for writing import fixtures."},{type:"action",action:CTe,input:{},result:{title:"LinkedIn data shapes",fields:{shapes:{label:"Shapes (JSON)",copyable:!0}}}}]},{type:"action",action:Wre,input:{}}]}}});function kTe(e){if(e?.permission!=="admin"||!e.isAnchor)throw new Ni("permission_denied",{publicMessage:"The LinkedIn import belongs to the Anchor alone"});return e.actor.id}function FFn(e){if(e instanceof Gre&&[401,403].includes(e.status))return"LinkedIn refused the connection. It may have been revoked; connect again.";return`LinkedIn could not be read: ${be(e)}`}async function T1i(e,t){if(!e.isAvailable())return;let i=async(n)=>{let o=await t.connections.get(kTe(n));if(!o||yTe(o))throw new Ni("conflict",{publicMessage:"Connect LinkedIn before importing."});return o},r=e.source({definition:I1i,bind:(n)=>I1i.bind(n,{load:async({caller:o,query:s})=>{let a=kTe(o),{connection:c}=s.get(DTe),u=await t.connections.get(a);if(!u||yTe(u))return{status:"disconnected",expired:u!==null,startUrl:t.startUrl,connection:c};try{return{status:"ready",fields:(await t.profileImport.preview(u.accessToken)).fields,connection:c}}catch(d){return{status:"unavailable",message:FFn(d),startUrl:t.startUrl,connection:c}}},actions:[BTe.bind(n,async({caller:o})=>t.profileImport.apply((await i(o)).accessToken),async({caller:o})=>{let s=await t.profileImport.preview((await i(o)).accessToken),a=(d)=>s.fields.filter((p)=>p.outcome===d).map((p)=>_1i[p.field].toLowerCase()),c=a("fill"),u=a("preserve");if(c.length===0)throw new Ni("conflict",{publicMessage:"Your profile already has everything LinkedIn holds."});return{summary:`Fill your ${C1i(c)} from LinkedIn?${u.length>0?` Your ${C1i(u)} stay as you wrote them.`:""}`,revision:s.revision}}),CTe.bind(n,async({caller:o})=>{let s=await S1i(t.clientFor((await i(o)).accessToken));return{shapes:JSON.stringify(s,null,2)}}),Wre.bind(n,async({caller:o})=>(await t.connections.forget(kTe(o)),{disconnected:!0}))]})});return e.register({...r,accessHandler:async(n)=>n.isAnchor&&await r.accessHandler(n)})}var P1i={name:"@brains/linkedin-import",license:"AGPL-3.0-only",version:"0.2.0-alpha.726",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 OFn="/studio",NFn=l.object({clientId:l.string().trim().min(1).describe("LinkedIn app client ID"),clientSecret:l.string().trim().min(1).describe("LinkedIn app client secret"),redirectUri:l.url({protocol:/^https?$/}).describe(`This brain's callback URL ending at ${KL}, registered with the LinkedIn app`)}),LFn=l.object({url:l.url({protocol:/^https$/}).describe("The managed broker's origin"),instanceId:l.string().trim().min(1).describe("This brain's broker instance"),secret:l.string().min(32).describe("This brain's broker instance secret"),returnUri:l.url({protocol:/^https?$/}).describe(`This brain's return URL ending at ${YL}, registered with the broker`)}),R1i=l.object({oauth:NFn.optional().describe("The instance's own LinkedIn app, for direct-mode OAuth"),broker:LFn.optional().describe("The managed broker holding the shared LinkedIn app")});function zFn(e,t){let{oauth:i,broker:r}=e;if(i&&r)throw Error("linkedin-import: configure either oauth (direct) or broker, not both");if(i&&new URL(i.redirectUri).pathname!==KL)throw Error(`linkedin-import: oauth.redirectUri must end at ${KL}`);if(r&&new URL(r.returnUri).pathname!==YL)throw Error(`linkedin-import: broker.returnUri must end at ${YL}`);if(i)return{kind:"direct",oauth:new HL(i,t.fetch)};if(r)return{kind:"broker",broker:new ETe(r,t.fetch)};return null}function F1i(e={}){let t=Xt({id:"linkedin-import",config:R1i,setup:(i)=>{let{config:r}=i,n=zFn(r,e),o=r.oauth?.redirectUri??r.broker?.returnUri;if(!n||!o)return{routes:[]};let s=Lt(i),a=new gTe(s.accountSettings,{pluginId:s.pluginId,packageName:P1i.name}),c=OFn;return s.registered(async()=>{let u=await T1i(s.studio,{profileImport:new ATe(s.messaging,e.fetch),clientFor:(d)=>new $L(d,e.fetch),connections:a,startUrl:new URL(vTe,o).toString()});if(u)c=u}),{routes:E1i({mode:n,states:m1i(),connections:a,resolveSession:async(u)=>s.auth()?.resolveSession(u),workspaceUrl:()=>c,now:e.now??Date.now,logger:s.logger})}}});return ts(t,({state:i})=>i.routes)}var ITe=F1i();import{createHash as jFn,timingSafeEqual as UFn}from"crypto";function M1i(e){return jFn("sha256").update(e).digest()}function qFn(e){if(!e?.startsWith("Basic "))return null;let t=Buffer.from(e.slice(6),"base64").toString("utf8"),i=t.indexOf(":");if(i<=0||i===t.length-1)return null;return{id:t.slice(0,i),secret:t.slice(i+1)}}class _Te{instances;constructor(e){this.instances=new Map(e.map((t)=>[t.id,{id:t.id,returnUris:{...t.returnUris},secretHash:M1i(t.secret)}]))}authenticate(e){let t=qFn(e.headers.get("authorization")),i=t?this.instances.get(t.id):void 0;if(!t||!i)return null;return UFn(M1i(t.secret),i.secretHash)?{id:i.id,returnUris:i.returnUris}:null}}var $Fn=10,GFn=600000,PTe={"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"};function nw(e,t=200){return Response.json(e,{status:t,headers:PTe})}function O1i(){return Response.json({error:"Broker instance authentication required"},{status:401,headers:{...PTe,"WWW-Authenticate":'Basic realm="oauth-broker"'}})}async function N1i(e){if(!e.headers.get("content-type")?.startsWith("application/json"))return;try{return await e.json()}catch{return}}function Zre(e,t){let i=new URL(e.returnUri);return i.searchParams.set("provider",e.provider),i.searchParams.set("state",e.brainState),Object.entries(t).forEach(([r,n])=>i.searchParams.set(r,n)),new Response(null,{status:303,headers:{...PTe,Location:i.toString()}})}function j1i(e){let t=new Map(e.providers.map((c)=>[c.id,c])),i=new Map,r=(c)=>{let u=e.now(),d=(i.get(c)??[]).filter((m)=>m>u-GFn),p=d.length<$Fn;return i.set(c,p?[...d,u]:d),p},n=(c)=>new URL(TTe(c),e.publicUrl).toString(),o=async(c)=>{let u=e.instances.authenticate(c);if(!u)return O1i();let d=L1i.safeParse(await N1i(c));if(!d.success)return nw({error:"Invalid authorization request"},400);let p=t.get(d.data.provider),m=u.returnUris[d.data.provider];if(!p||!m)return nw({error:"Provider is unavailable for this instance"},400);if(!r(u.id))return nw({error:"Too many connections started; try later"},429);let h=e.authorizations.issue({provider:p.id,instanceId:u.id,returnUri:m,brainState:d.data.brainState}),f=p.authorizationUrl({redirectUri:n(p.id),state:h}).toString();return nw({authorizationUrl:f})},s=async(c)=>{let u=e.instances.authenticate(c);if(!u)return O1i();let d=z1i.safeParse(await N1i(c));if(!d.success)return nw({error:"Invalid grant redemption request"},400);let{provider:p}=d.data,m=e.grants.take(d.data.grant,(h)=>h.provider===p&&h.instanceId===u.id);if(!m)return nw({error:"Invalid or expired grant"},400);return nw({provider:p,credential:m.credential})},a=(c)=>async(u)=>{let d=new URL(u.url).searchParams,p=e.authorizations.take(d.get("state")??"",(h)=>h.provider===c.id);if(!p)return nw({error:"Invalid, expired or used authorization"},400);if(d.has("error"))return Zre(p,{error:"provider_denied"});let m=d.get("code")?.trim();if(!m)return Zre(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 Zre(p,{grant:f})}catch(h){return e.logger.warn(`OAuth broker exchange for ${c.id} failed: ${be(h)}`),Zre(p,{error:"credential_exchange_failed"})}};return[{path:sD.authorizations,method:"POST",public:!0,handler:o},{path:sD.redeem,method:"POST",public:!0,handler:s},...e.providers.map((c)=>({path:TTe(c.id),method:"GET",public:!0,handler:a(c)}))]}var HFn=600000,WFn=120000,U1i=1000,ZFn=l.object({clientId:l.string().trim().min(1),clientSecret:l.string().trim().min(1)}),VFn=l.object({id:l.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/),secret:l.string().min(32).describe("Revocable instance secret"),returnUris:l.record(RTe,l.url({protocol:/^https?$/})).describe("Per provider, the one address the browser returns to")}),q1i=l.object({publicUrl:l.url({protocol:/^https?$/}).describe("The broker's public origin, where provider callbacks land"),providers:l.record(RTe,ZFn).default({}).describe("Per provider, the shared app the broker holds"),instances:l.array(VFn).default([])});function KFn(e,t){return Object.entries(e.providers).map(([i,r])=>{let n=t.providers[i];if(!n)throw Error(`oauth-broker: no adapter for provider "${i}"`);let o=n(r);if(o.id!==i)throw Error(`oauth-broker: adapter for "${i}" reports provider "${o.id}"`);return o})}function FTe(e){let t=Xt({id:"oauth-broker",config:q1i,setup:(i)=>{let{config:r}=i,n=KFn(r,e);if(r.instances.length===0||n.length===0)return{routes:[]};return{routes:j1i({publicUrl:r.publicUrl,providers:n,instances:new _Te(r.instances),authorizations:new GL({ttlMs:HFn,maxPending:U1i,now:e.now}),grants:new GL({ttlMs:WFn,maxPending:U1i,now:e.now}),now:e.now??Date.now,logger:Lt(i).logger})}}});return ts(t,({state:i})=>i.routes)}import{existsSync as oMn,mkdirSync as sMn,readFileSync as aMn,renameSync as cMn,rmSync as lMn,writeFileSync as uMn}from"fs";import{join as mg}from"path";var MTe=l.object({baseFolder:l.string().default("_obsidian")});function YFn(e){let t=qJ(e);if(t==="enum"){let i=GJ(e);return i?{type:"enum",enumValues:i}:{type:"enum"}}if(t==="literal")return{type:"string",defaultValue:HJ(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 $1i(e){let t=[];for(let[i,r]of Object.entries(e.shape)){if(eO(r)?.studioWidget==="hidden")continue;let{inner:n,required:o,defaultValue:s}=$J(r),a=YFn(n),c={name:i,type:a.type,required:o},u=s!==void 0?s:a.defaultValue;if(u!==void 0)c.defaultValue=u;if(a.enumValues)c.enumValues=a.enumValues;t.push(c)}return t}function JFn(e,t){if(e.name==="entityType")return String(e.defaultValue??t);if(e.name==="title")return'"{{title}}"';if(e.type==="date"&&(e.name==="created"||e.name==="updated"))return'"{{date}}"';if(e.defaultValue!==void 0){if(Array.isArray(e.defaultValue))return"[]";if(typeof e.defaultValue==="boolean")return String(e.defaultValue);if(typeof e.defaultValue==="number")return String(e.defaultValue);return String(e.defaultValue)}if(e.type==="enum"&&e.enumValues&&e.enumValues.length>0)return e.enumValues[0]??"";switch(e.type){case"string":return'""';case"number":return"";case"boolean":return"false";case"array":return"[]";case"date":return'""';default:return'""'}}function G1i(e,t,i=""){let r=["---"];for(let n of t){let o=JFn(n,e);if(o==="")r.push(`${n.name}:`);else r.push(`${n.name}: ${o}`)}if(r.push("---"),r.push(""),i)r.push(i);else r.push("<!-- Write your content here -->"),r.push("");return r.join(`
9387
9387
  `)}var QFn={string:"Input",number:"Number",boolean:"Boolean",date:"Date",enum:"Select",array:"Multi",unknown:"Input"};function XFn(e){let t={name:e.name,id:e.name,type:QFn[e.type]};if(e.type==="enum"&&e.enumValues){let i={};e.enumValues.forEach((r,n)=>{i[String(n)]=r}),t.options=i}return t}function H1i(e,t){let i={filesPaths:e,fields:t.map(XFn)};return`---
9388
9388
  ${aD(i)}---
9389
9389
  `}var eMn=new Set(["entityType"]),Z1i={base:"Notes"};function tMn(e){return Z1i[e]??W1i(e)}function V1i(e){let t=Z1i[e];if(t)return t;let i=e.split("-").map((n)=>n.charAt(0).toUpperCase()+n.slice(1)),r=i.pop();return[...i,...r?[px(r)]:[]].join(" ")}var iMn=new Set(["note"]);function rMn(e){let t=["file.name"];for(let i of e)if(!eMn.has(i.name))t.push(i.name);return t}function nMn(e){return e.some((t)=>t.name==="status"&&t.type==="enum")}function Vre(e,t,i=tMn(e)){let r=nMn(t),n=rMn(t),o=[{type:"table",name:`All ${i}`,order:n}];if(r)o.push({type:"table",name:"By Status",groupBy:{property:"status",direction:"ASC"},order:n});let a={filters:{and:[iMn.has(e)?'file.folder == "/"':`file.inFolder("${e}")`]},views:o};return{filename:`${i}.base`,content:aD(a),hasStatus:r}}function K1i(e){if(e.length===0)return null;let t=e.map((r)=>`file.inFolder("${r}")`),i={filters:{and:[t.length===1?t[0]:{or:t}]},views:[{type:"table",name:"Settings",order:["file.name","file.folder"]}]};return aD(i)}function Y1i(e){if(e.length===0)return null;let t=e.map((r)=>`file.inFolder("${r.entityType}")`),i={filters:{and:[t.length===1?t[0]:{or:t},'status != "published"']},views:[{type:"table",name:"Pipeline",groupBy:{property:"status",direction:"ASC"},order:["file.name","file.folder","status"]}]};return aD(i)}var dMn={mkdir:sMn,writeFile:uMn,existsFile:oMn,readFile:(e)=>aMn(e,"utf8"),renameFile:cMn,removeFile:(e)=>lMn(e,{force:!0})};function pMn(e,t,i,r,n){let{deps:o,logger:s}=e,a=Vre(t,i,V1i(t)),c=mg(r,a.filename);if(c===n||!o.existsFile(c)||o.existsFile(n))return;if(o.readFile(c)===a.content)o.writeFile(n,Vre(t,i).content),o.removeFile(c);else o.renameFile(c,n);s.info(`Renamed base ${a.filename} to its current name`)}function J1i(e){let{shapes:t,dataDir:i,config:r,deps:n,logger:o,filterTypes:s}=e,a=t.types(),c=s?a.filter((R)=>s.includes(R)):a,u=mg(i,r.baseFolder),d=mg(u,"templates"),p=mg(u,"fileClasses"),m=mg(u,"bases");n.mkdir(d,{recursive:!0}),n.mkdir(p,{recursive:!0}),n.mkdir(m,{recursive:!0});let h=[],f=[],g=[],y=[],b=[],v=[];for(let R of c){let O=t.frontmatterSchema(R);if(!O){o.debug(`Skipping ${R}: no frontmatter schema`),f.push(R);continue}let k=$1i(O),j=H1i(R,k);if(n.writeFile(mg(p,`${R}.md`),j),g.push(R),t.isSingleton(R)){b.push(R),o.debug(`Generated fileClass (singleton): ${R}`);continue}let N=G1i(R,k,t.bodyTemplate(R));n.writeFile(mg(d,`${R}.md`),N),h.push(R);let q=Vre(R,k),K=mg(m,q.filename);if(pMn(e,R,k,m,K),!n.existsFile(K))n.writeFile(K,q.content),y.push(R),o.debug(`Generated base: ${q.filename}`);if(q.hasStatus)v.push({entityType:R,fields:k});o.debug(`Generated template + fileClass: ${R}`)}let w=K1i(b);if(w){let R=mg(m,"Settings.base");if(!n.existsFile(R))n.writeFile(R,w),y.push("Settings"),o.debug("Generated Settings.base")}let D=Y1i(v);if(D){let R=mg(m,"Pipeline.base");if(!n.existsFile(R))n.writeFile(R,D),y.push("Pipeline"),o.debug("Generated Pipeline.base")}return o.info(`Synced ${h.length} templates, ${g.length} fileClasses, ${y.length} bases (${f.length} skipped)`),{generated:h,skipped:f,fileClasses:g,bases:y}}function Q1i(e={}){let t={...dMn,...e};return Xt({id:"obsidian-vault",config:MTe},{subscriptions:(i)=>{let{config:r}=i,{logger:n,entityShapes:o,dataDir:s,ready:a}=Lt(i);return a(()=>{n.info("Auto-syncing Obsidian templates, fileClasses, and bases");try{J1i({shapes:o,dataDir:s,config:r,deps:t,logger:n})}catch(c){n.error("Failed to sync",{error:c})}}),[]}})}var mMn=Q1i(),OTe=mMn;var cD=l.enum(["draft","active","archived"]),lD=l.enum(["admin","trusted","public"]),Kre=l.enum(["agent-confirmed","manual"]),hMn=l.enum(["draft","active","archived"]),fMn=l.enum(["admin","trusted","public"]),xMn=l.enum(["agent-confirmed","manual"]);function X1i(){return l.codec(l.string().optional(),l.string().min(1).optional(),{decode:(e)=>e?.trim().length===0?void 0:e,encode:(e)=>e})}var hg=X1i(),EE=X1i(),NTe=l.object({event:l.string().min(1),target:l.string().min(1),operatorAction:l.boolean().optional(),label:EE,description:EE,operatorDescription:EE}),Yre=l.enum(["reply"]),JL=l.object({id:l.string().min(1),title:l.string().min(1),prompt:EE,requiredDetails:l.array(l.string().min(1)).default([]),instructions:l.array(l.string().min(1)).default([]),doneWhen:l.array(l.string().min(1)).default([]),provenBy:l.array(Yre).min(1).optional(),transitions:l.array(NTe).default([])}),Jre=l.object({purpose:l.string().min(1),operatingRules:l.array(l.string().min(1)).default([]),initialState:l.string().min(1),states:l.array(JL).min(1),finalStates:l.array(l.string().min(1)).min(1),nextPrompts:l.array(l.string().min(1)).default([])}),AE=l.object({title:l.string(),status:cD.default("active"),audience:lD.default("admin"),trigger:hg.optional(),lifecycle:hg.optional(),once:l.boolean().optional(),starterText:hg.optional(),description:hg.optional(),starterPrompt:hg.optional(),completionMode:Kre.default("agent-confirmed")}),Qre=l.object({title:l.string(),status:cD,audience:lD,trigger:hg.optional(),lifecycle:hg.optional(),once:l.boolean().optional(),starterText:hg.optional(),description:hg.optional(),starterPrompt:hg.optional(),completionMode:Kre}),gMn=l.object({title:l.string(),status:hMn,audience:fMn,trigger:EE.optional(),lifecycle:EE.optional(),once:l.boolean().optional(),starterText:EE.optional(),description:EE.optional(),starterPrompt:EE.optional(),completionMode:xMn}),ewi=$i.extend({entityType:l.literal("playbook"),metadata:gMn});class Xre extends C0{constructor(){super(Jre,{title:"Playbook",mappings:[{key:"purpose",label:"Purpose",type:"string"},{key:"operatingRules",label:"Operating Rules",type:"array",itemType:"string"},{key:"initialState",label:"Initial State",type:"string"},{key:"states",label:"States",type:"array",itemType:"object",itemMappings:[{key:"id",label:"ID",type:"string"},{key:"title",label:"Title",type:"string"},{key:"prompt",label:"Prompt",type:"custom",formatter:LTe,parser:zTe},{key:"requiredDetails",label:"Required Details",type:"array",itemType:"string"},{key:"instructions",label:"Instructions",type:"array",itemType:"string"},{key:"doneWhen",label:"Done When",type:"array",itemType:"string"},{key:"provenBy",label:"Proven By",type:"custom",formatter:yMn,parser:bMn},{key:"transitions",label:"Transitions",type:"array",itemType:"object",itemMappings:[{key:"event",label:"Event",type:"string"},{key:"target",label:"Target",type:"string"},{key:"operatorAction",label:"User Choice",type:"custom",formatter:EMn,parser:AMn},{key:"label",label:"Label",type:"custom",formatter:LTe,parser:zTe},{key:"description",label:"Description",type:"string"},{key:"operatorDescription",label:"Operator Description",type:"custom",formatter:LTe,parser:zTe}]}]},{key:"finalStates",label:"Final States",type:"array",itemType:"string"},{key:"nextPrompts",label:"Next Prompts",type:"array",itemType:"string"}]})}}var ene=new Xre;function LTe(e){return typeof e==="string"?e:""}function zTe(e){let t=e.trim();return t.length>0?t:void 0}function yMn(e){return Array.isArray(e)?e.join(", "):""}function bMn(e){let t=e.split(",").map((i)=>i.trim()).filter((i)=>i.length>0);return t.length>0?t:void 0}function EMn(e){return typeof e==="boolean"?String(e):""}function AMn(e){let t=e.trim().toLowerCase();if(t==="true")return!0;if(t==="false")return!1;return}function jTe(e){let t=[],i=new Set,r=new Set;for(let n of e.states){if(i.has(n.id))r.add(n.id);i.add(n.id)}if(!i.has(e.initialState))t.push(`Playbook initial state '${e.initialState}' is not defined.`);for(let n of r)t.push(`Duplicate playbook state id '${n}'.`);for(let n of e.finalStates)if(!i.has(n))t.push(`Playbook final state '${n}' is not defined.`);for(let n of e.states)for(let o of n.transitions)if(!i.has(o.target))t.push(`Playbook transition '${n.id}' -> '${o.target}' targets an undefined state.`);for(let n of vMn(e,i))t.push(`Playbook state '${n}' is unreachable.`);return{valid:t.length===0,errors:t}}function uD(e){let t=jTe(e);if(!t.valid)throw Error(t.errors.join(`
@@ -10876,5 +10876,5 @@ ${Ioe}</style><link rel="stylesheet" href="${J$n}"></head><body class="guest-pag
10876
10876
  `);return{kind:"text",filename:"inbox-source.txt",mediaType:"text/plain",content:u,sizeBytes:new TextEncoder().encode(u).byteLength}}catch{return xki()}}async handleContextSessionRequest(e){let t=sc(e);if(t)return t;return h9i(e,{conversations:this.runtime.conversations,resolveAccess:(i)=>this.resolveConversationAccess(i),interfaceType:Xd,authorizeSource:async({sourceId:i,itemId:r,permissionLevel:n,signal:o})=>{let s=this.runtime.inbox.getSource(i);if(!s?.resolveDetail)return!1;return await s.resolveDetail(r,{permissionLevel:n},o),!0}})}async handleSessionsRequest(e){return S9i(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Xd})}async handleDeleteSessionRequest(e){return k9i(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Xd})}async handleRenameSessionRequest(e){return B9i(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Xd})}async handleArchiveSessionRequest(e){return C9i(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Xd})}async handleDocumentAttachmentRequest(e){return w2i(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleImageAttachmentRequest(e){return S2i(e,{resolvePermissionLevel:(t)=>this.resolveAttachmentPermissionLevel(t),createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),entityService:this.runtime.entityReads})}async handleJobStatusRequest(e){return g9i(e,{resolveAuthSession:this.resolveAuthSession,createAuthLoginRequiredResponse:(t)=>this.createAuthLoginRequiredResponse(t),jobs:this.runtime.jobs})}async handleMessagesRequest(e){return _9i(e,{conversations:this.runtime.conversations,resolveAccess:(t)=>this.resolveConversationAccess(t),interfaceType:Xd})}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,Xd,t)}ensureWebChatConversation(e,t){return this.ensureBrowserConversation(e,Xd,"Web Chat",t)}async requireExistingBrowserConversation(e,t,i){let r=await this.runtime.conversations.get(e);return bg(r,i,t)?void 0:new Response("Conversation not found",{status:404})}async ensureBrowserConversation(e,t,i,r){let n=await this.runtime.conversations.get(e);if(n)return bg(n,r,t)?void 0:new Response("Conversation not found",{status:404});if(r.permissionLevel==="trusted"&&!r.personId)return new Response("Forbidden",{status:403});await this.runtime.conversations.start({sessionId:e,interfaceType:t,channelId:e,...r.personId?{personId:r.personId}:{},metadata:{channelName:i,interfaceType:t,channelId:e}});let o=await this.runtime.conversations.get(e);return bg(o,r,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 r=t.status==="active"&&(t.permissionLevel==="admin"||t.permissionLevel==="trusted");return{principal:t,permissionLevel:r?t.permissionLevel:"public",hasChatAccess:r}}if(this.resolveCallerPermissionLevel){let r=await this.resolveCallerPermissionLevel(e);return{permissionLevel:r,hasChatAccess:r==="admin"||r==="trusted"}}let i=this.resolveAuthSessionOverride?await this.resolveAuthSessionOverride(e):!1;return{permissionLevel:i?"admin":"public",hasChatAccess:i}}async resolvePermissionLevel(e){return(await this.resolveBrowserAccess(e)).permissionLevel}async resolveAttachmentPermissionLevel(e){return this.resolvePermissionLevel(e)}createAuthLoginRequiredResponse(e){let t=this.runtime.auth();if(t)return t.createAuthLoginResponse(e);return new Response("Authentication required",{status:401,headers:{"Content-Type":"text/plain; charset=utf-8"}})}writeText(e,t,i){return Boe(e,t,i,(r)=>this.createId(r))}createId(e){return`${e}-${crypto.randomUUID()}`}}function xki(){return new Response("Inbox context is unavailable",{status:409})}function QFe(e={}){let t=m0({id:Xd,config:NFe,setup:async(n)=>{let o=es(n),s=new bki(n.config,e,o,n.runtimeState(Fee));return await s.register(),o.ready(()=>s.onReady()),s}}),i=ts(t,({state:n})=>n.webRoutes()),r=kf(i,({state:n})=>{let o=n.maintenanceDaemon();return{id:"guest-maintenance",start:()=>o.start(),stop:()=>o.stop(),healthCheck:()=>o.healthCheck()}});return LJ(r,({state:n})=>n.transport())}var UGn=QFe(),Eki=UGn;var XFe='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 Aki={critical:0,high:1,medium:2,low:3};function vki(e){return[...e].sort((t,i)=>{let r=i.metadata.requested-t.metadata.requested;if(r!==0)return r;return Aki[t.metadata.priority]-Aki[i.metadata.priority]})}var jz=l.enum(["new","planned","in-progress","done","declined"]),Uz=l.enum(["low","medium","high","critical"]),Uoe=l.object({title:l.string(),status:jz,priority:Uz.default("medium"),requested:l.number().int().default(1).meta({studioWidget:"provenance"}),declinedReason:l.string().optional()}),eMe=l.object({title:l.string(),status:jz,priority:Uz,requested:l.number().int().meta({studioWidget:"provenance"}),slug:l.string().optional().meta({studioWidget:"hidden"}),declinedReason:l.string().optional()});var qGn=l.object({items:l.array(l.object({id:l.string(),name:l.string(),count:l.number().int().nonnegative(),priority:Uz,status:jz}))});function $Gn(e){if(e==="critical")return"error";if(e==="high")return"warn";return"neutral"}var tMe=zn({id:"top-wishes",title:"Top Wishes",group:"knowledge",placement:"secondary",priority:30,permission:"public",data:qGn,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:$Gn(t.priority)},{label:t.status,tone:t.status==="done"?"good":"neutral"}]}))}]})});function GGn(e){return tMe.bind(e,async({entities:t,signal:i})=>(i.throwIfAborted(),{items:vki(await t.list(Ag,{limit:10})).map((n)=>({id:n.id,name:n.metadata.title,count:n.metadata.requested,priority:n.metadata.priority,status:n.metadata.status}))}))}var Ag=Mi(Ft({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:eMe,markdown:{decode:({content:e,frontmatter:t})=>{let i=Uoe.parse(t);return{content:e,metadata:{title:i.title,status:i.status,priority:i.priority,requested:i.requested,slug:Ut(i.title),...i.declinedReason!==void 0&&{declinedReason:i.declinedReason}}}},encode:({content:e,metadata:t})=>({content:e,frontmatter:{title:t.title,status:t.status,priority:t.priority,requested:t.requested,...t.declinedReason!==void 0&&{declinedReason:t.declinedReason}}})},config:{projectionSource:!1,projectionSourceRole:"excluded"},instructions:XFe,dashboardWidgets:(e)=>[GGn(e)]}),Uoe);var wki=0.3,HGn="Do these two wishes ask for the same thing?",WGn=l.object({same:l.boolean().describe("True only when delivering one would fulfil the other.")});async function ZGn(e,t,i){let{same:r}=await e.generateObject([HGn,"Answer yes when both ask for the same capability, even if wording, timing or detail differ (weekly vs every Monday, calendar sync vs Google Calendar integration).","Opposite or different capabilities are different wishes, even when worded almost alike: send emails vs stop sending emails, add vs remove.","","New wish:",t,"","Existing wish:",i].join(`
10877
10877
  `),WGn);return r}function qoe(e,t,i){return{nearest:(r,n)=>e.nearest(Ag,r,{maxDistance:n}),getEntity:(r)=>t.get(Ag,r),maxDistance:i,ai:e}}async function $oe(e,t){let i=(await e.nearest(t.content,e.maxDistance)).flatMap(({entity:s})=>s.visibility==="public"?[s]:[]),r=async(s)=>{let a=i[s];if(!a)return;return await ZGn(e.ai,t.content,VGn(a))?a:r(s+1)},n=await r(0);if(n)return n;let o=await e.getEntity(Ut(t.title));return o?.visibility==="public"?o:null}function VGn(e){let{title:t,status:i,priority:r,requested:n,declinedReason:o}=e.metadata;return qz({title:t,status:i,priority:r,requested:n,declinedReason:o},e.content)}function qz(e,t){let i=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0&&r!==null));return Object.keys(i).length>0?lr(i,t):t}var Ski=l.object({title:l.string(),description:l.string()}),KGn=l.object({stored:Ski,incoming:Ski}),iMe="eval-stored-wish";function kki(e){return qz({title:e.title,status:"new",priority:"medium",requested:1},e.description)}function Bki(e){return{sameWish:async(t,i)=>{let{stored:r,incoming:n}=KGn.parse(t),{fixtures:o}=i;await o.reset(),await o.seed({id:iMe,entityType:"wish",content:kki(r),metadata:{title:r.title,status:"new",priority:"medium",requested:1,slug:Ut(r.title)}}),await o.settleEmbeddings();let s=Ht(i),a=kki(n),c=(await s.nearest(Ag,a,{maxDistance:2})).find(({entity:d})=>d.id===iMe)?.distance;if(c===void 0)throw Error("The stored wish was not embedded");let u=await $oe(qoe(s,i.entities,e),{title:n.title,content:a});return{distance:c,shortlisted:c<=e,sameWish:u?.id===iMe}}}}async function YGn(e,t){let{input:i}=e;if(i.visibility!==void 0&&i.visibility!=="public")return{refuse:"Wish creation currently supports public visibility only; use a note for shared or restricted capture."};let r=i.title??i.prompt??"Untitled wish",n=i.content??i.prompt??"",o={title:r,status:"new",priority:"medium",requested:1},s=await $oe(qoe(Ht(e),e.entities,t),{title:r,content:qz(o,n)});if(s)return{update:{id:s.id,content:s.content.trim(),metadata:{...s.metadata,requested:s.metadata.requested+1}}};let a=Ut(r);return{create:{id:a,content:n,metadata:{...o,slug:a}}}}function Cki(e){let t={resolve:(i)=>YGn(i,e)};return{fromPrompt:t,fromContent:t,fromUpload:t}}var rMe=l.object({sameWishDistance:l.number().min(0).max(1).default(wki)});var JGn=Lr({id:"wishlist",config:rMe,entities:[Ag],configure:({config:e})=>({entities:[{entity:Ag,create:Cki(e.sameWishDistance),evals:Bki(e.sameWishDistance)}]})}),Dki=JGn;var Iki="gpt-6-luna";var r2={create:"trusted",update:"trusted",delete:"admin",extract:"admin",publish:"admin"},_ki=[{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}}],Tki=["Use the installed publishing capabilities for professional website content, essays, projects, decks, newsletters, and social distribution workflows. Treat publishing requests as production and distribution work rather than generic shared-memory capture.",`When answering questions like "what have I written about X" or "which posts relate to this deck/source", search first and use semantic search results as candidates, not proof. Summarize only clearly relevant entities whose title or content directly matches the asked topic or has substantial overlap with the source's main themes; omit weak/tangential candidates rather than presenting them as definite matches. A match based on only an isolated shared term or pattern is not enough; when one candidate is clearly stronger than the rest, list only the strongest clear match and say the others were tangential rather than naming them as matches.`,'Draft blog posts are only post entities with status draft. If the user asks whether draft blog posts exist, call only system_list for entityType post with status draft; do not also list social-post, newsletter, deck, or other draft entity types. After telling the user there are no draft blog posts, treat follow-ups like "make one draft" or "make one a draft" as requests to change an existing published post back to draft: ask which existing published post they want changed; do not offer to create a brand-new post and do not call system_generate to create a fresh draft from that ambiguous follow-up.'],Pki=[{member:"topics",value:{extractableStatuses:["published","draft"]}},{member:"conversation-memory",value:{memoryVisibility:"shared"}},{member:"action-board",value:{cardVisibility:"shared"}}],Rki=["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 dw="capability-bundles-v1",nMe="core",oMe="media",sMe="automation",$z="web",aMe="chat",cMe="site",lMe="publishing",uMe="federation",dMe="team",Goe=u0({id:nMe,members:["profile","prompt","style-guide","directory-sync","note","link","topics","unified-inbox","mcp","a2a","agents"],evalDisable:["mcp"]}),Hoe=u0({id:oMe,members:["document","image"]}),Woe=u0({id:sMe,members:["playbooks","onboarding"]}),Zoe=u0({id:$z,members:["auth-service","admin","dashboard","studio"],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"]}),Voe=u0({id:aMe,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"]}),Koe=u0({id:cMe,members:["site-info","site-content","site-builder","form","analytics"],config:[{member:"dashboard",value:{routePath:"/dashboard"},overrides:$z}]}),Yoe=u0({id:lMe,members:["blog","series","portfolio","decks","content-pipeline","social-media","newsletter","stock-photo"],config:_ki,agentInstructions:Tki}),Joe=u0({id:uMe,members:["atproto","atproto-registry"],evalDisable:["atproto"]}),Qoe=u0({id:dMe,members:[],config:Pki,permissions:[{member:"note",config:{entityActions:{note:r2}}},{member:"link",config:{entityActions:{link:r2}}},{member:"image",config:{entityActions:{image:r2}}},{member:"docs",config:{entityActions:{doc:r2}}},{member:"conversation-memory",config:{entityActions:{decision:r2,"action-item":r2}}},{member:"mcp",config:{rules:[{pattern:"mcp:http",level:"admin"}]},overrides:$z}],agentInstructions:Rki}),Fki=[Goe,Hoe,Woe,Zoe,Voe,Koe,Yoe,Joe,Qoe];function pMe(e,t,i){let r={name:e,version:pw.version};return(n)=>d0(t,n,r,i)}function QGn(e){let{entity:t,provider:i}=$vi(e),r={name:"@brains/newsletter",version:pw.version};return[...d0(t.definition,t.config,r,{pluginId:"newsletter"}),...i?d0(i.definition,i.config,r,{pluginId:i.kind}):[]]}function er(e,t,i,r={},n=void 0){return[e,pMe(t,i,r),n]}function Gz(e,t,i,r,n={}){return[e,pMe(t,i,n),r]}var Mki=kse({name:"brain",version:pw.version,bundleContract:dw,model:Iki,reasoningEffort:"low",capabilities:[er("prompt","@brains/prompt",y8i,{pluginId:"prompt"}),er("profile","@brains/profile",IPe,{pluginId:"profile"}),er("style-guide","@brains/style-guide",bSi,{pluginId:"style-guide"}),er("ask-content","@brains/ask-content",ASi,{pluginId:"ask-content"}),er("image","@brains/image-plugin",YAi,{pluginId:"image"}),er("document","@brains/document-plugin",aai,{pluginId:"document"}),er("note","@brains/note",n1i,{pluginId:"note"}),er("link","@brains/link",mvi,{pluginId:"link"}),er("wishlist","@brains/wishlist",Dki,{pluginId:"wishlist"}),["topics",(e)=>[...d0(y6i,e,{name:"@brains/topics",version:pw.version},{pluginId:"topics"}),...d0(rFe,{},{name:"@brains/knowledge-map",version:pw.version},{pluginId:"knowledge-map"})],void 0],er("decks","@brains/decks",Oii,{pluginId:"decks"}),er("directory-sync","@brains/directory-sync",soi,{pluginId:"directory-sync"},{seedContent:!0,seedContentPath:"./seed-content",initialSync:!0}),er("atproto-registry","@brains/atproto-registry",spe,{pluginId:"atproto-registry"}),["agents",(e)=>{let{enableSkillDerivation:t,notifyOnNewAgents:i}=EGe.parse(e),r={name:"@brains/agent-discovery",version:pw.version};return[...d0(pde,{},r,{pluginId:"agent-discovery",ownedTypePluginId:"agent-entity"}),...d0(mde,{notifyOnNewAgents:i},r,{pluginId:"agent"}),...d0(t?hde:fde,{},r,{pluginId:"skill",ownedTypePluginId:"skill-entity"})]},void 0],["assessment",(e)=>d0(jde.parse(e).enableSwotDerivation?Ude:qde,{},{name:"@brains/assessment",version:pw.version},{pluginId:"swot"}),void 0],er("auth-service","@brains/auth-service",ufe,{pluginId:"auth-service"}),er("notifications","@brains/notifications",a1i,{pluginId:"notifications"}),er("contact","@brains/contact",jXt,{pluginId:"contact",dependencies:zXt}),er("quiz","@brains/quiz",WXt,{pluginId:"quiz",dependencies:HXt}),er("playbooks","@brains/playbooks",ePe,{pluginId:"playbooks"}),er("onboarding","@brains/onboarding",v8i,{pluginId:"onboarding",dependencies:["playbook","playbooks"]}),er("studio","@brains/studio",UQt,{pluginId:"studio"}),er("dashboard","@brains/dashboard",cii,{pluginId:"dashboard"}),er("admin","@brains/admin",ace,{pluginId:"admin"}),er("site-info","@brains/site-info",fRe,{pluginId:"site-metadata"}),er("site-content","@brains/site-content",Q5i,{pluginId:"site-content",ownedTypePluginId:"site-content-entity"}),er("site-builder","@brains/site-builder-plugin",K5i,{pluginId:"site-builder"}),er("form","@brains/form",UXt,{pluginId:"form"}),er("analytics","@brains/analytics",qGe,{pluginId:"analytics"}),er("blog","@brains/blog",sat,{pluginId:"blog"}),er("series","@brains/series",z8i,{pluginId:"series"}),er("portfolio","@brains/portfolio",Zwi,{pluginId:"portfolio"}),er("content-pipeline","@brains/content-pipeline",bXt,{pluginId:"content-pipeline"}),er("social-media","@brains/social-media",mSi,{pluginId:"social-media"}),["newsletter",QGn,void 0],er("stock-photo","@brains/stock-photo",gSi,{pluginId:"stock-photo"}),["atproto",pMe("@brains/atproto",wHe,{pluginId:"atproto"}),(e)=>({...e.ATPROTO_APP_PASSWORD?{appPassword:e.ATPROTO_APP_PASSWORD}:{}})],er("conversation-memory","@brains/conversation-memory",P9e,{pluginId:"conversation-memory"}),er("action-board","@brains/action-board",PFe,{pluginId:"action-board"}),er("faq","@brains/faq",Iti,{pluginId:"faq",ownedTypePluginId:"faq-entity"}),er("docs","@brains/doc",Coi,{pluginId:"docs"}),er("guides","@brains/guide",Yoi,{pluginId:"guides"}),er("book","@brains/book",Qsi,{pluginId:"book",ownedTypePluginId:"book-entity"}),er("obsidian-vault","@brains/obsidian-vault",OTe,{pluginId:"obsidian-vault"},{autoSync:!0}),er("email-workflows","@brains/email-workflows",MAi,{pluginId:"email-workflows"}),er("unified-inbox","@brains/unified-inbox",EFe,{pluginId:"unified-inbox"}),er("linkedin-import","@brains/linkedin-import",ITe,{pluginId:"linkedin-import"}),er("oauth-broker","@brains/oauth-broker",FTe({providers:{linkedin:bTe}}),{pluginId:"oauth-broker"})],interfaces:[Gz("mcp","@brains/mcp",Svi,(e)=>({...e.MCP_AUTH_TOKEN?{authToken:e.MCP_AUTH_TOKEN}:{}}),{pluginId:"mcp"}),Gz("email","@brains/email",AAi,()=>({}),{pluginId:"email"}),Gz("web-chat","@brains/web-chat",Eki,()=>({}),{pluginId:"web-chat"}),Gz("chat","@brains/chat",CJt,(e)=>L6e(e,{captureUrls:!0}),{pluginId:"chat"}),Gz("a2a","@brains/a2a",yOe,()=>({}),{pluginId:"a2a"})],bundles:Fki,permissions:{rules:[{pattern:"cli:*",level:"admin"},{pattern:"mcp:stdio",level:"admin"}]},deployment:{cdn:{enabled:!0,provider:"bunny"},dns:{enabled:!0,provider:"bunny"}}});var XGn=["headless","personal","professional","team"];var eHn={headless:{bundleContract:dw,bundles:["core"]},personal:{bundleContract:dw,anchor:"person",kind:"professional",bundles:["core","media","web","chat"],plugins:{"directory-sync":{seedContentPath:"./seed-content"}}},professional:{bundleContract:dw,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:dw,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 tHn(e){return structuredClone(e)}function iHn(e){return tHn(eHn[e])}var rHn=Mki,R1a=Goe,F1a=Hoe,M1a=Woe,O1a=Zoe,N1a=Voe,L1a=Koe,z1a=Yoe,j1a=Joe,U1a=Qoe,$1a=rHn;export{sMe as AUTOMATION_BUNDLE_ID,XGn as BRAIN_RECIPE_NAMES,dw as CANONICAL_BUNDLE_CONTRACT,aMe as CHAT_BUNDLE_ID,nMe as CORE_BUNDLE_ID,uMe as FEDERATION_BUNDLE_ID,oMe as MEDIA_BUNDLE_ID,lMe as PUBLISHING_BUNDLE_ID,cMe as SITE_BUNDLE_ID,dMe as TEAM_BUNDLE_ID,$z as WEB_BUNDLE_ID,M1a as automationBundle,rHn as canonicalBrain,N1a as chatBundle,R1a as coreBundle,$1a as default,iHn as expandBrainRecipe,j1a as federationBundle,F1a as mediaBundle,z1a as publishingBundle,L1a as siteBundle,U1a as teamBundle,O1a as webBundle};
10878
10878
 
10879
- //# debugId=0E5FA5B1211A4DCD64756E2164756E21
10879
+ //# debugId=928F47D217D381D564756E2164756E21
10880
10880
  //# sourceMappingURL=model.js.map