agentix-cli 0.213.0 → 0.213.2
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/{App-5CLRBC3C.js → App-OUWMH6QG.js} +2 -2
- package/dist/{ChatApp-LDNQVD2C.js → ChatApp-EZ5A47FV.js} +2 -2
- package/dist/{absorb-eval-JWQPGUJS.js → absorb-eval-WM6JQGYG.js} +2 -2
- package/dist/{adapter-AOKK2LFM.js → adapter-W26OC6ET.js} +2 -2
- package/dist/{agent-TF6XQQGV.js → agent-2GK32HCI.js} +2 -2
- package/dist/{board-dashboard-LDMIS7MM.js → board-dashboard-6JUASBDZ.js} +131 -131
- package/dist/{board-dashboard-LDMIS7MM.js.map → board-dashboard-6JUASBDZ.js.map} +1 -1
- package/dist/{chunk-D6H4DH32.js → chunk-2CO3NK6Z.js} +2 -2
- package/dist/{chunk-DPA3IOMU.js → chunk-35UGFFHA.js} +2 -2
- package/dist/{chunk-X7UEV4O2.js → chunk-3JH3HUHX.js} +2 -2
- package/dist/{chunk-EE5RZDQE.js → chunk-7T5Y4H2J.js} +2 -2
- package/dist/{chunk-WKBGQGVL.js → chunk-ACPGDZOV.js} +2 -2
- package/dist/{chunk-NWE3B245.js → chunk-B7HDWFKR.js} +2 -2
- package/dist/{chunk-ERKK22QV.js → chunk-CAH6TNC6.js} +2 -2
- package/dist/{chunk-36RIIHPS.js → chunk-EUJT7JT3.js} +98 -98
- package/dist/chunk-EUJT7JT3.js.map +1 -0
- package/dist/{chunk-N7IX77SL.js → chunk-FR4DTMCA.js} +2 -2
- package/dist/{chunk-CUCIMPFI.js → chunk-H4DWZIU7.js} +2 -2
- package/dist/{chunk-DNPPPUDP.js → chunk-HY4PE6R3.js} +2 -2
- package/dist/{chunk-4W5KRZTT.js → chunk-IHFOW4JF.js} +2 -2
- package/dist/{chunk-VKLTCUD7.js → chunk-J2R47R56.js} +2 -2
- package/dist/{chunk-DSUL5L3T.js → chunk-JEBU5JUM.js} +2 -2
- package/dist/{chunk-D3FIIEDR.js → chunk-JKMFKNGS.js} +2 -2
- package/dist/chunk-KAM4ZWRE.js +133 -0
- package/dist/chunk-KAM4ZWRE.js.map +1 -0
- package/dist/{chunk-IXV3BPUZ.js → chunk-MIUITI47.js} +2 -2
- package/dist/{chunk-G3GFE3GK.js → chunk-N476XZD3.js} +2 -2
- package/dist/{chunk-7JWMLYOA.js → chunk-NERO7F3J.js} +2 -2
- package/dist/chunk-NERO7F3J.js.map +1 -0
- package/dist/{chunk-BU6V75KD.js → chunk-PSYHAO57.js} +2 -2
- package/dist/{chunk-O4WFPH6H.js → chunk-QR3P5RG7.js} +2 -2
- package/dist/{chunk-XBFXSSHA.js → chunk-RMXG5GNW.js} +2 -2
- package/dist/{chunk-MOATCFT5.js → chunk-SPXXLPAS.js} +2 -2
- package/dist/{chunk-NZFWW2YG.js → chunk-UPWNWSK3.js} +296 -296
- package/dist/chunk-UPWNWSK3.js.map +1 -0
- package/dist/{chunk-KU3ZF3WO.js → chunk-UUOCCLIL.js} +2 -2
- package/dist/{chunk-Z6N7POAU.js → chunk-WAVO3U3I.js} +78 -78
- package/dist/chunk-WAVO3U3I.js.map +1 -0
- package/dist/{chunk-FCF47R4W.js → chunk-XHON5WB5.js} +3 -3
- package/dist/{chunk-I722PWJE.js → chunk-Z7632XS3.js} +2 -2
- package/dist/{chunk-BERSMN6Y.js → chunk-ZMGDHLZD.js} +2 -2
- package/dist/{chunk-DGCYMSXU.js → chunk-ZRBTLW2B.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-2TFSAO3Y.js → client-U3OFNJ5W.js} +2 -2
- package/dist/{config-LTXRWDRK.js → config-S522VXLI.js} +2 -2
- package/dist/{config-mutate-UFVJUJQO.js → config-mutate-KBZV2T4X.js} +2 -2
- package/dist/{config-mutator-RRKU33OL.js → config-mutator-YNNEGRV3.js} +2 -2
- package/dist/{contributions-5XUEOSLT.js → contributions-FXUTKU6R.js} +2 -2
- package/dist/{doctor-L675OBBF.js → doctor-ABJSFSMM.js} +2 -2
- package/dist/{follow-up-tool-2OEZMPPQ.js → follow-up-tool-C4PLLZIT.js} +2 -2
- package/dist/{hub-VJZYQXKB.js → hub-PPQGFC35.js} +2 -2
- package/dist/index.d.ts +16 -0
- package/dist/index.js +1 -1
- package/dist/{org-tool-QBLKCMY3.js → org-tool-6PPIGWH2.js} +2 -2
- package/dist/{program-4WR4ZYXQ.js → program-VCNJHSWN.js} +27 -27
- package/dist/{promote-Z6KL6GOL.js → promote-CXXMZWWH.js} +2 -2
- package/dist/{query-SZA6UMHA.js → query-RPZIRN3X.js} +2 -2
- package/dist/{query-settings-BALRO5J4.js → query-settings-EBOBWOAL.js} +2 -2
- package/dist/{registry-LD2IYY7L.js → registry-QTFATS6J.js} +2 -2
- package/dist/{request-planner-Y5HG5DQ4.js → request-planner-LNNKTY7K.js} +2 -2
- package/dist/{review-candidates-BZJOFMFO.js → review-candidates-HQBKXAJA.js} +2 -2
- package/dist/{routing-3JDN3Z6L.js → routing-XXA7GIBA.js} +2 -2
- package/dist/schedule-tool-65TFOUWK.js +2 -0
- package/dist/{scheduler-JJOO2ODF.js → scheduler-DIPOBJBF.js} +2 -2
- package/dist/{seat-5FTOWN5J.js → seat-BSWBTNCP.js} +2 -2
- package/dist/{select-BRQQP7OP.js → select-T4F42G6W.js} +2 -2
- package/dist/{set-enabled-EZLQFASM.js → set-enabled-UK4TPVC7.js} +2 -2
- package/dist/{sprint-tool-YJ4WT3AD.js → sprint-tool-DN3BKLUY.js} +2 -2
- package/dist/{tool-RCEOKPES.js → tool-2VRNH43W.js} +2 -2
- package/dist/{tool-CXJHLIHJ.js → tool-JJGEGQF3.js} +2 -2
- package/dist/{tool-MT5YQ7F3.js → tool-Z2YLBCN7.js} +2 -2
- package/dist/{tool-BFKCGAD6.js → tool-ZVYUWVJQ.js} +2 -2
- package/dist/{wiki-F3LZSBN3.js → wiki-FP4JMCYP.js} +2 -2
- package/dist/wiki-enrich-3SPIVYSG.js +2 -0
- package/dist/{workspace-setup-VLLF37SJ.js → workspace-setup-PIPGUMLG.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-36RIIHPS.js.map +0 -1
- package/dist/chunk-7JWMLYOA.js.map +0 -1
- package/dist/chunk-NZFWW2YG.js.map +0 -1
- package/dist/chunk-UWDDVDU6.js +0 -133
- package/dist/chunk-UWDDVDU6.js.map +0 -1
- package/dist/chunk-Z6N7POAU.js.map +0 -1
- package/dist/schedule-tool-VM5OJ7XB.js +0 -2
- package/dist/wiki-enrich-KIONW7SB.js +0 -2
- /package/dist/{App-5CLRBC3C.js.map → App-OUWMH6QG.js.map} +0 -0
- /package/dist/{ChatApp-LDNQVD2C.js.map → ChatApp-EZ5A47FV.js.map} +0 -0
- /package/dist/{absorb-eval-JWQPGUJS.js.map → absorb-eval-WM6JQGYG.js.map} +0 -0
- /package/dist/{adapter-AOKK2LFM.js.map → adapter-W26OC6ET.js.map} +0 -0
- /package/dist/{agent-TF6XQQGV.js.map → agent-2GK32HCI.js.map} +0 -0
- /package/dist/{chunk-D6H4DH32.js.map → chunk-2CO3NK6Z.js.map} +0 -0
- /package/dist/{chunk-DPA3IOMU.js.map → chunk-35UGFFHA.js.map} +0 -0
- /package/dist/{chunk-X7UEV4O2.js.map → chunk-3JH3HUHX.js.map} +0 -0
- /package/dist/{chunk-EE5RZDQE.js.map → chunk-7T5Y4H2J.js.map} +0 -0
- /package/dist/{chunk-WKBGQGVL.js.map → chunk-ACPGDZOV.js.map} +0 -0
- /package/dist/{chunk-NWE3B245.js.map → chunk-B7HDWFKR.js.map} +0 -0
- /package/dist/{chunk-ERKK22QV.js.map → chunk-CAH6TNC6.js.map} +0 -0
- /package/dist/{chunk-N7IX77SL.js.map → chunk-FR4DTMCA.js.map} +0 -0
- /package/dist/{chunk-CUCIMPFI.js.map → chunk-H4DWZIU7.js.map} +0 -0
- /package/dist/{chunk-DNPPPUDP.js.map → chunk-HY4PE6R3.js.map} +0 -0
- /package/dist/{chunk-4W5KRZTT.js.map → chunk-IHFOW4JF.js.map} +0 -0
- /package/dist/{chunk-VKLTCUD7.js.map → chunk-J2R47R56.js.map} +0 -0
- /package/dist/{chunk-DSUL5L3T.js.map → chunk-JEBU5JUM.js.map} +0 -0
- /package/dist/{chunk-D3FIIEDR.js.map → chunk-JKMFKNGS.js.map} +0 -0
- /package/dist/{chunk-IXV3BPUZ.js.map → chunk-MIUITI47.js.map} +0 -0
- /package/dist/{chunk-G3GFE3GK.js.map → chunk-N476XZD3.js.map} +0 -0
- /package/dist/{chunk-BU6V75KD.js.map → chunk-PSYHAO57.js.map} +0 -0
- /package/dist/{chunk-O4WFPH6H.js.map → chunk-QR3P5RG7.js.map} +0 -0
- /package/dist/{chunk-XBFXSSHA.js.map → chunk-RMXG5GNW.js.map} +0 -0
- /package/dist/{chunk-MOATCFT5.js.map → chunk-SPXXLPAS.js.map} +0 -0
- /package/dist/{chunk-KU3ZF3WO.js.map → chunk-UUOCCLIL.js.map} +0 -0
- /package/dist/{chunk-FCF47R4W.js.map → chunk-XHON5WB5.js.map} +0 -0
- /package/dist/{chunk-I722PWJE.js.map → chunk-Z7632XS3.js.map} +0 -0
- /package/dist/{chunk-BERSMN6Y.js.map → chunk-ZMGDHLZD.js.map} +0 -0
- /package/dist/{chunk-DGCYMSXU.js.map → chunk-ZRBTLW2B.js.map} +0 -0
- /package/dist/{client-2TFSAO3Y.js.map → client-U3OFNJ5W.js.map} +0 -0
- /package/dist/{config-LTXRWDRK.js.map → config-S522VXLI.js.map} +0 -0
- /package/dist/{config-mutate-UFVJUJQO.js.map → config-mutate-KBZV2T4X.js.map} +0 -0
- /package/dist/{config-mutator-RRKU33OL.js.map → config-mutator-YNNEGRV3.js.map} +0 -0
- /package/dist/{contributions-5XUEOSLT.js.map → contributions-FXUTKU6R.js.map} +0 -0
- /package/dist/{doctor-L675OBBF.js.map → doctor-ABJSFSMM.js.map} +0 -0
- /package/dist/{follow-up-tool-2OEZMPPQ.js.map → follow-up-tool-C4PLLZIT.js.map} +0 -0
- /package/dist/{hub-VJZYQXKB.js.map → hub-PPQGFC35.js.map} +0 -0
- /package/dist/{org-tool-QBLKCMY3.js.map → org-tool-6PPIGWH2.js.map} +0 -0
- /package/dist/{program-4WR4ZYXQ.js.map → program-VCNJHSWN.js.map} +0 -0
- /package/dist/{promote-Z6KL6GOL.js.map → promote-CXXMZWWH.js.map} +0 -0
- /package/dist/{query-SZA6UMHA.js.map → query-RPZIRN3X.js.map} +0 -0
- /package/dist/{query-settings-BALRO5J4.js.map → query-settings-EBOBWOAL.js.map} +0 -0
- /package/dist/{registry-LD2IYY7L.js.map → registry-QTFATS6J.js.map} +0 -0
- /package/dist/{request-planner-Y5HG5DQ4.js.map → request-planner-LNNKTY7K.js.map} +0 -0
- /package/dist/{review-candidates-BZJOFMFO.js.map → review-candidates-HQBKXAJA.js.map} +0 -0
- /package/dist/{routing-3JDN3Z6L.js.map → routing-XXA7GIBA.js.map} +0 -0
- /package/dist/{schedule-tool-VM5OJ7XB.js.map → schedule-tool-65TFOUWK.js.map} +0 -0
- /package/dist/{scheduler-JJOO2ODF.js.map → scheduler-DIPOBJBF.js.map} +0 -0
- /package/dist/{seat-5FTOWN5J.js.map → seat-BSWBTNCP.js.map} +0 -0
- /package/dist/{select-BRQQP7OP.js.map → select-T4F42G6W.js.map} +0 -0
- /package/dist/{set-enabled-EZLQFASM.js.map → set-enabled-UK4TPVC7.js.map} +0 -0
- /package/dist/{sprint-tool-YJ4WT3AD.js.map → sprint-tool-DN3BKLUY.js.map} +0 -0
- /package/dist/{tool-RCEOKPES.js.map → tool-2VRNH43W.js.map} +0 -0
- /package/dist/{tool-CXJHLIHJ.js.map → tool-JJGEGQF3.js.map} +0 -0
- /package/dist/{tool-MT5YQ7F3.js.map → tool-Z2YLBCN7.js.map} +0 -0
- /package/dist/{tool-BFKCGAD6.js.map → tool-ZVYUWVJQ.js.map} +0 -0
- /package/dist/{wiki-F3LZSBN3.js.map → wiki-FP4JMCYP.js.map} +0 -0
- /package/dist/{wiki-enrich-KIONW7SB.js.map → wiki-enrich-3SPIVYSG.js.map} +0 -0
- /package/dist/{workspace-setup-VLLF37SJ.js.map → workspace-setup-PIPGUMLG.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as by,b as ga,g as $y}from"./chunk-O4WFPH6H.js";import{a as yy,b as wy}from"./chunk-MOATCFT5.js";import{b as hy}from"./chunk-DNPPPUDP.js";import{$ as Kh,A as Dh,B as qh,C as Fh,E as Uh,G as Wh,H as Bh,I as Hc,J as Hh,U as Jh,V as Gh,W as Jc,X as zh,_ as Yh,aa as Xh,ba as Vh,ca as ty,da as oy,ea as ny,fa as sy,g as vh,ga as ry,h as xh,ha as iy,ja as Gc,ka as ay,l as Sh,la as ly,m as Eh,na as cy,o as Ds,p as Ps,q as Ah,qa as dy,r as Rh,ra as uy,s as Th,sa as gy,t as Ch,u as Oh,v as Ih,x as zt,z as _h}from"./chunk-D6H4DH32.js";import{a as Qh,c as Zh,d as ey}from"./chunk-FFOGEFPT.js";import{n as zc}from"./chunk-VKLTCUD7.js";import{a as my,b as py,d as Dr,e as fy}from"./chunk-4W5KRZTT.js";import"./chunk-EFGAPAYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as Nh,c as jh}from"./chunk-BERSMN6Y.js";import"./chunk-WMZ4TGMR.js";import{d as Ph,e as Bc,h as Mh,i as Lh}from"./chunk-6UI7GJSB.js";import"./chunk-2YDG5CSS.js";import{b as jo}from"./chunk-7NQQIDDI.js";import{a as Uc}from"./chunk-LNY6N73E.js";import{a as xp,b as $c}from"./chunk-GMP2IB4E.js";import{a as fc,b as sp}from"./chunk-RKPAVWXF.js";import{$ as Jf,A as Ac,Aa as jr,B as bf,Ba as fh,C as Rc,Ca as pt,D as $f,Da as la,E as kf,Ea as ca,F as vf,Fa as _r,G as xf,Ga as Lc,H as Sf,Ha as hh,I as Ef,Ia as wh,J as Tc,Ja as Fc,K as Af,Ka as $h,L as ta,La as da,M as Rf,Ma as _s,N as Cc,Na as ua,O as Tf,Oa as Wc,P as Cf,Pa as kh,Q as Of,R as If,S as Nf,T as oa,U as Mf,V as Ff,W as Uf,X as Wf,Y as Bf,Z as Hf,_ as Ic,a as Tp,aa as Gf,b as Cp,ba as zf,ca as Yf,da as Kf,ea as Xf,fa as Vf,ga as Qf,h as Ji,ha as Zf,i as Os,ia as eh,j as jp,ja as ah,k as Cr,ka as ra,l as Gi,la as No,m as Dp,ma as Xo,n as Mp,na as Is,o as Qp,oa as ia,p as Zp,pa as aa,q as Qi,qa as Mc,r as Ec,ra as lh,s as af,sa as ch,t as mf,ta as dh,u as pf,ua as uh,v as ff,va as gh,w as hf,wa as mh,x as ea,xa as Ns,y as yf,ya as js,z as wf,za as ph}from"./chunk-NZFWW2YG.js";import{Bb as rh,Cb as ih,Db as Dc,Kb as Pc,P as lf,R as Or,S as cf,V as df,W as Zi,Zb as yh,_b as qc,ab as Ir,db as Nc,eb as na,fb as th,mb as Ko,mc as go,nb as oh,ob as jc,oc as bh,pa as jf,qa as _f,qb as _c,ra as Df,sa as Oc,sb as nh,tb as sh,ub as Nr,v as Pp,va as Pf,yb as sa}from"./chunk-Z6N7POAU.js";import"./chunk-GTJIKXDB.js";import{a as Op,c as vc,d as Tr,f as Ip,g as Np}from"./chunk-NWE3B245.js";import{A as Hp,B as Jp,C as Gp,D as zp,E as Yp,F as Kp,K as Ki,L as Xp,M as Vp,Q as uf,R as gf,a as mc,b as Qm,e as Zm,f as ep,o as Lp,s as zi,t as Yi,u as qp,v as Fp,w as Up,y as Wp,z as Bp}from"./chunk-EE5RZDQE.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as Lf,b as qf}from"./chunk-EKJG63EJ.js";import"./chunk-BU6V75KD.js";import{c as ef}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import{c as Sc}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as tf,e as Xi,g as Vi}from"./chunk-LQE73AZR.js";import{a as of,b as nf,c as sf,d as rf}from"./chunk-2D3RYIDU.js";import{a as Lt}from"./chunk-WKBGQGVL.js";import"./chunk-MRIVENBY.js";import"./chunk-GJOKXP5D.js";import"./chunk-A5GYG56I.js";import{a as xc,p as _p}from"./chunk-DSUL5L3T.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Mt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import{a as gp,b as mp,c as pp,d as fp,e as yc,f as hp,g as wc,h as bc,l as yp,m as wp}from"./chunk-RX5O5637.js";import{f as bp,i as $p,l as kp,m as vp}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{m as Sp,n as Ep,o as kc,p as Hi,q as Ap,r as Rp}from"./chunk-DPA3IOMU.js";import{a as pc,d as tp,e as Bi}from"./chunk-QPABR72X.js";import{b as Cs,e as np}from"./chunk-IFUAP7UD.js";import{c as op}from"./chunk-KP7KDLZ2.js";import{Ia as Vm,J as lc,K as Nm,Y as Yo,ca as zm,fa as Km,ga as Xm,l as vm,w as xm,x as Sm,y as Em}from"./chunk-36RIIHPS.js";import{I as Ss,J as Ui,K as Wi,L as Es,M as _m,N as Go,P as zo,b as xs,fa as Jm,r as Co,s as cc,t as jm,u as dc,ua as Gm,w as Oo,wa as Ym,x as Fi}from"./chunk-N7IX77SL.js";import{b as En}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-X7UEV4O2.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{a as Rr,e as rp,f as ip,g as hc,i as ap,j as lp,l as cp,m as dp,n as up}from"./chunk-CUCIMPFI.js";import{f as Mm,g as Lm,h as uc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as Fm,f as Io,k as Rs}from"./chunk-IH65GDJR.js";import{a as Om,l as qm,o as Hm}from"./chunk-ERKK22QV.js";import{a as Ye,b as pe,c as Be,d as Ts,e as Um}from"./chunk-G3GFE3GK.js";import{a as Wm,b as gc,h as Bm}from"./chunk-3UOTLMXD.js";import"./chunk-XVV7ZZ77.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Im}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-LIY5CHUV.js";import{a as As}from"./chunk-GV7S5BAX.js";import{e as Dm}from"./chunk-GSX4NK2N.js";import{c as Pm}from"./chunk-SZDACK6O.js";import"./chunk-VWTBHLMX.js";import"./chunk-FCF47R4W.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as Rm,j as Tm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as ac,b as Cm}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as rc,p as $m,w as km}from"./chunk-7JWMLYOA.js";import{d as fm,e as Sn,f as hm,g as vs,j as ym,k as wm,m as bm,n as sc,r as Mi,s as It,t as Li}from"./chunk-XL7UWG36.js";import{a as uo}from"./chunk-MNG2AMKZ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-HPRLRD4P.js";import{a as ic}from"./chunk-XBFXSSHA.js";import"./chunk-DGCYMSXU.js";import{g as Jo,i as qi}from"./chunk-I722PWJE.js";import"./chunk-WPNRDEHW.js";import{c as Am}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-D3FIIEDR.js";import{a as Kl,b as _g,c as V0,d as Ci,e as Dg,f as am,g as aS,h as lm,i as lS,m as ks,n as dm,q as um,u as gm,y as co,z as Ar}from"./chunk-IXV3BPUZ.js";import{a as To,b as $s,e as sm,f as Er}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Pi,b as cm}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as pm}from"./chunk-BYEL7KKR.js";import{h as Ho,j as mm}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as lo,b as X0}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as Hg,B as Wg,C as Bg,Ca as Xg,D as eS,Ea as Vg,Fa as Qg,Lb as nc,M as Vl,N as tS,Ob as _i,Pb as xn,Qb as O,Tb as Di,Ua as Zg,X as ws,Y as Sr,Ya as nS,_b as Z,aa as Jg,ba as Ql,f as Oi,fb as em,g as Pg,ga as Gg,gb as vn,ha as oS,ib as ec,j as Pt,k as Xl,m as Mg,ma as Ni,n as Ii,na as ji,p as Q0,pb as tc,qa as zg,qb as oc,sa as Yg,sb as tm,ta as bs,tb as sS,ua as Zl,va as Kg,x as qg,y as Fg,z as Ug,zb as nm}from"./chunk-UWDDVDU6.js";import"./chunk-KEUW6YLL.js";import{j as Ve,r as Bo}from"./chunk-N47Y5ADQ.js";import{a as om,c as rS}from"./chunk-YSCT6DPR.js";import{a as Lg,e as Z0}from"./chunk-VQRY4IDI.js";import{g as rm,k as im,l as iS}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as cS}from"commander";var ky=new cS().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new Cp({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});Z();import{Command as dS}from"commander";import{execFileSync as mo}from"node:child_process";import{cpSync as vy,existsSync as Xc,mkdirSync as Yc,mkdtempSync as uS,readdirSync as gS,rmSync as xy,writeFileSync as Sy}from"node:fs";import{dirname as Ey,join as ft}from"node:path";import{homedir as ma,release as mS,tmpdir as pS}from"node:os";import{setTimeout as fS}from"node:timers/promises";function pa(){let e=qp(process.platform,process.arch,mS());if(e)throw new Error(e)}function fa(){let e=ft(ma(),"Library/LaunchAgents"),t=[];try{t=gS(e).filter(Wp)}catch{}let o=t.flatMap(n=>{let s=ft(e,n);try{return[{file:s,plist:mo("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Bp(e,o)}function Pr(e){return`gui/${process.getuid()}/${e.label}`}async function Kc(e){try{mo("launchctl",["bootout",Pr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{mo("launchctl",["print",Pr(e)],{stdio:"pipe"})}catch{return}await fS(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Ay(e){if(!Xc(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{mo("launchctl",["print",Pr(e)],{stdio:"pipe"})}catch{t=!1}t||mo("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),mo("launchctl",["kickstart",Pr(e)],{stdio:"pipe"})}function hS(){let e=Kp();if(e&&Xc(ft(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Ms=new dS("desktop").description("install and control the macOS desktop assistant");Ms.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{pa();let t=O(),o=Fp(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=hS(),i=ft(ma(),"Applications"),{keep:a,remove:l}=fa();if(console.log(`Desktop assistant \u2192 ${ft(i,zi)}
|
|
1
|
+
import{a as by,b as ga,g as $y}from"./chunk-QR3P5RG7.js";import{a as yy,b as wy}from"./chunk-SPXXLPAS.js";import{b as hy}from"./chunk-HY4PE6R3.js";import{$ as Kh,A as Dh,B as qh,C as Fh,E as Uh,G as Wh,H as Bh,I as Hc,J as Hh,U as Jh,V as Gh,W as Jc,X as zh,_ as Yh,aa as Xh,ba as Vh,ca as ty,da as oy,ea as ny,fa as sy,g as vh,ga as ry,h as xh,ha as iy,ja as Gc,ka as ay,l as Sh,la as ly,m as Eh,na as cy,o as Ds,p as Ps,q as Ah,qa as dy,r as Rh,ra as uy,s as Th,sa as gy,t as Ch,u as Oh,v as Ih,x as zt,z as _h}from"./chunk-2CO3NK6Z.js";import{a as Qh,c as Zh,d as ey}from"./chunk-FFOGEFPT.js";import{n as zc}from"./chunk-J2R47R56.js";import{a as my,b as py,d as Dr,e as fy}from"./chunk-IHFOW4JF.js";import"./chunk-EFGAPAYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as Nh,c as jh}from"./chunk-ZMGDHLZD.js";import"./chunk-WMZ4TGMR.js";import{d as Ph,e as Bc,h as Mh,i as Lh}from"./chunk-6UI7GJSB.js";import"./chunk-2YDG5CSS.js";import{b as jo}from"./chunk-7NQQIDDI.js";import{a as Uc}from"./chunk-LNY6N73E.js";import{a as xp,b as $c}from"./chunk-GMP2IB4E.js";import{a as fc,b as sp}from"./chunk-RKPAVWXF.js";import{$ as Jf,A as Ac,Aa as jr,B as bf,Ba as fh,C as Rc,Ca as pt,D as $f,Da as la,E as kf,Ea as ca,F as vf,Fa as _r,G as xf,Ga as Lc,H as Sf,Ha as hh,I as Ef,Ia as wh,J as Tc,Ja as Fc,K as Af,Ka as $h,L as ta,La as da,M as Rf,Ma as _s,N as Cc,Na as ua,O as Tf,Oa as Wc,P as Cf,Pa as kh,Q as Of,R as If,S as Nf,T as oa,U as Mf,V as Ff,W as Uf,X as Wf,Y as Bf,Z as Hf,_ as Ic,a as Tp,aa as Gf,b as Cp,ba as zf,ca as Yf,da as Kf,ea as Xf,fa as Vf,ga as Qf,h as Ji,ha as Zf,i as Os,ia as eh,j as jp,ja as ah,k as Cr,ka as ra,l as Gi,la as No,m as Dp,ma as Xo,n as Mp,na as Is,o as Qp,oa as ia,p as Zp,pa as aa,q as Qi,qa as Mc,r as Ec,ra as lh,s as af,sa as ch,t as mf,ta as dh,u as pf,ua as uh,v as ff,va as gh,w as hf,wa as mh,x as ea,xa as Ns,y as yf,ya as js,z as wf,za as ph}from"./chunk-UPWNWSK3.js";import{Ab as ih,Bb as Dc,Ib as Pc,N as lf,P as Or,Q as cf,T as df,U as Zi,Xb as yh,Yb as qc,_a as Ir,bb as Nc,cb as na,db as th,kb as Ko,kc as go,lb as oh,mb as jc,mc as bh,na as jf,oa as _f,ob as _c,pa as Df,qa as Oc,qb as nh,rb as sh,sb as Nr,t as Pp,ta as Pf,wb as sa,zb as rh}from"./chunk-WAVO3U3I.js";import"./chunk-GTJIKXDB.js";import{a as Op,c as vc,d as Tr,f as Ip,g as Np}from"./chunk-B7HDWFKR.js";import{A as Hp,B as Jp,C as Gp,D as zp,E as Yp,F as Kp,K as Ki,L as Xp,M as Vp,Q as uf,R as gf,a as mc,b as Qm,e as Zm,f as ep,o as Lp,s as zi,t as Yi,u as qp,v as Fp,w as Up,y as Wp,z as Bp}from"./chunk-7T5Y4H2J.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as Lf,b as qf}from"./chunk-EKJG63EJ.js";import"./chunk-PSYHAO57.js";import{c as ef}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import{c as Sc}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as tf,e as Xi,g as Vi}from"./chunk-LQE73AZR.js";import{a as of,b as nf,c as sf,d as rf}from"./chunk-2D3RYIDU.js";import{a as Lt}from"./chunk-ACPGDZOV.js";import"./chunk-MRIVENBY.js";import"./chunk-GJOKXP5D.js";import"./chunk-A5GYG56I.js";import{a as xc,p as _p}from"./chunk-JEBU5JUM.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Mt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import{a as gp,b as mp,c as pp,d as fp,e as yc,f as hp,g as wc,h as bc,l as yp,m as wp}from"./chunk-RX5O5637.js";import{f as bp,i as $p,l as kp,m as vp}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{m as Sp,n as Ep,o as kc,p as Hi,q as Ap,r as Rp}from"./chunk-35UGFFHA.js";import{a as pc,d as tp,e as Bi}from"./chunk-QPABR72X.js";import{b as Cs,e as np}from"./chunk-IFUAP7UD.js";import{c as op}from"./chunk-KP7KDLZ2.js";import{J as lc,K as Nm,Ka as Vm,Y as Yo,ca as zm,fa as Km,ga as Xm,l as vm,w as xm,x as Sm,y as Em}from"./chunk-EUJT7JT3.js";import{I as Ss,J as Ui,K as Wi,L as Es,M as _m,N as Go,P as zo,b as xs,fa as Jm,r as Co,s as cc,t as jm,u as dc,ua as Gm,w as Oo,wa as Ym,x as Fi}from"./chunk-FR4DTMCA.js";import{b as En}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-3JH3HUHX.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{a as Rr,e as rp,f as ip,g as hc,i as ap,j as lp,l as cp,m as dp,n as up}from"./chunk-H4DWZIU7.js";import{f as Mm,g as Lm,h as uc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as Fm,f as Io,k as Rs}from"./chunk-IH65GDJR.js";import{a as Om,l as qm,o as Hm}from"./chunk-CAH6TNC6.js";import{a as Ye,b as pe,c as Be,d as Ts,e as Um}from"./chunk-N476XZD3.js";import{a as Wm,b as gc,h as Bm}from"./chunk-3UOTLMXD.js";import"./chunk-XVV7ZZ77.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Im}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-LIY5CHUV.js";import{a as As}from"./chunk-GV7S5BAX.js";import{e as Dm}from"./chunk-GSX4NK2N.js";import{c as Pm}from"./chunk-SZDACK6O.js";import"./chunk-VWTBHLMX.js";import"./chunk-XHON5WB5.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as Rm,j as Tm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as ac,b as Cm}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as rc,p as $m,w as km}from"./chunk-NERO7F3J.js";import{d as fm,e as Sn,f as hm,g as vs,j as ym,k as wm,m as bm,n as sc,r as Mi,s as It,t as Li}from"./chunk-XL7UWG36.js";import{a as uo}from"./chunk-MNG2AMKZ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-HPRLRD4P.js";import{a as ic}from"./chunk-RMXG5GNW.js";import"./chunk-ZRBTLW2B.js";import{g as Jo,i as qi}from"./chunk-Z7632XS3.js";import"./chunk-WPNRDEHW.js";import{c as Am}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-JKMFKNGS.js";import{a as Kl,b as _g,c as V0,d as Ci,e as Dg,f as am,g as aS,h as lm,i as lS,m as ks,n as dm,q as um,u as gm,y as co,z as Ar}from"./chunk-MIUITI47.js";import{a as To,b as $s,e as sm,f as Er}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Pi,b as cm}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as pm}from"./chunk-BYEL7KKR.js";import{h as Ho,j as mm}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as lo,b as X0}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as Hg,$a as nS,B as Wg,C as Bg,Cb as nm,D as eS,Fa as Xg,Ha as Vg,Ia as Qg,M as Vl,N as tS,Ob as nc,Rb as _i,Sb as xn,Tb as O,Wb as Di,X as ws,Xa as Zg,Y as Sr,aa as Jg,ba as Ql,bc as Z,f as Oi,g as Pg,ib as em,j as Pt,ja as Gg,jb as vn,k as Xl,ka as oS,lb as ec,m as Mg,n as Ii,p as Q0,pa as Ni,qa as ji,sb as tc,ta as zg,tb as oc,va as Yg,vb as tm,wa as bs,wb as sS,x as qg,xa as Zl,y as Fg,ya as Kg,z as Ug}from"./chunk-KAM4ZWRE.js";import"./chunk-KEUW6YLL.js";import{j as Ve,r as Bo}from"./chunk-N47Y5ADQ.js";import{a as om,c as rS}from"./chunk-YSCT6DPR.js";import{a as Lg,e as Z0}from"./chunk-VQRY4IDI.js";import{g as rm,k as im,l as iS}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as cS}from"commander";var ky=new cS().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new Cp({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});Z();import{Command as dS}from"commander";import{execFileSync as mo}from"node:child_process";import{cpSync as vy,existsSync as Xc,mkdirSync as Yc,mkdtempSync as uS,readdirSync as gS,rmSync as xy,writeFileSync as Sy}from"node:fs";import{dirname as Ey,join as ft}from"node:path";import{homedir as ma,release as mS,tmpdir as pS}from"node:os";import{setTimeout as fS}from"node:timers/promises";function pa(){let e=qp(process.platform,process.arch,mS());if(e)throw new Error(e)}function fa(){let e=ft(ma(),"Library/LaunchAgents"),t=[];try{t=gS(e).filter(Wp)}catch{}let o=t.flatMap(n=>{let s=ft(e,n);try{return[{file:s,plist:mo("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Bp(e,o)}function Pr(e){return`gui/${process.getuid()}/${e.label}`}async function Kc(e){try{mo("launchctl",["bootout",Pr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{mo("launchctl",["print",Pr(e)],{stdio:"pipe"})}catch{return}await fS(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Ay(e){if(!Xc(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{mo("launchctl",["print",Pr(e)],{stdio:"pipe"})}catch{t=!1}t||mo("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),mo("launchctl",["kickstart",Pr(e)],{stdio:"pipe"})}function hS(){let e=Kp();if(e&&Xc(ft(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Ms=new dS("desktop").description("install and control the macOS desktop assistant");Ms.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{pa();let t=O(),o=Fp(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=hS(),i=ft(ma(),"Applications"),{keep:a,remove:l}=fa();if(console.log(`Desktop assistant \u2192 ${ft(i,zi)}
|
|
2
2
|
Computer-use helper \u2192 ${ft(i,Yi)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -39,7 +39,7 @@ ${o.map(n=>` ${n}`).join(`
|
|
|
39
39
|
`)}}}},schedules:{"support-evening-open-questions":{agent:"support",schedule:"0 18 * * 1-5",prompt:"List the questions in open-questions.md that are still open: customer, question, since when. Then a count of the questions you answered today from docs/. Six lines at most. If nothing is open, say so in one line.",timeout:600,maxOutputTokens:500,autonomy:"report"},"support-weekly-doc-gaps":{agent:"support",schedule:"0 16 * * 5",prompt:"Read this week's lines in open-questions.md. Group the questions by topic and, for each topic, say which document in docs/ should answer it next time and the one sentence to add. Five topics at most. If there were no open questions this week, say so in one line.",timeout:600,maxOutputTokens:600,autonomy:"report"}},channels:[{kind:"telegram",agent:"support",why:"where customers ask their questions"},{kind:"email",agent:"support",why:"optional: a support mailbox; each reply waits for your approval, with its source"}]};var Cw=[Sw,Tw,Ew,Aw,Rw];function Sa(){return Cw.map(e=>Bs(e))}function Vo(e){let t=Cw.find(o=>o.name===e);return t?Bs(t):void 0}Z();import{existsSync as NE,readFileSync as jE}from"fs";import{connect as _E}from"net";import{cpus as DE,loadavg as PE}from"os";import{basename as ME,resolve as LE}from"path";function Ea(e=process.argv[1]??"",t=process.env){let o=e.replace(/\\/g,"/");return t.npm_command==="exec"||o.includes("/_npx/")?"npx agentix-cli":ME(o)==="cli.js"&&!o.includes("/node_modules/")?"node dist/cli.js":"agentx"}function Nw(e,t){return t?` Every hop of this run is in the ledgers, one per node: \`${e} ledger events --cwd .agentx-demo/node-a\`.`:""}async function jw(e,t="127.0.0.1"){let o=await Promise.all(e.map(n=>new Promise(s=>{let r=_E({port:n,host:t}),i=a=>{r.destroy(),s(a)};r.setTimeout(1e3,()=>i(!1)),r.once("connect",()=>i(!0)),r.once("error",()=>i(!1))})));return e.filter((n,s)=>o[s])}var Ow="AGENTX_DEMO_STARTUP_TIMEOUT",qE=60,FE=300;function UE(e,t){let o=Math.max(1,e/Math.max(1,t));return Math.min(FE,Math.ceil(qE*o))}function Iw(e,t){if(e===void 0||e.trim()==="")return;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new Error(`${t} must be a positive number of seconds, got "${e}"`);return o}function _w(e){let t=LE(e,"agentx.json");if(!NE(t))return;let o;try{o=JSON.parse(jE(t,"utf8"))}catch{return}let n=_i.shape.demo.safeParse(o?.demo);if(!n.success)throw new Error(`${t}: demo.startupTimeoutSeconds must be a whole number of seconds (1\u20133600)`);return n.data.startupTimeoutSeconds}function Dw(e){let t=Iw(e.flag,"--startup-timeout");if(t!==void 0)return{seconds:t,source:"--startup-timeout"};let o=Iw(e.env,Ow);if(o!==void 0)return{seconds:o,source:Ow};if(e.config!==void 0)return{seconds:e.config,source:"demo.startupTimeoutSeconds"};let n=e.load1??PE()[0],s=e.cpuCount??DE().length;return{seconds:UE(n,s),source:`default for load ${n.toFixed(1)} on ${s} CPUs`}}import{Command as WE}from"commander";import ye from"chalk";import{cpSync as BE,existsSync as Js,mkdirSync as Pw,readFileSync as md,writeFileSync as HE}from"fs";import{dirname as gd,resolve as On}from"path";import{fileURLToPath as JE}from"url";var Mw=["claude-code","codex-cli","opencode","sdk","orchestrator"];function pd(e){let t=Ye(e);return Js(t)||(console.log(ye.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),{path:t,config:JSON.parse(md(t,"utf-8"))}}function Nt(e){console.log(ye.red(` ${e.split(`
|
|
40
40
|
`).join(`
|
|
41
41
|
`)}`)),process.exit(1)}function Lw(e){let t=On(e);Js(t)||Nt(`No file at ${t}`);let o;try{o=JSON.parse(md(t,"utf-8"))}catch(n){Nt(`${t} is not JSON: ${n.message}`)}try{return Bs(o)}catch(n){Nt(n.message)}}function GE(e){let t=Vo(e);if(t)return t;if(Js(On(e))||e.endsWith(".json"))return Lw(e);Nt(`No team named "${e}". Run: agentx team list`)}async function Aa(e,t){t.tier&&!Mw.includes(t.tier)&&Nt(`--tier must be one of: ${Mw.join(", ")}`);let{path:o,config:n}=pd(t.config),s=On(gd(o),t.workspaces??"agents"),r=Hs(n,e,{workspaceRoot:s,force:t.force});r.length&&Nt(`Already in this install: ${r.join(", ")}.
|
|
42
|
-
Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choose another --workspaces folder, or edit the package's ids.`);let i,a=await pe(d=>{i=bw(d,e,{workspaceRoot:s,tier:t.tier,provider:t.provider,timezone:t.timezone,force:t.force})},{configPath:o,dryRun:!!t.dryRun});(!a.success||!i)&&Nt(`Config save failed: ${a.error}`),console.log(),console.log(` ${ye.bold(e.title)}${t.dryRun?ye.yellow(" (dry run: nothing written)"):""}`),console.log(ye.dim(` ${e.result}`)),console.log();let l=[];if(!t.dryRun){let{setupWorkspace:d}=await import("./workspace-setup-
|
|
42
|
+
Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choose another --workspaces folder, or edit the package's ids.`);let i,a=await pe(d=>{i=bw(d,e,{workspaceRoot:s,tier:t.tier,provider:t.provider,timezone:t.timezone,force:t.force})},{configPath:o,dryRun:!!t.dryRun});(!a.success||!i)&&Nt(`Config save failed: ${a.error}`),console.log(),console.log(` ${ye.bold(e.title)}${t.dryRun?ye.yellow(" (dry run: nothing written)"):""}`),console.log(ye.dim(` ${e.result}`)),console.log();let l=[];if(!t.dryRun){let{setupWorkspace:d}=await import("./workspace-setup-PIPGUMLG.js"),p=zE();for(let f of i.agents){Pw(f.workspace,{recursive:!0}),d(f.id,a.after&&a.after.agents[f.id],"19900",()=>{});let g=On(f.workspace,".claude/skills/wiki/SKILL.md");p&&f.tier==="claude-code"&&!Js(g)&&(Pw(gd(g),{recursive:!0}),BE(p,g,{errorOnExist:!0,force:!1}))}l=kw(e,i).kept}let c=t.dryRun?void 0:Fi(Co(),i.agents.map(d=>d.id));for(let d of i.agents){let p=d.skills.length?ye.dim(` skills: ${d.skills.join(", ")}`):"";console.log(` ${ye.green("+")} agent ${ye.cyan(d.id)} (${d.tier})${p}`),console.log(ye.dim(` ${d.workspace}`))}for(let d of i.schedules){let p=a.after.crons[d];console.log(` ${ye.green("+")} schedule ${ye.cyan(d)} \u2014 ${p.schedule} (${p.timezone})${p.enabled?"":ye.dim(" disabled")}`)}if(a.reloaded&&console.log(ye.dim(" (daemon hot-reloaded)")),c&&console.log(ye.yellow(` Added by agent "${c}": these agents start once the owner approves each one (agentx approvals list).`)),l.length){console.log(ye.yellow(` Kept ${l.length} file${l.length===1?"":"s"} already there instead of the team's version:`));for(let d of l)console.log(ye.dim(` ${d}`))}if(i.channels.length){console.log(),console.log(ye.bold(" One step left: connect the channel"));let d=[...new Set(i.channels.map(p=>p.kind))];for(let p of d){let f=i.channels.filter(g=>g.kind===p);console.log(` ${f[0].step}`);for(let g of f)g.why&&console.log(ye.dim(` ${g.agent}: ${g.why}`))}}let{delivery:u}=i;u.schedules.length&&(console.log(),u.to?console.log(` Results go to you on ${u.to.channel} (${u.to.chatId}): ${u.schedules.join(", ")}`):(console.log(ye.bold(" Then tell AgentX where to send you the results")),console.log(` ${u.schedules.join(", ")} will send ${u.schedules.length===1?"its":"their"} answers once you do one of these:`),console.log(` agentx connect telegram ${ye.dim("(say yes when it offers to listen for your first message)")}`),console.log(` agentx team notify ${e.name} telegram:<chat id>`))),console.log()}function zE(){return[On(process.cwd(),"src/wiki/SKILL.md"),On(gd(JE(import.meta.url)),"../wiki/SKILL.md")].find(t=>Js(t))??null}var In=new WE().name("team").description("ready-made teams \u2014 list, add one in one step, export and import");In.command("list").alias("ls").description("list the teams you can add, and the teams installed here").option("-c, --config <path>","path to agentx.json").action(e=>{let t=Ye(e.config),o=Js(t)?JSON.parse(md(t,"utf-8")):{},n=new Set(Object.values(o.agents||{}).map(r=>r?.team).filter(Boolean));console.log(),console.log(ye.bold(" Teams you can add"));for(let r of Sa()){let i=n.has(r.name)?ye.green(" installed"):"";console.log(` ${ye.cyan(r.name)} \u2014 ${r.title}${i}`),console.log(ye.dim(` ${r.result}`))}let s=[...n].filter(r=>!Vo(r)).sort();if(s.length){console.log(),console.log(ye.bold(" Other teams installed here"));for(let r of s)console.log(` ${ye.cyan(r)} \u2014 ${Cn(o,r).join(", ")}`)}console.log(),console.log(ye.dim(" Add one: agentx team add <name>")),console.log()});In.command("add <name>").description("add a team: its agents, skills and schedules. <name> is a team from `team list` or a package file").option("--tier <tier>","runtime for every agent of the team (default: the package's, else claude-code)").option("--timezone <tz>","time zone for schedules that do not set one (default: this machine's)").option("--workspaces <dir>","folder for the agents' workspaces, next to agentx.json","agents").option("--force","use workspace folders that already exist; files in them are never overwritten").option("--dry-run","show what would be added, write nothing").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Aa(GE(e),t)});In.command("import <file>").description("add a team from a package file made by `team export`").option("--tier <tier>","runtime for every agent of the team (default: the package's, else claude-code)").option("--timezone <tz>","time zone for schedules that do not set one (default: this machine's)").option("--workspaces <dir>","folder for the agents' workspaces, next to agentx.json","agents").option("--force","use workspace folders that already exist; files in them are never overwritten").option("--dry-run","show what would be added, write nothing").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Aa(Lw(e),t)});In.command("notify <name> [target]").description(`send the answers of a team's schedules to you. [target]: "me" (notifications.destination, the default) or "channel:chatId[:accountId]"`).option("-c, --config <path>","path to agentx.json").action(async(e,t,o)=>{let{path:n,config:s}=pd(o.config),r=Cn(s,e);r.length||Nt(`No agents belong to team "${e}". Run: agentx team list`);let i=YE(t??"me",s),a=Object.entries(s.crons||{}).filter(([,u])=>r.includes(u?.agent)&&u.deliverResult===!0).map(([u])=>u);a.length||Nt(`Team "${e}" has no schedules that report to you.`);let l=[],c=await pe(u=>{l=xa(u,i,{ids:a,replace:!0})},{configPath:n});c.success||Nt(`Config save failed: ${c.error}`),console.log(ye.green(` Results of ${l.join(", ")} now go to ${i.channel} (${i.chatId})`)),c.reloaded&&console.log(ye.dim(" (daemon hot-reloaded)"))});function YE(e,t){if(e==="me"){let r=ud(t);return r||Nt('No notifications.destination yet. Run: agentx connect telegram, or give "channel:chatId".'),r}let[o,n,s]=e.split(":");return(!o||!n)&&Nt(`Not a target: ${e} (use "me" or "channel:chatId[:accountId]")`),s?{channel:o,chatId:n,accountId:s}:{channel:o,chatId:n}}In.command("export <name>").description("write a team to one file you can share: agents, prompts, skills, schedules, channel kinds. No channel config, tokens checked").option("-o, --output <file>","file to write; - prints it (default: <name>.team.json)").option("--agents <ids...>","agents to export (default: the agents installed with this team)").option("--title <text>","title shown in `team list`").option("--result <text>","one line: the result this team delivers").option("--description <text>","a few lines on how the team works").option("-c, --config <path>","path to agentx.json").action((e,t)=>{let{config:o}=pd(t.config),n=Vo(e),s;try{s=vw(o,e,{agents:t.agents,title:t.title??n?.title,result:t.result??n?.result,description:t.description??n?.description,expectedChannels:n?.channels})}catch(c){Nt(c.message)}let r=JSON.stringify(s,null,2)+`
|
|
43
43
|
`;if(t.output==="-"){process.stdout.write(r);return}let i=On(t.output??`${e}.team.json`);HE(i,r);let a=Object.keys(s.agents).length,l=Object.keys(s.schedules).length;console.log(ye.green(` Team "${e}" written to ${i}`)),console.log(ye.dim(` ${a} agent${a===1?"":"s"}, ${l} schedule${l===1?"":"s"}; no chat ids, contacts, routes or commands`)),console.log(ye.dim(" Common token formats were checked; read the prompts and skills for passwords before you share it.")),console.log(ye.dim(` On the other install: agentx team import ${i.split("/").pop()}`))});import{existsSync as KE}from"fs";import{resolve as qw}from"path";var fd="assistant";function Fw(e){for(let t of[qw(e,"agentx.json"),qw(e,".agentx/config.json")])if(KE(t))return t;return null}function Uw(e,t){return{nodeName:e.trim()||"My team",agent:{id:fd,name:"Assistant",triggerWords:`@${fd}, ${fd}`,...t?{tier:"claude-code"}:{tier:"orchestrator",provider:"claude"}}}}function hd(e){let t=Object.keys(e.agents||{}),o=e.node?.defaultAgent;return o&&t.includes(o)?o:t[0]??null}function Ww(e){return`http://${e.replace(/^0\.0\.0\.0(?=:)/,"127.0.0.1").replace(/^\[::\](?=:)/,"127.0.0.1")}`}function Bw(e){return Ww(e.node?.bind||"127.0.0.1:18800")}function yd(e){return Ww(`${e.dashboard?.bind||"127.0.0.1"}:${e.dashboard?.port||4202}`)}function Hw(e,t){return`${yd(e)}/admin/agents/${encodeURIComponent(t)}#chat`}function Jw(e,t){let o=e?.node?.id;return!o||!t.node?.id||o===t.node.id}function Gw(e,t,o){let n=Vo(t);if(!n)return{error:`No team named "${t}".`};if(Cn(e,n.name).length)return{skip:`Team ${n.name} is already added (left as it is)`};let s=o?.workspaceRoot?Hs(e,n,{workspaceRoot:o.workspaceRoot}):Hs(e,n);if(s.length)return{error:`Team ${n.name} can't be added: already in this folder: ${s.join(", ")}. Remove or rename them, or run start without --team.`};let r=e.agents?.[hd(e)??""];return{add:{team:n.name,tier:r?.tier,provider:r?.provider}}}var eb=new XE().name("start").description("one command to a working agent: config, daemon, dashboard, and the chat in your browser").option("--port <n>","daemon port for a new install (default 18800; an existing agentx.json keeps its own)").option("--dashboard-port <n>","dashboard port for a new install (default 4202)").option("--startup-timeout <seconds>","seconds the daemon and the dashboard each may take to answer","60").option("--team <name>","also add a ready-made team (see `agentx team list`); a first run in a terminal asks").option("--no-open","don't open the browser").action(async e=>{let t=process.cwd(),o=Ea(),n=process.argv[1];(!n||!zw(n))&&Nn("Cannot resolve the agentx CLI entrypoint. Run it as `agentx start` or `npx agentix-cli start`.");let s=Math.max(1,Number(e.startupTimeout)||60)*1e3;console.log(),console.log(it.bold(" agentx start"));let r=Fw(t),i=!r,a=i?Uw(oA().replace(/\.local$/,""),!!Pc("claude")):void 0,l=e.team??(i&&process.stdin.isTTY&&process.stdout.isTTY?await sA():void 0),c=l?Gw(r?JSON.parse(Yw(r,"utf-8")):{agents:{[a.agent.id]:a.agent}},l,{workspaceRoot:Ta(r?nA(r):t,"agents")}):void 0;c&&"error"in c&&Nn(`${c.error} See \`${o} team list\`.`),r?console.log(it.dim(` Using ${r} (left as it is)`)):(xh(a,t,{daemonPort:Kw(e.port,"--port"),dashboardPort:Kw(e.dashboardPort,"--dashboard-port")}),r=Ta(t,"agentx.json"),console.log(it.green(` \u2713 Created agentx.json with one agent, ${a.agent.id} (engine: ${a.agent.tier})`)));let u=!1;c&&"skip"in c&&console.log(it.dim(` ${c.skip}`)),c&&"add"in c&&(await Aa(Vo(c.add.team),{config:r,tier:c.add.tier,provider:c.add.provider}),u=!0);let d;try{d=O(r)}catch(S){Nn(`${r}: ${S.message}`)}let p=hd(d);p||Nn(`No agent in ${r}. Add one with \`${o} setup\`, then run \`${o} start\` again.`);let f=Ta(t,".agentx");ZE(f,{recursive:!0});let g=Bw(d),h=await Vw(g);if(h&&!Jw(h,d)&&Nn(`${g} is another AgentX install (${h.node?.name||h.node?.id}). Run this one on another port: set node.bind in ${r}, or for a new folder use \`${o} start --port 18810 --dashboard-port 4212\`.`),h)console.log(it.green(` \u2713 Daemon already running at ${g}`)),u&&console.log(it.yellow(` Restart it to start the team's agents: ${o} daemon restart`));else{let S=Ra(f,"daemon.log");Xw(n,["daemon","start","-c",r],t,S),await Zw(`the daemon at ${g}`,async()=>!!await Vw(g),s,S),console.log(it.green(` \u2713 Daemon started at ${g}`)+it.dim(` (log: ${S})`))}let y=yd(d);if(await Qw(`${y}/live`))console.log(it.green(` \u2713 Dashboard already running at ${y}`));else{let S=Ra(f,"board.log"),k=Xw(n,["board","serve"],t,S);k&&tA(Ra(f,"board.pid"),String(k)),await Zw(`the dashboard at ${y}`,()=>Qw(`${y}/live`),s,S),console.log(it.green(` \u2713 Dashboard started at ${y}`)+it.dim(` (log: ${S})`))}let w=Hw(d,p),$=d.agents[p]?.name||p,x=Sh({rawConfig:JSON.parse(Yw(r,"utf-8")),agentId:p,env:process.env,dotenv:pm(Ta(t,".env")),hasBinary:S=>!!Pc(S),cliLoggedIn:Eh});console.log(),x.ready?console.log(it.bold(` Your first agent, ${$}, is answering at ${it.cyan(w)}`)):(console.log(it.bold(` Your first agent, ${$}, is waiting for a model at ${it.cyan(w)}`)),x.hint&&console.log(` ${x.hint}`)),console.log(it.dim(` Run \`${o} start\` again any time: it reuses what is running.`));let v=Ra(f,"board.pid");console.log(it.dim(` Stop the daemon: ${o} daemon stop`+(zw(v)?" \xB7 the dashboard: kill $(cat .agentx/board.pid)":""))),console.log(),e.open!==!1&&jo(w)});async function sA(){let{team:e}=await VE({type:"select",name:"team",message:"Start with a ready-made team as well?",choices:[{title:"No, one assistant for now",value:""},...Sa().map(t=>({title:`${t.name}: ${t.title}`,description:t.result,value:t.name}))],initial:0});return e||void 0}function Nn(e){console.error(it.red(` ${e}`)),process.exit(1)}function Kw(e,t){if(e===void 0)return;let o=Number(e);return(!Number.isInteger(o)||o<1||o>65535)&&Nn(`${t} must be a port number, got "${e}"`),o}function Xw(e,t,o,n){let s=eA(n,"a"),r=QE(process.execPath,[e,...t],{cwd:o,detached:!0,stdio:["ignore",s,s]});return r.unref(),r.pid}async function Vw(e){try{let t=await fetch(`${e}/health`,{signal:AbortSignal.timeout(3e3)});return t.ok?await t.json().catch(()=>({})):null}catch{return null}}async function Qw(e){try{return(await fetch(e,{signal:AbortSignal.timeout(3e3)})).ok}catch{return!1}}async function Zw(e,t,o,n){let s=Date.now()+o;for(;Date.now()<s;){if(await t())return;await new Promise(r=>setTimeout(r,400))}Nn(`Timed out after ${o/1e3}s waiting for ${e}. See ${n}, or raise --startup-timeout.`)}import{Command as rA}from"commander";import et from"chalk";var Hr=new rA().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Hr.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let t=new Mt,o=String(e.scope).split(",").map(i=>i.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:r}=t.create({name:e.name,scopes:o,expiresInDays:n});console.log(),console.log(et.bold(" Token created.")),console.log(),console.log(` id: ${et.cyan(r.id)}`),console.log(` name: ${r.name}`),console.log(` scopes: ${r.scopes.join(", ")}`),console.log(` expires: ${r.expiresAt||et.dim("never")}`),console.log(),console.log(et.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${et.green.bold(s)}`),console.log(),console.log(et.dim(" Use it via the Authorization header:")),console.log(et.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(t){console.log(et.red(` ${t.message}`)),process.exit(1)}});Hr.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new Mt().list();if(e.length===0){console.log(et.dim(`
|
|
44
44
|
No tokens issued.
|
|
45
45
|
`));return}console.log();for(let t of e){let o=t.revokedAt?et.red("revoked"):t.expiresAt&&Date.parse(t.expiresAt)<Date.now()?et.red("expired"):et.green("active");console.log(` ${et.cyan(t.id)} ${o} ${t.name}`),console.log(et.dim(` prefix: ${t.prefix}\u2026 scopes: ${t.scopes.join(", ")}`)),console.log(et.dim(` created: ${t.createdAt}${t.expiresAt?` expires: ${t.expiresAt}`:""}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(et.red(` ${e.message}`)),process.exit(1)}});Hr.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let t=new Mt().revoke(e);t||(console.log(et.red(` Token ${e} not found.`)),process.exit(1)),console.log(et.green(`
|
|
@@ -62,10 +62,10 @@ Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choos
|
|
|
62
62
|
`))});po.command("unpin <id-or-label>").description("remove a pinned page from the phone app").action(e=>{let{store:t}=wd(),o=t.list().find(s=>s.id===e||s.label.toLowerCase()===e.toLowerCase());o||(console.log(se.red(` No pinned page ${e}. See: agentx app pins`)),process.exit(1));let n=t.remove(o.id);n.ok||(console.log(se.red(` ${n.error}`)),process.exit(1)),console.log(se.green(`
|
|
63
63
|
\u2713 Removed ${o.label}.
|
|
64
64
|
`))});function sb(e){let t=Ve();return t||(console.log(se.red(" The database (.agentx/db.sqlite) can't be opened here.")),process.exit(1)),e(new Uc(t))}function cA(){let e=Ve({quiet:!0});if(!e)return[];let t=new Map;for(let o of new Uc(e).list()){if(!Sc(o.deviceId))continue;let n=t.get(o.deviceId)??{deviceId:o.deviceId,deviceName:o.deviceName,createdAt:o.createdAt,subscriptions:0};n.subscriptions++,n.createdAt=Math.max(n.createdAt,o.createdAt),t.set(o.deviceId,n)}return[...t.values()]}function dA(e){let t=Math.round(tf/6e4),o=[` Pairing code: ${se.bold.cyan(Xi(e.code))}`,se.dim(` Open the app from the phone's home screen and type this code. It works once, for ${t} minutes.`)," Or scan the QR code with the phone's camera and open the link.",` Device ${se.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,se.yellow(" \u26A0 Anyone who scans the QR code or types the code can use the app. Clear the terminal when done.")];return e.origin.startsWith("https://")||o.push(se.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),o}function bd(){let e;try{e=JSON.parse(nb("tailscale",["status","--json"],{encoding:"utf-8",timeout:5e3}))}catch{throw new Error("Could not read this machine's Tailscale name. Is Tailscale running? Or pass --url https://<address>.")}let t=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!t)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${t}`}var uA=new Set(["/app","/api/app","/member","/api/member"]),ob="/.well-known/assetlinks.json";function gA(){let e=new Set(["localhost","0.0.0.0","::","::1"]);try{let t=aA().toLowerCase().replace(/\.$/,"");t&&e.add(t).add(t.replace(/\.local$/,"")).add(`${t.replace(/\.local$/,"")}.local`)}catch{}try{for(let t of Object.values(lA()))for(let o of t??[])e.add(rb(o.address.toLowerCase().replace(/%.*$/,"")))}catch{}return e}var mA={http:80,https:443,"https+insecure":443};function pA(e){let t=e.match(/^(\d+)(\/[^?#]*)?$/);if(t)return{host:"localhost",port:Number(t[1]),path:t[2]??""};let o=e.match(/^(?:([a-z][a-z0-9+.-]*):\/\/)?(?:[^@/?#]*@)?(\[[^\]]*\]|[^/:?#]*)(?::(\d+))?([^?#]*)/i);if(!o)return null;let n=o[3]?Number(o[3]):mA[(o[1]??"http").toLowerCase()];return n?{host:rb(o[2].replace(/^\[|\]$/g,"").replace(/%.*$/,"").replace(/\.$/,"").toLowerCase()),port:n,path:o[4]}:null}function rb(e){let t=e.includes(":");if(!t&&!/^[0-9a-fx.]+$/.test(e))return e;let o;try{o=new URL(`http://${t?`[${e}]`:e}/`).hostname.replace(/^\[|\]$/g,"")}catch{return e}let n=o.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);if(!n)return o;let[s,r]=[parseInt(n[1],16),parseInt(n[2],16)];return`::ffff:${s>>8}.${s&255}.${r>>8}.${r&255}`}function fA(e,t){let o=e.replace(/^::ffff:/,"");return t.has(e)||t.has(o)||e===""||e.endsWith(".localhost")||/^127\.\d+\.\d+\.\d+$/.test(o)||o==="0.0.0.0"}function $d(e,t,o=gA()){let n=[e,...Object.values(e?.Foreground??{})],s=[];for(let l of n){s.push({label:"",cfg:l});for(let[c,u]of Object.entries(l?.Services??{}))s.push({label:`${c} `,cfg:u})}let r=new Set(o);for(let{cfg:l}of s){for(let c of Object.keys(l?.Web??{}))r.add(c.replace(/:\d+$/,"").replace(/\.$/,"").toLowerCase());for(let c of Object.values(l?.TCP??{}))c?.TerminateTLS&&r.add(String(c.TerminateTLS).replace(/\.$/,"").toLowerCase())}let i=l=>{let c=pA(l.trim());return c&&c.port===t&&fA(c.host,r)?c:null},a=[];for(let{label:l,cfg:c}of s){for(let[u,d]of Object.entries(c?.Web??{}))for(let[p,f]of Object.entries(d?.Handlers??{})){if(f?.Proxy==null)continue;let g=i(String(f.Proxy));if(!g)continue;let h=p.replace(/\/+$/,"")||"/",y=h===ob&&g.path===ob;!uA.has(h)&&!y&&a.push(`${l}${u}${p}`)}for(let[u,d]of Object.entries(c?.TCP??{}))d?.TCPForward==null||!i(String(d.TCPForward))||a.push(`${l}TCP port ${u}`)}return a}function kd(){try{return JSON.parse(nb("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Jr(){try{return O().dashboard.port||4202}catch{return 4202}}Z();import{Command as ho}from"commander";import b from"chalk";import at from"prompts";import{readFileSync as Zo,writeFileSync as Gs,existsSync as Ke,mkdirSync as fo,cpSync as xd,readdirSync as hA}from"fs";import{resolve as le,join as Qo,dirname as yA}from"path";import{fileURLToPath as wA}from"url";import{Command as ab}from"commander";import jn from"chalk";Z();tc();var ib=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function _n(e){console.error(jn.red(` ${e}`)),process.exitCode=1}function lb(e,t){let o;try{o=O()}catch(s){return _n(`${s.message.split(`
|
|
65
|
-
`)[0]}. Run this from the folder that holds agentx.json.`),!1}let n=e==="agent"?!!o.agents?.[t]:t===vn||(o.people??[]).some(s=>s.id===t);return n||_n(e==="agent"?`No agent "${t}" in agentx.json.`:`No person "${t}" in agentx.json: agentx people list`),n}async function cb(e,t,o){if(lb(e,t))try{await kp(process.cwd(),e,t,xp(o)),console.log(jn.green(` \u2713 picture set for ${e} "${t}". Pages show it on their next load.`))}catch(n){if(n instanceof bp){_n(n.message);return}throw n}}function db(e,t){lb(e,t)&&console.log(vp(process.cwd(),e,t)?jn.green(` \u2713 picture removed for ${e} "${t}"; the initials show again.`):jn.dim(` ${e} "${t}" has no picture.`))}function vd(e){let t=e.agent?.trim()||Oo();return t||_n("Say which agent: --agent <id>"),t}function ub(){let e=new ab("picture").description("an agent's profile picture: set, remove or show (an agent may set its own)");return e.command("set <file>").description("set the picture from a PNG, JPEG or WebP file (1 MB at most); it is cut to a square, metadata dropped").option("--agent <id>","which agent (default: the agent running this command)").action(async(t,o)=>{if(Oo()){let s=await $c(t,o.agent?.trim(),{daemonUrl:ib()});return s.ok?console.log(jn.green(` \u2713 ${s.message}`)):_n(s.message)}let n=vd(o);n&&await cb("agent",n,t)}),e.command("remove").alias("rm").description("remove the picture: the initials show again").option("--agent <id>","which agent (default: the agent running this command)").action(async t=>{if(Oo()){let n=await $c(null,t.agent?.trim(),{daemonUrl:ib()});return n.ok?console.log(jn.green(` \u2713 ${n.message}`)):_n(n.message)}let o=vd(t);o&&db("agent",o)}),e.command("show").description("say whether the agent has a picture").option("--agent <id>","which agent (default: the agent running this command)").action(t=>{let o=vd(t);if(!o)return;let n=$p(process.cwd(),"agent",o);console.log(n?` ${o}: picture set (.agentx/pictures/agent/${o}.${n}.webp)`:jn.dim(` ${o}: no picture, the initials show`))}),e}function gb(){let e=new ab("picture").description("a person's profile picture: set or remove (the owner only)"),t=()=>{let o=Oo();return o&&_n(`Only the owner sets a person's picture; agent "${o}" asked.`),!o};return e.command("set <id> <file>").description("set the picture from a PNG, JPEG or WebP file (1 MB at most); it is cut to a square, metadata dropped").action(async(o,n)=>{t()&&await cb("person",o,n)}),e.command("remove <id>").alias("rm").description("remove the picture: the initials show again").action(o=>{t()&&db("person",o)}),e}function Se(){let e=le(process.cwd(),"agentx.json");if(!Ke(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Zo(e,"utf-8"))}function gt(e){return pe(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(b.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(b.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(b.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var yo=new ho().name("agent").description("manage agents \u2014 add, list, remove, pause, resume");yo.command("list").alias("ls").description("list configured agents").action(()=>{let e=Se();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${b.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(b.dim(` workspace: ${o.workspace}`)),n&&console.log(b.dim(` mentions: ${n}`))}console.log()});yo.command("add").description("add a new agent interactively").action(async()=>{let e=Se(),t=await at([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:u=>/^[a-z0-9-]+$/.test(u)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:le(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!t.id)return;let o=t.workspace.endsWith(t.id)?t.workspace:Qo(t.workspace,t.id);fo(le(o,".claude/skills"),{recursive:!0});let n={name:t.name,workspace:o,tier:t.tier,model:t.model,mentions:t.mentions?.map(u=>u.trim()).filter(Boolean)||[],maxConcurrent:t.maxConcurrent,systemPrompt:t.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-
|
|
65
|
+
`)[0]}. Run this from the folder that holds agentx.json.`),!1}let n=e==="agent"?!!o.agents?.[t]:t===vn||(o.people??[]).some(s=>s.id===t);return n||_n(e==="agent"?`No agent "${t}" in agentx.json.`:`No person "${t}" in agentx.json: agentx people list`),n}async function cb(e,t,o){if(lb(e,t))try{await kp(process.cwd(),e,t,xp(o)),console.log(jn.green(` \u2713 picture set for ${e} "${t}". Pages show it on their next load.`))}catch(n){if(n instanceof bp){_n(n.message);return}throw n}}function db(e,t){lb(e,t)&&console.log(vp(process.cwd(),e,t)?jn.green(` \u2713 picture removed for ${e} "${t}"; the initials show again.`):jn.dim(` ${e} "${t}" has no picture.`))}function vd(e){let t=e.agent?.trim()||Oo();return t||_n("Say which agent: --agent <id>"),t}function ub(){let e=new ab("picture").description("an agent's profile picture: set, remove or show (an agent may set its own)");return e.command("set <file>").description("set the picture from a PNG, JPEG or WebP file (1 MB at most); it is cut to a square, metadata dropped").option("--agent <id>","which agent (default: the agent running this command)").action(async(t,o)=>{if(Oo()){let s=await $c(t,o.agent?.trim(),{daemonUrl:ib()});return s.ok?console.log(jn.green(` \u2713 ${s.message}`)):_n(s.message)}let n=vd(o);n&&await cb("agent",n,t)}),e.command("remove").alias("rm").description("remove the picture: the initials show again").option("--agent <id>","which agent (default: the agent running this command)").action(async t=>{if(Oo()){let n=await $c(null,t.agent?.trim(),{daemonUrl:ib()});return n.ok?console.log(jn.green(` \u2713 ${n.message}`)):_n(n.message)}let o=vd(t);o&&db("agent",o)}),e.command("show").description("say whether the agent has a picture").option("--agent <id>","which agent (default: the agent running this command)").action(t=>{let o=vd(t);if(!o)return;let n=$p(process.cwd(),"agent",o);console.log(n?` ${o}: picture set (.agentx/pictures/agent/${o}.${n}.webp)`:jn.dim(` ${o}: no picture, the initials show`))}),e}function gb(){let e=new ab("picture").description("a person's profile picture: set or remove (the owner only)"),t=()=>{let o=Oo();return o&&_n(`Only the owner sets a person's picture; agent "${o}" asked.`),!o};return e.command("set <id> <file>").description("set the picture from a PNG, JPEG or WebP file (1 MB at most); it is cut to a square, metadata dropped").action(async(o,n)=>{t()&&await cb("person",o,n)}),e.command("remove <id>").alias("rm").description("remove the picture: the initials show again").action(o=>{t()&&db("person",o)}),e}function Se(){let e=le(process.cwd(),"agentx.json");if(!Ke(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Zo(e,"utf-8"))}function gt(e){return pe(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(b.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(b.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(b.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var yo=new ho().name("agent").description("manage agents \u2014 add, list, remove, pause, resume");yo.command("list").alias("ls").description("list configured agents").action(()=>{let e=Se();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${b.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(b.dim(` workspace: ${o.workspace}`)),n&&console.log(b.dim(` mentions: ${n}`))}console.log()});yo.command("add").description("add a new agent interactively").action(async()=>{let e=Se(),t=await at([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:u=>/^[a-z0-9-]+$/.test(u)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:le(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!t.id)return;let o=t.workspace.endsWith(t.id)?t.workspace:Qo(t.workspace,t.id);fo(le(o,".claude/skills"),{recursive:!0});let n={name:t.name,workspace:o,tier:t.tier,model:t.model,mentions:t.mentions?.map(u=>u.trim()).filter(Boolean)||[],maxConcurrent:t.maxConcurrent,systemPrompt:t.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-PIPGUMLG.js"),r=s(t.id,n,"19900",(...u)=>{console.log(b.dim(` ${u.join(" ")}`))}),i=le(process.cwd(),"src/wiki/SKILL.md"),a=le(yA(wA(import.meta.url)),"../wiki/SKILL.md"),l=Ke(i)?i:a;Ke(l)&&(fo(le(o,".claude/skills/wiki"),{recursive:!0}),xd(l,le(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await gt(e),console.log(b.green(`
|
|
66
66
|
Agent "${t.id}" added`)),console.log(b.dim(` Workspace: ${o}`)),console.log(b.dim(` Created: ${r.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`));let c=Fi(Co(),[t.id]);c&&console.log(b.yellow(` Created by agent "${c}": it starts once the owner approves it (agentx approvals approve agent:${t.id}).`)),console.log()});yo.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=Se();if(!t.agents?.[e]){console.log(b.red(` Agent "${e}" not found`));return}delete t.agents[e],await gt(t),dc(Co(),e),console.log(b.green(` Agent "${e}" removed from config (workspace preserved)`))});yo.addCommand(ub());function mb(e){let t=Oo();return t?(console.log(b.red(` Only the owner can ${e}; agent "${t}" asked. Ask the owner, or raise a card.`)),process.exitCode=1,!1):!0}yo.command("pause <id>").description("pause an agent: it starts no run until resumed (applies at once)").action(e=>{if(mb("pause an agent")){if(!Se().agents?.[e]){console.log(b.red(` Agent "${e}" not found`)),process.exitCode=1;return}if(cc(Co())[e]?.kind==="approval"){console.log(b.yellow(` "${e}" waits for your approval and does not run yet: agentx approvals list`));return}jm(Co(),e,"paused","the owner"),console.log(b.green(` "${e}" paused. Messages and schedules for it are refused until you run: agentx agent resume ${e}`))}});yo.command("resume <id>").description("resume a paused agent").action(e=>{if(!mb("resume an agent"))return;let t=cc(Co())[e];if(t?.kind==="approval"){console.log(b.yellow(` "${e}" was created by ${t.by} and waits for your approval: agentx approvals approve agent:${e}`));return}console.log(dc(Co(),e,"paused")?b.green(` "${e}" resumed`):b.dim(` "${e}" was not paused`))});yo.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,t)=>{let o=Se(),n=o.agents?.[e];if(n||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log(b.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):b.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":b.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||b.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(t.intents!==void 0&&(t.intents==="-"||t.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(t.intents).split(",").map(r=>r.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),t.maxDelegationDepth!==void 0){let r=parseInt(t.maxDelegationDepth,10);(!Number.isFinite(r)||r<0||r>50)&&(console.log(b.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=r,s.push(`maxDelegationDepth=${r}`)}if(t.contextReferences!==void 0){let r=String(t.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(r)||(console.log(b.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=r==="true"||r==="on"||r==="1",s.push(`contextReferences=${n.contextReferences}`)}if(t.contextStrategy!==void 0&&(t.contextStrategy==="-"||t.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(t.contextStrategy)?(n.contextStrategy=t.contextStrategy,s.push(`contextStrategy=${t.contextStrategy}`)):(console.log(b.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),t.maxExecutionMinutes!==void 0){let r=parseInt(t.maxExecutionMinutes,10);(!Number.isFinite(r)||r<1||r>240)&&(console.log(b.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=r,s.push(`maxExecutionMinutes=${r}`)}s.length===0&&(console.log(b.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await gt(o),console.log(b.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(b.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var en=new ho().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");en.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,t)=>{let n=Se().agents?.[e];n||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(t.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(b.dim(`
|
|
67
67
|
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
68
|
-
`));return}console.log(),console.log(b.bold(` ${e}`));for(let r of s){let i=r.enabled!==!1,a=[],l=r.credentials??{};for(let[u,d]of Object.entries(l))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?b.green(`${u}:${d}=set`):b.yellow(`${u}:${d}=UNSET`)):u==="auth"&&d==="keyring"?a.push(b.dim("auth:keyring")):u==="sessionDir"&&typeof d=="string"&&a.push(b.dim(`sessionDir:${d}`));let c=Object.entries(r.metadata??{}).map(([u,d])=>`${u}=${d}`).join(" ");console.log(` ${i?b.cyan(r.kind.padEnd(14)):b.dim(r.kind.padEnd(14))} ${b.bold(r.label)}`),a.length&&console.log(` ${a.join(" ")}`),c&&console.log(` ${b.dim(c)}`),i||console.log(` ${b.dim("(disabled)")}`)}console.log()});en.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,t)=>{let o=Se();o.agents?.[e]||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-LTXRWDRK.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await at({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),r||(console.log(b.red(" --kind is required")),process.exit(1));let i=String(t.label||"").trim();!i&&n&&(i=((await at({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),i||(console.log(b.red(" --label is required")),process.exit(1));let a=String(t.tokenEnv||"").trim(),l=String(t.auth||"").trim(),c=String(t.sessionDir||"").trim();if(!a&&!l&&!c&&n){let p=await at({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});p.scheme==="tokenEnv"?a=((await at({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():p.scheme==="keyring"?l="keyring":p.scheme==="sessionDir"&&(c=((await at({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${r}-sessions/${e}`})).sessionDir||"").trim())}let u={};if(t.metadata)for(let p of String(t.metadata).split(",")){let[f,...g]=p.split("=");f&&(u[f.trim()]=g.join("=").trim())}else if(n){let p=await at({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(p.metadata)for(let f of String(p.metadata).split(",")){let[g,...h]=f.split("=");g&&(u[g.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(b.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),l==="keyring"&&(d.auth="keyring"),c&&(d.sessionDir=c),Object.keys(d).length||(console.log(b.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),o.agents[e].integrations=o.agents[e].integrations??[],o.agents[e].integrations.find(p=>p.kind===r&&p.label===i)&&(console.log(b.red(` Integration (${r}, ${i}) already exists on ${e}`)),process.exit(1)),o.agents[e].integrations.push({kind:r,label:i,credentials:d,metadata:u,enabled:!0}),await gt(o),console.log(b.green(` \u2713 ${e}: added ${r} integration "${i}"`)),a&&!process.env[a]&&console.log(b.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});en.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=Se(),n=o.agents?.[e];n||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[r,i]=t.includes(":")?t.split(":",2):[t,""],a=s.findIndex(c=>c.kind===r&&(!i||c.label===i)||c.label===t);a===-1&&(console.log(b.red(` No integration matched "${t}"`)),process.exit(1));let l=s.splice(a,1)[0];await gt(o),console.log(b.green(` \u2713 removed ${l.kind} integration "${l.label}" from ${e}`))});en.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=Se().agents?.[e];n||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],r=t?s.filter(a=>a.kind===t||a.label===t||`${a.kind}:${a.label}`===t):s;if(!r.length){console.log(b.yellow(" no integrations to test"));return}let i=0;console.log();for(let a of r){let l=a.credentials??{},c=[];for(let[u,d]of Object.entries(l))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&c.push(`${u}: env var ${d} is unset`);if(c.length){i+=1,console.log(` ${b.red("\u2717")} ${a.kind} "${a.label}"`);for(let u of c)console.log(` ${b.dim(u)}`)}else console.log(` ${b.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),i>0&&process.exit(1)});function pb(e,t,o,n){let s=e.agents[t];s.integrations=s.integrations??[];let r=s.integrations,i=r.findIndex(a=>a.kind===o&&(!n||a.label===n));return{list:r,idx:i}}en.command("connect <agentId> <kind>").description("sign in to an outside API (OAuth) and store the token for an agent").option("--label <text>","which integration of this kind (created when missing; default: the kind)").option("--client-id-env <name>","env var with the app's client id (default: <KIND>_CLIENT_ID)").option("--client-secret-env <name>","env var with the app's client secret (default: <KIND>_CLIENT_SECRET)").option("--with <names>","comma-separated optional permissions the provider offers (e.g. revenue)").option("--reads <names>","comma-separated reads this integration allows (default: every read the provider offers)").option("--store <where>","keyring or env (default: keyring when this machine has one)").option("--port <n>","loopback port for the sign-in answer","19876").option("--paste","no loopback: paste the address the browser lands on (for a machine without a browser)").option("--redirect-uri <url>","with --paste: the return address registered in the app, when it cannot be localhost (e.g. an https page for a Meta app in Live mode)").option("--no-browser","print the sign-in address instead of opening it").action(async(e,t,o)=>{let{providerFor:n,BUILTIN_PROVIDERS:s}=await import("./providers-D6IUAHQJ.js"),{resolveClient:r}=await import("./resolve-AYTQGEP2.js"),{signIn:i,storeGrant:a}=await import("./connect-AJKMRKXC.js"),{systemKeyring:l}=await import("./keyring-EKFUNQAO.js"),{waitForLoopbackCallback:c,parseCallback:u}=await import("./oauth-7J7DJMKN.js"),{setDotenvKey:d}=await import("./dotenv-DGZD3EDY.js"),p=Se();p.agents?.[e]||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let f=n(t);if(!f){let R=Object.keys(s);console.log(b.red(` No sign-in support for "${t}". ${R.length?`Supported: ${R.join(", ")}`:"No provider is built in yet."}`)),process.exit(1)}let g=Number(o.port);(!Number.isInteger(g)||g<1024||g>65535)&&(console.log(b.red(" --port must be 1024-65535")),process.exit(1));let h=String(o.store||"").trim()||(l().available()?"keyring":"env");h!=="keyring"&&h!=="env"&&(console.log(b.red(" --store must be keyring or env")),process.exit(1)),h==="keyring"&&!l().available()&&(console.log(b.red(" No OS keyring on this machine (macOS Keychain or Linux secret-tool). Use --store env.")),process.exit(1));let y=String(o.label||"").trim()||void 0,{list:w,idx:$}=pb(p,e,t,y),x=R=>R.replace(/[^A-Za-z0-9]+/g,"_").toUpperCase();if($===-1?(w.push({kind:t,label:y??t,credentials:{clientIdEnv:String(o.clientIdEnv||`${x(t)}_CLIENT_ID`),clientSecretEnv:String(o.clientSecretEnv||`${x(t)}_CLIENT_SECRET`)},metadata:{},enabled:!0}),$=w.length-1):(w[$].credentials={...w[$].credentials??{}},o.clientIdEnv&&(w[$].credentials.clientIdEnv=String(o.clientIdEnv)),o.clientSecretEnv&&(w[$].credentials.clientSecretEnv=String(o.clientSecretEnv)),w[$].credentials.clientIdEnv??=`${x(t)}_CLIENT_ID`,w[$].credentials.clientSecretEnv??=`${x(t)}_CLIENT_SECRET`),o.reads!==void 0){let R=String(o.reads).split(",").map(I=>I.trim()).filter(Boolean),T=R.filter(I=>!Object.prototype.hasOwnProperty.call(f.reads,I));T.length&&(console.log(b.red(` Unknown read(s): ${T.join(", ")}. ${f.title} offers: ${Object.keys(f.reads).join(", ")}`)),process.exit(1)),w[$].metadata={...w[$].metadata??{}},R.length?w[$].metadata.reads=R.join(","):delete w[$].metadata.reads}let v=w[$];for(let[R,T]of Object.entries(v.credentials))!/^[A-Z][A-Z0-9_]*$/.test(String(T))&&R.endsWith("Env")&&(console.log(b.red(` ${R} must be an uppercase env var name (got "${T}")`)),process.exit(1));let S=r(v);S.ok||(console.log(b.red(` ${S.reason}`)),console.log(b.dim(" Put the app's client id and secret in .env next to agentx.json, then run this again.")),process.exit(1));let k=`http://localhost:${g}/callback`;if(o.redirectUri!==void 0){o.paste||(console.log(b.red(" --redirect-uri works with --paste only: AgentX can wait for the answer on localhost only")),process.exit(1));let{checkRedirectUri:R}=await import("./connect-AJKMRKXC.js"),T=R(String(o.redirectUri));T||(console.log(b.red(" --redirect-uri must be an https address (or http://localhost) without #")),process.exit(1)),k=T}console.log(),console.log(b.bold(` Connect ${f.title} for ${e} ("${v.label}")`)),console.log(b.dim(` Redirect address (add it to your app's allowed redirects): ${k}`));let A=String(o.with||"").split(",").map(R=>R.trim()).filter(Boolean);try{let R=await i({agentId:e,spec:f,integration:v,clientId:S.clientId,clientSecret:S.clientSecret,redirectUri:k,extras:A,warn:I=>console.log(b.yellow(` ${I}`)),getCallback:async(I,M)=>{let D=o.paste?null:c(g,M);if(D&&await D.ready,console.log(`
|
|
68
|
+
`));return}console.log(),console.log(b.bold(` ${e}`));for(let r of s){let i=r.enabled!==!1,a=[],l=r.credentials??{};for(let[u,d]of Object.entries(l))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?b.green(`${u}:${d}=set`):b.yellow(`${u}:${d}=UNSET`)):u==="auth"&&d==="keyring"?a.push(b.dim("auth:keyring")):u==="sessionDir"&&typeof d=="string"&&a.push(b.dim(`sessionDir:${d}`));let c=Object.entries(r.metadata??{}).map(([u,d])=>`${u}=${d}`).join(" ");console.log(` ${i?b.cyan(r.kind.padEnd(14)):b.dim(r.kind.padEnd(14))} ${b.bold(r.label)}`),a.length&&console.log(` ${a.join(" ")}`),c&&console.log(` ${b.dim(c)}`),i||console.log(` ${b.dim("(disabled)")}`)}console.log()});en.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,t)=>{let o=Se();o.agents?.[e]||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-S522VXLI.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await at({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),r||(console.log(b.red(" --kind is required")),process.exit(1));let i=String(t.label||"").trim();!i&&n&&(i=((await at({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),i||(console.log(b.red(" --label is required")),process.exit(1));let a=String(t.tokenEnv||"").trim(),l=String(t.auth||"").trim(),c=String(t.sessionDir||"").trim();if(!a&&!l&&!c&&n){let p=await at({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});p.scheme==="tokenEnv"?a=((await at({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():p.scheme==="keyring"?l="keyring":p.scheme==="sessionDir"&&(c=((await at({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${r}-sessions/${e}`})).sessionDir||"").trim())}let u={};if(t.metadata)for(let p of String(t.metadata).split(",")){let[f,...g]=p.split("=");f&&(u[f.trim()]=g.join("=").trim())}else if(n){let p=await at({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(p.metadata)for(let f of String(p.metadata).split(",")){let[g,...h]=f.split("=");g&&(u[g.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(b.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),l==="keyring"&&(d.auth="keyring"),c&&(d.sessionDir=c),Object.keys(d).length||(console.log(b.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),o.agents[e].integrations=o.agents[e].integrations??[],o.agents[e].integrations.find(p=>p.kind===r&&p.label===i)&&(console.log(b.red(` Integration (${r}, ${i}) already exists on ${e}`)),process.exit(1)),o.agents[e].integrations.push({kind:r,label:i,credentials:d,metadata:u,enabled:!0}),await gt(o),console.log(b.green(` \u2713 ${e}: added ${r} integration "${i}"`)),a&&!process.env[a]&&console.log(b.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});en.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=Se(),n=o.agents?.[e];n||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[r,i]=t.includes(":")?t.split(":",2):[t,""],a=s.findIndex(c=>c.kind===r&&(!i||c.label===i)||c.label===t);a===-1&&(console.log(b.red(` No integration matched "${t}"`)),process.exit(1));let l=s.splice(a,1)[0];await gt(o),console.log(b.green(` \u2713 removed ${l.kind} integration "${l.label}" from ${e}`))});en.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=Se().agents?.[e];n||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],r=t?s.filter(a=>a.kind===t||a.label===t||`${a.kind}:${a.label}`===t):s;if(!r.length){console.log(b.yellow(" no integrations to test"));return}let i=0;console.log();for(let a of r){let l=a.credentials??{},c=[];for(let[u,d]of Object.entries(l))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&c.push(`${u}: env var ${d} is unset`);if(c.length){i+=1,console.log(` ${b.red("\u2717")} ${a.kind} "${a.label}"`);for(let u of c)console.log(` ${b.dim(u)}`)}else console.log(` ${b.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),i>0&&process.exit(1)});function pb(e,t,o,n){let s=e.agents[t];s.integrations=s.integrations??[];let r=s.integrations,i=r.findIndex(a=>a.kind===o&&(!n||a.label===n));return{list:r,idx:i}}en.command("connect <agentId> <kind>").description("sign in to an outside API (OAuth) and store the token for an agent").option("--label <text>","which integration of this kind (created when missing; default: the kind)").option("--client-id-env <name>","env var with the app's client id (default: <KIND>_CLIENT_ID)").option("--client-secret-env <name>","env var with the app's client secret (default: <KIND>_CLIENT_SECRET)").option("--with <names>","comma-separated optional permissions the provider offers (e.g. revenue)").option("--reads <names>","comma-separated reads this integration allows (default: every read the provider offers)").option("--store <where>","keyring or env (default: keyring when this machine has one)").option("--port <n>","loopback port for the sign-in answer","19876").option("--paste","no loopback: paste the address the browser lands on (for a machine without a browser)").option("--redirect-uri <url>","with --paste: the return address registered in the app, when it cannot be localhost (e.g. an https page for a Meta app in Live mode)").option("--no-browser","print the sign-in address instead of opening it").action(async(e,t,o)=>{let{providerFor:n,BUILTIN_PROVIDERS:s}=await import("./providers-D6IUAHQJ.js"),{resolveClient:r}=await import("./resolve-AYTQGEP2.js"),{signIn:i,storeGrant:a}=await import("./connect-AJKMRKXC.js"),{systemKeyring:l}=await import("./keyring-EKFUNQAO.js"),{waitForLoopbackCallback:c,parseCallback:u}=await import("./oauth-7J7DJMKN.js"),{setDotenvKey:d}=await import("./dotenv-DGZD3EDY.js"),p=Se();p.agents?.[e]||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let f=n(t);if(!f){let R=Object.keys(s);console.log(b.red(` No sign-in support for "${t}". ${R.length?`Supported: ${R.join(", ")}`:"No provider is built in yet."}`)),process.exit(1)}let g=Number(o.port);(!Number.isInteger(g)||g<1024||g>65535)&&(console.log(b.red(" --port must be 1024-65535")),process.exit(1));let h=String(o.store||"").trim()||(l().available()?"keyring":"env");h!=="keyring"&&h!=="env"&&(console.log(b.red(" --store must be keyring or env")),process.exit(1)),h==="keyring"&&!l().available()&&(console.log(b.red(" No OS keyring on this machine (macOS Keychain or Linux secret-tool). Use --store env.")),process.exit(1));let y=String(o.label||"").trim()||void 0,{list:w,idx:$}=pb(p,e,t,y),x=R=>R.replace(/[^A-Za-z0-9]+/g,"_").toUpperCase();if($===-1?(w.push({kind:t,label:y??t,credentials:{clientIdEnv:String(o.clientIdEnv||`${x(t)}_CLIENT_ID`),clientSecretEnv:String(o.clientSecretEnv||`${x(t)}_CLIENT_SECRET`)},metadata:{},enabled:!0}),$=w.length-1):(w[$].credentials={...w[$].credentials??{}},o.clientIdEnv&&(w[$].credentials.clientIdEnv=String(o.clientIdEnv)),o.clientSecretEnv&&(w[$].credentials.clientSecretEnv=String(o.clientSecretEnv)),w[$].credentials.clientIdEnv??=`${x(t)}_CLIENT_ID`,w[$].credentials.clientSecretEnv??=`${x(t)}_CLIENT_SECRET`),o.reads!==void 0){let R=String(o.reads).split(",").map(I=>I.trim()).filter(Boolean),T=R.filter(I=>!Object.prototype.hasOwnProperty.call(f.reads,I));T.length&&(console.log(b.red(` Unknown read(s): ${T.join(", ")}. ${f.title} offers: ${Object.keys(f.reads).join(", ")}`)),process.exit(1)),w[$].metadata={...w[$].metadata??{}},R.length?w[$].metadata.reads=R.join(","):delete w[$].metadata.reads}let v=w[$];for(let[R,T]of Object.entries(v.credentials))!/^[A-Z][A-Z0-9_]*$/.test(String(T))&&R.endsWith("Env")&&(console.log(b.red(` ${R} must be an uppercase env var name (got "${T}")`)),process.exit(1));let S=r(v);S.ok||(console.log(b.red(` ${S.reason}`)),console.log(b.dim(" Put the app's client id and secret in .env next to agentx.json, then run this again.")),process.exit(1));let k=`http://localhost:${g}/callback`;if(o.redirectUri!==void 0){o.paste||(console.log(b.red(" --redirect-uri works with --paste only: AgentX can wait for the answer on localhost only")),process.exit(1));let{checkRedirectUri:R}=await import("./connect-AJKMRKXC.js"),T=R(String(o.redirectUri));T||(console.log(b.red(" --redirect-uri must be an https address (or http://localhost) without #")),process.exit(1)),k=T}console.log(),console.log(b.bold(` Connect ${f.title} for ${e} ("${v.label}")`)),console.log(b.dim(` Redirect address (add it to your app's allowed redirects): ${k}`));let A=String(o.with||"").split(",").map(R=>R.trim()).filter(Boolean);try{let R=await i({agentId:e,spec:f,integration:v,clientId:S.clientId,clientSecret:S.clientSecret,redirectUri:k,extras:A,warn:I=>console.log(b.yellow(` ${I}`)),getCallback:async(I,M)=>{let D=o.paste?null:c(g,M);if(D&&await D.ready,console.log(`
|
|
69
69
|
Open this address and approve:
|
|
70
70
|
|
|
71
71
|
${b.cyan(I)}
|
|
@@ -82,16 +82,16 @@ Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choos
|
|
|
82
82
|
Not a guest anywhere. Join with: agentx mesh join <url> --code \u2026 --name \u2026
|
|
83
83
|
`));return}console.log();for(let n of o){let s=await t(n),r=s.ok?s.grant.state==="active"?b.green("active"):b.yellow(String(s.grant.state)):s.status===403?b.yellow(s.error):b.red(s.error);console.log(` ${b.cyan(n.name)} ${b.dim(n.url)} ${n.agentId} until ${n.expiresAt.slice(0,10)} ${r}`)}console.log()});Ut.command("ask <host> <message...>").description("ask the host's agent something, inside the grant").action(async(e,t)=>{let{GuestHostStore:o,askHost:n}=await import("./hosts-NFNCYKGY.js"),s=new o().get(e);s||(console.log(b.red(` No host "${e}". See \`agentx mesh hosts\`.`)),process.exit(1));let r=await n(s,t.join(" "));r.error&&(console.log(b.red(` ${r.error}`)),process.exit(1)),console.log(`
|
|
84
84
|
${r.content}
|
|
85
|
-
`)});Ut.command("leave <host>").description("forget a host you joined as a guest (the host can also end it on its side)").action(async e=>{let{GuestHostStore:t}=await import("./hosts-NFNCYKGY.js");new t().remove(e)||(console.log(b.red(` No host "${e}".`)),process.exit(1)),console.log(b.green(` \u2713 Left ${e}`))});var Pn=new ho().name("skill").description("manage skills \u2014 add to agent(s), list");Pn.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,t)=>{let o=Se(),n=le(e);if(!Ke(n)){console.log(b.red(` Skill not found: ${n}`));return}let s=Ke(Qo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),r;if(t.all)r=Object.keys(o.agents||{});else if(t.agent)r=t.agent;else{let i=Object.keys(o.agents||{});r=(await at({type:"multiselect",name:"agents",message:"Install to which agents?",choices:i.map(l=>({title:`${l} (${o.agents[l].name})`,value:l}))})).agents||[]}for(let i of r){let a=o.agents[i];if(!a){console.log(b.yellow(` Agent "${i}" not found, skipping`));continue}let l=Ds(a.tier,a.workspace);if(!l){console.log(b.yellow(` ${i}: its runtime (${a.tier}) does not use skills, skipping`));continue}let c=le(l,s);fo(c,{recursive:!0}),Ke(Qo(n,"SKILL.md"))?xd(n,c,{recursive:!0}):n.endsWith(".md")&&xd(n,Qo(c,"SKILL.md")),console.log(b.green(` ${s} -> ${i} (${a.workspace})`))}console.log()});Pn.command("list").alias("ls").description("list skills per agent").action(()=>{let e=Se();console.log();for(let[t,o]of Object.entries(e.agents||{})){if(!Ds(o.tier,o.workspace)){console.log(` ${b.cyan(t)}: ${b.dim(`(${o.tier} does not use skills)`)}`);continue}let n=Ps(o.tier,o.workspace).map(s=>s.name);console.log(` ${b.cyan(t)}: ${n.length?n.join(", "):b.dim("(none)")}`)}console.log()});Pn.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,t)=>{let{createHash:o}=await import("node:crypto"),n=process.cwd(),s=t.source?[t.source]:[le(n,"src",e,"SKILL.md"),le(n,"skills",e,"SKILL.md")],r=s.find(w=>Ke(w));if(!r){console.log(b.red(` No SKILL.md found for "${e}". Searched:`));for(let w of s)console.log(b.dim(` ${w}`));return}let i=Zo(r,"utf-8"),a=o("sha256").update(i).digest("hex").slice(0,12),l=(i.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),c;try{c=O()}catch(w){console.log(b.red(` Can't load agentx.json: ${w.message}`));return}let u=Object.entries(c.agents||{}),d=t.agent?u.filter(([w])=>w===t.agent):u;if(d.length===0){console.log(b.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(b.bold(` Skill sync \u2014 ${e}`)),console.log(b.dim(` Source: ${r}`)),console.log(b.dim(` Version: ${l} \xB7 hash ${a}`)),console.log(b.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,f=0,g=0,h=0;for(let[w,$]of d){let x=$.workspace;if(!x||!Ke(x)){console.log(` ${b.yellow("\u2717")} ${w.padEnd(22)} ${b.dim("(workspace missing: "+(x||"undefined")+")")}`),h++;continue}let v=Ds($.tier,x);if(!v){console.log(` ${b.dim("\xB7")} ${w.padEnd(22)} ${b.dim(`(skipped \u2014 ${$.tier} does not use skills)`)}`),h++;continue}let S=Ps($.tier,x).find(I=>I.name===e)?.dir??le(v,e),k=le(S,"SKILL.md");if(!Ke(k)){if(!t.allWorkspaces){console.log(` ${b.dim("\xB7")} ${w.padEnd(22)} ${b.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}t.dryRun||(fo(S,{recursive:!0}),Gs(k,i)),console.log(` ${b.green("+")} ${w.padEnd(22)} ${b.dim("\u2192 seeded v"+l)}`),p++;continue}let A=Zo(k,"utf-8");if(o("sha256").update(A).digest("hex").slice(0,12)===a){console.log(` ${b.dim("=")} ${w.padEnd(22)} ${b.dim("up to date (v"+l+")")}`),g++;continue}let T=(A.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||Gs(k,i),console.log(` ${b.yellow("\u21BB")} ${w.padEnd(22)} ${b.dim(`v${T} \u2192 v${l}`)}`),f++}console.log();let y=t.dryRun?"would":"did";console.log(b.dim(` Summary: ${y} seed ${p}, ${y} update ${f}, ${g} already current, ${h} skipped.`)),t.dryRun&&(p>0||f>0)&&console.log(b.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Pn.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:t}=await import("./loader-YFVSSYSL.js"),{auditAll:o}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),r=[];if(e.workspace){let f=Se().agents?.[e.workspace];f||(console.log(b.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),r.push(le(f.workspace))}else if(e.allWorkspaces){let p=Se();for(let f of Object.values(p.agents||{}))f?.workspace&&r.push(le(f.workspace))}else r.push(le(e.cwd));let i=le(e.referencesCwd||e.cwd),l=(await Promise.all(r.map(p=>t(p)))).flat(),[c,u]=await Promise.all([n(i),s(i)]),d=o({skills:l,references:c,recipes:u});if(e.json)console.log(JSON.stringify(d.map(p=>({name:p.name,verdict:p.verdict,reasons:p.reasons,path:p.skill?.path})),null,2));else{let p={PASS:0,REVIEW:0,FAILING:0};for(let f of d)p[f.verdict]++;console.log();for(let f of d){let g=f.verdict==="PASS"?b.green("PASS "):f.verdict==="REVIEW"?b.yellow("REVIEW "):b.red("FAILING");console.log(` ${g} ${b.bold(f.name)}${f.skill?.path?b.dim(` (${f.skill.path})`):""}`);for(let h of f.reasons)console.log(` ${b.dim("\xB7")} ${h}`)}console.log(),console.log(` ${b.green(`${p.PASS} PASS`)} ${b.yellow(`${p.REVIEW} REVIEW`)} ${b.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(d.some(p=>p.verdict==="FAILING")?1:0)});Pn.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,t)=>{let o=Se(),n=Object.entries(o.agents||{}),[s,r]=t.agent?n.find(([u])=>u===t.agent)??[]:n[0]??[];r||(console.log(b.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:i}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-
|
|
85
|
+
`)});Ut.command("leave <host>").description("forget a host you joined as a guest (the host can also end it on its side)").action(async e=>{let{GuestHostStore:t}=await import("./hosts-NFNCYKGY.js");new t().remove(e)||(console.log(b.red(` No host "${e}".`)),process.exit(1)),console.log(b.green(` \u2713 Left ${e}`))});var Pn=new ho().name("skill").description("manage skills \u2014 add to agent(s), list");Pn.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,t)=>{let o=Se(),n=le(e);if(!Ke(n)){console.log(b.red(` Skill not found: ${n}`));return}let s=Ke(Qo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),r;if(t.all)r=Object.keys(o.agents||{});else if(t.agent)r=t.agent;else{let i=Object.keys(o.agents||{});r=(await at({type:"multiselect",name:"agents",message:"Install to which agents?",choices:i.map(l=>({title:`${l} (${o.agents[l].name})`,value:l}))})).agents||[]}for(let i of r){let a=o.agents[i];if(!a){console.log(b.yellow(` Agent "${i}" not found, skipping`));continue}let l=Ds(a.tier,a.workspace);if(!l){console.log(b.yellow(` ${i}: its runtime (${a.tier}) does not use skills, skipping`));continue}let c=le(l,s);fo(c,{recursive:!0}),Ke(Qo(n,"SKILL.md"))?xd(n,c,{recursive:!0}):n.endsWith(".md")&&xd(n,Qo(c,"SKILL.md")),console.log(b.green(` ${s} -> ${i} (${a.workspace})`))}console.log()});Pn.command("list").alias("ls").description("list skills per agent").action(()=>{let e=Se();console.log();for(let[t,o]of Object.entries(e.agents||{})){if(!Ds(o.tier,o.workspace)){console.log(` ${b.cyan(t)}: ${b.dim(`(${o.tier} does not use skills)`)}`);continue}let n=Ps(o.tier,o.workspace).map(s=>s.name);console.log(` ${b.cyan(t)}: ${n.length?n.join(", "):b.dim("(none)")}`)}console.log()});Pn.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,t)=>{let{createHash:o}=await import("node:crypto"),n=process.cwd(),s=t.source?[t.source]:[le(n,"src",e,"SKILL.md"),le(n,"skills",e,"SKILL.md")],r=s.find(w=>Ke(w));if(!r){console.log(b.red(` No SKILL.md found for "${e}". Searched:`));for(let w of s)console.log(b.dim(` ${w}`));return}let i=Zo(r,"utf-8"),a=o("sha256").update(i).digest("hex").slice(0,12),l=(i.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),c;try{c=O()}catch(w){console.log(b.red(` Can't load agentx.json: ${w.message}`));return}let u=Object.entries(c.agents||{}),d=t.agent?u.filter(([w])=>w===t.agent):u;if(d.length===0){console.log(b.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(b.bold(` Skill sync \u2014 ${e}`)),console.log(b.dim(` Source: ${r}`)),console.log(b.dim(` Version: ${l} \xB7 hash ${a}`)),console.log(b.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,f=0,g=0,h=0;for(let[w,$]of d){let x=$.workspace;if(!x||!Ke(x)){console.log(` ${b.yellow("\u2717")} ${w.padEnd(22)} ${b.dim("(workspace missing: "+(x||"undefined")+")")}`),h++;continue}let v=Ds($.tier,x);if(!v){console.log(` ${b.dim("\xB7")} ${w.padEnd(22)} ${b.dim(`(skipped \u2014 ${$.tier} does not use skills)`)}`),h++;continue}let S=Ps($.tier,x).find(I=>I.name===e)?.dir??le(v,e),k=le(S,"SKILL.md");if(!Ke(k)){if(!t.allWorkspaces){console.log(` ${b.dim("\xB7")} ${w.padEnd(22)} ${b.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}t.dryRun||(fo(S,{recursive:!0}),Gs(k,i)),console.log(` ${b.green("+")} ${w.padEnd(22)} ${b.dim("\u2192 seeded v"+l)}`),p++;continue}let A=Zo(k,"utf-8");if(o("sha256").update(A).digest("hex").slice(0,12)===a){console.log(` ${b.dim("=")} ${w.padEnd(22)} ${b.dim("up to date (v"+l+")")}`),g++;continue}let T=(A.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||Gs(k,i),console.log(` ${b.yellow("\u21BB")} ${w.padEnd(22)} ${b.dim(`v${T} \u2192 v${l}`)}`),f++}console.log();let y=t.dryRun?"would":"did";console.log(b.dim(` Summary: ${y} seed ${p}, ${y} update ${f}, ${g} already current, ${h} skipped.`)),t.dryRun&&(p>0||f>0)&&console.log(b.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Pn.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:t}=await import("./loader-YFVSSYSL.js"),{auditAll:o}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),r=[];if(e.workspace){let f=Se().agents?.[e.workspace];f||(console.log(b.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),r.push(le(f.workspace))}else if(e.allWorkspaces){let p=Se();for(let f of Object.values(p.agents||{}))f?.workspace&&r.push(le(f.workspace))}else r.push(le(e.cwd));let i=le(e.referencesCwd||e.cwd),l=(await Promise.all(r.map(p=>t(p)))).flat(),[c,u]=await Promise.all([n(i),s(i)]),d=o({skills:l,references:c,recipes:u});if(e.json)console.log(JSON.stringify(d.map(p=>({name:p.name,verdict:p.verdict,reasons:p.reasons,path:p.skill?.path})),null,2));else{let p={PASS:0,REVIEW:0,FAILING:0};for(let f of d)p[f.verdict]++;console.log();for(let f of d){let g=f.verdict==="PASS"?b.green("PASS "):f.verdict==="REVIEW"?b.yellow("REVIEW "):b.red("FAILING");console.log(` ${g} ${b.bold(f.name)}${f.skill?.path?b.dim(` (${f.skill.path})`):""}`);for(let h of f.reasons)console.log(` ${b.dim("\xB7")} ${h}`)}console.log(),console.log(` ${b.green(`${p.PASS} PASS`)} ${b.yellow(`${p.REVIEW} REVIEW`)} ${b.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(d.some(p=>p.verdict==="FAILING")?1:0)});Pn.command("suggest").description("rank an agent's skills against a task (suggests, never loads)").argument("<task>","the task, in the words it arrived in").option("--agent <id>","whose skills to rank").option("--min <p>","minimum P(any skill applies)","0.6").option("--json","emit the ranking as JSON").action(async(e,t)=>{let o=Se(),n=Object.entries(o.agents||{}),[s,r]=t.agent?n.find(([u])=>u===t.agent)??[]:n[0]??[];r||(console.log(b.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:i}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-T4F42G6W.js"),l=await i(r.workspace);if(l.length===0){console.log(b.yellow(` ${s} has no skills`));return}let c=await a(l,e,{agent:s,minRelevant:Number(t.min)||.6});if(t.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:l.length,picked:c.skill?.frontmatter.name??null,anyRelevant:c.anyRelevant,confidence:c.confidence,judged:c.judged,reason:c.reason,shortlist:c.shortlist},null,2));return}if(console.log(),c.skill?(console.log(` ${b.green("\u2192")} ${b.bold(c.skill.frontmatter.name)} ${b.dim(`\xB7 ${c.reason}`)}`),console.log(` ${b.dim(c.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${b.yellow("\xB7")} no skill for this ${b.dim(`\u2014 ${c.reason}`)}`),c.shortlist.length>1){console.log(b.dim(`
|
|
86
86
|
shortlist (lexical -> judged)`));for(let u of c.shortlist.slice(0,6)){let d=u.p===void 0?" - ":u.p.toFixed(2);console.log(b.dim(` ${u.lexical.toFixed(2)} -> ${d} ${u.name}`))}}c.judged||console.log(b.dim(`
|
|
87
87
|
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Gr=new ho().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Gr.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(b.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let o=le(t.cwd),n=le(o,"references/example"),s=le(o,"references/recipes/example.yaml");Ke(n)||(console.log(b.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let r=le(o,".agentx/references",e),i=le(o,".agentx/references/recipes");fo(r,{recursive:!0}),fo(i,{recursive:!0});let a=hA(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),l=0,c=0;for(let d of a){let p=Qo(r,d);if(Ke(p)&&!t.force){console.log(b.dim(` skip ${p} (exists; --force to overwrite)`)),c++;continue}let g=Zo(Qo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Gs(p,g),console.log(b.green(` + ${p}`)),l++}let u=Qo(i,`${e}.yaml`);if(Ke(u)&&!t.force)console.log(b.dim(` skip ${u} (exists; --force to overwrite)`)),c++;else if(Ke(s)){let d=Zo(s,"utf-8").replaceAll("example.",`${e}.`);Gs(u,d),console.log(b.green(` + ${u}`)),l++}console.log(),console.log(b.dim(` ${l} written, ${c} skipped. Edit the placeholders, then:`)),console.log(b.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(b.dim(" 2. agentx skill audit # verify references resolve")),console.log(b.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Gr.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.example.com)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(b.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:o}=await import("./loader-YFVSSYSL.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),r=le(t.cwd),i=t.from?String(t.from).split(",").map(h=>h.trim()).filter(Boolean):[e],a=await o(r),l=n(a,{namespace:e,filter:i,gitlabHost:t.gitlabHost});if(console.log(),l.scannedSkills.length===0){console.log(b.yellow(` No skills matched filter [${i.join(", ")}] under ${r}`)),console.log(b.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(b.dim(` Scanned skills: ${l.scannedSkills.join(", ")}`));let c=Object.fromEntries(Object.entries(l.byKind).map(([h,y])=>[h,y.length]));console.log(` Discovered: ssh=${c.ssh} gitlab=${c.gitlab} paths=${c.path} contacts=${c.contact}`);let u=s(l,e),d=le(t.referencesCwd||t.cwd),p=le(d,".agentx/references",e);if(!t.write){console.log(),console.log(b.dim(` Dry-run \u2014 would write to ${p}/`));for(let[h,y]of Object.entries(u))console.log(b.cyan(`
|
|
88
88
|
--- ${h} ---`)),console.log(y.split(`
|
|
89
89
|
`).slice(0,30).map(w=>` ${w}`).join(`
|
|
90
90
|
`)),y.split(`
|
|
91
91
|
`).length>30&&console.log(b.dim(` \u2026 (${y.split(`
|
|
92
|
-
`).length-30} more lines truncated in preview)`));console.log(),console.log(b.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}fo(p,{recursive:!0});let f=0,g=0;for(let[h,y]of Object.entries(u)){let w=Qo(p,h);if(Ke(w)&&!t.force){console.log(b.dim(` skip ${w} (exists; --force to overwrite)`)),g++;continue}Gs(w,y),console.log(b.green(` + ${w}`)),f++}console.log(),console.log(b.dim(` ${f} written, ${g} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(b.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Gr.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:t}=await import("./loader-KKMG24O5.js"),o=await t(le(e.cwd)),n=[...o.byId.values()].sort((s,r)=>s.id.localeCompare(r.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(b.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let r=o.sourceById.get(s.id);console.log(` ${b.cyan(s.id)} ${b.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),r&&console.log(b.dim(` ${r}`))}console.log(),console.log(b.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Ed=new ho().name("hook").description("manage hooks \u2014 add to agent workspace");Ed.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=Se().agents?.[e];if(!o){console.log(b.red(` Agent "${e}" not found`));return}let n=le(o.workspace,".claude/settings.json"),s=Ke(n)?JSON.parse(Zo(n,"utf-8")):{},r=await at([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:l=>l==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!r.event||!r.value)return;s.hooks=s.hooks||{},s.hooks[r.event]=s.hooks[r.event]||[];let a={hooks:[{type:r.type,...r.type==="command"?{command:r.value}:{url:r.value}}]};r.matcher&&(a.matcher=r.matcher),s.hooks[r.event].push(a),fo(le(o.workspace,".claude"),{recursive:!0}),Gs(n,JSON.stringify(s,null,2)),console.log(b.green(` Hook added to ${e}: ${r.event} -> ${r.type}`)),console.log()});var Ad=new ho().name("migrate").description("import configuration from OpenClaw or other tools");Ad.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,t)=>{let o=[e,le(process.env.HOME||"",".openclaw/openclaw.json"),le(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of o)if(f&&Ke(f)){n=f;break}if(!n){console.log(b.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(b.dim(` Reading: ${n}`));let s=JSON.parse(Zo(n,"utf-8")),r=Ke(le(process.cwd(),"agentx.json"))?Se():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},i=s.agents?.list||[],a=s.bindings||[],l={};for(let f of a)f.match?.channel==="telegram"&&(l[f.match.accountId]=f.agentId);i.find(f=>f.id==="main"||f.default)&&(l.default="main");let c=0;for(let f of i){if(f.workspace?.startsWith("/data"))continue;let g=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),h=f.groupChat?.mentionPatterns||[];if(h.some(y=>y===g)||h.push(g),r.agents[g]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:h,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},c++,!t.dryRun){fo(le(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-
|
|
92
|
+
`).length-30} more lines truncated in preview)`));console.log(),console.log(b.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}fo(p,{recursive:!0});let f=0,g=0;for(let[h,y]of Object.entries(u)){let w=Qo(p,h);if(Ke(w)&&!t.force){console.log(b.dim(` skip ${w} (exists; --force to overwrite)`)),g++;continue}Gs(w,y),console.log(b.green(` + ${w}`)),f++}console.log(),console.log(b.dim(` ${f} written, ${g} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(b.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Gr.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:t}=await import("./loader-KKMG24O5.js"),o=await t(le(e.cwd)),n=[...o.byId.values()].sort((s,r)=>s.id.localeCompare(r.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(b.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let r=o.sourceById.get(s.id);console.log(` ${b.cyan(s.id)} ${b.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),r&&console.log(b.dim(` ${r}`))}console.log(),console.log(b.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Ed=new ho().name("hook").description("manage hooks \u2014 add to agent workspace");Ed.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=Se().agents?.[e];if(!o){console.log(b.red(` Agent "${e}" not found`));return}let n=le(o.workspace,".claude/settings.json"),s=Ke(n)?JSON.parse(Zo(n,"utf-8")):{},r=await at([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:l=>l==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!r.event||!r.value)return;s.hooks=s.hooks||{},s.hooks[r.event]=s.hooks[r.event]||[];let a={hooks:[{type:r.type,...r.type==="command"?{command:r.value}:{url:r.value}}]};r.matcher&&(a.matcher=r.matcher),s.hooks[r.event].push(a),fo(le(o.workspace,".claude"),{recursive:!0}),Gs(n,JSON.stringify(s,null,2)),console.log(b.green(` Hook added to ${e}: ${r.event} -> ${r.type}`)),console.log()});var Ad=new ho().name("migrate").description("import configuration from OpenClaw or other tools");Ad.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,t)=>{let o=[e,le(process.env.HOME||"",".openclaw/openclaw.json"),le(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of o)if(f&&Ke(f)){n=f;break}if(!n){console.log(b.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(b.dim(` Reading: ${n}`));let s=JSON.parse(Zo(n,"utf-8")),r=Ke(le(process.cwd(),"agentx.json"))?Se():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},i=s.agents?.list||[],a=s.bindings||[],l={};for(let f of a)f.match?.channel==="telegram"&&(l[f.match.accountId]=f.agentId);i.find(f=>f.id==="main"||f.default)&&(l.default="main");let c=0;for(let f of i){if(f.workspace?.startsWith("/data"))continue;let g=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),h=f.groupChat?.mentionPatterns||[];if(h.some(y=>y===g)||h.push(g),r.agents[g]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:h,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},c++,!t.dryRun){fo(le(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-PIPGUMLG.js");y(g,r.agents[g])}}console.log(` ${b.green(c)} agents imported (workspaces set up with Claude Code best practices)`);let u=s.channels?.telegram?.accounts||{},d=0;for(let[f,g]of Object.entries(u)){if(!g.botToken)continue;let y=l[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.channels.telegram.accounts[f]={token:g.botToken,agentBinding:y},r.channels.telegram.enabled=!0,d++}console.log(` ${b.green(d)} Telegram accounts imported`);let p=le(n,"../cron/jobs.json");if(Ke(p)){let f=JSON.parse(Zo(p,"utf-8")),g=0;for(let h of f.jobs||[]){let y=h.name||h.id,w=h.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.crons[y]={enabled:h.enabled||!1,schedule:h.schedule?.expr||"0 9 * * *",timezone:h.schedule?.tz||"UTC",agent:w,prompt:h.payload?.message||"",timeout:h.payload?.timeoutSeconds||600,onError:["log"]},g++}console.log(` ${b.green(g)} cron jobs imported`)}t.dryRun?(console.log(b.yellow(`
|
|
93
93
|
Dry run \u2014 nothing written`)),console.log(JSON.stringify(r,null,2))):(await gt(r),console.log(b.green(`
|
|
94
|
-
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var tn=new ho().name("config").description("validate and inspect configuration");tn.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let t=O(e.config);console.log(b.green(" \u2713 Config valid")),console.log(b.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(b.dim(` Bind: ${t.node.bind}`)),console.log(b.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(b.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(b.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(b.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(b.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Di(t);if(n.length){console.log(),console.log(b.yellow(" Warnings:"));for(let s of n)console.log(b.yellow(` \u26A0 ${s}`))}else console.log(b.green(" \u2713 All workspaces valid"));console.log();for(let[s,r]of Object.entries(t.agents)){let i=r.workspace,a=Ke(le(i,".claude")),l=Ke(le(i,"CLAUDE.md")),c=Ke(le(i,".claude/settings.json")),u=Ps(r.tier,i).length,d=[a?b.green("\u2713"):b.red("\u2717"),".claude",l?b.green("\u2713"):b.yellow("\u25CB"),"CLAUDE.md",c?b.green("\u2713"):b.yellow("\u25CB"),"settings",`${u} skills`];console.log(` ${b.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(b.red(` \u2717 ${t.message}`))}console.log()});tn.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=O(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(b.red(t.message))}});function bA(e,t){if(t)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(o=>o.trim()).filter(Boolean):e}function Sd(e){return e===void 0?b.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}tn.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,t)=>{let{readFileSync:o,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:r}=await import("./config-mutator-
|
|
94
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var tn=new ho().name("config").description("validate and inspect configuration");tn.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let t=O(e.config);console.log(b.green(" \u2713 Config valid")),console.log(b.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(b.dim(` Bind: ${t.node.bind}`)),console.log(b.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(b.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(b.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(b.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(b.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Di(t);if(n.length){console.log(),console.log(b.yellow(" Warnings:"));for(let s of n)console.log(b.yellow(` \u26A0 ${s}`))}else console.log(b.green(" \u2713 All workspaces valid"));console.log();for(let[s,r]of Object.entries(t.agents)){let i=r.workspace,a=Ke(le(i,".claude")),l=Ke(le(i,"CLAUDE.md")),c=Ke(le(i,".claude/settings.json")),u=Ps(r.tier,i).length,d=[a?b.green("\u2713"):b.red("\u2717"),".claude",l?b.green("\u2713"):b.yellow("\u25CB"),"CLAUDE.md",c?b.green("\u2713"):b.yellow("\u25CB"),"settings",`${u} skills`];console.log(` ${b.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(b.red(` \u2717 ${t.message}`))}console.log()});tn.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=O(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(b.red(t.message))}});function bA(e,t){if(t)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(o=>o.trim()).filter(Boolean):e}function Sd(e){return e===void 0?b.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}tn.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,t)=>{let{readFileSync:o,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:r}=await import("./config-mutator-YNNEGRV3.js"),{expandEnvVars:i}=await import("./config-S522VXLI.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(b.red(` No config at ${a}`)),process.exit(1));let l=JSON.parse(o(a,"utf-8")),c=t.raw?l:i(l),u=r(c,e);t.json?console.log(JSON.stringify(u)):console.log(Sd(u))});tn.command("set <path> <value>").description("write a config value by dot-path; validates against schema and hot-reloads the daemon").option("-c, --config <path>","path to agentx.json").option("--string","treat the value as a literal string (skip JSON parsing)").option("--dry-run","validate and diff without writing").action(async(e,t,o)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:r}=await import("./config-mutator-YNNEGRV3.js"),i=bA(t,!!o.string),a=await n(c=>{s(c,e,i)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(b.red(` \u2717 ${a.error}`)),process.exit(1));let l=r(a.after,e);o.dryRun?console.log(b.yellow(` (dry-run) ${b.cyan(e)} would become: ${Sd(l)}`)):(console.log(b.green(` \u2713 ${b.cyan(e)} = ${Sd(l)}`)),a.reloaded?console.log(b.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(b.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});tn.command("unset <path>").description("remove a config value by dot-path (validates + hot-reloads)").option("-c, --config <path>","path to agentx.json").option("--dry-run","validate without writing").action(async(e,t)=>{let{applyConfigMutation:o,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-YNNEGRV3.js"),r=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(r.success||(console.log(b.red(` \u2717 ${r.error}`)),process.exit(1)),n(r.after,e)!==void 0){console.log(b.dim(` (no-op) ${b.cyan(e)} was not set`));return}t.dryRun?console.log(b.yellow(` (dry-run) ${b.cyan(e)} would be removed`)):(console.log(b.green(` \u2713 ${b.cyan(e)} removed`)),r.reloaded&&console.log(b.dim(" Daemon hot-reloaded.")))});tn.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let t=!1,o=0,n;try{let d=O(e.config);t=!!d.business?.enabled,o=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),r=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),i=r==="true"||r==="1"||r==="yes",a=i&&t,l=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:l},pmGate:{envSet:i,businessEnabled:t,active:a,projects:o},configError:n},null,2));return}console.log(),console.log(b.bold(" Governance flags")),console.log(),n&&(console.log(b.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let c=s==="authoritative"?b.green:s==="shadow"?b.cyan:s==="off"?b.dim:b.red;console.log(` INTENT_LEDGER_MODE ${c(s)}${l?"":b.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let u=a?b.green("active"):i?b.yellow("env=true but business.enabled=false \u2192 inactive"):b.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${u}`),console.log(b.dim(` business.enabled ${t?b.green("true"):b.dim("false")}`)),console.log(b.dim(` business.projects[] ${o}`)),console.log(),console.log(b.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(b.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});Bo();import{Command as $A}from"commander";import on from"chalk";import{resolve as nn}from"path";import{existsSync as kA}from"fs";var _o=new $A().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Mn(e){let t=nn(e,".agentx/db.sqlite");kA(t)||(console.log(on.red(` No SQLite at ${t}`)),console.log(on.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=Ve({path:t});return o||(console.log(on.red(` Could not open ${t}`)),console.log(on.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function Ln(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(on.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.map(r=>Math.max(r.length,...e.map(i=>String(i[r]??"").length))),s=r=>r.map((i,a)=>String(i??"").padEnd(n[a])).join(" ");console.log(s(o)),console.log(o.map((r,i)=>"-".repeat(n[i])).join(" "));for(let r of e)console.log(s(o.map(i=>r[i])))}_o.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let t=Mn(nn(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.day&&(o.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(o.push("status = @status"),n.status=e.status);let s=`
|
|
95
95
|
SELECT agent_id, channel, status, duration_ms,
|
|
96
96
|
input_tokens, output_tokens,
|
|
97
97
|
substr(message_preview, 1, 60) AS message,
|
|
@@ -554,7 +554,7 @@ return aid ?? null`}function TC(e,t){if(e.kind==="path"){let s=e.pts,r=s[Math.fl
|
|
|
554
554
|
`):" not written yet"),n.builders){console.log(Y.dim(`
|
|
555
555
|
Background builders it had started (${n.builders.helpers.length}), stopped with it:`)),n.builders.helpers.forEach((s,r)=>console.log(` ${r+1}. ${s}`));for(let s of n.builders.folders){let r=s.wipBranch?Y.green(`saved on ${s.wipBranch} (${String(s.wipCommit).slice(0,12)})`):s.error?Y.red(`not saved: ${s.error}`):Y.dim("nothing to save: its commits are in the clone");console.log(` - ${s.path} (${s.branch??"no branch"}): ${r}`)}}});li(Kn.command("resume <id>").description("resume a stopped task from its plan, in the same chat").option("-r, --reason <reason>","why: recorded on the resume event")).action(async(e,t)=>{let o=await Yn(t,"POST","/api/signals/resume",{id:e,reason:t.reason,node:t.peer});console.log(Y.green(` resumed ${o.agentId} task ${o.id}`)),o.delivery&&console.log(Y.dim(` its answer goes to ${o.delivery}`))});li(Kn.command("drop <id>").description("forget a stopped task and its resume plan, when it won't be resumed")).action(async(e,t)=>{let o=await Yn(t,"POST","/api/signals/drop",{id:e,node:t.peer});console.log(Y.green(` dropped ${o.agentId} task ${o.id}`))});Z();import{Command as CO}from"commander";import Sk from"chalk";function mu(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m ${e%60}s`:`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`}function pu(e){return e.chatId?`${e.channel}:${e.chatId}`:e.channel}function xk(e,t=Date.now()){let o=[],n=e.enabled?e.mode==="observe"?"observe (logs only, nothing is held)":"on":"off (nothing is held)";o.push(`Admission queue: ${n}${e.checkedAt?` \u2014 checked ${e.checkedAt}`:""}`);let s=e.resources,r=e.limits;s&&r&&(o.push(""),o.push("Resources"),o.push(` memory ${s.memAvailableMB} MB available of ${s.memTotalMB} MB (needs ${r.minAvailableMemoryMB} MB)`),o.push(` swap ${s.swapTotalMB>0?`${s.swapUsedMB} MB used (limit ${r.maxSwapUsedMB} MB)`:"none"}`),o.push(` disk ${s.diskFreeMB===null?"unknown":`${s.diskFreeMB} MB free`}${r.minDiskFreeMB>0?` (needs ${r.minDiskFreeMB} MB)`:""}`),o.push(` load ${s.load1} on ${s.cpuCount} CPUs${r.maxLoad1>0?` (limit ${r.maxLoad1})`:""}`)),o.push(""),o.push(e.gate.open?"Gate: open":`Gate: closed \u2014 ${e.gate.reasons.join("; ")}`);let i=Object.entries(e.caps.classes).map(([a,l])=>`${a} ${l.running}/${l.max}`);if(o.push(`Caps: ${e.running.length}/${e.caps.maxSessions??"?"} sessions (owner +${e.caps.ownerExtraSessions}, helpers +${e.caps.delegationHeadroom})${i.length?`; ${i.join(", ")}`:""}`),e.warmUp.active){let a=Math.max(0,Math.round((Date.parse(e.warmUp.until)-t)/1e3));o.push(`Warm-up: ${e.warmUp.startsPerInterval} starts per ${e.warmUp.intervalSeconds}s for ${mu(a)} more`)}o.push(""),o.push(`Running (${e.running.length})`),e.running.length||o.push(" none");for(let a of e.running){let l=Math.max(0,Math.round((t-Date.parse(a.startedAt))/1e3));o.push(` ${a.agentId} ${a.priority}${a.class?` [${a.class}]`:""} ${pu(a)} for ${mu(l)}`)}o.push(""),o.push(`Waiting (${e.waiting.length})`),e.waiting.length||o.push(" none");for(let a of e.waiting)o.push(` ${a.position}. ${a.agentId} ${a.priority}${a.class?` [${a.class}]`:""} ${pu(a)} waiting ${mu(a.waitingSeconds)}`),a.blockedBy.length&&o.push(` held by: ${a.blockedBy.join("; ")}`);return o.push(""),o.push(e.next?`Next: ${e.next.agentId} (${e.next.priority}, ${pu(e.next)})`:"Next: nothing waiting"),o.join(`
|
|
556
556
|
`)}var Ek=new CO().name("queue").description("show the node's session queue: resources, running, waiting and next in line").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (default: dashboard.daemonUrl)").option("--json","print the raw JSON").action(async e=>{let t=e.node||"",o="";try{let s=O(e.config);t||(t=s.dashboard?.daemonUrl||""),o=s.dashboard?.token||""}catch{}t=(t||"http://localhost:18800").replace(/\/+$/,"");let n;try{let s=await fetch(`${t}/api/queue`,{headers:o?{Authorization:`Bearer ${o}`}:{},signal:AbortSignal.timeout(1e4)});s.ok||(console.log(Sk.red(` HTTP ${s.status} from ${t}/api/queue${s.status===404?" (the daemon is older than this command)":""}`)),process.exit(1)),n=await s.json()}catch(s){console.log(Sk.red(` could not reach daemon at ${t}: ${s?.message||s}`)),process.exit(1)}console.log(e.json?JSON.stringify(n,null,2):xk(n))});Z();import{Command as OO}from"commander";import Ak from"chalk";var Rk=new OO().name("node").description("show what this node knows about itself: machine, programs, Claude account limits and running work").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (default: dashboard.daemonUrl)").option("--json","print the raw JSON").action(async e=>{let t=e.node||"",o="";try{let s=O(e.config);t||(t=s.dashboard?.daemonUrl||""),o=s.dashboard?.token||""}catch{}t=(t||"http://localhost:18800").replace(/\/+$/,"");let n;try{let s=await fetch(`${t}/api/node`,{headers:o?{Authorization:`Bearer ${o}`}:{},signal:AbortSignal.timeout(1e4)});s.ok||(console.log(Ak.red(` HTTP ${s.status} from ${t}/api/node${s.status===404?" (the daemon is older than this command)":""}`)),process.exit(1)),n=await s.json()}catch(s){console.log(Ak.red(` could not reach daemon at ${t}: ${s?.message||s}`)),process.exit(1)}console.log(e.json?JSON.stringify(n,null,2):Gf(n))});Z();import{Command as IO}from"commander";import $t from"chalk";var ll=new IO().name("review-gate").description("independent pre-merge review of agent PRs against their linked issue");function NO(e){let t=e.node||"",o=e.token||"";if(!t||!o)try{let s=O(e.config);t||(t=s.dashboard?.daemonUrl||""),o||(o=s.dashboard?.token||"")}catch{}let n={"Content-Type":"application/json"};return o&&(n.Authorization=`Bearer ${o}`),{baseUrl:(t||"http://localhost:18800").replace(/\/+$/,""),headers:n}}async function Tk(e,t,o,n){let{baseUrl:s,headers:r}=NO(e),i;try{i=await fetch(`${s}${o}`,{method:t,headers:r,...n?{body:JSON.stringify(n)}:{}})}catch(a){console.log($t.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(!i.ok){let a=await i.json().catch(()=>({}));console.log($t.red(` HTTP ${i.status}${a.error?` \u2014 ${a.error}`:""}`)),process.exit(1)}return i}var Ck=e=>e.option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)"),Ok=e=>e==="success"?$t.green(e):e==="failure"?$t.red(e):$t.yellow(e);Ck(ll.command("list").description("recent reviews, with what they cost and how long they took").option("--days <n>","how many days back","7").option("--replays","include replayed reviews")).action(async e=>{let t=new URLSearchParams({days:String(e.days)});e.replays&&t.set("replays","1");let o=await(await Tk(e,"GET",`/api/review-gate/reviews?${t}`)).json(),n=o.summary;console.log($t.bold(` Last ${o.days} days: ${n.reviews} reviews on ${n.prs} PRs`)+$t.dim(` \u2014 ${n.byState.success} passed, ${n.byState.failure} failed, ${n.byState.error} errors`)),console.log($t.dim(` cost $${n.costUsd}${n.unpriced?` (+${n.unpriced} unpriced)`:""}, ${n.minutes} min, ${n.tokens} tokens`+(n.p90SincePushMinutes!==void 0?`, push \u2192 status p90 ${n.p90SincePushMinutes} min`:"")));for(let s of o.reviews)console.log(` ${s.at.slice(0,16).replace("T"," ")} ${s.repo}${s.forge==="gitlab"?"!":"#"}${s.pr} ${s.sha.slice(0,7)} ${Ok(s.state)} ${$t.dim(s.reason)}${s.replay?$t.dim(" (replay)"):""}`)});Ck(ll.command("replay <repo> <prs...>").description("review past PRs at their head commit without posting anything; counts how many get flagged").option("--gitlab","the repo is a GitLab project and the numbers are merge requests")).action(async(e,t,o)=>{let s=(await Tk(o,"POST","/api/review-gate/replay",{repo:e,prs:t.map(Number),...o.gitlab?{forge:"gitlab"}:{}})).body.getReader(),r=new TextDecoder,i="";for(;;){let{done:a,value:l}=await s.read();l&&(i+=r.decode(l,{stream:!0}));let c;for(;(c=i.indexOf(`
|
|
557
|
-
`))>=0;){let u=i.slice(0,c).trim();if(i=i.slice(c+1),!u)continue;let d=JSON.parse(u);d.done?console.log($t.bold(` flagged ${d.flagged} of ${d.of}`)):d.error?console.log(` #${d.pr} ${$t.yellow("error")} ${$t.dim(d.error)}`):console.log(` #${d.pr} ${Ok(d.state)}${d.flagged?$t.red(" flagged"):""} ${$t.dim(d.reason)}`)}if(a)break}});Z();import{Command as jO}from"commander";import Xn from"chalk";import{resolve as _O}from"path";var cl=new jO().name("cloud-sessions").description("list and close the Claude cloud sessions that block their GitHub issue"),Ik=e=>e.option("--file <path>","session file",".agentx/cloud-sessions.json").option("-c, --config <path>","daemon config file, for each agent's openHours");function Nk(e){return new Xm(_O(process.cwd(),e.file||".agentx/cloud-sessions.json"))}function DO(e){let t={};try{t=O(e.config).agents}catch{}return o=>t[o]?.cloudSessions?.openHours??Km.openHours}function PO(e){let t=e.trim().match(/^([^\/\s#:]+\/[^\/\s#:]+)(?:#|:(?:issue|pull):)(\d+)$/);if(!t)return;let o=Number(t[2]);return o>0?{repo:t[1],number:o}:void 0}Ik(cl.command("list").description("cloud sessions still open for their issue, newest first").option("--all","include sessions whose open time is over")).action(e=>{let t=DO(e),o=Date.now(),n=Nk(e).all().map(s=>({s,open:o-s.startedAt<t(s.agentId)*36e5})).filter(s=>e.all||s.open).sort((s,r)=>r.s.startedAt-s.s.startedAt);if(!n.length){console.log(Xn.dim(` no ${e.all?"":"open "}cloud sessions`));return}for(let{s,open:r}of n){let i=new Date(s.startedAt).toISOString().slice(0,16).replace("T"," ");console.log(` ${s.repo}#${s.number} ${s.sessionId} ${Xn.dim(`${s.agentId}, started ${i}`)} ${r?Xn.yellow("open"):Xn.dim("over")}`)}});Ik(cl.command("close <refs...>").description("forget the session for each issue (owner/repo#42), so its next comment runs normally")).action((e,t)=>{let o=Nk(t),n=!1;for(let s of e){let r=PO(s);if(!r){console.log(Xn.red(` ${s}: expected owner/repo#number`)),n=!0;continue}o.close(r.repo,r.number)?console.log(Xn.green(` closed ${r.repo}#${r.number}`)):console.log(Xn.dim(` ${r.repo}#${r.number}: no session recorded`))}n&&(process.exitCode=1)});import{Command as MO}from"commander";import yt from"chalk";import{existsSync as fu,rmSync as LO}from"fs";import{resolve as hu}from"path";var sr=new MO().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");sr.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,t,o)=>{t.length===0&&(console.log(yt.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),r=await Mm(e,t,{verbose:n}),i=Date.now()-s;console.log(yt.green(` \u2713 indexed ${r.docs} doc(s) for ${yt.bold(e)} in ${i}ms`)),console.log(yt.dim(` \u2192 ${r.path}`))});sr.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=hu(e.cwd,".agentx","rag");if(!fu(t)){console.log(yt.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>fu(hu(t,s,"index.json")));if(n.length===0){console.log(yt.dim(" (no indexes)"));return}for(let s of n.sort()){let r=uc(s);console.log(` ${yt.bold(s)} ${r.docs} doc(s) ${yt.dim(r.path)}`)}});sr.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,t,o)=>{let n=parseInt(o.k,10)||5,s=Lm(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let r=uc(e);r.exists?console.log(yt.dim(` (no hits in ${r.docs} indexed docs)`)):console.log(yt.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let r of s)console.log(` ${yt.bold(r.title)} ${yt.dim(`(${r.score.toFixed(2)})`)}`),console.log(` ${yt.dim(r.path)}`),console.log(` ${yt.dim(r.snippet.slice(0,200))}`)});sr.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=hu(process.cwd(),".agentx","rag",e);if(!fu(t)){console.log(yt.dim(` no index for ${e} \u2014 nothing to clear`));return}LO(t,{recursive:!0,force:!0}),console.log(yt.green(` \u2713 cleared index for ${e}`))});Z();import{Command as qO}from"commander";import we from"chalk";import rr from"prompts";var Vn=new qO().name("backlog").description("manage the local backlog used by business workSource=backlog");function ci(e){let t=O(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new yh(n)}}function FO(e){return e?we.cyan(`${e.type}:${e.project}#${e.iid}`):we.dim("manual")}function UO(e){return{todo:we.gray("todo"),doing:we.yellow("doing"),blocked:we.red("blocked"),done:we.green("done")}[e]}Vn.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:t}=ci(e.config),o=t.list();if(e.status&&(o=o.filter(n=>n.status===e.status)),e.assignee&&(o=o.filter(n=>n.assignee===e.assignee)),e.source&&(o=o.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!o.length){console.log(we.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?we.magenta(`@${n.assignee}`):we.dim("unassigned");console.log(` ${UO(n.status).padEnd(7)} ${FO(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(we.dim(` ${n.source.url}`))}console.log(),console.log(we.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});Vn.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,t,o)=>{let n=ci(o.config);n.store.findById(e)||(console.error(we.red(` item ${e} not found`)),process.exit(1));let r=n.store.update(e,{assignee:t,status:"doing"});if(console.log(we.green(` claimed: ${r.title} -> ${t}`)),r.source){let i=Df([t],r.source,n.config),a=await Oc(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...l)=>console.log(we.dim(" sync:"),...l));console.log(a.ok?we.dim(` synced -> ${a.url??r.source.type}`):we.yellow(` sync failed: ${a.error}`))}});Vn.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,t)=>{let o=ci(t.config);o.store.findById(e)||(console.error(we.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(we.green(` done: ${s.title}`)),s.source){let r=await Oc(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...i)=>console.log(we.dim(" sync:"),...i));console.log(r.ok?we.dim(` synced -> ${r.url??s.source.type}`):we.yellow(` sync failed: ${r.error}`))}});Vn.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,t)=>{let{store:o}=ci(t.config);o.remove(e)||(console.error(we.red(` item ${e} not found`)),process.exit(1)),console.log(we.green(` removed ${e}`))});Vn.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let t=ci(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(we.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await rr({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!o&&(console.error(we.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(we.red(" channels.github.token not configured")),process.exit(1));let r=e.project;if(!r){let y=s==="gitlab"?BO(t.config):HO(t.config);y.length?(r=(await rr({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map($=>({title:$,value:$})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,r==="__CUSTOM__"&&(r=(await rr({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):r=(await rr({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!r)return;let a=((await rr({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(we.dim(` fetching open issues from ${s}:${r}${a?` (search: ${a})`:""}\u2026`));let l=s==="gitlab"?await JO(t.config,r,a):await GO(t.config,r,a);if(!l.length){console.log(we.yellow(" no open issues matched"));return}console.log(we.dim(` ${l.length} open issue${l.length===1?"":"s"}`));let c=r,u=new Set(t.store.list().map(y=>y.id)),d=l.map(y=>{let w=qc({type:s,project:c,iid:y.iid,url:y.url}),$=u.has(w),x=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${x}${$?we.dim(" (already imported)"):""}`,value:y,disabled:$}}),f=(await rr({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(we.dim(" nothing selected"));return}let g=f.map(y=>{let w={type:s,host:s==="gitlab"?WO(t.config):void 0,project:c,iid:y.iid,url:y.url};return{id:qc(w),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:w,importedAt:new Date().toISOString()}}),h=t.store.addMany(g);console.log(we.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let y of h)console.log(we.dim(` ${y.id} \u2014 ${y.title}`))});function WO(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function BO(e){let t=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&t.add(n.project);let o=e.business?.workSource;if(o?.type==="gitlab")for(let n of o.projects??[])t.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&t.add(n.id);return[...t].sort()}function HO(e){let t=new Set;for(let o of e.channels.github?.routes??[])o.repo&&o.repo!=="*"&&t.add(o.repo);return[...t].sort()}async function JO(e,t,o){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});o&&s.set("search",o);let r=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(t)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);let i=await r.json();return Array.isArray(i)?i.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(l=>typeof l=="string"?l:l.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function GO(e,t,o){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},r;if(o){let l=`repo:${t} is:issue is:open ${o}`;r=`https://api.github.com/search/issues?q=${encodeURIComponent(l)}&per_page=100&sort=updated&order=desc`;let c=await fetch(r,{headers:s});if(!c.ok)throw new Error(`GitHub ${c.status}: ${await c.text().catch(()=>"")}`);return((await c.json()).items??[]).map(jk)}r=`https://api.github.com/repos/${t}/issues?state=open&per_page=100&sort=updated&direction=desc`;let i=await fetch(r,{headers:s});if(!i.ok)throw new Error(`GitHub ${i.status}: ${await i.text().catch(()=>"")}`);let a=await i.json();return Array.isArray(a)?a.filter(l=>!l.pull_request).map(jk):[]}function jk(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as zO}from"commander";import te from"chalk";import{existsSync as YO,readFileSync as KO}from"fs";import{resolve as XO}from"path";import VO from"prompts";Z();function _k(e){let t=e||XO(process.cwd(),"agentx.json");return YO(t)||(console.log(te.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(KO(t,"utf-8"))}async function QO(e,t){if(!e)return;if(e==="me"){let n=t?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(te.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:r,accountId:i}=await VO([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!r?void 0:{channel:s,chatId:r,accountId:i||void 0}}let o=e.split(":");if(o.length>=2)return{channel:o[0],chatId:o[1],accountId:o[2]};console.log(te.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Do=new zO().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Do.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--no-deliver","send only failures to --notify, not each run's answer").option("--only-exceptions","the run decides: an answer of NOTHING_TO_REPORT sends nothing to --notify").option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${Rr})`,Rr).option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,t)=>{if(!e){Do.help();return}t.agent||(console.log(te.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(te.red(' --do "<prompt>" is required')),process.exit(1));let o=fc(e);o||(console.log(te.red(` Couldn't parse: "${e}"`)),console.log(te.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(te.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(te.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=_k(t.config),s=xn(n);n.agents?.[t.agent]||(console.log(te.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(te.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let r=await QO(t.notify,s),i=t.id||sp(o.matched,t.agent),a=ip({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:r,deliverResult:t.deliver,report:t.onlyExceptions?"exceptions":void 0,onError:rp(t.onError),enabled:!t.disabled}),l=a.onError,c=await pe(d=>Be(d,`crons.${i}`,a),{configPath:t.config,dryRun:!!t.dryRun});c.success||(console.log(te.red(` \u2717 ${c.error}`)),process.exit(1));let u=t.dryRun?"would add":"Added";console.log(te.green(` \u2713 ${u} cron ${te.cyan(i)}`)),console.log(te.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(te.dim(` Agent: ${t.agent}`)),r&&console.log(te.dim(` Notify: ${r.channel} ${r.chatId} ${hc(a)}`)),l.length&&console.log(te.dim(` On error: ${l.join(", ")}`)),!t.dryRun&&c.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))});Do.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let o=_k(e.config).crons||{},n=Object.entries(o),s=new Set;try{let{loadDaemonConfig:r}=await import("./config-LTXRWDRK.js");for(let[i,a]of Object.entries(r(e.config).crons))o[i]||(s.add(i),n.push([i,a]))}catch{}if(!n.length){console.log(te.dim(" No scheduled jobs"));return}console.log();for(let[r,i]of n){let a=i.approval?te.yellow("\u25D0"):i.enabled?te.green("\u25CF"):te.dim("\u25CB"),l=i.schedule;try{l=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${a} ${te.cyan(r.padEnd(32))} ${te.dim(i.schedule.padEnd(14))} ${te.dim("\u2192")} ${i.agent}`),console.log(te.dim(` ${l} (${i.timezone||"UTC"})`)),i.notify&&console.log(te.dim(` notify: ${i.notify.channel} ${i.notify.chatId} ${hc(i)}`)),i.createdBy&&console.log(te.dim(` created by agent: ${i.createdBy}`)),s.has(r)&&console.log(te.dim(" built in: added by AgentX from your settings; a job of the same id in crons replaces it")),i.approval){let c=i.timezone||"UTC",u=lp(ap(i.schedule,c),c);console.log(te.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${u}`)),console.log(te.dim(` agentx schedule approve ${r} | agentx schedule reject ${r}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])Do.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await up(o,t);n.success||(console.log(te.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(te.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))});Do.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await pe(o=>{if(!Ts(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);Um(o,`crons.${e}`)});t.success||(console.log(te.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(te.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",cp,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",dp,"reject an agent's pending create/delete request (drops the request)"]])Do.command(`${e} <id>`).description(o).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let r=await t(n,{configPath:s.config});r.success||(console.log(te.red(` \u2717 ${r.message}`)),process.exit(1)),console.log(te.green(` \u2713 ${r.message}`)),r.result?.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))});Do.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=fc(t);o||(console.log(te.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(te.green(` "${t}"`)),console.log(te.dim(` \u2192 ${o.cron}`)),console.log(te.dim(` \u2192 ${o.human}`))});import{Command as w1}from"commander";import Kk from"chalk";import{existsSync as b1,readFileSync as $1}from"fs";import{resolve as Vk}from"path";import{existsSync as ZO,readFileSync as e1,writeFileSync as t1}from"fs";import{join as bu}from"path";var yu="leads.md",Dk="opt-outs.md",Pk=864e5,wu=/\d{4}-\d{2}-\d{2}/;function o1(e){return e.split(`
|
|
557
|
+
`))>=0;){let u=i.slice(0,c).trim();if(i=i.slice(c+1),!u)continue;let d=JSON.parse(u);d.done?console.log($t.bold(` flagged ${d.flagged} of ${d.of}`)):d.error?console.log(` #${d.pr} ${$t.yellow("error")} ${$t.dim(d.error)}`):console.log(` #${d.pr} ${Ok(d.state)}${d.flagged?$t.red(" flagged"):""} ${$t.dim(d.reason)}`)}if(a)break}});Z();import{Command as jO}from"commander";import Xn from"chalk";import{resolve as _O}from"path";var cl=new jO().name("cloud-sessions").description("list and close the Claude cloud sessions that block their GitHub issue"),Ik=e=>e.option("--file <path>","session file",".agentx/cloud-sessions.json").option("-c, --config <path>","daemon config file, for each agent's openHours");function Nk(e){return new Xm(_O(process.cwd(),e.file||".agentx/cloud-sessions.json"))}function DO(e){let t={};try{t=O(e.config).agents}catch{}return o=>t[o]?.cloudSessions?.openHours??Km.openHours}function PO(e){let t=e.trim().match(/^([^\/\s#:]+\/[^\/\s#:]+)(?:#|:(?:issue|pull):)(\d+)$/);if(!t)return;let o=Number(t[2]);return o>0?{repo:t[1],number:o}:void 0}Ik(cl.command("list").description("cloud sessions still open for their issue, newest first").option("--all","include sessions whose open time is over")).action(e=>{let t=DO(e),o=Date.now(),n=Nk(e).all().map(s=>({s,open:o-s.startedAt<t(s.agentId)*36e5})).filter(s=>e.all||s.open).sort((s,r)=>r.s.startedAt-s.s.startedAt);if(!n.length){console.log(Xn.dim(` no ${e.all?"":"open "}cloud sessions`));return}for(let{s,open:r}of n){let i=new Date(s.startedAt).toISOString().slice(0,16).replace("T"," ");console.log(` ${s.repo}#${s.number} ${s.sessionId} ${Xn.dim(`${s.agentId}, started ${i}`)} ${r?Xn.yellow("open"):Xn.dim("over")}`)}});Ik(cl.command("close <refs...>").description("forget the session for each issue (owner/repo#42), so its next comment runs normally")).action((e,t)=>{let o=Nk(t),n=!1;for(let s of e){let r=PO(s);if(!r){console.log(Xn.red(` ${s}: expected owner/repo#number`)),n=!0;continue}o.close(r.repo,r.number)?console.log(Xn.green(` closed ${r.repo}#${r.number}`)):console.log(Xn.dim(` ${r.repo}#${r.number}: no session recorded`))}n&&(process.exitCode=1)});import{Command as MO}from"commander";import yt from"chalk";import{existsSync as fu,rmSync as LO}from"fs";import{resolve as hu}from"path";var sr=new MO().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");sr.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,t,o)=>{t.length===0&&(console.log(yt.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),r=await Mm(e,t,{verbose:n}),i=Date.now()-s;console.log(yt.green(` \u2713 indexed ${r.docs} doc(s) for ${yt.bold(e)} in ${i}ms`)),console.log(yt.dim(` \u2192 ${r.path}`))});sr.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=hu(e.cwd,".agentx","rag");if(!fu(t)){console.log(yt.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>fu(hu(t,s,"index.json")));if(n.length===0){console.log(yt.dim(" (no indexes)"));return}for(let s of n.sort()){let r=uc(s);console.log(` ${yt.bold(s)} ${r.docs} doc(s) ${yt.dim(r.path)}`)}});sr.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,t,o)=>{let n=parseInt(o.k,10)||5,s=Lm(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let r=uc(e);r.exists?console.log(yt.dim(` (no hits in ${r.docs} indexed docs)`)):console.log(yt.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let r of s)console.log(` ${yt.bold(r.title)} ${yt.dim(`(${r.score.toFixed(2)})`)}`),console.log(` ${yt.dim(r.path)}`),console.log(` ${yt.dim(r.snippet.slice(0,200))}`)});sr.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=hu(process.cwd(),".agentx","rag",e);if(!fu(t)){console.log(yt.dim(` no index for ${e} \u2014 nothing to clear`));return}LO(t,{recursive:!0,force:!0}),console.log(yt.green(` \u2713 cleared index for ${e}`))});Z();import{Command as qO}from"commander";import we from"chalk";import rr from"prompts";var Vn=new qO().name("backlog").description("manage the local backlog used by business workSource=backlog");function ci(e){let t=O(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new yh(n)}}function FO(e){return e?we.cyan(`${e.type}:${e.project}#${e.iid}`):we.dim("manual")}function UO(e){return{todo:we.gray("todo"),doing:we.yellow("doing"),blocked:we.red("blocked"),done:we.green("done")}[e]}Vn.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:t}=ci(e.config),o=t.list();if(e.status&&(o=o.filter(n=>n.status===e.status)),e.assignee&&(o=o.filter(n=>n.assignee===e.assignee)),e.source&&(o=o.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!o.length){console.log(we.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?we.magenta(`@${n.assignee}`):we.dim("unassigned");console.log(` ${UO(n.status).padEnd(7)} ${FO(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(we.dim(` ${n.source.url}`))}console.log(),console.log(we.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});Vn.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,t,o)=>{let n=ci(o.config);n.store.findById(e)||(console.error(we.red(` item ${e} not found`)),process.exit(1));let r=n.store.update(e,{assignee:t,status:"doing"});if(console.log(we.green(` claimed: ${r.title} -> ${t}`)),r.source){let i=Df([t],r.source,n.config),a=await Oc(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...l)=>console.log(we.dim(" sync:"),...l));console.log(a.ok?we.dim(` synced -> ${a.url??r.source.type}`):we.yellow(` sync failed: ${a.error}`))}});Vn.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,t)=>{let o=ci(t.config);o.store.findById(e)||(console.error(we.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(we.green(` done: ${s.title}`)),s.source){let r=await Oc(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...i)=>console.log(we.dim(" sync:"),...i));console.log(r.ok?we.dim(` synced -> ${r.url??s.source.type}`):we.yellow(` sync failed: ${r.error}`))}});Vn.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,t)=>{let{store:o}=ci(t.config);o.remove(e)||(console.error(we.red(` item ${e} not found`)),process.exit(1)),console.log(we.green(` removed ${e}`))});Vn.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let t=ci(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(we.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await rr({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!o&&(console.error(we.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(we.red(" channels.github.token not configured")),process.exit(1));let r=e.project;if(!r){let y=s==="gitlab"?BO(t.config):HO(t.config);y.length?(r=(await rr({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map($=>({title:$,value:$})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,r==="__CUSTOM__"&&(r=(await rr({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):r=(await rr({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!r)return;let a=((await rr({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(we.dim(` fetching open issues from ${s}:${r}${a?` (search: ${a})`:""}\u2026`));let l=s==="gitlab"?await JO(t.config,r,a):await GO(t.config,r,a);if(!l.length){console.log(we.yellow(" no open issues matched"));return}console.log(we.dim(` ${l.length} open issue${l.length===1?"":"s"}`));let c=r,u=new Set(t.store.list().map(y=>y.id)),d=l.map(y=>{let w=qc({type:s,project:c,iid:y.iid,url:y.url}),$=u.has(w),x=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${x}${$?we.dim(" (already imported)"):""}`,value:y,disabled:$}}),f=(await rr({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(we.dim(" nothing selected"));return}let g=f.map(y=>{let w={type:s,host:s==="gitlab"?WO(t.config):void 0,project:c,iid:y.iid,url:y.url};return{id:qc(w),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:w,importedAt:new Date().toISOString()}}),h=t.store.addMany(g);console.log(we.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let y of h)console.log(we.dim(` ${y.id} \u2014 ${y.title}`))});function WO(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function BO(e){let t=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&t.add(n.project);let o=e.business?.workSource;if(o?.type==="gitlab")for(let n of o.projects??[])t.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&t.add(n.id);return[...t].sort()}function HO(e){let t=new Set;for(let o of e.channels.github?.routes??[])o.repo&&o.repo!=="*"&&t.add(o.repo);return[...t].sort()}async function JO(e,t,o){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});o&&s.set("search",o);let r=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(t)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);let i=await r.json();return Array.isArray(i)?i.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(l=>typeof l=="string"?l:l.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function GO(e,t,o){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},r;if(o){let l=`repo:${t} is:issue is:open ${o}`;r=`https://api.github.com/search/issues?q=${encodeURIComponent(l)}&per_page=100&sort=updated&order=desc`;let c=await fetch(r,{headers:s});if(!c.ok)throw new Error(`GitHub ${c.status}: ${await c.text().catch(()=>"")}`);return((await c.json()).items??[]).map(jk)}r=`https://api.github.com/repos/${t}/issues?state=open&per_page=100&sort=updated&direction=desc`;let i=await fetch(r,{headers:s});if(!i.ok)throw new Error(`GitHub ${i.status}: ${await i.text().catch(()=>"")}`);let a=await i.json();return Array.isArray(a)?a.filter(l=>!l.pull_request).map(jk):[]}function jk(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as zO}from"commander";import te from"chalk";import{existsSync as YO,readFileSync as KO}from"fs";import{resolve as XO}from"path";import VO from"prompts";Z();function _k(e){let t=e||XO(process.cwd(),"agentx.json");return YO(t)||(console.log(te.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(KO(t,"utf-8"))}async function QO(e,t){if(!e)return;if(e==="me"){let n=t?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(te.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:r,accountId:i}=await VO([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!r?void 0:{channel:s,chatId:r,accountId:i||void 0}}let o=e.split(":");if(o.length>=2)return{channel:o[0],chatId:o[1],accountId:o[2]};console.log(te.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Do=new zO().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Do.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--no-deliver","send only failures to --notify, not each run's answer").option("--only-exceptions","the run decides: an answer of NOTHING_TO_REPORT sends nothing to --notify").option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${Rr})`,Rr).option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,t)=>{if(!e){Do.help();return}t.agent||(console.log(te.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(te.red(' --do "<prompt>" is required')),process.exit(1));let o=fc(e);o||(console.log(te.red(` Couldn't parse: "${e}"`)),console.log(te.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(te.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(te.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=_k(t.config),s=xn(n);n.agents?.[t.agent]||(console.log(te.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(te.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let r=await QO(t.notify,s),i=t.id||sp(o.matched,t.agent),a=ip({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:r,deliverResult:t.deliver,report:t.onlyExceptions?"exceptions":void 0,onError:rp(t.onError),enabled:!t.disabled}),l=a.onError,c=await pe(d=>Be(d,`crons.${i}`,a),{configPath:t.config,dryRun:!!t.dryRun});c.success||(console.log(te.red(` \u2717 ${c.error}`)),process.exit(1));let u=t.dryRun?"would add":"Added";console.log(te.green(` \u2713 ${u} cron ${te.cyan(i)}`)),console.log(te.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(te.dim(` Agent: ${t.agent}`)),r&&console.log(te.dim(` Notify: ${r.channel} ${r.chatId} ${hc(a)}`)),l.length&&console.log(te.dim(` On error: ${l.join(", ")}`)),!t.dryRun&&c.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))});Do.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let o=_k(e.config).crons||{},n=Object.entries(o),s=new Set;try{let{loadDaemonConfig:r}=await import("./config-S522VXLI.js");for(let[i,a]of Object.entries(r(e.config).crons))o[i]||(s.add(i),n.push([i,a]))}catch{}if(!n.length){console.log(te.dim(" No scheduled jobs"));return}console.log();for(let[r,i]of n){let a=i.approval?te.yellow("\u25D0"):i.enabled?te.green("\u25CF"):te.dim("\u25CB"),l=i.schedule;try{l=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${a} ${te.cyan(r.padEnd(32))} ${te.dim(i.schedule.padEnd(14))} ${te.dim("\u2192")} ${i.agent}`),console.log(te.dim(` ${l} (${i.timezone||"UTC"})`)),i.notify&&console.log(te.dim(` notify: ${i.notify.channel} ${i.notify.chatId} ${hc(i)}`)),i.createdBy&&console.log(te.dim(` created by agent: ${i.createdBy}`)),s.has(r)&&console.log(te.dim(" built in: added by AgentX from your settings; a job of the same id in crons replaces it")),i.approval){let c=i.timezone||"UTC",u=lp(ap(i.schedule,c),c);console.log(te.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${u}`)),console.log(te.dim(` agentx schedule approve ${r} | agentx schedule reject ${r}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])Do.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await up(o,t);n.success||(console.log(te.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(te.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))});Do.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await pe(o=>{if(!Ts(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);Um(o,`crons.${e}`)});t.success||(console.log(te.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(te.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",cp,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",dp,"reject an agent's pending create/delete request (drops the request)"]])Do.command(`${e} <id>`).description(o).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let r=await t(n,{configPath:s.config});r.success||(console.log(te.red(` \u2717 ${r.message}`)),process.exit(1)),console.log(te.green(` \u2713 ${r.message}`)),r.result?.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))});Do.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=fc(t);o||(console.log(te.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(te.green(` "${t}"`)),console.log(te.dim(` \u2192 ${o.cron}`)),console.log(te.dim(` \u2192 ${o.human}`))});import{Command as w1}from"commander";import Kk from"chalk";import{existsSync as b1,readFileSync as $1}from"fs";import{resolve as Vk}from"path";import{existsSync as ZO,readFileSync as e1,writeFileSync as t1}from"fs";import{join as bu}from"path";var yu="leads.md",Dk="opt-outs.md",Pk=864e5,wu=/\d{4}-\d{2}-\d{2}/;function o1(e){return e.split(`
|
|
558
558
|
`).map(t=>t.trim()).filter(t=>/^[-*]\s+\S/.test(t)).map(t=>t.replace(/^[-*]\s+/,"").split("|").map(o=>o.trim()))}function n1(e){return e.split(`
|
|
559
559
|
`).filter(t=>/^\s*[-*]\s+\S/.test(t)).map(t=>{let[o,n="",...s]=t.trim().replace(/^[-*]\s+/,"").split("|").map(i=>i.trim()),r={name:o,company:n,line:t.trim()};for(let i of s){let a=i.toLowerCase();a.startsWith("last contact")?r.lastContact=i.match(wu)?.[0]:a.startsWith("added")?r.added=i.match(wu)?.[0]:a.startsWith("offered:")?r.offered=i.slice(8).trim():a.startsWith("next:")&&(r.next=i.slice(5).trim())}return r}).filter(t=>t.name)}function Mk(e){return o1(e).map(([t="",o="",n,s])=>({name:t,company:o,date:n?.match(wu)?.[0],reason:s||void 0})).filter(t=>t.name)}var dl=e=>e.trim().toLowerCase().replace(/\s+/g," ");function di(e,t){return t.some(o=>dl(o.name)===dl(e.name)&&(!o.company||dl(o.company)===dl(e.company)))}var s1=e=>/^done\b/i.test(e.next??""),ir=e=>Date.parse(`${e}T00:00:00Z`);function Lk(e,t,o,n=7){let s=ir(o)-n*Pk;return e.filter(r=>{if(s1(r)||di(r,t))return!1;let i=r.lastContact??r.added;return!i||ir(i)<=s})}function qk(e,t,o,n=1){let s=ir(o)-(n-1)*Pk;return e.filter(r=>r.added&&ir(r.added)>=s&&ir(r.added)<=ir(o)&&!di(r,t))}function $u(e){return ZO(e)?e1(e,"utf-8"):""}function Fk(e){return n1($u(bu(e,yu)))}function Uk(e){return Mk($u(bu(e,Dk)))}var r1=`# Opt-outs
|
|
560
560
|
|
|
@@ -605,7 +605,7 @@ ${oe.text}`));T.delivery.reached.of++,ie&&T.delivery.reached.n++;let j=P[0]??Q[0
|
|
|
605
605
|
Plan ${q.dim(`[${r.state}] by ${r.createdBy}, ${os(r.createdAt)}`)}`),$v(s.steps(e)),console.log(`
|
|
606
606
|
Log`);for(let i of s.events(e))console.log(q.dim(` ${os(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});Mo.command("step <id> <step>").description("move a step of a request's plan on: --retry, --skip or --done").option("--retry","hand the step to its agent again, with a fresh count of nudges (approves a message whose card expired)").option("--skip","leave the step out; the plan goes on with the next one").option("--done","mark the step done yourself").option("--note <text>","why, or the evidence for --done").action((e,t,o)=>{let n=["retry","skip","done"].filter(l=>o[l]);if(n.length!==1){console.error(q.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=cr();if(!s)return;let r=fl();if(!r){process.exitCode=1;return}let i=Number(t),a=Rf(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(q.red(` ${a}`)),process.exitCode=1;return}console.log(q.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+q.dim(" (the daemon goes on within a minute)")),$v(r.steps(e))});function kv(e,t,o,n){let s=Mo.command(`${e} <id>`).description(t).option(o,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped");e==="done"&&s.option("--reason <text>",'close it by hand without a link, saying why ("checked by hand"); also closes a loop its check cannot verify'),s.action((r,i)=>{let a=cr();if(!a)return;let l=e==="done"?i.evidence??(i.reason?`closed by owner: ${i.reason}`:void 0):i.reason??"dropped by the owner";if(!l){console.error(q.red(` ${n}`)),process.exitCode=1;return}let c=a.get(r);if(!c||c.state==="candidate"){console.error(q.red(` no request "${r}"`)),process.exitCode=1;return}let u=process.env.AGENTX_AGENT_ID?.trim()||Kg;if(!a.close(r,e==="done"?"done":"dropped",l,Date.now(),null,u)){console.error(q.red(` ${r} is already closed (${_u[c.state]??c.state})`)),process.exitCode=1;return}console.log(q.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}kv("done","close a request as finished, with a link to the evidence or the reason","--evidence <link>","a finished request needs --evidence <link> or --reason <text>");kv("drop","drop a request you no longer want","--reason <text>","");Mo.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").option("--headlines <on|off>","write a headline for a request its agent did not describe (one small model call each)").option("--catch <on|off>","read the reply of each of your turns for a promise or a question to you (one small model call each)").option("--catch-cap <n>","model calls a day the promise catch may make").option("--settle <on|off>","close a quiet request whose handed work all came back done, instead of bringing it back to you").option("--home-closes <on|off>","close a request once its issue or merge request home is merged or closed as completed").option("--plans <on|off>","follow requests of two or more steps as tracked plans").option("--stall-minutes <n>","minutes without progress before a plan step's agent is nudged").option("--max-nudges <n>","nudges per step before it counts as blocked and you are told").option("--approve-kinds <kind,...>",'step kinds you approve once when the plan is made; "none" to clear').option("--plans-off-for <agent,...>",'agents that may not open a plan; "none" to clear').option("--plan-for <work,...>",'kinds of work an agent must plan before it starts (default code); "none" to clear').option("--plan-over <minutes>","work estimated over this many minutes needs a plan (default 30); 0 turns it off").option("--checks <kind,...>",`checks agents may use to close a loop (${Ni.join(", ")}); "none" to turn them all off`).option("--check-every <minutes>","how often each open loop's check runs").option("--auto-resend <on|off>","send a request stopped by a usage limit or a restart back to its agent once, on its own").option("--resend-after <minutes>","minutes after it stopped before it is resent (a limit also waits for its reset)").option("--resend-hold-hours <n>","hours your notice waits for the resend before you are told anyway").option("--flow-zone <zone>","the time zone whose day the flow rate counts by, for example Africa/Tunis").action(async e=>{let t={};try{let u=(y,w)=>{if(w===void 0)return;let $=Number(w);if(!($>0))throw new Error(`${y} must be a positive number`);return $},d=(y,w)=>y===void 0?void 0:y===w?[]:y.split(",").map($=>$.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");t.enabled=e.enabled==="on"}if(t.from=d(e.from,"none"),t.channels=d(e.channels,"all"),t.staleAfterHours=u("--stale-hours",e.staleHours),t.retentionDays=u("--retention-days",e.retentionDays),e.headlines!==void 0){if(e.headlines!=="on"&&e.headlines!=="off")throw new Error("--headlines takes on or off");t.headlines={enabled:e.headlines==="on"}}if(e.catch!==void 0||e.catchCap!==void 0){if(e.catch!==void 0&&e.catch!=="on"&&e.catch!=="off")throw new Error("--catch takes on or off");let y=u("--catch-cap",e.catchCap);if(y!==void 0&&!Number.isInteger(y))throw new Error("--catch-cap must be a whole number");t.catchPromises={...e.catch!==void 0?{enabled:e.catch==="on"}:{},...y!==void 0?{dailyCap:y}:{}}}if(e.settle!==void 0){if(e.settle!=="on"&&e.settle!=="off")throw new Error("--settle takes on or off");t.settleHandedBack=e.settle==="on"}if(e.homeCloses!==void 0){if(e.homeCloses!=="on"&&e.homeCloses!=="off")throw new Error("--home-closes takes on or off");t.homeCloses=e.homeCloses==="on"}let p={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");p.enabled=e.plans==="on"}if(p.stallMinutes=u("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let y=Number(e.maxNudges);if(!Number.isInteger(y)||y<0)throw new Error("--max-nudges must be a whole number, 0 or more");p.maxNudges=y}if(p.approveKinds=d(e.approveKinds,"none"),p.disabledAgents=d(e.plansOffFor,"none"),p.requireForWork=d(e.planFor,"none"),e.planOver!==void 0){let y=Number(e.planOver);if(!(y>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");p.requireOverMinutes=y}Object.values(p).some(y=>y!==void 0)&&(t.plans=p);let f={},g=d(e.checks,"none");if(g){let y=g.filter(w=>!Ni.includes(w));if(y.length)throw new Error(`unknown check ${y.join(", ")}: use ${Ni.join(", ")}`);f.enabled=g}f.checkEveryMinutes=u("--check-every",e.checkEvery),Object.values(f).some(y=>y!==void 0)&&(t.checkers=f);let h={};if(e.autoResend!==void 0){if(e.autoResend!=="on"&&e.autoResend!=="off")throw new Error("--auto-resend takes on or off");h.enabled=e.autoResend==="on"}if(e.resendAfter!==void 0){let y=Number(e.resendAfter);if(!(y>=0))throw new Error("--resend-after must be a number of minutes, 0 or more");h.afterMinutes=y}h.holdMaxHours=u("--resend-hold-hours",e.resendHoldHours),Object.values(h).some(y=>y!==void 0)&&(t.autoResend=h),e.flowZone!==void 0&&(t.flow={timeZone:e.flowZone})}catch(u){console.error(q.red(` ${u.message}`)),process.exitCode=1;return}if(Object.values(t).some(u=>u!==void 0)){let u=await cf(t);if(!u.success){console.error(q.red(` ${u.error}`)),process.exitCode=1;return}console.log(q.green(" \u2713 saved")+(u.reloaded?q.dim(" (daemon reloaded)"):""))}let o=Or();console.log(` Requests ${o.enabled?"on":"off"}`),console.log(` Channels ${o.channels.length?o.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${o.from.length?o.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${o.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${o.retentionDays} day(s)`),console.log(` Headlines ${o.headlines?.enabled===!1?"off: titled with the start of your words":"on: written when the agent gave none"}`);let n=o.catchPromises;console.log(` Catch promises ${n?.enabled?`on: each of your turns' reply is read, up to ${n.dailyCap} call(s) a day`:"off"}`),console.log(` Handed work came back ${o.settleHandedBack===!1?"comes back to you when quiet":"closed when quiet, with its link or marked unproven"}`),console.log(` Home closed ${o.homeCloses===!1?"left open":"closes the request: merged, or closed as completed"}`);let s=o.plans??ta;console.log(` Plans ${s.enabled?"on":"off"}`),console.log(` Nudge a quiet step after ${s.stallMinutes} minute(s), up to ${s.maxNudges} time(s)`),console.log(` You approve up front ${s.approveKinds.length?s.approveKinds.join(", "):"nothing"}`),console.log(` Plans off for ${s.disabledAgents.length?s.disabledAgents.join(", "):"no agent"}`);let r=s.requireOverMinutes??ta.requireOverMinutes,i=s.requireForWork??ta.requireForWork;console.log(` Plan before starting ${[i.length?`${i.join(", ")} work`:"",r>0?`work over ${r} minute(s)`:""].filter(Boolean).join("; ")||"never required"}`);let a=o.autoResend??Af;console.log(` Resend once ${a.enabled?`on: after a usage limit resets or a restart, ${a.afterMinutes} minute(s) on; you are told after ${a.holdMaxHours} hour(s) or a second stop`:"off"}`),console.log(` Flow rate counts by ${(o.flow??kc).timeZone} days`);let l=o.checkers??ji;console.log(` Loop checks ${l.enabled.length?l.enabled.join(", "):"off"}, every ${l.checkEveryMinutes} minute(s)`);let c=Object.keys(l.repos);console.log(` Repos for git-ancestor ${c.length?c.join(", "):"none (requests.checkers.repos in agentx.json)"}`)});import{Command as sI}from"commander";import dr from"chalk";Z();var vv=new sI("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Jc.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(dr.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await pe(r=>{n=zh(r,e,t==="on")});s.success||(console.error(dr.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(dr.green(`\u2713 ${n}`)),s.reloaded&&console.log(dr.dim(" daemon hot-reloaded"))}let o=O().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Jc)console.log(` ${n.padEnd(8)} ${o.includes(n)?dr.green("on"):dr.dim("off")}`)});import{Command as jI}from"commander";import ur from"chalk";import Ee from"chalk";import gi from"prompts";import{readFileSync as rI,writeFileSync as iI,existsSync as aI}from"fs";import{resolve as xv}from"path";var lI=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function cI(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Pu(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Sv(e=".env"){let t=xv(e);if(!aI(t))return[];let o=rI(t,"utf-8"),n=[];for(let s of o.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let r=s.match(lI);r?n.push({kind:"kv",key:r[1],value:cI(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function dI(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Pu(t.value)}`:t.raw).join(`
|
|
607
607
|
`)+`
|
|
608
|
-
`}function ns(e,t,o=".env"){let n=xv(o),s=Sv(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Pu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Pu(t)}`})),iI(n,dI(s))}function Mu(e,t=".env"){return Sv(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Ev="https://t.me/BotFather";async function uI(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function gI(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Av(e={}){console.log(),console.log(Ee.bold(" Connect Telegram")),console.log(),console.log(Ee.dim(` 1. Open ${Ev}`)),console.log(Ee.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Ee.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await gi({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&jo(Ev);let{token:o}=await gi({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:v=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(v.trim())||"That doesn't look like a Telegram token"});o||(console.log(Ee.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await uI(o.trim());n||(console.log(Ee.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Ee.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(Ee.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let l=JSON.parse(s(a,"utf-8")),c=Object.keys(l.agents||{});c.length===0&&(console.log(Ee.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await gi({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:c.map(S=>({title:S,value:S})),initial:0})).agent),u||(console.log(Ee.red(" Aborted")),process.exit(1));let d=l.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await gi({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Ee.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;ns(f,o.trim()),process.env[f]=o.trim();let g=await pe(v=>{Be(v,"channels.telegram.enabled",!0),Be(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let S=Ts(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),Be(v,`agents.${u}.mentions`,S))},{configPath:e.configPath});if(g.success||(console.log(Ee.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(Ee.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(Ee.dim(` Token stored in .env as ${f}`)),console.log(Ee.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await gi({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(Ee.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Ee.dim(" Waiting up to 90s..."));let y=await gI(o.trim(),9e4);if(!y){console.log(Ee.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Ee.dim(" agentx config set notifications.destination.channel telegram")),console.log(Ee.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Ee.dim(` agentx config set notifications.destination.accountId ${p}`));return}let w={channel:"telegram",chatId:String(y.chatId),accountId:p},$=[],x=await pe(v=>{Be(v,"notifications.destination",w),$=xa(v,w)},{configPath:e.configPath});if(!x.success){console.log(Ee.red(` \u2717 failed to save destination: ${x.error}`));return}console.log(Ee.green(" \u2713 Default --notify target set")),console.log(Ee.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Ee.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(Ee.dim(` Schedules that now report here: ${$.join(", ")}`)),x.reloaded&&console.log(Ee.dim(" Daemon hot-reloaded."))}import Le from"chalk";import Lu from"prompts";import{existsSync as Fu,mkdirSync as mI,readdirSync as pI,readFileSync as Rv}from"fs";import{resolve as qu}from"path";var fI=".agentx/whatsapp-sessions";function hI(){let e=qu(process.cwd(),".agentx/daemon.pid");if(!Fu(e))return!1;try{let t=parseInt(Rv(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function yI(e){if(!Fu(e))return!1;try{return pI(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function wI(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Le.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Le.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;mI(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let l={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>l},c=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,l):r.keys},...a?{version:a}:{},logger:l,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return c.ev.on("creds.update",i),await new Promise(u=>{let p=setTimeout(()=>{t(Le.yellow(" Timed out waiting for scan (2min)."));try{c.end(void 0)}catch{}u(!1)},12e4);c.ev.on("connection.update",async f=>{if(f.qr){t(Le.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(p),t(Le.green(" \u2713 Paired"));try{c.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(Le.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Tv(e={}){if(console.log(),console.log(Le.bold(" Connect WhatsApp")),console.log(),hI()){console.log(Le.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Le.dim(" agentx daemon stop")),console.log();let{cont:c}=await Lu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});c||(console.log(Le.red(" Aborted")),process.exit(1))}let t=e.configPath||qu(process.cwd(),"agentx.json");Fu(t)||(console.log(Le.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Rv(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||fI,s=qu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Le.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Lu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(Le.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(yI(s)&&a){let{keep:c}=await Lu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!c,c&&console.log(Le.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await wI(s,u=>console.log(u))||(console.log(Le.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let l=await pe(c=>{Be(c,"channels.whatsapp.enabled",!0),Be(c,"channels.whatsapp.sessionDir",n),Be(c,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});l.success||(console.log(Le.red(` \u2717 ${l.error}`)),process.exit(1)),console.log(),console.log(Le.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Le.dim(` Session: ${n}`)),console.log(Le.dim(" Start the daemon to begin receiving:")),console.log(Le.dim(" agentx daemon start")),console.log(Le.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Le.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Le.dim(" Add routes later with:")),console.log(Le.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Tt from"chalk";import bI from"prompts";import{existsSync as $I,readFileSync as kI}from"fs";import{resolve as vI}from"path";async function xI(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function SI(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Lo(e){console.log(Tt.red(` ${e}`)),process.exit(1)}async function ss(e){return(await bI(e,{onCancel:()=>Lo("Aborted")}))[e.name]}async function Cv(e={}){console.log(),console.log(Tt.bold(" Connect email")),console.log();let t=e.configPath||vI(process.cwd(),"agentx.json");$I(t)||Lo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(kI(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Lo("No agents configured. Run: agentx agent add");let s=e.agent??await ss({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(w=>({title:w,value:w}))});o.agents?.[s]||Lo(`No agent "${s}" in ${t}`);let r=(e.address??await ss({type:"text",name:"address",message:"Email address customers write to:",validate:w=>/^\S+@\S+\.\S+$/.test(w.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=Kh(r),l=e.imapHost??a?.imapHost??await ss({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),c=Number(e.imapPort??a?.imapPort??await ss({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await ss({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await ss({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(c)||!Number.isInteger(d))&&Lo("Ports must be numbers.");let p=e.passwordEnv||Vh(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Lo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Tt.dim(` Gmail needs an app password, not your account password: ${Yh}`)),console.log(Tt.dim(" (2-step verification must be on for that page to show.)"))),f=(await ss({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Lo("Aborted");let g={agent:s,address:r,imapHost:l,imapPort:c,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:p,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let w=await xI(g,f);w&&(console.log(Tt.red("\u2717")),Lo(w)),console.log(Tt.green("\u2713"))}e.passwordEnv||(ns(p,f),process.env[p]=f);let h=await pe(w=>{Be(w,"channels.email.enabled",!0),Be(w,`channels.email.accounts.${i}`,Xh(g))},{configPath:e.configPath});h.success||Lo(`Config save failed: ${h.error}`),console.log(),console.log(Tt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Tt.dim(` Password stored in .env as ${p}`)),console.log(Tt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let y=SI(o.agents[s]?.tier,g.allowFrom);y&&console.log(Tt.yellow(` ${y}`)),console.log(g.send==="auto"?Tt.yellow(" Replies are sent as soon as the agent writes them."):Tt.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Tt.dim(" Only mail that arrives from now on is answered.")),console.log(Tt.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as EI}from"crypto";import Qe from"chalk";import Ov from"prompts";var hl="agentx-mesh:",yl="//join/";function AI(e){return Buffer.from(e,"utf-8").toString("base64url")}function RI(e){return Buffer.from(e,"base64url").toString("utf-8")}function TI(e){return`${hl}${yl}${AI(JSON.stringify(e))}`}function CI(e){if(!e.startsWith(`${hl}${yl}`))throw new Error(`Not a mesh invite link \u2014 expected ${hl}${yl}\u2026`);let t=e.slice(hl.length+yl.length),o=JSON.parse(RI(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function OI(){return EI(32).toString("hex")}function II(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function NI(e){return e?.node?.name||e?.node?.id||"node"}async function Iv(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Qe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Mu("MESH_TOKEN");i||(i=OI(),ns("MESH_TOKEN",i),console.log(Qe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||II(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Ov({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(Qe.red(" Aborted")),process.exit(1)),a=d}let c=await pe(d=>{Be(d,"mesh.enabled",!0)},{configPath:e.configPath});c.success||(console.log(Qe.red(` \u2717 ${c.error}`)),process.exit(1));let u=TI({url:a,token:i,name:NI(r),version:1});console.log(),console.log(Qe.bold(" Mesh invite")),console.log(),console.log(` ${Qe.cyan(u)}`),console.log(),console.log(Qe.dim(" Run on the other node:")),console.log(Qe.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Qe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Nv(e,t={}){let o;try{o=CI(e)}catch(r){console.log(Qe.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Mu("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Ov({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Qe.red(" Aborted (keeping existing .env)")),process.exit(1))}ns("MESH_TOKEN",o.token);let s=await pe(r=>{Be(r,"mesh.enabled",!0);let i=Ts(r,"mesh.peers")||[],a=i.findIndex(c=>c.name===o.name),l={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=l:i.push(l),Be(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Qe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Qe.green(" \u2713 Joined mesh")),console.log(Qe.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Qe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Qe.dim(" Daemon hot-reloaded.")):console.log(Qe.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Qe.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Qe.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Qe.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var rs=new jI().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");rs.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Av({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});rs.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Tv({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});rs.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await Cv({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var jv=rs.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");jv.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Iv({url:e.url,configPath:e.config})});jv.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Nv(e,{configPath:t.config})});rs.action(()=>{console.log(),console.log(ur.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${ur.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${ur.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${ur.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${ur.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(ur.dim(" GitLab connect is the next slice.")),console.log()});Z();import{Command as _I}from"commander";import ce from"chalk";var is=new _I().name("usage").description("token usage analysis and reporting");is.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(ce.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ce.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${ce.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${ce.red(String(s.totalErrors))}`),console.log(),console.log(ce.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,l)=>l[1].total-a[1].total);for(let[a,l]of i){let c=r(l.total||l.input+l.output+l.cacheRead+l.cacheCreate),u=l.avgDuration?`${(l.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ce.cyan(a)}: ${c} tokens (${l.tasks} tasks) ${ce.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${e.message}`))}});is.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=O(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(p=>a(p.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:ce.dim(" No hold to lift.")),console.log();return}let l=i.now,c=new Set(i.holds.map(d=>d.window));console.log(ce.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(ce.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let p=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-l)/6e4)),h=d.resetsAt>l?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",y=c.has(d.window)?ce.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${p.padEnd(12)} ${[f,h,y].filter(Boolean).join(", ")}`)}console.log();let u=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${u(i.maxPerHour)} in the last hour, ${i.last5h}${u(i.maxPer5h)} in the last 5 hours`),c.size&&console.log(ce.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${t.message}`))}});is.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(ce.red(` Script not found: ${s}`)),console.log(ce.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ce.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ce.red(" Analysis failed. Is Python 3 installed?"))}});is.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=g=>/^\d{4}-\d{2}-\d{2}$/.test(g)&&!Number.isNaN(Date.parse(g));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(ce.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let l=null;if(e.baseline)try{l=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(ce.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(l?{baseline:l,current:a}:a,null,2));return}let c=g=>g===null?"-":`$${g.toFixed(g<10?3:2)}`,u=g=>`${(g/1e6).toFixed(1)}M`;console.log(),console.log(ce.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),l&&console.log(ce.dim(` Baseline: ${l.from} to ${l.to} (${l.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(ce.dim(l?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(l?.channels||{})])].map(g=>[g,a.channels[g],l?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,l?.total]);for(let[g,h,y]of f){let w=r(h),$=` ${g.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${u(h?.cacheRead||0).padStart(11)} ${u(h?.cacheCreate||0).padStart(11)} ${u(h?.output||0).padStart(8)} ${c(h?.cost||0).padStart(10)} ${c(w).padStart(9)}`;if(l){let x=r(y),v=w!==null&&x?`${((w-x)/x*100).toFixed(0)}%`:"-";$+=` ${c(x).padStart(9)} ${v.padStart(7)}`}console.log($)}console.log(),l&&console.log(ce.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(ce.dim(` Saved ${e.save}`)),console.log()});is.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y23TE5AN.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-4WR4ZYXQ.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),l=[],c=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();l.push(g),c(f,g)}};c(i,"");let u=l.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:u},null,2));return}console.log(),console.log(ce.bold(` Never used in the last ${e.days} days (${u.length}/${l.length})`)),console.log();for(let d of u)console.log(` ${ce.dim("\xB7")} ${d}`);console.log(),console.log(ce.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ce.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(ce.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ce.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ce.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(ce.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=ce.dim(`${r.days}d`);console.log(` ${ce.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(ce.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as DI}from"commander";import Ge from"chalk";import{readFileSync as PI}from"fs";import{resolve as MI}from"path";Z();var mn=new DI().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");mn.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{mm(MI(process.cwd(),".env"))}catch{}let t=LI(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-LDMIS7MM.js");o(t)}catch(t){console.log(Ge.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ge.dim(t.stack)),process.exit(1)}});function LI(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ge.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ge.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
608
|
+
`}function ns(e,t,o=".env"){let n=xv(o),s=Sv(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Pu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Pu(t)}`})),iI(n,dI(s))}function Mu(e,t=".env"){return Sv(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Ev="https://t.me/BotFather";async function uI(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function gI(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Av(e={}){console.log(),console.log(Ee.bold(" Connect Telegram")),console.log(),console.log(Ee.dim(` 1. Open ${Ev}`)),console.log(Ee.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Ee.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await gi({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&jo(Ev);let{token:o}=await gi({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:v=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(v.trim())||"That doesn't look like a Telegram token"});o||(console.log(Ee.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await uI(o.trim());n||(console.log(Ee.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Ee.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(Ee.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let l=JSON.parse(s(a,"utf-8")),c=Object.keys(l.agents||{});c.length===0&&(console.log(Ee.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await gi({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:c.map(S=>({title:S,value:S})),initial:0})).agent),u||(console.log(Ee.red(" Aborted")),process.exit(1));let d=l.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await gi({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Ee.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;ns(f,o.trim()),process.env[f]=o.trim();let g=await pe(v=>{Be(v,"channels.telegram.enabled",!0),Be(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let S=Ts(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),Be(v,`agents.${u}.mentions`,S))},{configPath:e.configPath});if(g.success||(console.log(Ee.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(Ee.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(Ee.dim(` Token stored in .env as ${f}`)),console.log(Ee.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await gi({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(Ee.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Ee.dim(" Waiting up to 90s..."));let y=await gI(o.trim(),9e4);if(!y){console.log(Ee.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Ee.dim(" agentx config set notifications.destination.channel telegram")),console.log(Ee.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Ee.dim(` agentx config set notifications.destination.accountId ${p}`));return}let w={channel:"telegram",chatId:String(y.chatId),accountId:p},$=[],x=await pe(v=>{Be(v,"notifications.destination",w),$=xa(v,w)},{configPath:e.configPath});if(!x.success){console.log(Ee.red(` \u2717 failed to save destination: ${x.error}`));return}console.log(Ee.green(" \u2713 Default --notify target set")),console.log(Ee.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Ee.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(Ee.dim(` Schedules that now report here: ${$.join(", ")}`)),x.reloaded&&console.log(Ee.dim(" Daemon hot-reloaded."))}import Le from"chalk";import Lu from"prompts";import{existsSync as Fu,mkdirSync as mI,readdirSync as pI,readFileSync as Rv}from"fs";import{resolve as qu}from"path";var fI=".agentx/whatsapp-sessions";function hI(){let e=qu(process.cwd(),".agentx/daemon.pid");if(!Fu(e))return!1;try{let t=parseInt(Rv(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function yI(e){if(!Fu(e))return!1;try{return pI(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function wI(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Le.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Le.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;mI(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let l={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>l},c=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,l):r.keys},...a?{version:a}:{},logger:l,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return c.ev.on("creds.update",i),await new Promise(u=>{let p=setTimeout(()=>{t(Le.yellow(" Timed out waiting for scan (2min)."));try{c.end(void 0)}catch{}u(!1)},12e4);c.ev.on("connection.update",async f=>{if(f.qr){t(Le.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(p),t(Le.green(" \u2713 Paired"));try{c.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(Le.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Tv(e={}){if(console.log(),console.log(Le.bold(" Connect WhatsApp")),console.log(),hI()){console.log(Le.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Le.dim(" agentx daemon stop")),console.log();let{cont:c}=await Lu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});c||(console.log(Le.red(" Aborted")),process.exit(1))}let t=e.configPath||qu(process.cwd(),"agentx.json");Fu(t)||(console.log(Le.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Rv(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||fI,s=qu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Le.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Lu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(Le.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(yI(s)&&a){let{keep:c}=await Lu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!c,c&&console.log(Le.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await wI(s,u=>console.log(u))||(console.log(Le.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let l=await pe(c=>{Be(c,"channels.whatsapp.enabled",!0),Be(c,"channels.whatsapp.sessionDir",n),Be(c,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});l.success||(console.log(Le.red(` \u2717 ${l.error}`)),process.exit(1)),console.log(),console.log(Le.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Le.dim(` Session: ${n}`)),console.log(Le.dim(" Start the daemon to begin receiving:")),console.log(Le.dim(" agentx daemon start")),console.log(Le.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Le.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Le.dim(" Add routes later with:")),console.log(Le.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Tt from"chalk";import bI from"prompts";import{existsSync as $I,readFileSync as kI}from"fs";import{resolve as vI}from"path";async function xI(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function SI(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Lo(e){console.log(Tt.red(` ${e}`)),process.exit(1)}async function ss(e){return(await bI(e,{onCancel:()=>Lo("Aborted")}))[e.name]}async function Cv(e={}){console.log(),console.log(Tt.bold(" Connect email")),console.log();let t=e.configPath||vI(process.cwd(),"agentx.json");$I(t)||Lo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(kI(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Lo("No agents configured. Run: agentx agent add");let s=e.agent??await ss({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(w=>({title:w,value:w}))});o.agents?.[s]||Lo(`No agent "${s}" in ${t}`);let r=(e.address??await ss({type:"text",name:"address",message:"Email address customers write to:",validate:w=>/^\S+@\S+\.\S+$/.test(w.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=Kh(r),l=e.imapHost??a?.imapHost??await ss({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),c=Number(e.imapPort??a?.imapPort??await ss({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await ss({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await ss({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(c)||!Number.isInteger(d))&&Lo("Ports must be numbers.");let p=e.passwordEnv||Vh(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Lo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Tt.dim(` Gmail needs an app password, not your account password: ${Yh}`)),console.log(Tt.dim(" (2-step verification must be on for that page to show.)"))),f=(await ss({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Lo("Aborted");let g={agent:s,address:r,imapHost:l,imapPort:c,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:p,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let w=await xI(g,f);w&&(console.log(Tt.red("\u2717")),Lo(w)),console.log(Tt.green("\u2713"))}e.passwordEnv||(ns(p,f),process.env[p]=f);let h=await pe(w=>{Be(w,"channels.email.enabled",!0),Be(w,`channels.email.accounts.${i}`,Xh(g))},{configPath:e.configPath});h.success||Lo(`Config save failed: ${h.error}`),console.log(),console.log(Tt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Tt.dim(` Password stored in .env as ${p}`)),console.log(Tt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let y=SI(o.agents[s]?.tier,g.allowFrom);y&&console.log(Tt.yellow(` ${y}`)),console.log(g.send==="auto"?Tt.yellow(" Replies are sent as soon as the agent writes them."):Tt.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Tt.dim(" Only mail that arrives from now on is answered.")),console.log(Tt.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as EI}from"crypto";import Qe from"chalk";import Ov from"prompts";var hl="agentx-mesh:",yl="//join/";function AI(e){return Buffer.from(e,"utf-8").toString("base64url")}function RI(e){return Buffer.from(e,"base64url").toString("utf-8")}function TI(e){return`${hl}${yl}${AI(JSON.stringify(e))}`}function CI(e){if(!e.startsWith(`${hl}${yl}`))throw new Error(`Not a mesh invite link \u2014 expected ${hl}${yl}\u2026`);let t=e.slice(hl.length+yl.length),o=JSON.parse(RI(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function OI(){return EI(32).toString("hex")}function II(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function NI(e){return e?.node?.name||e?.node?.id||"node"}async function Iv(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Qe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Mu("MESH_TOKEN");i||(i=OI(),ns("MESH_TOKEN",i),console.log(Qe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||II(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Ov({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(Qe.red(" Aborted")),process.exit(1)),a=d}let c=await pe(d=>{Be(d,"mesh.enabled",!0)},{configPath:e.configPath});c.success||(console.log(Qe.red(` \u2717 ${c.error}`)),process.exit(1));let u=TI({url:a,token:i,name:NI(r),version:1});console.log(),console.log(Qe.bold(" Mesh invite")),console.log(),console.log(` ${Qe.cyan(u)}`),console.log(),console.log(Qe.dim(" Run on the other node:")),console.log(Qe.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Qe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Nv(e,t={}){let o;try{o=CI(e)}catch(r){console.log(Qe.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Mu("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Ov({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Qe.red(" Aborted (keeping existing .env)")),process.exit(1))}ns("MESH_TOKEN",o.token);let s=await pe(r=>{Be(r,"mesh.enabled",!0);let i=Ts(r,"mesh.peers")||[],a=i.findIndex(c=>c.name===o.name),l={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=l:i.push(l),Be(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Qe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Qe.green(" \u2713 Joined mesh")),console.log(Qe.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Qe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Qe.dim(" Daemon hot-reloaded.")):console.log(Qe.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Qe.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Qe.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Qe.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var rs=new jI().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");rs.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Av({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});rs.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Tv({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});rs.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await Cv({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var jv=rs.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");jv.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Iv({url:e.url,configPath:e.config})});jv.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Nv(e,{configPath:t.config})});rs.action(()=>{console.log(),console.log(ur.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${ur.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${ur.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${ur.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${ur.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(ur.dim(" GitLab connect is the next slice.")),console.log()});Z();import{Command as _I}from"commander";import ce from"chalk";var is=new _I().name("usage").description("token usage analysis and reporting");is.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(ce.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ce.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${ce.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${ce.red(String(s.totalErrors))}`),console.log(),console.log(ce.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,l)=>l[1].total-a[1].total);for(let[a,l]of i){let c=r(l.total||l.input+l.output+l.cacheRead+l.cacheCreate),u=l.avgDuration?`${(l.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ce.cyan(a)}: ${c} tokens (${l.tasks} tasks) ${ce.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${e.message}`))}});is.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=O(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(p=>a(p.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:ce.dim(" No hold to lift.")),console.log();return}let l=i.now,c=new Set(i.holds.map(d=>d.window));console.log(ce.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(ce.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let p=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-l)/6e4)),h=d.resetsAt>l?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",y=c.has(d.window)?ce.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${p.padEnd(12)} ${[f,h,y].filter(Boolean).join(", ")}`)}console.log();let u=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${u(i.maxPerHour)} in the last hour, ${i.last5h}${u(i.maxPer5h)} in the last 5 hours`),c.size&&console.log(ce.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${t.message}`))}});is.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(ce.red(` Script not found: ${s}`)),console.log(ce.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ce.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ce.red(" Analysis failed. Is Python 3 installed?"))}});is.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=g=>/^\d{4}-\d{2}-\d{2}$/.test(g)&&!Number.isNaN(Date.parse(g));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(ce.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let l=null;if(e.baseline)try{l=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(ce.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(l?{baseline:l,current:a}:a,null,2));return}let c=g=>g===null?"-":`$${g.toFixed(g<10?3:2)}`,u=g=>`${(g/1e6).toFixed(1)}M`;console.log(),console.log(ce.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),l&&console.log(ce.dim(` Baseline: ${l.from} to ${l.to} (${l.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(ce.dim(l?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(l?.channels||{})])].map(g=>[g,a.channels[g],l?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,l?.total]);for(let[g,h,y]of f){let w=r(h),$=` ${g.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${u(h?.cacheRead||0).padStart(11)} ${u(h?.cacheCreate||0).padStart(11)} ${u(h?.output||0).padStart(8)} ${c(h?.cost||0).padStart(10)} ${c(w).padStart(9)}`;if(l){let x=r(y),v=w!==null&&x?`${((w-x)/x*100).toFixed(0)}%`:"-";$+=` ${c(x).padStart(9)} ${v.padStart(7)}`}console.log($)}console.log(),l&&console.log(ce.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(ce.dim(` Saved ${e.save}`)),console.log()});is.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y23TE5AN.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-VCNJHSWN.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),l=[],c=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();l.push(g),c(f,g)}};c(i,"");let u=l.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:u},null,2));return}console.log(),console.log(ce.bold(` Never used in the last ${e.days} days (${u.length}/${l.length})`)),console.log();for(let d of u)console.log(` ${ce.dim("\xB7")} ${d}`);console.log(),console.log(ce.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ce.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(ce.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ce.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ce.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(ce.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=ce.dim(`${r.days}d`);console.log(` ${ce.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(ce.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as DI}from"commander";import Ge from"chalk";import{readFileSync as PI}from"fs";import{resolve as MI}from"path";Z();var mn=new DI().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");mn.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{mm(MI(process.cwd(),".env"))}catch{}let t=LI(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-6JUASBDZ.js");o(t)}catch(t){console.log(Ge.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ge.dim(t.stack)),process.exit(1)}});function LI(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ge.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ge.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
609
609
|
`)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}mn.command("list").description("list configured boards").action(()=>{try{let e=O();if(!e.boards?.length){console.log(Ge.dim(`
|
|
610
610
|
No boards configured.
|
|
611
611
|
`));return}console.log();for(let t of e.boards){console.log(` ${Ge.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(Ge.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(Ge.dim(` primary label: ${t.primaryToolLabel}`)),console.log(Ge.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(Ge.red(` ${e.message}`)),process.exit(1)}});mn.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{mi(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(r=>r.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(r=>r.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(Ge.red(` ${o.message}`)),process.exit(1)}});mn.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,t)=>{try{mi(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=[];if(t.name&&(s.name=t.name,r.push(`name="${t.name}"`)),t.projects){let i=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(i.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:i},r.push(`projects=${i.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,r.push("label cleared")):(s.primaryToolLabel=t.label,r.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,r.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,r.push(`closed-days=${s.closedWindowDays}`)),r.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${r.join(", ")})`})}catch(o){console.log(Ge.red(` ${o.message}`)),process.exit(1)}});var Uu=mn.command("column").description("manage a board's columns (add / remove / edit / list)");Uu.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(PI("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log(Ge.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let r=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${Ge.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${Ge.dim(r)}`)}}catch(t){console.log(Ge.red(` ${t.message}`)),process.exit(1)}});Uu.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,t,o)=>{try{mi(n=>{let r=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!r)throw new Error(`board "${e}" not found`);if(r.columns=r.columns||[],r.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let i={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");i.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");i.mapsToLabel=o.label}return o.accent&&(i.accent=o.accent),r.columns.push(i),`column "${t}" added to board "${e}"`})}catch(n){console.log(Ge.red(` ${n.message}`)),process.exit(1)}});Uu.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{mi(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(i=>i.id!==t),s.columns.length===r)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(Ge.red(` ${o.message}`)),process.exit(1)}});mn.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{mi(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(Ge.red(` ${t.message}`)),process.exit(1)}});function mi(e){let{summary:t,backupPath:o}=Lt(n=>e(n));console.log(Ge.green(`
|
|
@@ -635,21 +635,21 @@ An edit that breaks these rules is refused and the note is deferred.
|
|
|
635
635
|
|
|
636
636
|
${t}
|
|
637
637
|
`}function Mv(e,t,o,n){let s=n.today??new Date().toISOString().slice(0,10),r=new Map;for(let i of t){let a=e.find(l=>l.id===i.id||i.id.length>=4&&l.id.startsWith(i.id));a&&!r.has(a.id)&&r.set(a.id,i)}return e.map(i=>{let a=r.get(i.id);if(!a)return{id:i.id,outcome:"deferred",reason:"absorb did not answer this note",patched:[]};let l=wl(a.reason||"no reason given");if(a.outcome!=="patched")return{id:i.id,outcome:a.outcome,reason:l,patched:[]};let c=qI(a.edits,o,n.paths,n.agentId);if("refused"in c)return{id:i.id,outcome:"deferred",reason:wl(`patch refused: ${c.refused}. Absorb said: ${l}`),patched:[]};let u=[],d="";for(let[f,{article:g,content:h}]of c.articles){let y=!1;try{y=o.writeArticle(f,{...g.meta,lastUpdated:s,sources:[...new Set([...g.meta.sources??[],Bu(i.id)])]},h,n.agentId)}catch(w){d=`${f}: ${w?.message??w}`}if(!y){d||=f;break}u.push({path:f,article:g})}if(d){for(let f of u)try{o.writeArticle(f.path,f.article.meta,f.article.content,n.agentId)}catch{}return{id:i.id,outcome:"deferred",reason:wl(`patch not saved: could not write ${d}. Absorb said: ${l}`),patched:[]}}let p=u.map(f=>f.path);return{id:i.id,outcome:"patched",reason:wl(`${l} (edited ${p.join(", ")})`),patched:p}})}function qI(e,t,o,n){if(e.length===0)return{refused:"patched with no edits"};if(e.length>pi.edits)return{refused:`more than ${pi.edits} edits`};let s=new Map;for(let r of e){if(!o.has(r.path))return{refused:`${r.path} is not an article shown in full`};let i=s.get(r.path);if(!i){let l=t.readArticle(r.path);if(!l)return{refused:`${r.path} is not an existing article`};if(t.canWrite&&!t.canWrite(l.meta,n))return{refused:`no permission to write ${r.path}`};i={article:l,content:l.content,replaced:0},s.set(r.path,i)}if(!r.find.trim())return{refused:`an edit to ${r.path} quotes nothing`};if(r.find.length>pi.find||r.replace.length>pi.replace)return{refused:`an edit to ${r.path} is too long for a patch`};if(i.replaced+=r.find.length,i.replaced>i.article.content.length*pi.share)return{refused:`the edits replace most of ${r.path}; a note only patches`};let a=i.content.indexOf(r.find);if(a<0)return{refused:`the quoted passage is not in ${r.path}`};if(i.content.indexOf(r.find,a+1)>=0)return{refused:`the quoted passage appears more than once in ${r.path}`};i.content=i.content.slice(0,a)+r.replace+i.content.slice(a+r.find.length)}for(let[r,{article:i,content:a}]of s){let l=[...FI(i.content,a),...HI(i.content,a)];if(l.length>0)return{refused:`the edit to ${r} drops ${l.slice(0,4).join("; ")}${l.length>4?"; \u2026":""}`}}return{articles:s}}function FI(e,t){let o=Dr(e,t),n=Dr(t,e),s=i=>i.startsWith("link [[")?"wikilink":i.split(" ")[0],r=new Map;for(let i of n)r.set(s(i),(r.get(s(i))??0)+1);return o.filter(i=>{let a=r.get(s(i))??0;return a===0?!0:(r.set(s(i),a-1),!1)})}var UI=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,WI=/(?<![\w@.])@[A-Za-z0-9_]{3,}/g,BI=/^\s*(?:[-*]\s*)?(?:\|\s*)?\**\s*(role|job title|position|organi[sz]ation|company|team|employer|e-?mail|phone|mobile|tel|whatsapp|telegram|signal|slack|handle|contact|address)\s*\**\s*(?::|\|)\s*\**\s*(.+?)\s*\|?\s*$/gim;function HI(e,t){let o=t.toLowerCase(),n=[];for(let s of e.matchAll(UI))o.includes(s[0].toLowerCase())||n.push(`email ${s[0]}`);for(let s of e.matchAll(WI))o.includes(s[0].toLowerCase())||n.push(`handle ${s[0]}`);for(let s of e.matchAll(BI)){let r=s[2].replace(/\*+/g,"").trim();!r||/^(unknown|n\/a|none|-+|tbd)$/i.test(r)||o.includes(r.toLowerCase())||n.push(`${s[1].toLowerCase()} "${r}"`)}return[...new Set(n)]}function wl(e){return e.length>gc.reason?`${e.slice(0,gc.reason-1)}\u2026`:e}import Xe from"chalk";import{resolve as JI}from"path";var GI=e=>e||JI(process.cwd(),".agentx/wiki");async function gr(e){let{FactLedger:t}=await import("./ledger-5GMBLR7W.js");return new t(GI(e))}function mr(e){return async(...t)=>{try{await e(...t)}catch(o){o?.name!=="LedgerCorruptError"&&console.error(Xe.red(` ${o?.message??o}`)),process.exitCode=1}}}function Lv(e){let t=e.command("facts").description("facts with a source and a check date: list, show, set, proposals");t.command("list").description("every recorded fact, with where and when it was checked").option("--dir <path>","wiki directory").option("--stale","only facts past their time limit, or never checked").option("--json").action(mr(async n=>{let{isStaleFact:s}=await import("./ledger-5GMBLR7W.js"),r=(await gr(n.dir)).list().filter(i=>!n.stale||s(i));if(n.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(Xe.dim(" no facts recorded"));return}for(let i of r){let a=i.undated?Xe.yellow(" UNCHECKED"):s(i)?Xe.yellow(" STALE"):"";console.log(` ${Xe.cyan(i.id)} ${Xe.bold(i.subject)} \xB7 ${i.attribute}: ${i.value}${a}`),console.log(Xe.dim(` ${i.volatility} \xB7 ${i.source} \xB7 checked ${i.verifiedAt.slice(0,10)} by ${i.verifiedBy}`))}})),t.command("show <id>").description("one fact, with its earlier values").option("--dir <path>","wiki directory").action(mr(async(n,s)=>{let r=(await gr(s.dir)).get(n);if(!r){console.error(Xe.red(` no fact "${n}"`)),process.exitCode=1;return}console.log(JSON.stringify(r,null,2))})),t.command("set").description("record a fact you checked; a different value needs a newer --checked-at, or --confirm by a person").requiredOption("--subject <text>",'what the fact is about, e.g. "vendor account"').requiredOption("--attribute <text>",'which property, e.g. "billing status"').requiredOption("--value <text>","the value you found").requiredOption("--source <text>",'where you checked: a system, URL, command, or "owner said"').option("--by <id>","who checked it (agent id or person)",process.env.AGENTX_AGENT_ID||"operator").option("--checked-at <iso>",`when you checked it: an ISO date, or "now". Without it the value can't replace a different one already recorded`).option("--class <class>",`volatility class: ${ac.join(" | ")}`).option("--ttl-days <n>","days it stays trusted, overriding the class").option("--confirm","a person confirms this value: replace a newer-dated one").option("--dir <path>","wiki directory").action(mr(async n=>{if(n.class&&!Cm(n.class)){console.error(Xe.red(` --class must be one of ${ac.join(", ")}`)),process.exitCode=1;return}let r=(await gr(n.dir)).write({subject:n.subject,attribute:n.attribute,value:n.value,source:n.source,verifiedBy:n.by,verifiedAt:n.checkedAt,volatility:n.class,ttlDays:n.ttlDays!==void 0?Number(n.ttlDays):void 0},n.confirm?{confirmedBy:n.by}:{});if(r.status==="contradiction"){let i=r.fact.confirmedBy?`${r.fact.confirmedBy} confirmed it, so only a person can change it`:n.checkedAt?"and this check is not newer":"and this value has no --checked-at";console.log(Xe.yellow(` not replaced: the wiki says "${r.fact.value}" (checked ${r.fact.verifiedAt.slice(0,10)}), ${i}.`)),console.log(r.questionId?Xe.dim(` Queued question ${r.questionId}: agentx wiki questions \xB7 agentx wiki answer ${r.questionId} "<true value>"`):r.questionClosed?Xe.dim(` A person already ${r.questionClosed} this same claim, so it is not asked again.`):Xe.red(" No question could be queued: the questions file is unreadable. Repair .agentx/wiki/_questions.json.")),process.exitCode=2;return}console.log(Xe.green(` ${r.status}: ${r.fact.id} ${r.fact.subject} \xB7 ${r.fact.attribute}: ${r.fact.value}`))}));let o=t.command("proposals").description("claims from session summaries, waiting for a check (list, approve, reject)");o.command("list").description("claims waiting for a check (pending by default)").option("--dir <path>","wiki directory").option("--all","include approved and rejected").option("--json").action(mr(async n=>{let{listFactProposals:s}=await import("./fact-proposals-Z7HJG7QJ.js"),r=s(await gr(n.dir),n.all?void 0:"pending");if(n.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(Xe.dim(" no fact proposals waiting"));return}for(let i of r)console.log(` ${Xe.cyan(i.id)} ${i.status==="pending"?"":Xe.dim(`[${i.status}] `)}${i.claim}`),console.log(Xe.dim(` ${i.agentId} \xB7 ${i.origin} \xB7 ${i.source} \xB7 ${i.verifiedAt.slice(0,10)}`));console.log(Xe.dim(`
|
|
638
|
-
Check each claim at its source, then: agentx wiki facts proposals approve <id> \xB7 reject <id>`))})),o.command("approve <id>").description("confirm a claim and record it as a fact").option("--subject <text>","correct the subject read from the claim").option("--attribute <text>","correct the attribute").option("--value <text>","correct the value").option("--source <text>","where you checked it").option("--by <id>","who confirms it","operator").option("--dir <path>","wiki directory").action(mr(async(n,s)=>{let{approveFactProposal:r}=await import("./fact-proposals-Z7HJG7QJ.js"),{write:i}=r(await gr(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(Xe.green(` ${i.status}: ${i.fact.id} ${i.fact.subject} \xB7 ${i.fact.attribute}: ${i.fact.value}`))})),o.command("reject <id>").description("drop a claim; it is not recorded").option("--reason <text>","why, kept with the decision").option("--by <id>","who rejects it","operator").option("--dir <path>","wiki directory").action(mr(async(n,s)=>{let{rejectFactProposal:r}=await import("./fact-proposals-Z7HJG7QJ.js"),i=r(await gr(s.dir),n,s.by,s.reason);console.log(Xe.dim(` rejected: ${i.claim}`))}))}import ot from"chalk";import{existsSync as qv,readFileSync as Fv}from"fs";import{resolve as Ju}from"path";var Hu=e=>e||Ju(process.cwd(),".agentx/wiki");function zI(e){if(e)return e.replace(/\/+$/,"");if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL.replace(/\/+$/,"");try{let t=Ju(process.cwd(),"agentx.json");if(qv(t)){let o=JSON.parse(Fv(t,"utf-8"))?.node?.bind;if(typeof o=="string"&&o.includes(":")){let[n,s]=o.split(":");return`http://${n==="0.0.0.0"?"127.0.0.1":n}:${s}`}}}catch{}return"http://127.0.0.1:18800"}function xo(e){console.error(ot.red(` ${e}`)),process.exitCode=1}function bl(e){return async(...t)=>{try{await e(...t)}catch(o){xo(o?.message??String(o))}}}function Uv(e){let t=e.command("notes").description("notes agents leave for the wiki observe/sweep run: add, list, handle, config");t.command("add").description("leave a note for the wiki observe/sweep run: what changed, the source, the date").requiredOption("--change <text>","what changed, in a sentence or two").requiredOption("--source <text>",'where you saw it: a system, URL, command, or "owner said"').option("--date <YYYY-MM-DD>","when it changed or when you saw it (default: today)").option("--from <agent>","your agent id",process.env.AGENTX_AGENT_ID).option("--daemon <url>","this node's daemon (default: AGENTX_DAEMON_URL, else node.bind in agentx.json)").option("--dir <path>","write straight into this wiki directory instead of going through the daemon (needs --to)").option("--to <agent>","inbox agent, with --dir").option("--json").action(bl(async o=>{if(!o.from){xo("say who you are with --from <agent id>");return}let n={from:o.from,change:o.change,source:o.source,date:o.date},s;if(o.dir){if(!o.to){xo("--dir needs --to <inbox agent>");return}let{NoteStore:a,validateNote:l}=await import("./notes-WJJEJ4CJ.js"),c=l({...n,to:o.to});if("error"in c){xo(c.error);return}s={ok:!0,...new a(Hu(o.dir)).add(c.note)}}else{let a=zI(o.daemon),l;try{l=await fetch(`${a}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(2e4)})}catch(c){xo(`could not reach the daemon at ${a}: ${c?.message??c}`);return}if(s=await l.json().catch(()=>({})),!l.ok){xo(s?.error||`daemon answered ${l.status}`);return}}if(o.json){console.log(JSON.stringify(s,null,2));return}let r=s.note,i=s.peer?` on ${s.peer}`:"";console.log(s.added===!1?ot.dim(` already in the inbox${i}: ${r?.id} (${r?.status})`):ot.green(` note ${r?.id} left for ${r?.to}${i}; the next observe/sweep run reads it`))})),t.command("list").description("notes in this node's inbox (waiting ones by default)").option("--status <status>","waiting | open | patched | rejected | deferred | expired | all","waiting").option("--dir <path>","wiki directory").option("--json").action(bl(async o=>{let{NoteStore:n}=await import("./notes-WJJEJ4CJ.js"),s=["waiting","open","patched","rejected","deferred","expired","all"];if(!s.includes(o.status)){xo(`--status must be one of ${s.join(", ")}`);return}let r=new n(Hu(o.dir)),i=r.load();if(i.unreadable){xo(`${r.path} is unreadable (${i.unreadable}); repair or move it aside`);return}let a=r.list(o.status==="all"?void 0:o.status);if(o.json){console.log(JSON.stringify(a,null,2));return}if(a.length===0){console.log(ot.dim(` no ${o.status==="all"?"":`${o.status} `}notes`));return}for(let l of a){let c=l.status==="open"?ot.yellow("open"):l.status==="deferred"?ot.yellow("deferred"):ot.dim(l.status);console.log(` ${ot.cyan(l.id)} ${c} \xB7 from ${l.from}${l.fromNode?` on ${l.fromNode}`:""} \xB7 ${l.date}`),console.log(` ${l.change}`),console.log(ot.dim(` source: ${l.source}`)),l.listedIn?.length&&console.log(ot.dim(` given to: ${l.listedIn.at(-1)}${l.listedIn.length>1?` (+${l.listedIn.length-1} earlier)`:""}`)),l.handled&&console.log(ot.dim(` ${l.handled.outcome}${l.deferrals?` (deferred ${l.deferrals}x)`:""} by ${l.handled.by} ${l.handled.at.slice(0,10)}: ${l.handled.reason}`)),l.expired&&console.log(ot.dim(` expired ${l.expired.at.slice(0,10)} after ${l.expired.after} deferrals; no longer offered to the run`))}})),t.command("handle <id>").description("record what the run did with a note: patched, rejected or deferred, with a reason").requiredOption("--outcome <outcome>","patched | rejected | deferred").requiredOption("--reason <text>","what you patched, why you rejected it, or why it waits").option("--run <id>","the run that used it").option("--by <agent>","who handled it",process.env.AGENTX_AGENT_ID||"operator").option("--dir <path>","wiki directory").action(bl(async(o,n)=>{let{NoteStore:s}=await import("./notes-WJJEJ4CJ.js"),r=new s(Hu(n.dir)).handle(o,n.outcome,n.reason,n.by,n.run);console.log(ot.green(` note ${r.id}: ${r.status}`))})),t.command("config").description("show or set the inbox agent, and the schedules and absorb pass that read it").option("--inbox <agent>",'agent that runs the wiki observe/sweep schedule ("" clears it)').option("--cron <ids>",'comma-separated schedule ids that read the inbox ("" for none)').option("--absorb <agent>",'agent whose `wiki absorb` pass reads and answers the notes ("" clears it)').option("--max <n>","most notes one run is given (1-100)").option("--max-deferrals <n>","times a note may be deferred before it expires (1-20)").option("--enable","turn wiki notes on").option("--disable","turn wiki notes off").option("--json").action(bl(async o=>{let{patchWikiNotes:n,wikiNotesSettings:s}=await import("./notes-settings-VPXI5IIS.js"),r={};if(o.inbox!==void 0&&(r.inbox=o.inbox),o.cron!==void 0&&(r.crons=String(o.cron).split(",")),o.absorb!==void 0&&(r.absorbAgent=o.absorb),o.max!==void 0&&(r.maxNotesPerRun=Number(o.max)),o.maxDeferrals!==void 0&&(r.maxDeferrals=Number(o.maxDeferrals)),o.enable&&o.disable){xo("pick one of --enable and --disable");return}if(o.enable&&(r.enabled=!0),o.disable&&(r.enabled=!1),Object.keys(r).length>0){let{mutateAgentxConfig:l}=await import("./config-mutate-UFVJUJQO.js"),{summary:c}=l(u=>n(u,r));console.log(ot.green(` ${c}`))}let i=Ju(process.cwd(),"agentx.json");if(!qv(i)){xo(`agentx.json not found at ${i}`);return}let a=s(JSON.parse(Fv(i,"utf-8"))?.wikiNotes);if(o.json){console.log(JSON.stringify(a,null,2));return}console.log(` wiki notes: ${a.enabled?ot.green("on"):ot.dim("off")}`),console.log(` inbox agent: ${a.inbox||ot.dim("not set")}`),console.log(` schedules that read it: ${a.crons.length?a.crons.join(", "):ot.dim("none on this node")}`),console.log(` absorb that reads it: ${a.absorbAgent?`wiki absorb for ${a.absorbAgent}`:ot.dim("none")}`),console.log(` most notes per run: ${a.maxNotesPerRun}`),console.log(` deferrals before a note expires: ${a.maxDeferrals}`)}))}import pn from"chalk";import{resolve as YI}from"path";var Gu=e=>e||YI(process.cwd(),".agentx/wiki");function Wv(e){let t=e.command("ontology").description("the wiki's pillars, types, typed relations and page lenses (show, init, check)");t.command("init").description("write the default ontology to ontology.yaml in the wiki, to edit").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{writeDefaultOntology:n}=await import("./load-Q3HCFXDT.js");try{let s=n(Gu(o.dir));console.log(pn.green(` wrote ${s}`))}catch(s){console.error(pn.red(` ${s.message}`)),process.exitCode=1}}),t.command("check").description("report problems in ontology.yaml").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{loadOntology:n}=await import("./load-Q3HCFXDT.js"),{file:s,errors:r}=n(Gu(o.dir));if(!s){console.log(pn.dim(" no ontology.yaml: the built-in defaults are in use"));return}if(r.length===0){console.log(pn.green(` ${s}: no problems`));return}console.log(pn.yellow(` ${s}: ${r.length} problem(s)`));for(let i of r)console.log(` - ${i}`);process.exitCode=1}),t.command("show").description("pages per pillar and type, as the wiki view groups them").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--json","print JSON").action(async o=>{let{loadOntology:n}=await import("./load-Q3HCFXDT.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{WikiHub:r}=await import("./hub-VJZYQXKB.js"),i=Gu(o.dir),{loadRoster:a}=await import("./roster-BZGKG2ZA.js"),{ontology:l,errors:c}=n(i),u=new r(i,()=>{}),d=new s().get(u,l,a(i,u.listAgents([]),l.agent_names)),p=new Map;for(let f of d.entities.values())p.set(f.type,(p.get(f.type)??0)+1);if(o.json){console.log(JSON.stringify({entities:d.entities.size,types:Object.fromEntries(p),errors:c},null,2));return}console.log(pn.bold(` ${d.entities.size} entities`));for(let f of l.pillars){let g=l.types.filter(y=>y.pillar===f.id),h=g.reduce((y,w)=>y+(p.get(w.id)??0),0);console.log(` ${f.label.padEnd(26)} ${String(h).padStart(6)} ${pn.dim(g.map(y=>`${y.id} ${p.get(y.id)??0}`).join(" \xB7 "))}`)}c.length&&console.log(pn.yellow(` ontology.yaml has ${c.length} problem(s): agentx wiki ontology check`))})}import lt from"chalk";import{resolve as KI}from"path";var zu=e=>e||KI(process.cwd(),".agentx/wiki"),XI=()=>new Date().toISOString().slice(0,10);async function Yu(e){let{WikiHub:t}=await import("./hub-VJZYQXKB.js"),{GraphCache:o}=await import("./graph-ZVKV3JBD.js"),{loadOntology:n}=await import("./load-Q3HCFXDT.js"),{loadRoster:s}=await import("./roster-BZGKG2ZA.js"),r=new t(e,()=>{}),{ontology:i}=n(e),a=new o().get(r,i,s(e,r.listAgents([]),i.agent_names));return{hub:r,g:a}}function Bv(e,t){let o=Number(e);return Number.isInteger(o)&&o>=1?o:(console.error(lt.red(` ${t} must be a whole number, 1 or more`)),process.exitCode=1,null)}function Hv(e){let t=e.command("events").description("give each event page an importance level (minor, normal, major) and the pages it is about").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--about <titles...>","only events linked to or naming these pages (a pilot)").option("--max <n>","most events per run","200").option("--batch <n>","events per model call","20").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","haiku").option("--rules-only","use only the importance rules in ontology.yaml; no model call").option("--force","redo events whose level this job set earlier").option("--dry-run","show what would be written, write nothing").option("--json","print the run as JSON").action(async o=>{let{runEvents:n,summariseAbout:s}=await import("./event-levels-PCFARGKL.js"),{claudeCall:r}=await import("./wiki-enrich-KIONW7SB.js"),i=Bv(o.max,"--max"),a=Bv(o.batch,"--batch");if(i===null||a===null)return;let l=Number(o.maxCost);if(!Number.isFinite(l)||l<=0){console.error(lt.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let{hub:c,g:u}=await Yu(zu(o.dir)),d=o.about??[],{normName:p}=await import("./graph-ZVKV3JBD.js"),f=d.filter(w=>!u.names.has(p(w))&&!u.entities.has(w));if(f.length){console.error(lt.red(` no page is titled: ${f.join(", ")}`)),process.exitCode=1;return}let g=await n(c,u,r(o.model),{about:d,max:i,batch:a,maxCostUsd:l,dryRun:!!o.dryRun,force:!!o.force,rulesOnly:!!o.rulesOnly,today:XI()}),h=s(u,g,d);if(o.json){console.log(JSON.stringify({...g,about:h},null,2));return}for(let w of g.outcomes){let $=w.status==="written"?lt.green("\u2713"):w.status==="dry-run"?lt.cyan("~"):lt.yellow("\xB7"),x=w.importance?`${w.importance}${w.proposed?` (proposed ${w.proposed})`:""}`:w.status;console.log(` ${$} ${w.date||"no date "} ${x.padEnd(8)} ${w.title} ${lt.dim(`${w.by??w.status}${w.about.length?` \xB7 about ${w.about.join(", ")}`:""}${w.why?` \xB7 ${w.why}`:""}`)}`);for(let v of w.dropped.slice(0,4))console.log(lt.dim(` dropped: ${v}`))}for(let w of h)console.log(lt.bold(` ${w.title}`)+lt.dim(` (${w.type}): ${w.before} events in its History before \xB7 after: ${w.after.major} major, ${w.after.normal} normal, ${w.after.minor} minor (folded)`));let y=g.outcomes.filter(w=>w.importance).length;g.outcomes.length===0&&console.log(lt.dim(" nothing to do: every event in scope already has a level (--force redoes the ones this job set)")),console.log(lt.dim(` ${y} event${y===1?"":"s"} ${o.dryRun?"would get":"got"} a level \xB7 ${g.left} left \xB7 ${g.calls} model call${g.calls===1?"":"s"} \xB7 spent $${g.costUsd.toFixed(3)} of $${l}${g.capped?" \xB7 stopped at the cap":""}`)),g.outcomes.some(w=>w.status==="failed")&&(process.exitCode=1)});t.command("set <title> <level>").description("set an event's importance yourself (minor, normal or major); no later run changes it").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(o,n,s,r)=>{let{setEventLevel:i}=await import("./event-levels-PCFARGKL.js"),{IMPORTANCE_LEVELS:a}=await import("./types-YZX46RES.js"),l=n.toLowerCase();if(!a.includes(l)){console.error(lt.red(` level must be one of ${a.join(", ")}`)),process.exitCode=1;return}let{hub:c,g:u}=await Yu(zu(r.optsWithGlobals().dir)),d=i(c,u,o,l);d.ok?console.log(lt.green(` ${d.title} is now ${l}`)+lt.dim(` (${d.page})`)):(console.error(lt.red(` not set: ${d.reason}`)),process.exitCode=1)}),t.command("proposed").description("list events a run suggests as major, waiting for you to decide").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--json","print as JSON").action(async(o,n)=>{let s=n.optsWithGlobals(),{g:r}=await Yu(zu(s.dir)),i=[...r.entities.values()].filter(a=>a.type==="event"&&a.importanceProposed&&a.importanceProposed!==a.importance).sort((a,l)=>(l.date||"").localeCompare(a.date||""));if(s.json){console.log(JSON.stringify(i.map(a=>({id:a.id,title:a.title,date:a.date,importance:a.importance,proposed:a.importanceProposed})),null,2));return}for(let a of i)console.log(` ${a.date||"no date "} ${a.title} ${lt.dim(`now ${a.importance}, proposed ${a.importanceProposed}`)}`);console.log(lt.dim(i.length?` ${i.length} waiting. Decide each with: agentx wiki events set "<title>" major (or normal)`:" none waiting"))})}import _t from"chalk";import{resolve as VI}from"path";var QI=e=>e||VI(process.cwd(),".agentx/wiki");function Jv(e){e.command("rules [pages...]").description("write one obligation page per rule the wiki states, with deadline, penalty, source and check date").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--words <list>","comma-separated words that mark a page as stating rules (default: deadline, penalty, filing\u2026 in English, French and Arabic)").option("--max <n>","most source pages per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","read again pages that did not change").option("--dry-run","show what would be written, write nothing").option("--json","print the run as JSON").action(async(t,o)=>{let{WikiHub:n}=await import("./hub-VJZYQXKB.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{loadOntology:r}=await import("./load-Q3HCFXDT.js"),{loadRoster:i}=await import("./roster-BZGKG2ZA.js"),{loadRulesState:a,ruleWordsPattern:l,runRules:c,saveRulesState:u}=await import("./rules-FBOLGE2S.js"),d=QI(o.dir),p=Number(o.max);if(!Number.isInteger(p)||p<1){console.error(_t.red(" --max must be a whole number of pages, 1 or more")),process.exitCode=1;return}let f=Number(o.maxCost);if(!Number.isFinite(f)||f<=0){console.error(_t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let g=o.words?.split(",").map(v=>v.trim()).filter(Boolean);if(o.words!==void 0&&!g?.length){console.error(_t.red(" --words needs at least one word")),process.exitCode=1;return}let h=new n(d,()=>{}),{ontology:y}=r(d);if(!y.types.some(v=>v.id==="obligation")){console.error(_t.red(" ontology.yaml has no `obligation` type; add it back to write rule pages")),process.exitCode=1;return}let w=new s().get(h,y,i(d,h.listAgents([]),y.agent_names)),$=a(d),x=await c(h,w,yy(o.model),{only:t,words:l(g),max:p,maxCostUsd:f,dryRun:!!o.dryRun,force:!!o.force,today:new Date().toISOString().slice(0,10),save:v=>u(d,v)},$);if(o.json){console.log(JSON.stringify(x,null,2));return}for(let v of x.outcomes){let S=v.status==="written"?_t.green("\u2713"):v.status==="dry-run"?_t.cyan("~"):_t.yellow("\xB7");console.log(` ${S} ${v.title} ${_t.dim(`${v.status} \xB7 ${v.page??"no page"} \xB7 ${v.rules.length} rules \xB7 $${v.costUsd.toFixed(3)}`)}`);for(let k of v.rules){let A=[k.deadline?"":"no deadline",k.penalty?"":"no penalty"].filter(Boolean);console.log(` ${k.created?"new":"updated"}: ${k.title} ${_t.dim(`\xB7 ${k.page}${A.length?` \xB7 ${A.join(", ")}`:""}${k.linked.length?` \xB7 linked from ${k.linked.join(", ")}`:""}`)}`),k.preview&&console.log(_t.dim(k.preview.split(`
|
|
638
|
+
Check each claim at its source, then: agentx wiki facts proposals approve <id> \xB7 reject <id>`))})),o.command("approve <id>").description("confirm a claim and record it as a fact").option("--subject <text>","correct the subject read from the claim").option("--attribute <text>","correct the attribute").option("--value <text>","correct the value").option("--source <text>","where you checked it").option("--by <id>","who confirms it","operator").option("--dir <path>","wiki directory").action(mr(async(n,s)=>{let{approveFactProposal:r}=await import("./fact-proposals-Z7HJG7QJ.js"),{write:i}=r(await gr(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(Xe.green(` ${i.status}: ${i.fact.id} ${i.fact.subject} \xB7 ${i.fact.attribute}: ${i.fact.value}`))})),o.command("reject <id>").description("drop a claim; it is not recorded").option("--reason <text>","why, kept with the decision").option("--by <id>","who rejects it","operator").option("--dir <path>","wiki directory").action(mr(async(n,s)=>{let{rejectFactProposal:r}=await import("./fact-proposals-Z7HJG7QJ.js"),i=r(await gr(s.dir),n,s.by,s.reason);console.log(Xe.dim(` rejected: ${i.claim}`))}))}import ot from"chalk";import{existsSync as qv,readFileSync as Fv}from"fs";import{resolve as Ju}from"path";var Hu=e=>e||Ju(process.cwd(),".agentx/wiki");function zI(e){if(e)return e.replace(/\/+$/,"");if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL.replace(/\/+$/,"");try{let t=Ju(process.cwd(),"agentx.json");if(qv(t)){let o=JSON.parse(Fv(t,"utf-8"))?.node?.bind;if(typeof o=="string"&&o.includes(":")){let[n,s]=o.split(":");return`http://${n==="0.0.0.0"?"127.0.0.1":n}:${s}`}}}catch{}return"http://127.0.0.1:18800"}function xo(e){console.error(ot.red(` ${e}`)),process.exitCode=1}function bl(e){return async(...t)=>{try{await e(...t)}catch(o){xo(o?.message??String(o))}}}function Uv(e){let t=e.command("notes").description("notes agents leave for the wiki observe/sweep run: add, list, handle, config");t.command("add").description("leave a note for the wiki observe/sweep run: what changed, the source, the date").requiredOption("--change <text>","what changed, in a sentence or two").requiredOption("--source <text>",'where you saw it: a system, URL, command, or "owner said"').option("--date <YYYY-MM-DD>","when it changed or when you saw it (default: today)").option("--from <agent>","your agent id",process.env.AGENTX_AGENT_ID).option("--daemon <url>","this node's daemon (default: AGENTX_DAEMON_URL, else node.bind in agentx.json)").option("--dir <path>","write straight into this wiki directory instead of going through the daemon (needs --to)").option("--to <agent>","inbox agent, with --dir").option("--json").action(bl(async o=>{if(!o.from){xo("say who you are with --from <agent id>");return}let n={from:o.from,change:o.change,source:o.source,date:o.date},s;if(o.dir){if(!o.to){xo("--dir needs --to <inbox agent>");return}let{NoteStore:a,validateNote:l}=await import("./notes-WJJEJ4CJ.js"),c=l({...n,to:o.to});if("error"in c){xo(c.error);return}s={ok:!0,...new a(Hu(o.dir)).add(c.note)}}else{let a=zI(o.daemon),l;try{l=await fetch(`${a}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(2e4)})}catch(c){xo(`could not reach the daemon at ${a}: ${c?.message??c}`);return}if(s=await l.json().catch(()=>({})),!l.ok){xo(s?.error||`daemon answered ${l.status}`);return}}if(o.json){console.log(JSON.stringify(s,null,2));return}let r=s.note,i=s.peer?` on ${s.peer}`:"";console.log(s.added===!1?ot.dim(` already in the inbox${i}: ${r?.id} (${r?.status})`):ot.green(` note ${r?.id} left for ${r?.to}${i}; the next observe/sweep run reads it`))})),t.command("list").description("notes in this node's inbox (waiting ones by default)").option("--status <status>","waiting | open | patched | rejected | deferred | expired | all","waiting").option("--dir <path>","wiki directory").option("--json").action(bl(async o=>{let{NoteStore:n}=await import("./notes-WJJEJ4CJ.js"),s=["waiting","open","patched","rejected","deferred","expired","all"];if(!s.includes(o.status)){xo(`--status must be one of ${s.join(", ")}`);return}let r=new n(Hu(o.dir)),i=r.load();if(i.unreadable){xo(`${r.path} is unreadable (${i.unreadable}); repair or move it aside`);return}let a=r.list(o.status==="all"?void 0:o.status);if(o.json){console.log(JSON.stringify(a,null,2));return}if(a.length===0){console.log(ot.dim(` no ${o.status==="all"?"":`${o.status} `}notes`));return}for(let l of a){let c=l.status==="open"?ot.yellow("open"):l.status==="deferred"?ot.yellow("deferred"):ot.dim(l.status);console.log(` ${ot.cyan(l.id)} ${c} \xB7 from ${l.from}${l.fromNode?` on ${l.fromNode}`:""} \xB7 ${l.date}`),console.log(` ${l.change}`),console.log(ot.dim(` source: ${l.source}`)),l.listedIn?.length&&console.log(ot.dim(` given to: ${l.listedIn.at(-1)}${l.listedIn.length>1?` (+${l.listedIn.length-1} earlier)`:""}`)),l.handled&&console.log(ot.dim(` ${l.handled.outcome}${l.deferrals?` (deferred ${l.deferrals}x)`:""} by ${l.handled.by} ${l.handled.at.slice(0,10)}: ${l.handled.reason}`)),l.expired&&console.log(ot.dim(` expired ${l.expired.at.slice(0,10)} after ${l.expired.after} deferrals; no longer offered to the run`))}})),t.command("handle <id>").description("record what the run did with a note: patched, rejected or deferred, with a reason").requiredOption("--outcome <outcome>","patched | rejected | deferred").requiredOption("--reason <text>","what you patched, why you rejected it, or why it waits").option("--run <id>","the run that used it").option("--by <agent>","who handled it",process.env.AGENTX_AGENT_ID||"operator").option("--dir <path>","wiki directory").action(bl(async(o,n)=>{let{NoteStore:s}=await import("./notes-WJJEJ4CJ.js"),r=new s(Hu(n.dir)).handle(o,n.outcome,n.reason,n.by,n.run);console.log(ot.green(` note ${r.id}: ${r.status}`))})),t.command("config").description("show or set the inbox agent, and the schedules and absorb pass that read it").option("--inbox <agent>",'agent that runs the wiki observe/sweep schedule ("" clears it)').option("--cron <ids>",'comma-separated schedule ids that read the inbox ("" for none)').option("--absorb <agent>",'agent whose `wiki absorb` pass reads and answers the notes ("" clears it)').option("--max <n>","most notes one run is given (1-100)").option("--max-deferrals <n>","times a note may be deferred before it expires (1-20)").option("--enable","turn wiki notes on").option("--disable","turn wiki notes off").option("--json").action(bl(async o=>{let{patchWikiNotes:n,wikiNotesSettings:s}=await import("./notes-settings-VPXI5IIS.js"),r={};if(o.inbox!==void 0&&(r.inbox=o.inbox),o.cron!==void 0&&(r.crons=String(o.cron).split(",")),o.absorb!==void 0&&(r.absorbAgent=o.absorb),o.max!==void 0&&(r.maxNotesPerRun=Number(o.max)),o.maxDeferrals!==void 0&&(r.maxDeferrals=Number(o.maxDeferrals)),o.enable&&o.disable){xo("pick one of --enable and --disable");return}if(o.enable&&(r.enabled=!0),o.disable&&(r.enabled=!1),Object.keys(r).length>0){let{mutateAgentxConfig:l}=await import("./config-mutate-KBZV2T4X.js"),{summary:c}=l(u=>n(u,r));console.log(ot.green(` ${c}`))}let i=Ju(process.cwd(),"agentx.json");if(!qv(i)){xo(`agentx.json not found at ${i}`);return}let a=s(JSON.parse(Fv(i,"utf-8"))?.wikiNotes);if(o.json){console.log(JSON.stringify(a,null,2));return}console.log(` wiki notes: ${a.enabled?ot.green("on"):ot.dim("off")}`),console.log(` inbox agent: ${a.inbox||ot.dim("not set")}`),console.log(` schedules that read it: ${a.crons.length?a.crons.join(", "):ot.dim("none on this node")}`),console.log(` absorb that reads it: ${a.absorbAgent?`wiki absorb for ${a.absorbAgent}`:ot.dim("none")}`),console.log(` most notes per run: ${a.maxNotesPerRun}`),console.log(` deferrals before a note expires: ${a.maxDeferrals}`)}))}import pn from"chalk";import{resolve as YI}from"path";var Gu=e=>e||YI(process.cwd(),".agentx/wiki");function Wv(e){let t=e.command("ontology").description("the wiki's pillars, types, typed relations and page lenses (show, init, check)");t.command("init").description("write the default ontology to ontology.yaml in the wiki, to edit").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{writeDefaultOntology:n}=await import("./load-Q3HCFXDT.js");try{let s=n(Gu(o.dir));console.log(pn.green(` wrote ${s}`))}catch(s){console.error(pn.red(` ${s.message}`)),process.exitCode=1}}),t.command("check").description("report problems in ontology.yaml").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{loadOntology:n}=await import("./load-Q3HCFXDT.js"),{file:s,errors:r}=n(Gu(o.dir));if(!s){console.log(pn.dim(" no ontology.yaml: the built-in defaults are in use"));return}if(r.length===0){console.log(pn.green(` ${s}: no problems`));return}console.log(pn.yellow(` ${s}: ${r.length} problem(s)`));for(let i of r)console.log(` - ${i}`);process.exitCode=1}),t.command("show").description("pages per pillar and type, as the wiki view groups them").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--json","print JSON").action(async o=>{let{loadOntology:n}=await import("./load-Q3HCFXDT.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{WikiHub:r}=await import("./hub-PPQGFC35.js"),i=Gu(o.dir),{loadRoster:a}=await import("./roster-BZGKG2ZA.js"),{ontology:l,errors:c}=n(i),u=new r(i,()=>{}),d=new s().get(u,l,a(i,u.listAgents([]),l.agent_names)),p=new Map;for(let f of d.entities.values())p.set(f.type,(p.get(f.type)??0)+1);if(o.json){console.log(JSON.stringify({entities:d.entities.size,types:Object.fromEntries(p),errors:c},null,2));return}console.log(pn.bold(` ${d.entities.size} entities`));for(let f of l.pillars){let g=l.types.filter(y=>y.pillar===f.id),h=g.reduce((y,w)=>y+(p.get(w.id)??0),0);console.log(` ${f.label.padEnd(26)} ${String(h).padStart(6)} ${pn.dim(g.map(y=>`${y.id} ${p.get(y.id)??0}`).join(" \xB7 "))}`)}c.length&&console.log(pn.yellow(` ontology.yaml has ${c.length} problem(s): agentx wiki ontology check`))})}import lt from"chalk";import{resolve as KI}from"path";var zu=e=>e||KI(process.cwd(),".agentx/wiki"),XI=()=>new Date().toISOString().slice(0,10);async function Yu(e){let{WikiHub:t}=await import("./hub-PPQGFC35.js"),{GraphCache:o}=await import("./graph-ZVKV3JBD.js"),{loadOntology:n}=await import("./load-Q3HCFXDT.js"),{loadRoster:s}=await import("./roster-BZGKG2ZA.js"),r=new t(e,()=>{}),{ontology:i}=n(e),a=new o().get(r,i,s(e,r.listAgents([]),i.agent_names));return{hub:r,g:a}}function Bv(e,t){let o=Number(e);return Number.isInteger(o)&&o>=1?o:(console.error(lt.red(` ${t} must be a whole number, 1 or more`)),process.exitCode=1,null)}function Hv(e){let t=e.command("events").description("give each event page an importance level (minor, normal, major) and the pages it is about").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--about <titles...>","only events linked to or naming these pages (a pilot)").option("--max <n>","most events per run","200").option("--batch <n>","events per model call","20").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","haiku").option("--rules-only","use only the importance rules in ontology.yaml; no model call").option("--force","redo events whose level this job set earlier").option("--dry-run","show what would be written, write nothing").option("--json","print the run as JSON").action(async o=>{let{runEvents:n,summariseAbout:s}=await import("./event-levels-PCFARGKL.js"),{claudeCall:r}=await import("./wiki-enrich-3SPIVYSG.js"),i=Bv(o.max,"--max"),a=Bv(o.batch,"--batch");if(i===null||a===null)return;let l=Number(o.maxCost);if(!Number.isFinite(l)||l<=0){console.error(lt.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let{hub:c,g:u}=await Yu(zu(o.dir)),d=o.about??[],{normName:p}=await import("./graph-ZVKV3JBD.js"),f=d.filter(w=>!u.names.has(p(w))&&!u.entities.has(w));if(f.length){console.error(lt.red(` no page is titled: ${f.join(", ")}`)),process.exitCode=1;return}let g=await n(c,u,r(o.model),{about:d,max:i,batch:a,maxCostUsd:l,dryRun:!!o.dryRun,force:!!o.force,rulesOnly:!!o.rulesOnly,today:XI()}),h=s(u,g,d);if(o.json){console.log(JSON.stringify({...g,about:h},null,2));return}for(let w of g.outcomes){let $=w.status==="written"?lt.green("\u2713"):w.status==="dry-run"?lt.cyan("~"):lt.yellow("\xB7"),x=w.importance?`${w.importance}${w.proposed?` (proposed ${w.proposed})`:""}`:w.status;console.log(` ${$} ${w.date||"no date "} ${x.padEnd(8)} ${w.title} ${lt.dim(`${w.by??w.status}${w.about.length?` \xB7 about ${w.about.join(", ")}`:""}${w.why?` \xB7 ${w.why}`:""}`)}`);for(let v of w.dropped.slice(0,4))console.log(lt.dim(` dropped: ${v}`))}for(let w of h)console.log(lt.bold(` ${w.title}`)+lt.dim(` (${w.type}): ${w.before} events in its History before \xB7 after: ${w.after.major} major, ${w.after.normal} normal, ${w.after.minor} minor (folded)`));let y=g.outcomes.filter(w=>w.importance).length;g.outcomes.length===0&&console.log(lt.dim(" nothing to do: every event in scope already has a level (--force redoes the ones this job set)")),console.log(lt.dim(` ${y} event${y===1?"":"s"} ${o.dryRun?"would get":"got"} a level \xB7 ${g.left} left \xB7 ${g.calls} model call${g.calls===1?"":"s"} \xB7 spent $${g.costUsd.toFixed(3)} of $${l}${g.capped?" \xB7 stopped at the cap":""}`)),g.outcomes.some(w=>w.status==="failed")&&(process.exitCode=1)});t.command("set <title> <level>").description("set an event's importance yourself (minor, normal or major); no later run changes it").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(o,n,s,r)=>{let{setEventLevel:i}=await import("./event-levels-PCFARGKL.js"),{IMPORTANCE_LEVELS:a}=await import("./types-YZX46RES.js"),l=n.toLowerCase();if(!a.includes(l)){console.error(lt.red(` level must be one of ${a.join(", ")}`)),process.exitCode=1;return}let{hub:c,g:u}=await Yu(zu(r.optsWithGlobals().dir)),d=i(c,u,o,l);d.ok?console.log(lt.green(` ${d.title} is now ${l}`)+lt.dim(` (${d.page})`)):(console.error(lt.red(` not set: ${d.reason}`)),process.exitCode=1)}),t.command("proposed").description("list events a run suggests as major, waiting for you to decide").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--json","print as JSON").action(async(o,n)=>{let s=n.optsWithGlobals(),{g:r}=await Yu(zu(s.dir)),i=[...r.entities.values()].filter(a=>a.type==="event"&&a.importanceProposed&&a.importanceProposed!==a.importance).sort((a,l)=>(l.date||"").localeCompare(a.date||""));if(s.json){console.log(JSON.stringify(i.map(a=>({id:a.id,title:a.title,date:a.date,importance:a.importance,proposed:a.importanceProposed})),null,2));return}for(let a of i)console.log(` ${a.date||"no date "} ${a.title} ${lt.dim(`now ${a.importance}, proposed ${a.importanceProposed}`)}`);console.log(lt.dim(i.length?` ${i.length} waiting. Decide each with: agentx wiki events set "<title>" major (or normal)`:" none waiting"))})}import _t from"chalk";import{resolve as VI}from"path";var QI=e=>e||VI(process.cwd(),".agentx/wiki");function Jv(e){e.command("rules [pages...]").description("write one obligation page per rule the wiki states, with deadline, penalty, source and check date").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--words <list>","comma-separated words that mark a page as stating rules (default: deadline, penalty, filing\u2026 in English, French and Arabic)").option("--max <n>","most source pages per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","read again pages that did not change").option("--dry-run","show what would be written, write nothing").option("--json","print the run as JSON").action(async(t,o)=>{let{WikiHub:n}=await import("./hub-PPQGFC35.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{loadOntology:r}=await import("./load-Q3HCFXDT.js"),{loadRoster:i}=await import("./roster-BZGKG2ZA.js"),{loadRulesState:a,ruleWordsPattern:l,runRules:c,saveRulesState:u}=await import("./rules-FBOLGE2S.js"),d=QI(o.dir),p=Number(o.max);if(!Number.isInteger(p)||p<1){console.error(_t.red(" --max must be a whole number of pages, 1 or more")),process.exitCode=1;return}let f=Number(o.maxCost);if(!Number.isFinite(f)||f<=0){console.error(_t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let g=o.words?.split(",").map(v=>v.trim()).filter(Boolean);if(o.words!==void 0&&!g?.length){console.error(_t.red(" --words needs at least one word")),process.exitCode=1;return}let h=new n(d,()=>{}),{ontology:y}=r(d);if(!y.types.some(v=>v.id==="obligation")){console.error(_t.red(" ontology.yaml has no `obligation` type; add it back to write rule pages")),process.exitCode=1;return}let w=new s().get(h,y,i(d,h.listAgents([]),y.agent_names)),$=a(d),x=await c(h,w,yy(o.model),{only:t,words:l(g),max:p,maxCostUsd:f,dryRun:!!o.dryRun,force:!!o.force,today:new Date().toISOString().slice(0,10),save:v=>u(d,v)},$);if(o.json){console.log(JSON.stringify(x,null,2));return}for(let v of x.outcomes){let S=v.status==="written"?_t.green("\u2713"):v.status==="dry-run"?_t.cyan("~"):_t.yellow("\xB7");console.log(` ${S} ${v.title} ${_t.dim(`${v.status} \xB7 ${v.page??"no page"} \xB7 ${v.rules.length} rules \xB7 $${v.costUsd.toFixed(3)}`)}`);for(let k of v.rules){let A=[k.deadline?"":"no deadline",k.penalty?"":"no penalty"].filter(Boolean);console.log(` ${k.created?"new":"updated"}: ${k.title} ${_t.dim(`\xB7 ${k.page}${A.length?` \xB7 ${A.join(", ")}`:""}${k.linked.length?` \xB7 linked from ${k.linked.join(", ")}`:""}`)}`),k.preview&&console.log(_t.dim(k.preview.split(`
|
|
639
639
|
`).map(R=>` | ${R}`).join(`
|
|
640
|
-
`)))}for(let k of v.dropped.slice(0,6))console.log(_t.dim(` dropped: ${k}`))}x.outcomes.length===0&&console.log(_t.dim(" nothing to do: no page that states rules changed since the last run (--force reads them again)")),console.log(_t.dim(` spent $${x.costUsd.toFixed(3)} of $${f}${x.capped?" \xB7 stopped at the cap":""}`))})}import $l from"chalk";import{resolve as ZI}from"path";var eN=e=>e||ZI(process.cwd(),".agentx/wiki");function Gv(e){e.command("summarize").description("write the one-line page summaries `wiki query` picks pages from; only new or changed pages are summarised").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--agent <id>","summarise this agent's pages (default: the calling agent)").option("--all","summarise every agent's pages and the shared pages").option("--model <m>","model (default: wiki.summaries.model, haiku)").option("--batch <n>","pages per model call (default: wiki.summaries.batchSize, 20)").option("--workers <n>","model calls running at once","4").option("--limit <n>","most pages to summarise per agent in this run (0 = all)","0").option("--dry-run","show how many pages are due, call no model, write nothing").option("--json","print the run as JSON").action(async t=>{let{WikiHub:o}=await import("./wiki-
|
|
640
|
+
`)))}for(let k of v.dropped.slice(0,6))console.log(_t.dim(` dropped: ${k}`))}x.outcomes.length===0&&console.log(_t.dim(" nothing to do: no page that states rules changed since the last run (--force reads them again)")),console.log(_t.dim(` spent $${x.costUsd.toFixed(3)} of $${f}${x.capped?" \xB7 stopped at the cap":""}`))})}import $l from"chalk";import{resolve as ZI}from"path";var eN=e=>e||ZI(process.cwd(),".agentx/wiki");function Gv(e){e.command("summarize").description("write the one-line page summaries `wiki query` picks pages from; only new or changed pages are summarised").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--agent <id>","summarise this agent's pages (default: the calling agent)").option("--all","summarise every agent's pages and the shared pages").option("--model <m>","model (default: wiki.summaries.model, haiku)").option("--batch <n>","pages per model call (default: wiki.summaries.batchSize, 20)").option("--workers <n>","model calls running at once","4").option("--limit <n>","most pages to summarise per agent in this run (0 = all)","0").option("--dry-run","show how many pages are due, call no model, write nothing").option("--json","print the run as JSON").action(async t=>{let{WikiHub:o}=await import("./wiki-FP4JMCYP.js"),{summarizeStore:n}=await import("./summaries-BIRSNWGH.js"),{claudeModelCall:s}=await import("./model-call-HMVMUAXS.js"),r={model:"haiku",batchSize:20,maxWords:35};try{let{loadDaemonConfig:u}=await import("./config-S522VXLI.js");r=u().wiki.summaries}catch{}let i=new o(eN(t.dir),void 0,"graph"),a=t.agent||process.env.AGENTX_AGENT_ID;if(!t.all&&!a){console.log($l.red(" Name an agent with --agent <id>, or pass --all.")),process.exitCode=1;return}let l=t.all?[...i.sharedScope("").map(u=>({id:u.id,store:u.store,skip:u.skip}))]:[{id:a,store:i.getAgentWiki(a),skip:void 0}],c=[];for(let u of l){let d=await n(u.store,{call:s,model:t.model??r.model,batchSize:t.batch?parseInt(t.batch):r.batchSize,maxWords:r.maxWords,workers:parseInt(t.workers),limit:parseInt(t.limit),dryRun:t.dryRun,skip:u.skip,log:t.json?void 0:p=>console.log($l.dim(` ${u.id}: ${p}`))});if(c.push({agent:u.id,...d}),!t.json&&(d.pages>0||d.removed>0)){let p=t.dryRun?`${d.due} due`:`${d.written} written${d.failed?$l.yellow(`, ${d.failed} failed`):""}${d.removed?`, ${d.removed} removed`:""}`;console.log(` ${$l.bold(u.id)}: ${d.pages} pages, ${p}`)}}t.json&&console.log(JSON.stringify(c,null,2)),c.some(u=>u.failed>0)&&(process.exitCode=1)})}import{resolve as B,relative as zv,dirname as Yv}from"path";import{exec as oN,execSync as as}from"child_process";import{promisify as nN}from"util";import{appendFileSync as sN,statSync as rN,writeFileSync as Jt,mkdirSync as so,readFileSync as Dt,readdirSync as iN,renameSync as kl,rmSync as Xu,existsSync as nt}from"fs";var ex=nN(oN);function $e(e,t){return new ic(vt(e),void 0,t||"graph")}async function tx(e){let t=[];try{let{loadDaemonConfig:n}=await import("./config-S522VXLI.js");t=(n().mesh?.peers||[]).map(s=>({url:s.url,token:s.token}))}catch{}if(!e?.length)return t;let o=n=>n.replace(/\/$/,"");return e.map(n=>({url:n,token:t.find(s=>o(s.url)===o(n))?.token}))}async function ox(){try{let{loadDaemonConfig:e}=await import("./config-S522VXLI.js"),t=Object.keys(e().agents||{});return t.length?new Set(t):null}catch{return null}}async function Kv(){try{let{loadDaemonConfig:e}=await import("./config-S522VXLI.js"),t=e().wikiNotes;return!t?.enabled||!t.inbox||!t.absorbAgent?null:{inbox:t.inbox,absorbAgent:t.absorbAgent,max:t.maxNotesPerRun,maxDeferrals:t.maxDeferrals}}catch{return null}}async function aN(){try{let{loadDaemonConfig:e}=await import("./config-S522VXLI.js");return sy(e().agents||{})}catch{return new Set}}function ls(e,t){let o=e.syncedFrom(t);return o?(console.log(m.yellow(` ${t}'s articles are copied from ${o.node} and read-only here; change them on ${o.node}.`)),process.exitCode=1,!0):!1}async function Xv(){let{sharedQueryEnabled:e}=await import("./query-RPZIRN3X.js");return e()}async function nx(e){let{loadQuerySettings:t}=await import("./query-settings-EBOBWOAL.js"),o=await t();if(e.method&&!["auto","summaries","catalog"].includes(e.method))return console.log(m.red(` --method takes auto, summaries or catalog, not "${e.method}".`)),process.exitCode=1,null;let n=e.linked===void 0?o.summaries.linkedPages:Number(e.linked);if(!Number.isInteger(n)||n<0||n>10)return console.log(m.red(` --linked takes a whole number from 0 to 10, not "${e.linked}".`)),process.exitCode=1,null;let s={...o.summaries.live,enabled:o.summaries.live.enabled&&e.live!==!1},r={...o.notes,enabled:o.notes.enabled&&e.notes!==!1};return{...o,method:e.method??o.method,summaries:{...o.summaries,linkedPages:n,live:s},notes:r}}function vt(e){return e||B(process.cwd(),".agentx/wiki")}function Vu(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var X=new tN().name("wiki").description("wiki knowledge base management");Lv(X);Uv(X);Wv(X);wy(X);Hv(X);Jv(X);Gv(X);X.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let t=e.mode,o=$e(e.dir,t),n=o.summary(),r=o.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${Vu(t)}]`)),console.log(),console.log(` Total raw entries: ${r}`),console.log(` Agents: ${n.length}`);let i=B(o.getBaseDir(),Sm);if(nt(i)){let l=new Date(Date.now()-6048e5).toISOString(),c=Em(Dt(i,"utf-8"),l),u=c.failed>0?m.red(`${c.failed} failed to write`):"0 failed to write";console.log(` Tasks, last 7 days: ${c.total} captured ${c.captured} \xB7 skipped ${c.skipped} \xB7 ${u}`);let d=Object.entries(c.skippedBy).sort((p,f)=>f[1]-p[1]).slice(0,3);d.length&&console.log(m.dim(` skipped because: ${d.map(([p,f])=>`${p} (${f})`).join(", ")}`))}console.log();for(let l of n){let c=l.unabsorbed>0?m.yellow(`${l.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(l.agentId)}`),console.log(` Entries: ${l.totalEntries} Articles: ${l.totalArticles} ${c}`),console.log(m.dim(` Cited by an article: ${l.cited} Read, not cited: ${l.readNotCited}`)),l.articles.length>0){for(let u of l.articles.slice(0,3))console.log(m.dim(` - ${u.title} [${(u.tags||[]).slice(0,3).join(", ")}]`));l.articles.length>3&&console.log(m.dim(` ... and ${l.articles.length-3} more`))}console.log()}let a=n.reduce((l,c)=>l+c.unabsorbed,0);a>0&&(console.log(m.dim(` ${a} raw entries wait for absorb \u2014 run 'agentx wiki absorb'.`)),console.log())});X.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(async e=>{let t=$e(e.dir,e.mode),o=e.agent?[e.agent]:t.listAgents(),n=0;console.log();for(let i of o){let l=t.getAgentWiki(i).lint();if(n+=l.length,l.length===0)console.log(` ${m.cyan(i)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(i)}: ${m.yellow(`${l.length} issues`)}`);for(let c of l){let u=c.type==="broken-link"?"x":c.type==="orphan"?"?":"!";console.log(` [${u}] ${m.dim(c.type)} ${c.article}: ${c.message}`)}}}let{factContradictions:s}=await import("./ledger-5GMBLR7W.js"),r=s(vt(e.dir));if(n+=r.length,r.length>0){console.log(` ${m.cyan("facts")}: ${m.yellow(`${r.length} contradiction(s)`)}`);for(let i of r)console.log(` [!] ${m.dim(i.type)} ${i.articles[0]}: ${i.message}`)}console.log(),n===0&&console.log(m.green(" All agent wikis are healthy")),console.log()});X.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--no-facts","skip the system-of-record lookups").option("--max <n>","max entries per agent","10").option("--since <date>","only entries dated on or after YYYY-MM-DD").option("--until <date>","only entries dated on or before YYYY-MM-DD").option("--model <model>","compile model (default: AGENTX_WIKI_ABSORB_MODEL, else sonnet)").option("--run-label <label>","tag this run's lines in _absorb-runs.jsonl, for `wiki absorb-runs`").option("--no-notes","do not read the wiki notes inbox, even for wikiNotes.absorbAgent").action(async e=>{let t=e.mode,o;try{o=Wu(e.model)}catch(R){console.log(m.red(` ${R.message}`)),process.exitCode=1;return}let n=$e(e.dir,t),s=await ox(),{agents:r,skipped:i}=ry(n.listAgents().filter(R=>!s||s.has(R)),{only:e.agent,off:await aN()}),a=i.length&&e.notes!==!1?(await Kv())?.absorbAgent:void 0;for(let R of i)console.log(` ${m.cyan(R)}: ${m.dim(iy(R,a))}`);let l=r.filter(R=>{let T=n.syncedFrom(R);return T&&console.log(` ${m.cyan(R)}: ${m.dim(`copied from ${T.node}, read-only here; absorb it there`)}`),!T}),c=parseInt(e.max),u=(()=>{try{let R=B(process.cwd(),".agentx/graph");return nt(R)?new Jo({baseDir:R}):null}catch{return null}})(),d=new Map;if(u)try{let R=u.loadIndex();for(let[T,I]of Object.entries(R.entries))d.set(T,I.path)}catch{}let p,f=R=>{let T=R.meta?.intentPath;if(Array.isArray(T)&&T.every(D=>typeof D=="string")&&T.length>0)return T;if(!u||d.size===0)return;let I=String(R.meta?.sender??""),M=u.fingerprint({text:R.content,channel:R.source,sender:I});return d.get(M)},g=(R,T)=>{let I=new Map;for(let D of R){let H=T.find(z=>z.id===D);if(!H)continue;let U=f(H);if(!U?.length)continue;let E=U.join("/"),_=I.get(E);_?_.n++:I.set(E,{path:U,n:1})}if(I.size===0)return;let M;for(let D of I.values())(!M||D.n>M.n)&&(M=D);return M?.path},h=0,y=0,w=0,$=B(n.getBaseDir(),"_absorb-runs.jsonl"),x=typeof e.runLabel=="string"&&e.runLabel.trim()?e.runLabel.trim():void 0,v=R=>{if(!e.dryRun)try{sN($,`${JSON.stringify(R)}
|
|
641
641
|
`)}catch{}},S=new Date().toISOString(),k=e.notes===!1?null:await Kv(),A=k?new Bm(n.getBaseDir()):null;for(let R of l){let T=Date.now(),I=typeof e.since=="string"?e.since.trim():"",M=typeof e.until=="string"?e.until.trim():"",D=n.getUnabsorbedEntries(R).filter(me=>!I||(me.date??"")>=I).filter(me=>!M||(me.date??"").slice(0,10)<=M).slice(0,c),H=!!(k&&A&&k.absorbAgent===R),U=`absorb/${R}/${S.replace(/[:.]/g,"-")}`,E=[];if(H&&e.dryRun?E=A.peekForRun(k.inbox,k.max,k.maxDeferrals):H&&(E=A.takeForRun(k.inbox,U,k.max,k.maxDeferrals)),D.length===0&&E.length===0){console.log(` ${m.cyan(R)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(R)}: ${D.length} entries to absorb`));for(let me of D.slice(0,3))console.log(m.dim(` [${me.date} via ${me.source}] ${me.content.slice(0,80)}...`));if(D.length>3&&console.log(m.dim(` ... and ${D.length-3} more`)),E.length>0&&console.log(m.dim(` Wiki notes: ${E.length} from the ${k.inbox} inbox${e.dryRun?"":` (run ${U})`}`)),e.dryRun)continue;let _=n.getAgentWiki(R),z=_.rebuildIndex(),he=_.getWorldview()||n.getSharedStore().getWorldview()||"",P=D.map(me=>`--- ENTRY ${me.id} [${me.date} ${me.agentId} via ${me.source}] ---
|
|
642
642
|
${me.content}
|
|
643
643
|
--- END ENTRY ---`).join(`
|
|
644
644
|
|
|
645
|
-
`),Q="";if(e.facts!==!1){let{extractHints:me,resolveFacts:bn,mergeRecords:ps,renderFactsBlock:fs,installPrompts:Ti,defaultSources:hs,recordsFromEntries:$n}=await import("./facts-XGZWX6CR.js");if(!p){let W=new Set;for(let ze of n.listAgents())for(let xt of n.getAgentWiki(ze).listArticles(ze))xt.meta.type==="person"&&W.add(xt.meta.title);p=[...W]}let kn=me(D.map(W=>({context:W.sourceContext,content:W.content,sender:typeof W.meta?.sender=="string"?W.meta.sender:void 0})),{known:p}),ys=$n(D);if(kn.length>0||ys.length>0){let W=hs(),{records:ze,results:xt}=kn.length>0?await bn(kn,{sources:W}):{records:[],results:[]},Ce=ps([...ys,...ze]);Q=fs(Ce);let ut=[...ys.length>0?[`entries:${ys.length}`]:[],...xt.filter(We=>We.records.length>0).map(We=>`${We.source}:${We.records.length}`)];console.log(m.dim(` Facts: ${kn.length} entities \u2192 ${Ce.length} resolved${ut.length?` (${ut.join(" ")})`:""}`));for(let We of Ti(xt,W))console.log(m.yellow(` ! ${We.source} ${We.kind} \u2014 would supply ${We.provides.join(", ")}`)),console.log(m.dim(` ${We.hint}`))}}let ve=z.articles.filter(me=>me.path&&!me.path.includes("/_versions/")),ie=await my([...D,...E.map(me=>({id:Bu(me.id),content:me.change}))],_,R,ve);ie.length>0&&console.log(m.dim(` Existing: ${ie.map(me=>me.path).join(", ")}`));let j=py(ie),oe=Pv(E),Ze=xc(t,R,he,z.articles,P,D.length,Q,j,oe);console.log(m.dim(` Mode: ${Vu(t)}`));let ao=B(_.baseDir,"_tmp");so(ao,{recursive:!0});let Fe=B(ao,"absorb-prompt.txt");Jt(Fe,Ze),console.log(m.dim(` Compiling with Claude (${o})...`));let Ue={kind:"call",at:"",label:x,agent:R,model:o,entries:D.length,articles:0,refused:0,failed:!0,wallMs:0,promptChars:Ze.length,promptParts:{entries:P.length,catalog:Ze.length-xc(t,R,he,[],P,D.length,Q,j,oe).length,catalogArticles:z.articles.length,covering:j.length,facts:Q.length,worldview:he.length,notes:oe.length},...E.length?{notes:E.length}:{}},Ro=Date.now();Ue.prepMs=Ro-T;try{let me,bn=!1;try{me=as(`cat '${Fe}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Ho(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(W){if(me=W.stdout||"",!me)throw W;bn=!0}let ps=me;try{let W=JSON.parse(me);Object.assign(Ue,zc(W)),W.is_error===!0&&(bn=!0),ps=W.result||W.content||"",ps||(console.log(m.dim(` Claude envelope keys: ${Object.keys(W).join(", ")}`)),console.log(m.dim(` is_error: ${W.is_error}, stop_reason: ${W.stop_reason}`)))}catch{}let fs=_v(ps);if("error"in fs){E.length>0&&console.log(m.yellow(` ${E.length} wiki note(s) stay waiting`)),console.log(m.red(` ${fs.error}`)),console.log(m.dim(` First 500 chars: ${ps.slice(0,500)}`));continue}let{articles:Ti,gaps:hs}=fs,$n=new Set,kn=new Set,ys=new Set(D.map(W=>W.id));for(let W of Ti){let ze=new Date().toISOString().slice(0,10),xt=Array.isArray(W.sources)?W.sources:[],Ce=E.length>0?xt.filter(Wo=>ys.has(Wo)):xt;if(E.length>0&&Ce.length===0){console.log(m.yellow(` ! refused ${W.path}: cites no entry from this batch; a wiki note only patches`)),Ue.refused++;continue}let ut=fy(W,ve);ut!==W.path&&(console.log(m.dim(` ~ ${W.path} \u2192 ${ut} (an article with this title exists)`)),W.path=ut);let We=_.readArticle(W.path);if(We){let Wo=Dr(We.content,String(W.content??""));if(Wo.length>0){console.log(m.yellow(` ! refused ${W.path}: the rewrite drops ${Wo.length} fact(s) the article has`)),console.log(m.dim(` ${Wo.slice(0,8).join("; ")}${Wo.length>8?"; \u2026":""}`));for(let K0 of Ce)$n.add(K0);Ue.refused++;continue}}let Yl=g(Ce,D)??We?.meta.graphPath;_.writeArticle(W.path,{title:W.title,type:W.type,related:Array.isArray(W.related)?W.related:void 0,tags:W.tags||[],owner:R,access:We?.meta.access??"public",sharedWith:We?.meta.sharedWith?.length?We.meta.sharedWith:void 0,created:We?.meta.created||ze,lastUpdated:ze,sources:[...new Set([...We?.meta.sources??[],...Ce])],graphPath:Yl},W.content,R);let z0=W.type?m.magenta(`[${W.type}]`)+" ":"",Y0=Array.isArray(W.related)&&W.related.length?` \u2192 ${W.related.slice(0,3).join(", ")}${W.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(We?"~":"+")} ${z0}${W.path}: ${W.title}${m.dim(Y0)}`);let jg=(W.tags||[]).slice(0,4).join(", ");jg&&console.log(m.dim(` tags: ${jg}`)),Yl?.length&&(console.log(m.dim(` graphPath: ${Yl.join(" \u203A ")}`)),y++),h++,Ue.articles++;for(let Wo of Ce)kn.add(Wo)}if(E.length>0&&!bn){let W=E.filter(Ce=>{let ut=A.get(Ce.id);return ut&&ut.status!=="open"&&ut.status!=="deferred"?(console.log(m.dim(` note ${Ce.id} already ${ut.status} by ${ut.handled?.by??"another run"}; left as it is`)),!1):ut?.handled&&ut.handled.at>S?(console.log(m.dim(` note ${Ce.id} already deferred by ${ut.handled.by} during this run; left as it is`)),!1):!0}),ze=Mv(W,Dv(fs.notes),_,{agentId:R,paths:new Set(ie.map(Ce=>Ce.path))}),xt=0;for(let Ce of ze){try{A.handle(Ce.id,Ce.outcome,Ce.reason,R,U),xt++}catch(We){console.log(m.yellow(` ! note ${Ce.id}: could not record ${Ce.outcome}: ${We?.message??We}`))}let ut=Ce.outcome==="patched"?m.green("~"):Ce.outcome==="rejected"?m.red("x"):m.yellow("\u2026");console.log(` ${ut} note ${Ce.id} ${Ce.outcome}: ${m.dim(Ce.reason.slice(0,160))}`)}Ue.notesPatched=ze.filter(Ce=>Ce.outcome==="patched").length,Ue.notesRecorded=xt}else E.length>0&&console.log(m.yellow(` ${E.length} wiki note(s) stay waiting`));if(Ue.failed=bn,Ue.heldCited=[...$n].filter(W=>kn.has(W)).length,bn)console.log(m.yellow(` Run reported an error \u2014 ${D.length} entries stay queued`));else{let W=D.map(ze=>ze.id).filter(ze=>!$n.has(ze));$n.size>0&&console.log(m.yellow(` ${D.length-W.length} entries stay queued behind refused saves`)),n.markProcessed(R,W,Ti.flatMap(ze=>ze.sources||[]).filter(ze=>!$n.has(ze)))}if(hs.length>0){console.log(),console.log(m.yellow(` Gaps detected (${hs.length} missing pieces):`));for(let W of hs)console.log(m.yellow(` ? ${W}`));try{let{QuestionStore:W}=await import("./questions-ZATLU5AW.js"),ze=new W(vt(e.dir)).add(hs.map(xt=>({kind:"article",agentId:R,path:"",subject:String(xt).slice(0,120),question:`No article yet for: ${String(xt).slice(0,160)}`})));ze.added>0&&console.log(m.dim(` queued ${ze.added} for follow-up (agentx wiki questions)`))}catch{}}_.rebuildIndex()}catch(me){console.log(m.red(` Absorb failed: ${me.message?.slice(0,200)}`)),me.stderr&&console.log(m.dim(String(me.stderr).slice(0,300))),me.stdout&&console.log(m.dim("stdout: "+String(me.stdout).slice(0,300)))}finally{Ue.at=new Date().toISOString(),Ue.wallMs=Date.now()-Ro,Ue.failed&&w++,v(Ue)}}if(v({kind:"run",label:x,startedAt:S,endedAt:new Date().toISOString(),max:c,model:o,failed:w}),console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(h>0&&(console.log(m.green(` ${h} articles compiled across ${l.length} agent(s)`)),u)){let R=h>0?Math.round(y/h*100):0;console.log(m.dim(` ${y}/${h} carry graphPath (${R}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}w>0&&(console.log(m.red(` ${w} absorb call(s) failed; their entries stay queued`)),process.exitCode=1),console.log()});X.command("absorb-eval").description("score absorbed articles against the entries they cite").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's articles").option("--since <date>","only articles last updated on or after YYYY-MM-DD").option("--changed-after <time>","only articles whose file changed after this time (ISO, e.g. 2026-10-07T20:05:00Z)").option("--n <n>","articles in the sample","40").option("--seed <seed>","sample seed; the same seed picks the same articles","absorb-eval").option("--sample <file>","reuse the sample saved in this file, or save it there on first use").option("--judge","also ask a model to check each article's claims (one call per article)").option("--judge-model <model>","model for --judge","sonnet").option("--out <file>","write the scorecard as Markdown to this file").option("--json","print the scorecard and every article's checks as JSON").action(async e=>{let{pickSample:t,checkArticle:o,findDuplicates:n,buildJudgePrompt:s,parseJudgeReply:r,buildScorecard:i,renderScorecard:a,uncitedWithFacts:l}=await import("./absorb-eval-
|
|
645
|
+
`),Q="";if(e.facts!==!1){let{extractHints:me,resolveFacts:bn,mergeRecords:ps,renderFactsBlock:fs,installPrompts:Ti,defaultSources:hs,recordsFromEntries:$n}=await import("./facts-XGZWX6CR.js");if(!p){let W=new Set;for(let ze of n.listAgents())for(let xt of n.getAgentWiki(ze).listArticles(ze))xt.meta.type==="person"&&W.add(xt.meta.title);p=[...W]}let kn=me(D.map(W=>({context:W.sourceContext,content:W.content,sender:typeof W.meta?.sender=="string"?W.meta.sender:void 0})),{known:p}),ys=$n(D);if(kn.length>0||ys.length>0){let W=hs(),{records:ze,results:xt}=kn.length>0?await bn(kn,{sources:W}):{records:[],results:[]},Ce=ps([...ys,...ze]);Q=fs(Ce);let ut=[...ys.length>0?[`entries:${ys.length}`]:[],...xt.filter(We=>We.records.length>0).map(We=>`${We.source}:${We.records.length}`)];console.log(m.dim(` Facts: ${kn.length} entities \u2192 ${Ce.length} resolved${ut.length?` (${ut.join(" ")})`:""}`));for(let We of Ti(xt,W))console.log(m.yellow(` ! ${We.source} ${We.kind} \u2014 would supply ${We.provides.join(", ")}`)),console.log(m.dim(` ${We.hint}`))}}let ve=z.articles.filter(me=>me.path&&!me.path.includes("/_versions/")),ie=await my([...D,...E.map(me=>({id:Bu(me.id),content:me.change}))],_,R,ve);ie.length>0&&console.log(m.dim(` Existing: ${ie.map(me=>me.path).join(", ")}`));let j=py(ie),oe=Pv(E),Ze=xc(t,R,he,z.articles,P,D.length,Q,j,oe);console.log(m.dim(` Mode: ${Vu(t)}`));let ao=B(_.baseDir,"_tmp");so(ao,{recursive:!0});let Fe=B(ao,"absorb-prompt.txt");Jt(Fe,Ze),console.log(m.dim(` Compiling with Claude (${o})...`));let Ue={kind:"call",at:"",label:x,agent:R,model:o,entries:D.length,articles:0,refused:0,failed:!0,wallMs:0,promptChars:Ze.length,promptParts:{entries:P.length,catalog:Ze.length-xc(t,R,he,[],P,D.length,Q,j,oe).length,catalogArticles:z.articles.length,covering:j.length,facts:Q.length,worldview:he.length,notes:oe.length},...E.length?{notes:E.length}:{}},Ro=Date.now();Ue.prepMs=Ro-T;try{let me,bn=!1;try{me=as(`cat '${Fe}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Ho(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(W){if(me=W.stdout||"",!me)throw W;bn=!0}let ps=me;try{let W=JSON.parse(me);Object.assign(Ue,zc(W)),W.is_error===!0&&(bn=!0),ps=W.result||W.content||"",ps||(console.log(m.dim(` Claude envelope keys: ${Object.keys(W).join(", ")}`)),console.log(m.dim(` is_error: ${W.is_error}, stop_reason: ${W.stop_reason}`)))}catch{}let fs=_v(ps);if("error"in fs){E.length>0&&console.log(m.yellow(` ${E.length} wiki note(s) stay waiting`)),console.log(m.red(` ${fs.error}`)),console.log(m.dim(` First 500 chars: ${ps.slice(0,500)}`));continue}let{articles:Ti,gaps:hs}=fs,$n=new Set,kn=new Set,ys=new Set(D.map(W=>W.id));for(let W of Ti){let ze=new Date().toISOString().slice(0,10),xt=Array.isArray(W.sources)?W.sources:[],Ce=E.length>0?xt.filter(Wo=>ys.has(Wo)):xt;if(E.length>0&&Ce.length===0){console.log(m.yellow(` ! refused ${W.path}: cites no entry from this batch; a wiki note only patches`)),Ue.refused++;continue}let ut=fy(W,ve);ut!==W.path&&(console.log(m.dim(` ~ ${W.path} \u2192 ${ut} (an article with this title exists)`)),W.path=ut);let We=_.readArticle(W.path);if(We){let Wo=Dr(We.content,String(W.content??""));if(Wo.length>0){console.log(m.yellow(` ! refused ${W.path}: the rewrite drops ${Wo.length} fact(s) the article has`)),console.log(m.dim(` ${Wo.slice(0,8).join("; ")}${Wo.length>8?"; \u2026":""}`));for(let K0 of Ce)$n.add(K0);Ue.refused++;continue}}let Yl=g(Ce,D)??We?.meta.graphPath;_.writeArticle(W.path,{title:W.title,type:W.type,related:Array.isArray(W.related)?W.related:void 0,tags:W.tags||[],owner:R,access:We?.meta.access??"public",sharedWith:We?.meta.sharedWith?.length?We.meta.sharedWith:void 0,created:We?.meta.created||ze,lastUpdated:ze,sources:[...new Set([...We?.meta.sources??[],...Ce])],graphPath:Yl},W.content,R);let z0=W.type?m.magenta(`[${W.type}]`)+" ":"",Y0=Array.isArray(W.related)&&W.related.length?` \u2192 ${W.related.slice(0,3).join(", ")}${W.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(We?"~":"+")} ${z0}${W.path}: ${W.title}${m.dim(Y0)}`);let jg=(W.tags||[]).slice(0,4).join(", ");jg&&console.log(m.dim(` tags: ${jg}`)),Yl?.length&&(console.log(m.dim(` graphPath: ${Yl.join(" \u203A ")}`)),y++),h++,Ue.articles++;for(let Wo of Ce)kn.add(Wo)}if(E.length>0&&!bn){let W=E.filter(Ce=>{let ut=A.get(Ce.id);return ut&&ut.status!=="open"&&ut.status!=="deferred"?(console.log(m.dim(` note ${Ce.id} already ${ut.status} by ${ut.handled?.by??"another run"}; left as it is`)),!1):ut?.handled&&ut.handled.at>S?(console.log(m.dim(` note ${Ce.id} already deferred by ${ut.handled.by} during this run; left as it is`)),!1):!0}),ze=Mv(W,Dv(fs.notes),_,{agentId:R,paths:new Set(ie.map(Ce=>Ce.path))}),xt=0;for(let Ce of ze){try{A.handle(Ce.id,Ce.outcome,Ce.reason,R,U),xt++}catch(We){console.log(m.yellow(` ! note ${Ce.id}: could not record ${Ce.outcome}: ${We?.message??We}`))}let ut=Ce.outcome==="patched"?m.green("~"):Ce.outcome==="rejected"?m.red("x"):m.yellow("\u2026");console.log(` ${ut} note ${Ce.id} ${Ce.outcome}: ${m.dim(Ce.reason.slice(0,160))}`)}Ue.notesPatched=ze.filter(Ce=>Ce.outcome==="patched").length,Ue.notesRecorded=xt}else E.length>0&&console.log(m.yellow(` ${E.length} wiki note(s) stay waiting`));if(Ue.failed=bn,Ue.heldCited=[...$n].filter(W=>kn.has(W)).length,bn)console.log(m.yellow(` Run reported an error \u2014 ${D.length} entries stay queued`));else{let W=D.map(ze=>ze.id).filter(ze=>!$n.has(ze));$n.size>0&&console.log(m.yellow(` ${D.length-W.length} entries stay queued behind refused saves`)),n.markProcessed(R,W,Ti.flatMap(ze=>ze.sources||[]).filter(ze=>!$n.has(ze)))}if(hs.length>0){console.log(),console.log(m.yellow(` Gaps detected (${hs.length} missing pieces):`));for(let W of hs)console.log(m.yellow(` ? ${W}`));try{let{QuestionStore:W}=await import("./questions-ZATLU5AW.js"),ze=new W(vt(e.dir)).add(hs.map(xt=>({kind:"article",agentId:R,path:"",subject:String(xt).slice(0,120),question:`No article yet for: ${String(xt).slice(0,160)}`})));ze.added>0&&console.log(m.dim(` queued ${ze.added} for follow-up (agentx wiki questions)`))}catch{}}_.rebuildIndex()}catch(me){console.log(m.red(` Absorb failed: ${me.message?.slice(0,200)}`)),me.stderr&&console.log(m.dim(String(me.stderr).slice(0,300))),me.stdout&&console.log(m.dim("stdout: "+String(me.stdout).slice(0,300)))}finally{Ue.at=new Date().toISOString(),Ue.wallMs=Date.now()-Ro,Ue.failed&&w++,v(Ue)}}if(v({kind:"run",label:x,startedAt:S,endedAt:new Date().toISOString(),max:c,model:o,failed:w}),console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(h>0&&(console.log(m.green(` ${h} articles compiled across ${l.length} agent(s)`)),u)){let R=h>0?Math.round(y/h*100):0;console.log(m.dim(` ${y}/${h} carry graphPath (${R}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}w>0&&(console.log(m.red(` ${w} absorb call(s) failed; their entries stay queued`)),process.exitCode=1),console.log()});X.command("absorb-eval").description("score absorbed articles against the entries they cite").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's articles").option("--since <date>","only articles last updated on or after YYYY-MM-DD").option("--changed-after <time>","only articles whose file changed after this time (ISO, e.g. 2026-10-07T20:05:00Z)").option("--n <n>","articles in the sample","40").option("--seed <seed>","sample seed; the same seed picks the same articles","absorb-eval").option("--sample <file>","reuse the sample saved in this file, or save it there on first use").option("--judge","also ask a model to check each article's claims (one call per article)").option("--judge-model <model>","model for --judge","sonnet").option("--out <file>","write the scorecard as Markdown to this file").option("--json","print the scorecard and every article's checks as JSON").action(async e=>{let{pickSample:t,checkArticle:o,findDuplicates:n,buildJudgePrompt:s,parseJudgeReply:r,buildScorecard:i,renderScorecard:a,uncitedWithFacts:l}=await import("./absorb-eval-WM6JQGYG.js"),{extractJson:c}=await import("./extract-json-7775Q7KO.js"),u=$e(e.dir,e.mode),d=e.agent?[e.agent]:u.listAgents(),p=typeof e.since=="string"?e.since.trim():"",f=typeof e.changedAfter=="string"&&e.changedAfter.trim()?new Date(e.changedAfter.trim()):null;if(f&&Number.isNaN(f.getTime())){console.log(m.red(` not a time: ${e.changedAfter}`)),process.exitCode=1;return}let g=f?f.toISOString().slice(0,19):p,h=new Map;for(let P of u.getSharedStore().listEntries())h.set(P.id,{id:P.id,date:P.date,content:P.content});let y=[];for(let P of d)for(let Q of u.getAgentWiki(P).listArticles(P))y.push({key:`${P}/${Q.path}`,agent:P,article:Q});let w=new Map;for(let P of y)for(let Q of P.article.meta.sources??[]){let ve=w.get(Q);ve?ve.push(P.article.content):w.set(Q,[P.article.content])}let $=P=>{if(!f)return!0;try{return rN(B(u.getAgentWiki(P.agent).baseDir,P.article.path)).mtimeMs>f.getTime()}catch{return!1}},x=y.filter(P=>!p||(P.article.meta.lastUpdated??"")>=p.slice(0,10)).filter($),v=String(e.seed),S;if(e.sample&&nt(e.sample)){let P=JSON.parse(Dt(e.sample,"utf-8"));v=P.seed??v;let Q=new Map(y.map(ie=>[ie.key,ie]));S=P.keys.map(ie=>Q.get(ie)).filter(ie=>!!ie);let ve=P.keys.length-S.length;ve>0&&console.error(m.yellow(` ${ve} sampled article(s) no longer exist`))}else S=t(x.map(P=>({...P,path:P.key})),parseInt(e.n),v),e.sample&&(Jt(e.sample,`${JSON.stringify({seed:v,since:g||void 0,keys:S.map(P=>P.key)},null,2)}
|
|
646
646
|
`),console.error(m.dim(` sample saved to ${e.sample}`)));if(S.length===0){console.log(m.yellow(` no articles${g?` changed since ${g}`:""} to score`));return}let k=P=>P.replace(/^---\n[\s\S]*?\n---\n?/,""),A=P=>{let Q=u.getAgentWiki(P.agent).getVersions(P.article.path),ve=g?Q.filter(j=>j.timestamp>=g):Q.slice(0,1),ie=ve[ve.length-1];if(ie)try{return k(Dt(ie.path,"utf-8"))}catch{return}},R=S.map(P=>({path:P.key,title:P.article.meta.title,type:P.article.meta.type,content:P.article.content,sources:P.article.meta.sources??[],lastUpdated:P.article.meta.lastUpdated,previous:A(P)})),T=R.map(P=>o(P,h,Q=>w.get(Q)??[])),I=new Set(S.map(P=>P.key)),M=d.flatMap(P=>n(y.filter(Q=>Q.agent===P).map(Q=>({path:Q.key,title:Q.article.meta.title,type:Q.article.meta.type,sources:Q.article.meta.sources})),I)),D=[];if(e.judge){let P;try{P=Wu(e.judgeModel)}catch(ie){console.log(m.red(` ${ie.message}`)),process.exitCode=1;return}let Q=B(u.getBaseDir(),"_tmp");so(Q,{recursive:!0});let ve=R.map((ie,j)=>({a:ie,i:j}));await Promise.all(Array.from({length:Math.min(3,ve.length)},async()=>{for(let ie=ve.shift();ie;ie=ve.shift()){let{a:j,i:oe}=ie,Ze=j.sources.map(Fe=>h.get(Fe)).filter(Fe=>!!Fe),ao=B(Q,`absorb-eval-${process.pid}-${oe}.txt`);Jt(ao,s(j,Ze));try{let{stdout:Fe}=await ex(`cat '${ao}' | claude -p - --output-format json --max-turns 1 --model '${P}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Ho(),encoding:"utf-8",timeout:3e5,maxBuffer:4194304}),Ue=Fe;try{Ue=JSON.parse(Fe).result??Fe}catch{}let Ro=r(c(Ue));Ro?D.push({path:j.path,verdict:Ro}):console.error(m.yellow(` judge reply for ${j.path} was not usable`))}catch(Fe){console.error(m.yellow(` judge failed for ${j.path}: ${String(Fe?.message??Fe).slice(0,160)}`))}finally{Xu(ao,{force:!0})}}})),D.sort((ie,j)=>ie.path.localeCompare(j.path))}let H=new Set(y.flatMap(P=>P.article.meta.sources??[])),U=[];for(let P of d){let Q=B(u.getBaseDir(),"agents",P,"_absorbed.json");if(!nt(Q))continue;let ve={};try{ve=JSON.parse(Dt(Q,"utf-8")).entries??{}}catch{continue}for(let[ie,j]of Object.entries(ve)){if(H.has(ie)||g&&String(j.at??"")<g)continue;let oe=h.get(ie);oe&&U.push(oe)}}let E=y.map(P=>P.article.content).join(`
|
|
647
|
-
`),_=l(U,E),z=i(T,M,{seed:v,since:g||void 0},D,5,{entries:U.length,lost:_}),he=a(z);e.out&&Jt(e.out,he),e.json?console.log(JSON.stringify({card:z,checks:T},null,2)):e.out?console.log(m.green(` scorecard written to ${e.out}`)):console.log(he)});X.command("query-runs").description("count wiki queries by outcome, with timing").option("--dir <path>","wiki directory").option("--since <date>","only queries on or after this date or time (ISO)").option("--json","print the summary as JSON").action(async e=>{let{QUERY_RUNS_FILE:t,summariseQueryRuns:o}=await import("./query-runs-AENEZOM6.js"),n=B(vt(e.dir),t);if(!nt(n)){console.log(m.yellow(` no queries recorded yet (${n})`));return}let s=o(Dt(n,"utf-8"),typeof e.since=="string"?e.since.trim():void 0);if(e.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(m.bold(` ${s.total} queries \xB7 ${s.failed} failed \xB7 p50 ${(s.wallMsP50/1e3).toFixed(1)} s \xB7 p95 ${(s.wallMsP95/1e3).toFixed(1)} s`));for(let[r,i]of Object.entries(s.byStatus).sort((a,l)=>l[1]-a[1]))console.log(` ${r.padEnd(14)} ${i}`);console.log(m.dim(` from: ${Object.entries(s.bySource).map(([r,i])=>`${r} ${i}`).join(" \xB7 ")}`)),console.log()});X.command("absorb-runs").description("time, cost and throughput of absorb runs, grouped by --run-label").option("--dir <path>","wiki directory").option("--label <label>","only this run label").option("--json","print the summary as JSON").action(async e=>{let{summariseRuns:t}=await import("./absorb-eval-
|
|
648
|
-
`).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}).filter(l=>!e.label||(l.label||"(none)")===e.label),s=t(n);if(e.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){console.log(m.yellow(" no matching runs"));return}let r=[["label",l=>l.label],["calls",l=>`${l.calls}${l.failed?` (${l.failed} failed)`:""}`],["entries",l=>String(l.entries)],["articles",l=>`${l.articles}${l.refused?` (${l.refused} refused${l.heldCited?`, ${l.heldCited} held entries lost`:""})`:""}`],["wall",l=>`${(l.wallMs/6e4).toFixed(1)} min`],["call p50/p95",l=>`${Math.round(l.callMsP50/1e3)}/${Math.round(l.callMsP95/1e3)} s`],["entries/min",l=>l.entriesPerMinute.toFixed(1)],["prep",l=>`${(l.prepMs/6e4).toFixed(1)} min`],["cost",l=>`$${l.costUsd.toFixed(2)}`],["$/entry",l=>`$${l.costPerEntry.toFixed(3)}`]],i=s.map(l=>r.map(([,c])=>c(l))),a=r.map(([l],c)=>Math.max(l.length,...i.map(u=>u[c].length)));console.log(),console.log(m.bold(r.map(([l],c)=>l.padEnd(a[c])).join(" ")));for(let l of i)console.log(l.map((c,u)=>c.padEnd(a[u])).join(" "));console.log()});X.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let t=lN(e.since),o=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=o.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let r=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-
|
|
647
|
+
`),_=l(U,E),z=i(T,M,{seed:v,since:g||void 0},D,5,{entries:U.length,lost:_}),he=a(z);e.out&&Jt(e.out,he),e.json?console.log(JSON.stringify({card:z,checks:T},null,2)):e.out?console.log(m.green(` scorecard written to ${e.out}`)):console.log(he)});X.command("query-runs").description("count wiki queries by outcome, with timing").option("--dir <path>","wiki directory").option("--since <date>","only queries on or after this date or time (ISO)").option("--json","print the summary as JSON").action(async e=>{let{QUERY_RUNS_FILE:t,summariseQueryRuns:o}=await import("./query-runs-AENEZOM6.js"),n=B(vt(e.dir),t);if(!nt(n)){console.log(m.yellow(` no queries recorded yet (${n})`));return}let s=o(Dt(n,"utf-8"),typeof e.since=="string"?e.since.trim():void 0);if(e.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(m.bold(` ${s.total} queries \xB7 ${s.failed} failed \xB7 p50 ${(s.wallMsP50/1e3).toFixed(1)} s \xB7 p95 ${(s.wallMsP95/1e3).toFixed(1)} s`));for(let[r,i]of Object.entries(s.byStatus).sort((a,l)=>l[1]-a[1]))console.log(` ${r.padEnd(14)} ${i}`);console.log(m.dim(` from: ${Object.entries(s.bySource).map(([r,i])=>`${r} ${i}`).join(" \xB7 ")}`)),console.log()});X.command("absorb-runs").description("time, cost and throughput of absorb runs, grouped by --run-label").option("--dir <path>","wiki directory").option("--label <label>","only this run label").option("--json","print the summary as JSON").action(async e=>{let{summariseRuns:t}=await import("./absorb-eval-WM6JQGYG.js"),o=B(vt(e.dir),"_absorb-runs.jsonl");if(!nt(o)){console.log(m.yellow(` no absorb runs recorded yet (${o})`));return}let n=Dt(o,"utf-8").split(`
|
|
648
|
+
`).filter(Boolean).flatMap(l=>{try{return[JSON.parse(l)]}catch{return[]}}).filter(l=>!e.label||(l.label||"(none)")===e.label),s=t(n);if(e.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){console.log(m.yellow(" no matching runs"));return}let r=[["label",l=>l.label],["calls",l=>`${l.calls}${l.failed?` (${l.failed} failed)`:""}`],["entries",l=>String(l.entries)],["articles",l=>`${l.articles}${l.refused?` (${l.refused} refused${l.heldCited?`, ${l.heldCited} held entries lost`:""})`:""}`],["wall",l=>`${(l.wallMs/6e4).toFixed(1)} min`],["call p50/p95",l=>`${Math.round(l.callMsP50/1e3)}/${Math.round(l.callMsP95/1e3)} s`],["entries/min",l=>l.entriesPerMinute.toFixed(1)],["prep",l=>`${(l.prepMs/6e4).toFixed(1)} min`],["cost",l=>`$${l.costUsd.toFixed(2)}`],["$/entry",l=>`$${l.costPerEntry.toFixed(3)}`]],i=s.map(l=>r.map(([,c])=>c(l))),a=r.map(([l],c)=>Math.max(l.length,...i.map(u=>u[c].length)));console.log(),console.log(m.bold(r.map(([l],c)=>l.padEnd(a[c])).join(" ")));for(let l of i)console.log(l.map((c,u)=>c.padEnd(a[u])).join(" "));console.log()});X.command("promote").description("promote per-agent memories into shared, authoritative wiki articles").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--memory-dir <path>","the .agentx dir holding agent-memory/ (default .agentx)").option("--since <duration>","memory window, e.g. 24h, 7d","7d").option("--agent <id>","only this agent's memories").option("--types <list>","comma-separated memory types","project,reference,feedback").option("--max <n>","max candidate memories per run","20").option("--via <agentId>","route the LLM call through an agent \u2014 uses the agent's own session, no API key").option("--model <model>","direct Anthropic API \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--reviews","also promote findings from session-monitor reviews").option("--review-kinds <list>","which review kinds","decisions,warnings,friction,context").option("--failures","also propose lessons from failures that recur across sessions").option("--min-sessions <n>","sessions a failure must recur in for --failures","3").option("--commit","judge and write proposals for review (default: dry-run)",!1).option("--budget <tokens>","max estimated tokens for the judge prompt","60000").action(async e=>{let t=lN(e.since),o=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=o.find(a=>!n.includes(a));s&&(console.log(m.red(` Invalid memory type "${s}". Valid: ${n.join(", ")}`)),process.exit(1)),e.commit&&!e.via&&!e.model&&(console.log(m.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1)),console.log(),console.log(m.bold(" Memory \u2192 Wiki Promotion")),console.log();let r=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-HQBKXAJA.js"),{default:l}=await import("better-sqlite3"),c=B(process.cwd(),".agentx/db.sqlite");if(!nt(c))console.log(m.yellow(` --reviews: no ${c}`));else{let u=new l(c,{readonly:!0});try{let d=u.prepare("SELECT id, session_id, agent, source, updated_at, result FROM session_reviews WHERE status='ready' AND result IS NOT NULL AND updated_at >= ? ORDER BY updated_at DESC").all(Date.now()-(t??6048e5));r=a(d,{kinds:String(e.reviewKinds).split(",").map(g=>g.trim()).filter(Boolean)});let p=r.filter(g=>(g.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${r.length} candidate finding(s), ${p} seen in more than one session`));let f=r[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.memory.description.slice(0,84)}`))}finally{u.close()}}}if(e.failures){let a=Number(e.minSessions);(!Number.isInteger(a)||a<2)&&(console.log(m.red(` Invalid --min-sessions "${e.minSessions}". Use a whole number of 2 or more.`)),process.exit(1));let{loadFailedTraces:l,failuresToCandidates:c}=await import("./failure-candidates-FASPEOBF.js"),{default:u}=await import("better-sqlite3"),d=B(process.cwd(),".agentx/db.sqlite");if(!nt(d))console.log(m.yellow(` --failures: no ${d}`));else{let p=new u(d,{readonly:!0});try{let f=l(p,{since:Date.now()-(t??6048e5)}),g=c(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${g.length} failure(s) seen in ${a}+ sessions`));let h=g[0];h&&console.log(m.dim(` most recurrent (${h.occurrences} sessions, ${h.failure.runs} runs): ${h.memory.description.slice(0,84)}`)),r=[...r,...g]}finally{p.close()}}}let i=await _p({extraCandidates:r,wikiDir:e.dir?B(e.dir):void 0,memoryRoot:e.memoryDir?B(e.memoryDir):void 0,sinceMs:t,agentFilter:e.agent,types:o,max:Number(e.max)||20,viaAgent:e.via,model:e.model,daemonUrl:e.daemon,commit:e.commit,budgetTokens:Number(e.budget)||void 0,log:a=>console.log(m.dim(` ${a}`))});if(i.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${i.candidates.length} candidate(s) in ${i.clusters.length} cluster(s):`);for(let a of i.clusters){let l=a.candidates[0],c=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${l.memory.type}]`)} ${l.memory.name}${c} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${l.memory.description}`))}if(console.log(),i.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of i.proposed){let l=a.type?m.magenta(`[${a.type}]`)+" ":"",c=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${l}${a.path}: ${a.title} ${m.dim(`(${c})`)}`),console.log(m.dim(` proposal ${a.id}`))}for(let a of i.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(i.gaps.length){console.log(),console.log(m.yellow(` Gaps (${i.gaps.length}):`));for(let a of i.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of i.warnings)console.log(m.dim(` ! ${a}`));for(let a of i.errors)console.log(m.red(` x ${a}`));console.log(),console.log(i.errors.length?m.red(` ${i.proposed.length} proposed, ${i.errors.length} error(s)`):m.green(` ${i.proposed.length} proposed, ${i.skipped.length} skipped`)),i.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),i.errors.length&&process.exit(1)});var vl=X.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function xl(e){return e?B(e):B(process.cwd(),".agentx","wiki")}vl.command("list").description("list proposals (pending by default)").option("--all","include approved and rejected").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async e=>{let{listProposals:t}=await import("./proposals-O4B5LD5T.js"),o=t(xl(e.dir),e.all?void 0:"pending");if(o.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of o){let s=n.evidence,r=s.sources.some(c=>c.kind==="failure")?" \xB7 from a recurring failure":"",i=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${r}`,a=n.status==="pending"?"":m.dim(` [${n.status}]`),l=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${l} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${i}`))}});vl.command("show").description("the proposed article and the evidence behind it").argument("<id>","proposal id").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{readProposal:o}=await import("./proposals-O4B5LD5T.js"),n=o(xl(t.dir),e);if(!n){console.error(m.red(` no proposal "${e}"`)),process.exitCode=1;return}console.log(m.bold(` ${n.article.title}`)+m.dim(` \u2192 ${n.article.path} (${n.replaces?"updates an existing article":"new article"}, ${n.status})`)),console.log(),console.log(n.article.content.split(`
|
|
649
649
|
`).map(s=>` ${s}`).join(`
|
|
650
|
-
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let r=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,i=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${r}, ${s.updatedAt.slice(0,10)}${i})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});vl.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{approveProposal:o}=await import("./promote-
|
|
650
|
+
`)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let r=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,i=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${r}, ${s.updatedAt.slice(0,10)}${i})`)}`),console.log(m.dim(` ${s.description}`)),s.failure&&console.log(m.dim(` failing tool: ${s.failure.tool} \xB7 error: ${s.failure.errorClass} \xB7 ${s.failure.runs} run(s)`)),s.sessions?.length&&console.log(m.dim(` sessions: ${s.sessions.join(", ")}`)),s.tasks?.length&&console.log(m.dim(` runs: ${s.tasks.join(", ")} (agentx trace show <id>)`))}});vl.command("approve").description("write the proposed article into the shared wiki").argument("<id>","proposal id").option("--force","approve even if the article changed since the proposal").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{approveProposal:o}=await import("./promote-CXXMZWWH.js"),n=o(xl(t.dir),e,{force:t.force});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${n.proposal.article.path} written to the shared wiki`))});vl.command("reject").description("decline a proposal; its sources aren't judged again until they change").argument("<id>","proposal id").option("--reason <text>","why, kept with the decision").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async(e,t)=>{let{rejectProposal:o}=await import("./promote-CXXMZWWH.js"),n=o(xl(t.dir),e,{reason:t.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});var Sl=X.command("decisions").description("approve the decision pages agents follow ahead of older chat history (list, show, approve, revoke)");Sl.command("list").description("decision pages updated in the last 7 days, and whether each is approved").option("--agent <id>","one agent only").option("--all","every decision page, whatever its date").option("--dir <path>","wiki directory").action(async e=>{let{readApprovals:t,decisionState:o}=await import("./decision-approvals-NJS2ARAF.js"),{DECISION_DAYS:n}=await import("./owner-decisions-D3MBTX4D.js"),s=$e(e.dir),r=e.agent?[e.agent]:s.sharedScope("").filter(l=>l.id!=="shared").map(l=>l.id),i=Date.now()-n*864e5,a=0;for(let l of r){let c=s.getAgentWiki(l),u=t(c.baseDir),d=c.listAllArticles().filter(p=>p.meta.type==="decision").filter(p=>e.all||Date.parse(p.meta.lastUpdated||p.meta.created||"")>=i).sort((p,f)=>String(f.meta.lastUpdated).localeCompare(String(p.meta.lastUpdated)));for(let p of d){let f=o(p,u),g=f==="approved"?m.green("approved"):f==="changed"?m.yellow("changed since approval"):m.yellow("waiting for approval");console.log(` ${m.cyan(l)} ${p.path}: ${p.meta.title} ${m.dim(`(updated ${p.meta.lastUpdated||p.meta.created})`)} \xB7 ${g}`),a++}}a===0&&console.log(m.dim(e.all?" no decision pages":` no decision pages updated in the last ${n} days`))});Sl.command("show <agent> <titleOrPath>").description("print a decision page and whether it is approved").option("--dir <path>","wiki directory").action(async(e,t,o)=>{let{readApprovals:n,decisionState:s}=await import("./decision-approvals-NJS2ARAF.js"),r=$e(o.dir).getAgentWiki(e),i=fn(r,t,e),a=i?r.readArticle(i):null;if(!a){console.error(m.red(` no article matches "${t}" in ${e}'s wiki`)),process.exitCode=1;return}let l=a.meta.type==="decision"?s(a,n(r.baseDir)):"not a decision page";console.log(m.bold(` ${a.meta.title}`)+m.dim(` \u2192 ${e}/${a.path} (updated ${a.meta.lastUpdated||a.meta.created}, ${l})`)),console.log(),console.log(a.content.split(`
|
|
651
651
|
`).map(c=>` ${c}`).join(`
|
|
652
|
-
`))});Sl.command("approve <agent> <titleOrPath>").description("approve a decision page as it stands now; any later edit needs a new approval").option("--note <text>","why, kept with the approval").option("--dir <path>","wiki directory").action(async(e,t,o)=>{let{approvalRefusal:n,approveDecision:s}=await import("./decision-approvals-NJS2ARAF.js"),r=n();if(r){console.error(m.red(` ${r}`)),process.exitCode=1;return}let i=$e(o.dir).getAgentWiki(e),a=fn(i,t,e),l=a?i.readArticle(a):null;if(!l){console.error(m.red(` no article matches "${t}" in ${e}'s wiki`)),process.exitCode=1;return}if(l.meta.type!=="decision"){console.error(m.red(` ${l.path} is not a decision page (type: ${l.meta.type??"none"})`)),process.exitCode=1;return}s(i.baseDir,l,{note:o.note}),console.log(m.green(` \u2713 ${e}/${l.path} approved: "${l.meta.title}"`))});Sl.command("revoke <agent> <titleOrPath>").description("take back an approval; with approvals required, the page stops reaching new conversations").option("--dir <path>","wiki directory").action(async(e,t,o)=>{let{approvalRefusal:n,revokeDecision:s}=await import("./decision-approvals-NJS2ARAF.js"),r=n();if(r){console.error(m.red(` ${r}`)),process.exitCode=1;return}let i=$e(o.dir).getAgentWiki(e),a=fn(i,t,e)??t;if(!s(i.baseDir,a)){console.error(m.red(` ${e}/${a} has no approval`)),process.exitCode=1;return}console.log(m.green(` \u2713 approval of ${e}/${a} taken back`))});function lN(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());t||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}X.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",B(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:t}=await import("./query-
|
|
652
|
+
`))});Sl.command("approve <agent> <titleOrPath>").description("approve a decision page as it stands now; any later edit needs a new approval").option("--note <text>","why, kept with the approval").option("--dir <path>","wiki directory").action(async(e,t,o)=>{let{approvalRefusal:n,approveDecision:s}=await import("./decision-approvals-NJS2ARAF.js"),r=n();if(r){console.error(m.red(` ${r}`)),process.exitCode=1;return}let i=$e(o.dir).getAgentWiki(e),a=fn(i,t,e),l=a?i.readArticle(a):null;if(!l){console.error(m.red(` no article matches "${t}" in ${e}'s wiki`)),process.exitCode=1;return}if(l.meta.type!=="decision"){console.error(m.red(` ${l.path} is not a decision page (type: ${l.meta.type??"none"})`)),process.exitCode=1;return}s(i.baseDir,l,{note:o.note}),console.log(m.green(` \u2713 ${e}/${l.path} approved: "${l.meta.title}"`))});Sl.command("revoke <agent> <titleOrPath>").description("take back an approval; with approvals required, the page stops reaching new conversations").option("--dir <path>","wiki directory").action(async(e,t,o)=>{let{approvalRefusal:n,revokeDecision:s}=await import("./decision-approvals-NJS2ARAF.js"),r=n();if(r){console.error(m.red(` ${r}`)),process.exitCode=1;return}let i=$e(o.dir).getAgentWiki(e),a=fn(i,t,e)??t;if(!s(i.baseDir,a)){console.error(m.red(` ${e}/${a} has no approval`)),process.exitCode=1;return}console.log(m.green(` \u2713 approval of ${e}/${a} taken back`))});function lN(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());t||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}X.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",B(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:t}=await import("./query-RPZIRN3X.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:r,join:i}=await import("path"),a=$e(e.dir),l=e.agent;if(!l){console.log(m.red(" --agent <id> is required"));return}let c=a.getAgentWiki(l),u=parseInt(e.n),d=r(e.history,l);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let p=[],f=o(d).sort().reverse();for(let y of f){let w=i(d,y),$=[];try{$=o(w).filter(x=>x.endsWith(".json")).sort().reverse()}catch{continue}for(let x of $){if(p.length>=u)break;try{let v=JSON.parse(n(i(w,x),"utf-8")),S=v.message||v.task?.message;typeof S=="string"&&S.trim().length>10&&p.push({id:v.id||x.replace(".json",""),message:S.trim(),ts:v.at||v.timestamp||y})}catch{}}if(p.length>=u)break}if(p.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${p.length} messages from ${l}`)),console.log(m.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(m.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let g=[`# Wiki A/B: ${l}`,"",`_Generated ${new Date().toISOString()} \xB7 ${p.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<p.length;y++){let w=p[y];process.stdout.write(m.dim(` [${y+1}/${p.length}] querying... `));let x=c.findRelevant(w.message,l,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
|
|
653
653
|
`)||"_(none returned)_",v;try{let S=await t(w.message,c,l,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")v=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let k=S.citations.map(A=>`\`${A.title}\` [${A.type||"?"}]`).join(", ");v=`**Answer:**
|
|
654
654
|
|
|
655
655
|
${S.answer}
|
|
@@ -666,14 +666,14 @@ Q: ${j.q}
|
|
|
666
666
|
A: ${j.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",$||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${d}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
|
|
667
667
|
`),v=B(a.baseDir,"_tmp");so(v,{recursive:!0});let S=B(v,`interview-${o().slice(0,8)}.txt`);Jt(S,x),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let k="";try{let j=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,oe=as(j,{env:Ho(),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Ze=JSON.parse(oe);k=String(Ze.result||Ze.content||"")}catch{k=oe}}catch(j){console.log(m.red(` synthesis failed: ${j.message?.slice(0,200)}`)),l?.close();return}k=k.trim();let A=k.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);A&&(k=A[1].trim());let R=k.indexOf("---");R>0&&(k=k.slice(R));let T=k.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!T){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(k.slice(0,600)),l?.close();return}let I={};for(let j of T[1].split(`
|
|
668
668
|
`)){let oe=j.match(/^(\w+):\s*(.+)$/);oe&&(I[oe[1]]=oe[2].trim().replace(/^"(.*)"$/,"$1"))}let M=T[2],D=I.title||u,H=D.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),E=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${H}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${E}`)),console.log(),console.log(k),console.log();let _=await c(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(l?.close(),_==="scrap"||_==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${S} (prompt only; no article file)`));return}let z=M,he={title:D,type:I.type||d,related:I.related?I.related.replace(/^\[|\]$/g,"").split(",").map(j=>j.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:I.tags?I.tags.replace(/^\[|\]$/g,"").split(",").map(j=>j.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:I.access||"public",created:I.created||new Date().toISOString().slice(0,10),lastUpdated:I.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(_==="edit"){let j=process.env.EDITOR||"vi",oe=B(v,`draft-${o().slice(0,8)}.md`);Jt(oe,k);try{as(`${j} '${oe}'`,{stdio:"inherit"});let ao=Dt(oe,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(ao){let Fe={};for(let Ue of ao[1].split(`
|
|
669
|
-
`)){let Ro=Ue.match(/^(\w+):\s*(.+)$/);Ro&&(Fe[Ro[1]]=Ro[2].trim().replace(/^"(.*)"$/,"$1"))}z=ao[2],he={...he,title:Fe.title||he.title,type:Fe.type||he.type,access:Fe.access||he.access,related:Fe.related?Fe.related.replace(/^\[|\]$/g,"").split(",").map(Ue=>Ue.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.related,tags:Fe.tags?Fe.tags.replace(/^\[|\]$/g,"").split(",").map(Ue=>Ue.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.tags}}}catch(Ze){console.log(m.red(` editor failed: ${Ze.message}`));return}}if(!a.writeArticle(E,he,z,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${E} saved.`));let Q=a.extractWikilinks(z),ve=new Map;for(let j of a.listArticles(e.agent))ve.set(j.meta.title.toLowerCase(),!0);let ie=Q.filter(j=>!ve.has(j.toLowerCase()));if(ie.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let j of ie.slice(0,8))console.log(m.dim(` - ${j}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});X.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{agenticQuery:n}=await import("./query-
|
|
669
|
+
`)){let Ro=Ue.match(/^(\w+):\s*(.+)$/);Ro&&(Fe[Ro[1]]=Ro[2].trim().replace(/^"(.*)"$/,"$1"))}z=ao[2],he={...he,title:Fe.title||he.title,type:Fe.type||he.type,access:Fe.access||he.access,related:Fe.related?Fe.related.replace(/^\[|\]$/g,"").split(",").map(Ue=>Ue.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.related,tags:Fe.tags?Fe.tags.replace(/^\[|\]$/g,"").split(",").map(Ue=>Ue.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):he.tags}}}catch(Ze){console.log(m.red(` editor failed: ${Ze.message}`));return}}if(!a.writeArticle(E,he,z,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${E} saved.`));let Q=a.extractWikilinks(z),ve=new Map;for(let j of a.listArticles(e.agent))ve.set(j.meta.title.toLowerCase(),!0);let ie=Q.filter(j=>!ve.has(j.toLowerCase()));if(ie.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let j of ie.slice(0,8))console.log(m.dim(` - ${j}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});X.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{agenticQuery:n}=await import("./query-RPZIRN3X.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=$e(e.dir);if(e.commit!==!1&&ls(s,e.agent))return;let r;try{r=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let i=null;if(e.script){let g=Dt(e.script,"utf-8").split(/\n\s*\n/).map(h=>h.trim()).filter(Boolean);i=[];for(let h of g){let y=h.split(/\r?\n/).filter(x=>x.trim());if(y.length<2)continue;let w=y[0].replace(/^Q:\s*/i,"").trim(),$=y.slice(1).join(" ").trim();w&&$&&i.push({q:w,verdict:$})}}let a=i?null:t.createInterface({input:process.stdin,output:process.stdout}),l=async f=>a?(await a.question(f)).trim():"",c=Math.min(parseInt(e.rounds)||20,i?.length??999),u=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${c} \xB7 ${u?"commit":"dry-run"} \xB7 ${i?`scripted (${i.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],p=0;for(let f=0;f<c;f++){let g,h;if(i){let U=i[f];if(!U)break;g=U.q,h=U.verdict,console.log(m.cyan(` [${f+1}] Q: `)+g)}else{if(g=await l(m.cyan(` [${f+1}] Q: `)),!g||g==="/done"||g==="/abort")break;h=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(g,r,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(U){console.log(m.red(`failed: ${U.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let U=y.citations.map(E=>`${E.title} [${E.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
|
|
670
670
|
`)),console.log(m.dim(" citations: "+U))}i||(h=await l(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+h);let w={q:g,answer:y.answer,citations:y.citations,verdict:h},$=h.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!$){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(w);continue}let x=$[1].toLowerCase(),v=($[2]||"").trim();if(d.push(w),x==="/ok"||x==="/skip")continue;if(!v){console.log(m.yellow(` ${x} without note \u2014 skipping.`));continue}let S=y.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let k=r.readArticle(S.path);if(!k){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let A=gN(k.content,x,v,k.meta.title,k.meta.type),R=B(r.baseDir,"_tmp");so(R,{recursive:!0});let T=B(R,`quiz-patch-${o().slice(0,8)}.txt`);Jt(T,A);let I="";try{let U=`cat '${T}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,E=as(U,{env:Ho(),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let z=JSON.parse(E);I=String(z.result||z.content||"")}catch{I=E}let _=I.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);_&&(I=_[1].trim()),I=I.trim()}catch(U){console.log(m.red(` patch failed: ${U.message?.slice(0,120)}`));continue}if(!I||I.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let M=k.content.split(`
|
|
671
671
|
`).length,D=I.split(`
|
|
672
672
|
`).length;if(console.log(m.dim(` diff: ${M} \u2192 ${D} lines (${D-M>=0?"+":""}${D-M})`)),!u){console.log(m.dim(" (--no-commit: patch not written)")),w.patched=S.path+" (dry)";continue}if(!r.writeArticle(S.path,{...k.meta,lastUpdated:new Date().toISOString().slice(0,10)},I,e.agent)){console.log(m.red(" write failed (permission?)"));continue}p++,w.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),p>0&&u&&r.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${p} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${p} patches_`,""];for(let g=0;g<d.length;g++){let h=d[g];f.push(`## ${g+1}. Q: ${h.q}`,"",`**A:** ${h.answer}`,"",`**Citations:** ${h.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${h.verdict}\``+(h.patched?` \u2192 patched \`${h.patched}\``:""),"")}Jt(e.out,f.join(`
|
|
673
|
-
`)),console.log(m.dim(` Transcript written to ${e.out}`))}});X.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,t,o)=>{let n=$e(o.dir);if(ls(n,e))return;let s;try{s=n.getAgentWiki(e)}catch(c){console.log(m.red(` can't open wiki for agent "${e}": ${c.message}`));return}let r=fn(s,t,e);if(!r){console.log(m.yellow(` no article matches "${t}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let i=B(s.baseDir,r),a=o.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${r} in ${a}...`));try{as(`${a} '${i}'`,{stdio:"inherit"})}catch(c){console.log(m.red(` editor exited with error: ${c.message?.slice(0,150)}`));return}let l=s.readArticle(r);if(l){let c=new Set,u=s.extractWikilinks(l.content).filter(f=>c.has(f)?!1:(c.add(f),!0)),d=l.meta.related||[];(u.some(f=>!d.includes(f))||d.some(f=>!u.includes(f)))&&(s.writeArticle(r,{...l.meta,related:u.length?u:void 0,lastUpdated:new Date().toISOString().slice(0,10)},l.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${u.length} wikilink${u.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${r} saved. Catalog rebuilt.`))}catch(c){console.log(m.yellow(` saved, but catalog rebuild failed: ${c.message?.slice(0,100)}`))}});async function cN(){let{loadDaemonConfig:e}=await import("./config-
|
|
673
|
+
`)),console.log(m.dim(` Transcript written to ${e.out}`))}});X.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,t,o)=>{let n=$e(o.dir);if(ls(n,e))return;let s;try{s=n.getAgentWiki(e)}catch(c){console.log(m.red(` can't open wiki for agent "${e}": ${c.message}`));return}let r=fn(s,t,e);if(!r){console.log(m.yellow(` no article matches "${t}" in ${e}'s wiki.`)),console.log(m.dim(` Tip: ${m.green("agentx wiki status")} lists agents; ${m.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let i=B(s.baseDir,r),a=o.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${r} in ${a}...`));try{as(`${a} '${i}'`,{stdio:"inherit"})}catch(c){console.log(m.red(` editor exited with error: ${c.message?.slice(0,150)}`));return}let l=s.readArticle(r);if(l){let c=new Set,u=s.extractWikilinks(l.content).filter(f=>c.has(f)?!1:(c.add(f),!0)),d=l.meta.related||[];(u.some(f=>!d.includes(f))||d.some(f=>!u.includes(f)))&&(s.writeArticle(r,{...l.meta,related:u.length?u:void 0,lastUpdated:new Date().toISOString().slice(0,10)},l.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${u.length} wikilink${u.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(m.green(` \u2713 ${r} saved. Catalog rebuilt.`))}catch(c){console.log(m.yellow(` saved, but catalog rebuild failed: ${c.message?.slice(0,100)}`))}});async function cN(){let{loadDaemonConfig:e}=await import("./config-S522VXLI.js"),t=e(),o=t.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",n={"Content-Type":"application/json"};return t.dashboard?.token&&(n.Authorization=`Bearer ${t.dashboard.token}`),{url:o,headers:n}}function dN(e){console.log(m.bold(` Page changed: +${e.added} / \u2212${e.removed} lines`));for(let t of e.diff||[]){let o=` ${t.op===" "?" ":t.op} ${t.text}`;console.log(t.op==="+"?m.green(o):t.op==="-"?m.red(o):m.dim(o))}if(e.sources?.length){console.log(m.bold(" Sources"));for(let t of e.sources)console.log(` - ${t}`)}else console.log(m.yellow(" No sources were cited for this change."));e.version&&console.log(m.dim(` Undo: agentx wiki restore <agent> <page> ${e.version}`))}X.command("curate <agent> <titleOrPath> <instruction>").description("ask the page curator agent to research and edit one page (needs the daemon)").option("--dir <path>","wiki directory").option("--timeout <minutes>","stop waiting after this long","30").action(async(e,t,o,n)=>{let s=$e(n.dir);if(ls(s,e))return;let r=fn(s.getAgentWiki(e),t,e);if(!r){console.log(m.yellow(` no page matches "${t}" in ${e}'s wiki.`)),process.exitCode=1;return}let{url:i,headers:a}=await cN(),l=async(p,f,g)=>{let h=await fetch(i+f,{method:p,headers:a,...g?{body:JSON.stringify(g)}:{}}),y=await h.json().catch(()=>({}));if(!h.ok)throw new Error(y.error||`HTTP ${h.status}`);return y},c;try{c=await l("POST","/api/wiki/curate",{agent:e,path:r,message:o})}catch(p){console.log(m.red(` ${p.message?.includes("fetch failed")?`the daemon at ${i} is not running`:p.message}`)),process.exitCode=1;return}console.log(m.dim(` ${c.curator} is working on ${r}\u2026`));let u=`?agent=${encodeURIComponent(e)}&path=${encodeURIComponent(r)}`,d=Date.now()+Number(n.timeout||30)*6e4;for(;Date.now()<d;){await new Promise(g=>setTimeout(g,2e3));let f=(await l("GET",`/api/wiki/curate${u}`).catch(()=>null))?.messages?.find(g=>g.id===c.id);if(!(!f||f.status==="pending")){console.log(f.status==="error"?m.red(` ${f.text}`):` ${f.text}`),f.edit&&(f.edit.added||f.edit.removed)&&dN(f.edit),f.status==="error"&&(process.exitCode=1);return}}console.log(m.yellow(" still working; the result will show in the chat on the page."))});X.command("versions <agent> <titleOrPath>").description("list the saved earlier versions of one page, newest first").option("--dir <path>","wiki directory").action((e,t,o)=>{let n=$e(o.dir).getAgentWiki(e),s=fn(n,t,e);if(!s){console.log(m.yellow(` no page matches "${t}" in ${e}'s wiki.`)),process.exitCode=1;return}let r=n.getVersions(s);if(!r.length){console.log(m.dim(` ${s} has no earlier versions.`));return}console.log(m.bold(` ${s}`));for(let i of r)console.log(` ${i.timestamp}`)});X.command("restore <agent> <titleOrPath> [version]").description("put a page back to an earlier version (default: the newest); the current text is kept as a version").option("--dir <path>","wiki directory").action((e,t,o,n)=>{let s=$e(n.dir);if(ls(s,e))return;let r=s.getAgentWiki(e),i=fn(r,t,e);if(!i){console.log(m.yellow(` no page matches "${t}" in ${e}'s wiki.`)),process.exitCode=1;return}let a=o||r.getVersions(i)[0]?.timestamp,l=!1;try{l=!!a&&r.restoreVersion(i,a)}catch(c){if(!(c instanceof Am))throw c;console.log(m.red(` ${i} was not restored: the page was busy; run again.`)),process.exitCode=1;return}if(!l){console.log(m.red(` no version ${a?`"${a}" `:""}of ${i}; see agentx wiki versions ${e} "${t}"`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${i} restored to ${a}.`))});X.command("curator").description("show or change the page curator: the chat bubble on wiki pages").option("--on","show the bubble on wiki pages").option("--off","hide the bubble and refuse curator requests").option("--agent <id>","agent that answers on every page").option("--owner","let each page's owner agent answer (the default)").action(async e=>{if(e.on&&e.off){console.log(m.red(" pick --on or --off, not both")),process.exitCode=1;return}if(e.agent&&e.owner){console.log(m.red(" pick --agent or --owner, not both")),process.exitCode=1;return}let{loadDaemonConfig:t}=await import("./config-S522VXLI.js");if(e.on||e.off||e.agent||e.owner){if(e.agent&&!Object.keys(t().agents||{}).includes(e.agent)){console.log(m.red(` no agent "${e.agent}" in agentx.json`)),process.exitCode=1;return}let{mutateAgentxConfig:n}=await import("./config-mutate-KBZV2T4X.js");n(s=>(s.wiki=s.wiki||{},s.wiki.curator=s.wiki.curator||{},e.on&&(s.wiki.curator.enabled=!0),e.off&&(s.wiki.curator.enabled=!1),e.agent&&(s.wiki.curator.agent=e.agent),e.owner&&delete s.wiki.curator.agent,"wiki.curator updated"))}let o=t().wiki?.curator??{enabled:!0};console.log(` Page curator: ${o.enabled?m.green("on"):m.yellow("off")}`),console.log(` Answers: ${o.agent?o.agent:"each page's owner agent"}`)});X.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").option("--allow-fact-loss","save even when the patch shrinks the article or drops a phone number, email, role, link or number it had").action(async(e,t,o,n)=>{let s=await import("node:readline/promises"),{randomUUID:r}=await import("node:crypto"),i=$e(n.dir);if(ls(i,e))return;let a;try{a=i.getAgentWiki(e)}catch(v){console.log(m.red(` can't open wiki for agent "${e}": ${v.message}`));return}let l=fn(a,t,e);if(!l){console.log(m.yellow(` no article matches "${t}" in ${e}'s wiki.`));return}let c=a.readArticle(l);if(!c){console.log(m.red(` can't read ${l}.`));return}let u=uN(c.content,c.meta.title,c.meta.type,o),d=B(a.baseDir,"_tmp");so(d,{recursive:!0});let p=B(d,`patch-${r().slice(0,8)}.txt`);Jt(p,u),console.log(),console.log(m.dim(` Target: ${c.meta.title} (${l})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let v=`cat '${p}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,S=as(v,{env:Ho(),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let A=JSON.parse(S);f=String(A.result||A.content||"")}catch{f=S}let k=f.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(f=k[1].trim()),f=f.trim()}catch(v){console.log(m.red(` patch failed: ${v.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let g=c.content.split(`
|
|
674
674
|
`).length,h=f.split(`
|
|
675
|
-
`).length;console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${g} \u2192 ${h} lines (${h-g>=0?"+":""}${h-g})`)),console.log(),console.log(f),console.log();let y=hy(c.content,f);if(y.length){for(let v of y)console.log(m.yellow(` ! ${v}`));if(n.commit&&!n.allowFactLoss){console.log(m.yellow(" not saved. If this change is intended, run again with --allow-fact-loss.")),process.exitCode=1;return}}if(!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let w=!!n.yes;if(!w){let v=s.createInterface({input:process.stdin,output:process.stdout}),S=(await v.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();v.close(),w=S==="y"||S==="yes"}if(!w){console.log(m.dim(" aborted."));return}if(a.readArticle(l)?.content!==c.content){console.log(m.yellow(` ${l} changed while this patch was made (another patch or edit). Not saved; run the patch again.`)),process.exitCode=1;return}let $=[...new Set([...c.meta.related||[],...a.extractWikilinks(f)])];if(!a.writeArticle(l,{...c.meta,related:$.length?$:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${l} patched.`))});var Vv=X.command("contribute").description("queue sourced wiki patches from an agent's work since its last run (enable, disable)").option("--dir <path>","wiki directory").option("--agent <id>","contribute for this agent").option("--all","every agent with wiki.contribute.enabled in agentx.json").option("--since <time>","first run only: read work from this date or time (default: the last 24 hours)").option("--max-patches <n>","patches per agent per run (default: the agent's setting, else 30)").option("--max-cost <usd>","model spend per agent per run, in USD (default: the agent's setting, else wiki.contributions.maxCostUsd, else 0.5)").option("--max-items <n>","chat entries and tasks read per agent per run","60").option("--model <model>","model (default: the agent's setting, else wiki.contributions.model, else sonnet)").option("--db <path>","trace database with the agents' task runs",".agentx/db.sqlite").option("--dry-run","show the patches without queueing them or moving the cursor").option("--json","print the batches as JSON").action(async e=>{let{runContribution:t}=await import("./contributions-
|
|
676
|
-
agentx wiki contributions approve <id> \xB7 agentx wiki contributions reject <id>`)),console.log()});fi.command("approve <id>").description("apply a held patch as it is").option("--dir <path>","wiki directory").action(async(e,t)=>{let{approveHeld:o}=await import("./contributions-
|
|
675
|
+
`).length;console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${g} \u2192 ${h} lines (${h-g>=0?"+":""}${h-g})`)),console.log(),console.log(f),console.log();let y=hy(c.content,f);if(y.length){for(let v of y)console.log(m.yellow(` ! ${v}`));if(n.commit&&!n.allowFactLoss){console.log(m.yellow(" not saved. If this change is intended, run again with --allow-fact-loss.")),process.exitCode=1;return}}if(!n.commit){console.log(m.dim(" --no-commit: preview only, not written."));return}let w=!!n.yes;if(!w){let v=s.createInterface({input:process.stdin,output:process.stdout}),S=(await v.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();v.close(),w=S==="y"||S==="yes"}if(!w){console.log(m.dim(" aborted."));return}if(a.readArticle(l)?.content!==c.content){console.log(m.yellow(` ${l} changed while this patch was made (another patch or edit). Not saved; run the patch again.`)),process.exitCode=1;return}let $=[...new Set([...c.meta.related||[],...a.extractWikilinks(f)])];if(!a.writeArticle(l,{...c.meta,related:$.length?$:void 0,lastUpdated:new Date().toISOString().slice(0,10)},f,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${l} patched.`))});var Vv=X.command("contribute").description("queue sourced wiki patches from an agent's work since its last run (enable, disable)").option("--dir <path>","wiki directory").option("--agent <id>","contribute for this agent").option("--all","every agent with wiki.contribute.enabled in agentx.json").option("--since <time>","first run only: read work from this date or time (default: the last 24 hours)").option("--max-patches <n>","patches per agent per run (default: the agent's setting, else 30)").option("--max-cost <usd>","model spend per agent per run, in USD (default: the agent's setting, else wiki.contributions.maxCostUsd, else 0.5)").option("--max-items <n>","chat entries and tasks read per agent per run","60").option("--model <model>","model (default: the agent's setting, else wiki.contributions.model, else sonnet)").option("--db <path>","trace database with the agents' task runs",".agentx/db.sqlite").option("--dry-run","show the patches without queueing them or moving the cursor").option("--json","print the batches as JSON").action(async e=>{let{runContribution:t}=await import("./contributions-FXUTKU6R.js"),o=$e(e.dir),n=vt(e.dir),s={},r={};try{let{loadDaemonConfig:d}=await import("./config-S522VXLI.js"),p=d();s=Object.fromEntries(Object.entries(p.agents||{}).map(([f,g])=>[f,g.wiki?.contribute])),r=p.wiki.contributions}catch{}let i=e.agent?[e.agent]:e.all?Object.keys(s).filter(d=>s[d]?.enabled).sort():[];if(i.length===0){console.log(m.yellow(e.all?" No agent has wiki.contribute.enabled. Turn one on with `agentx wiki contribute enable <agent>`.":" Name an agent with --agent <id>, or use --all.")),e.all||(process.exitCode=1);return}let a,l=B(process.cwd(),e.db);if(nt(l)){let d=(await import("better-sqlite3")).default;a=new d(l,{readonly:!0})}else e.json||console.log(m.dim(` no trace database at ${l}; reading chat turns only`));let c=d=>async(p,f)=>{let g=B(n,"_tmp");so(g,{recursive:!0});let h=B(g,`contribute-${process.pid}-${Date.now()}.txt`);Jt(h,p);try{let{stdout:y}=await ex(`cat '${h}' | claude -p - --output-format json --max-turns 1 --max-budget-usd ${f.toFixed(2)} --model ${d} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Ho(),timeout:18e4,maxBuffer:4194304});try{let w=JSON.parse(y);return{text:String(w.result||w.content||""),costUsd:zc(w).costUsd}}catch{return{text:y}}}finally{Xu(h,{force:!0})}},u=[];try{for(let d of i){if(ls(o,d))continue;let p=s[d],f=e.model||p?.model||r.model||process.env.AGENTX_WIKI_CONTRIBUTE_MODEL||"sonnet";try{let g=await t(o,n,d,{model:f,call:c(f),db:a,since:e.since,dryRun:!!e.dryRun,maxPatches:e.maxPatches?parseInt(e.maxPatches):p?.maxPatches,maxCostUsd:e.maxCost?parseFloat(e.maxCost):p?.maxCostUsd??r.maxCostUsd,maxItems:parseInt(e.maxItems)});if(u.push(g),e.json)continue;let h=g.stoppedBy?m.yellow(` \xB7 stopped at ${g.stoppedBy}`):"";console.log(` ${m.cyan(d)}: ${g.patches.length} patch(es) from ${g.workIds.length} item(s) of work \xB7 $${g.costUsd.toFixed(4)}${h}${e.dryRun?m.dim(" \xB7 dry run, not queued"):""}`);for(let y of g.patches){let w=y.attribute?`${y.attribute}: ${y.previous?`${y.previous} \u2192 `:""}${y.value??""}`:y.summary??"";console.log(m.dim(` ${y.kind.padEnd(8)} ${y.page} \xB7 ${w} (${y.source}, ${y.checkedAt.slice(0,10)})`))}}catch(g){console.log(m.red(` ${d}: ${g.message?.slice(0,200)}`)),process.exitCode=1}}}finally{a?.close()}e.json?console.log(JSON.stringify(u,null,2)):!e.dryRun&&u.some(d=>d.patches.length)&&console.log(m.dim(" queued; `agentx wiki contributions merge` applies them."))});for(let[e,t]of[["enable",!0],["disable",!1]])Vv.command(`${e} <agent>`).description(t?"turn on an agent's daily wiki contribution in agentx.json":"turn off an agent's daily wiki contribution").option("--max-cost <usd>","model spend per run, in USD").option("--max-patches <n>","patches per run").option("-c, --config <path>","path to agentx.json").action(async(o,n)=>{let{applyConfigMutation:s}=await import("./config-mutator-YNNEGRV3.js"),r=await s(i=>{let a=i.agents?.[o];if(!a)throw new Error(`no agent "${o}" in agentx.json`);a.wiki??={},a.wiki.contribute??={},a.wiki.contribute.enabled=t;let l={...Vv.opts(),...n};l.maxCost&&(a.wiki.contribute.maxCostUsd=parseFloat(l.maxCost)),l.maxPatches&&(a.wiki.contribute.maxPatches=parseInt(l.maxPatches))},{configPath:n.config});if(!r.success){console.log(m.red(` \u2717 ${r.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${o}: daily wiki contribution ${t?"on":"off"}`)),t&&console.log(m.dim(" The daily jobs wiki-contribute and wiki-contribute-merge now show in `agentx schedule list`."))});var fi=X.command("contributions").description("the daily merge of agents' wiki patches (list, merge, held, approve, reject)");fi.command("list",{isDefault:!0}).description("patches waiting for the merge, and what the last merge did").option("--dir <path>","wiki directory").option("--json").action(async e=>{let{listPendingBatches:t,latestReport:o,listHeld:n}=await import("./contributions-FXUTKU6R.js"),s=vt(e.dir),r=t(s),i=o(s),a=n(s);if(e.json){console.log(JSON.stringify({pending:r,lastMerge:i,held:a.length},null,2));return}console.log(),console.log(m.bold(` Waiting for the merge: ${r.reduce((l,c)=>l+c.patches.length,0)} patch(es) in ${r.length} batch(es)`));for(let l of r)console.log(m.dim(` ${l.agentId} \xB7 ${l.runAt.slice(0,16)} \xB7 ${l.patches.length} patch(es) \xB7 $${l.costUsd.toFixed(4)}`));i?(console.log(m.bold(` Last merge ${i.at.slice(0,16)}:`)+` ${i.applied.length} fact(s) applied, ${i.pagesUpdated.length} page(s) updated, ${i.pagesCreated.length} created, ${i.contradictions.length} contradiction(s), ${i.held.length} held`),i.duplicates.length&&console.log(m.yellow(` ${i.duplicates.length} subject(s) have more than one page: ${i.duplicates.slice(0,5).map(l=>l.title).join(", ")}${i.duplicates.length>5?", \u2026":""}`))):console.log(m.dim(" No merge has run yet.")),a.length&&console.log(m.yellow(` ${a.length} patch(es) held for a person: agentx wiki contributions held`)),console.log()});fi.command("merge").description("apply the queued patches: newest checked fact wins, fact-losing changes are held").option("--dir <path>","wiki directory").option("--dry-run","show what would change without writing").option("--json","print the report as JSON").action(async e=>{let{mergeContributions:t}=await import("./contributions-FXUTKU6R.js"),o=t($e(e.dir),vt(e.dir),{dryRun:!!e.dryRun,log:n=>console.error(n)});if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),o.batches.length===0){console.log(m.dim(" Nothing to merge.")),console.log();return}console.log(m.bold(` ${o.patches} patch(es) from ${o.agents.join(", ")}${o.dryRun?m.dim(" (dry run, nothing written)"):""}`)),console.log(` ${o.applied.length} fact(s) applied \xB7 ${o.pagesUpdated.length} page(s) updated \xB7 ${o.pagesCreated.length} page(s) created`);for(let n of o.pagesCreated)console.log(m.green(` + ${n}`));for(let n of o.pagesUpdated)console.log(m.dim(` ~ ${n}`));for(let n of o.contradictions)console.log(m.yellow(` ? ${n.page} \xB7 ${n.attribute}: ${n.by} reports "${n.value}" with an older check than the wiki's; a person is asked${n.questionId?` (${n.questionId})`:""}`));for(let n of o.held)console.log(m.yellow(` ! held ${n.id} \xB7 ${n.page}${n.attribute?` \xB7 ${n.attribute}`:""} from ${n.by}: ${n.reason}${n.lost?.length?` (${n.lost.slice(0,4).join(", ")})`:""}`));for(let n of o.duplicates.slice(0,10))console.log(m.yellow(` = ${n.title}: ${n.pages.join(" \xB7 ")}`));console.log()});fi.command("held").description("patches the merge held for a person, with the reason").option("--dir <path>","wiki directory").option("--all","include approved and rejected").option("--json").action(async e=>{let{listHeld:t}=await import("./contributions-FXUTKU6R.js"),o=t(vt(e.dir),{all:!!e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(),o.length===0&&console.log(m.dim(" Nothing held."));for(let n of o){let s=n.patch,r=n.status==="held"?"":m.dim(` [${n.status}]`);console.log(` ${m.bold(n.id)}${r} \xB7 ${m.cyan(s.agentId)} \xB7 ${s.kind} \xB7 ${s.page}${s.attribute?` \xB7 ${s.attribute}`:""}${s.value?`: ${s.value}`:""}`),console.log(m.dim(` ${n.reason}${n.lost?.length?`: ${n.lost.join(", ")}`:""} \xB7 source: ${s.source}, checked ${s.checkedAt.slice(0,10)}`))}o.some(n=>n.status==="held")&&console.log(m.dim(`
|
|
676
|
+
agentx wiki contributions approve <id> \xB7 agentx wiki contributions reject <id>`)),console.log()});fi.command("approve <id>").description("apply a held patch as it is").option("--dir <path>","wiki directory").action(async(e,t)=>{let{approveHeld:o}=await import("./contributions-FXUTKU6R.js"),n=o($e(t.dir),vt(t.dir),e,{by:process.env.USER||"operator"});if(!n.ok){console.log(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} applied${n.page?` to ${n.page}`:""}. The page's previous version is kept.`))});fi.command("reject <id>").description("drop a held patch").option("--dir <path>","wiki directory").action(async(e,t)=>{let{rejectHeld:o}=await import("./contributions-FXUTKU6R.js"),n=o(vt(t.dir),e,{by:process.env.USER||"operator"});if(!n.ok){console.log(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected.`))});function fn(e,t,o){let n=t.trim(),s=e.listArticles(o),r=n.toLowerCase(),i=s.find(c=>c.meta.title.toLowerCase()===r);if(i)return i.path;if(n.includes("/")||n.endsWith(".md")){let c=n.endsWith(".md")?n:`${n}.md`,u=s.find(d=>d.path===c||d.path===n);if(u)return u.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),l=s.find(c=>{let u=c.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return u===a||u.includes(a)||c.path.toLowerCase().includes(a)});return l?l.path:null}function uN(e,t,o,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${t}" (type: ${o||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",n,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
|
|
677
677
|
`)}function gN(e,t,o,n,s){let r={"/correct":`The operator says the article contains an error:
|
|
678
678
|
|
|
679
679
|
${o}
|
|
@@ -728,17 +728,17 @@ Output (JSON array, one entry per input article, same order):
|
|
|
728
728
|
[
|
|
729
729
|
{"path": "path/to/article.md", "type": "project"},
|
|
730
730
|
...
|
|
731
|
-
]`}X.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=$e(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});X.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let t=e.dir||B(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=await tx(e.peer),s=n.map(r=>r.url);console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${o}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),s.length>0&&console.log(` Mesh: ${m.cyan(s.length+" peer(s)")} \u2014 ${s.join(", ")}`),console.log(m.dim(` Wiki: ${t}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),dy(t,o,e.agent,n,e.mode)});X.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:t,articleQualityState:o,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:r,reportFields:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-
|
|
731
|
+
]`}X.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=$e(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});X.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let t=e.dir||B(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=await tx(e.peer),s=n.map(r=>r.url);console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${o}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),s.length>0&&console.log(` Mesh: ${m.cyan(s.length+" peer(s)")} \u2014 ${s.join(", ")}`),console.log(m.dim(` Wiki: ${t}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),dy(t,o,e.agent,n,e.mode)});X.command("grade").description("grade absorbed articles with the article-quality seat").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","grade only this agent's wiki").option("--limit <n>","articles to grade","20").option("--min <n>","only show articles scoring below this","3").option("--fields","also check the required fields for each article's type").option("--type <t>","grade only articles of this type (person, place, project, \u2026)").option("--json").action(async e=>{let{articleQualityQuestionsFor:t,articleQualityState:o,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:r,reportFields:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-BSWBTNCP.js"),l=$e(e.dir,e.mode),c=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),d=parseFloat(e.min),p=[];e:for(let y of c){let w=l.getAgentWiki(y);for(let $ of w.listArticles(y)){if(p.length>=u)break e;let x=w.readArticle($.path);if(!x||e.type&&x.meta.type!==e.type)continue;let v={...t(x.meta.type),...e.fields?r(x.meta.type):{}},S=await a(s,o({path:$.path,title:x.meta.title,type:x.meta.type,tags:x.meta.tags,body:x.content}),v,{links:[{kind:"article",id:$.path}],features:{agent:y,type:x.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let k=n(S.answers),A=e.fields?i(x.meta.type,S.answers):null;k.completeness>=d&&!(A&&!A.fit)||p.push({agent:y,type:x.meta.type??"?",score:k.completeness.toFixed(2),standsAlone:k.standsAlone.toFixed(2),gap:k.biggestGap,...A?{missing:A.missingCritical.join(",")||"-",cov:`${Math.round(A.coverage*100)}%`}:{},title:x.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(" no articles below the threshold"));return}p.sort((y,w)=>parseFloat(y.score)-parseFloat(w.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],g=f.map(y=>Math.max(y.length,...p.map(w=>String(w[y]).length))),h=y=>y.map((w,$)=>String(w).padEnd(g[$])).join(" ");console.log(),console.log(m.bold(h(f)));for(let y of p)console.log(h(f.map(w=>y[w])));if(e.fields){let y=p.filter(w=>w.missing!=="-").length;console.log(m.dim(`
|
|
732
732
|
${p.length} article(s) flagged; ${y} missing a required field.`)),console.log(m.dim(" 'missing' is the actionable column \u2014 a named field beats a score."))}else console.log(m.dim(`
|
|
733
|
-
${p.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});X.command("query <question>").description("agentic wiki query \u2014 picks pages from their one-line summaries, reads live state at the source, then answers; walks the catalog + wikilink graph where no summaries exist").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to search first (default: the calling agent, else the first one with a catalog)").option("--method <m>","how pages are picked: auto, summaries or catalog (default: wiki.query.method)").option("--no-live","skip the live read of the summaries method").option("--linked <n>","also open up to n pages linked from the picked pages (summaries method; default: wiki.query.linkedPages)").option("--no-notes","leave the agent's own notes out (wiki.query.notes)").option("--selector-model <m>","candidate-selection model (default haiku)").option("--synth-model <m>","synthesis model (default sonnet)").option("--max-candidates <n>","candidates from selector (catalog method)","3").option("--max-hops <n>","wikilink hops from candidates (catalog method)","2").option("--max-articles <n>","cap on total articles walked (catalog method)","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").option("--own-only","search only the agent's own articles, not the shared wiki").action(async(e,t)=>{let{agenticQuery:o}=await import("./query-
|
|
733
|
+
${p.length} article(s) below ${d}. standsAlone is the one that matters:`)),console.log(m.dim(" an article can open with a tidy identity line and still send the reader back to the source."))});X.command("query <question>").description("agentic wiki query \u2014 picks pages from their one-line summaries, reads live state at the source, then answers; walks the catalog + wikilink graph where no summaries exist").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to search first (default: the calling agent, else the first one with a catalog)").option("--method <m>","how pages are picked: auto, summaries or catalog (default: wiki.query.method)").option("--no-live","skip the live read of the summaries method").option("--linked <n>","also open up to n pages linked from the picked pages (summaries method; default: wiki.query.linkedPages)").option("--no-notes","leave the agent's own notes out (wiki.query.notes)").option("--selector-model <m>","candidate-selection model (default haiku)").option("--synth-model <m>","synthesis model (default sonnet)").option("--max-candidates <n>","candidates from selector (catalog method)","3").option("--max-hops <n>","wikilink hops from candidates (catalog method)","2").option("--max-articles <n>","cap on total articles walked (catalog method)","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").option("--own-only","search only the agent's own articles, not the shared wiki").action(async(e,t)=>{let{agenticQuery:o}=await import("./query-RPZIRN3X.js"),{noteSourceFor:n}=await import("./query-settings-EBOBWOAL.js"),{QUERY_RUNS_FILE:s,queryFailed:r,recordQueryRun:i,timedQuery:a}=await import("./query-runs-AENEZOM6.js"),l=await nx(t);if(!l)return;let c=$e(t.dir),u=t.agent?[t.agent]:c.listAgents(),d=B(c.getBaseDir(),s),p=Date.now(),f=t.agent||process.env.AGENTX_AGENT_ID,g=f&&!t.ownOnly&&await Xv()?f:null;for(let x of g?[]:u){let v=c.getAgentWiki(x),S=B(v.baseDir,"_index.md");try{if((await import("fs")).existsSync(S)){g=x;break}}catch{}}if(!g){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first.")),i(d,{at:new Date().toISOString(),agent:f||"",status:"no-catalog",source:"cli",wallMs:Date.now()-p}),process.exitCode=1;return}let h=g,y=c.getAgentWiki(h),w=t.ownOnly||!await Xv()?void 0:c.sharedScope(h),$=await a(d,h,"cli",()=>o(e,y,h,{selectorModel:t.selectorModel,synthModel:t.synthModel,maxCandidates:parseInt(t.maxCandidates),maxHops:parseInt(t.maxHops),maxArticles:parseInt(t.maxArticles),shared:w,method:l.method,summaries:l.summaries,notes:n(l,h)}));if(r($.status)&&(process.exitCode=1),t.json){console.log(JSON.stringify($,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${g} \xB7 status: ${$.status} \xB7 walked: ${$.walked.length}`)),console.log(),$.status!=="ok"){console.log(m.yellow(` (no answer) ${$.error||$.status}`));return}if(console.log($.answer),console.log(),$.basis==="search"&&(console.log(m.dim(" No wiki page was used: the answer comes from a search at the source.")),console.log()),$.citations.length){console.log(m.dim(" Citations:"));for(let x of $.citations){let v=x.type?m.magenta(` [${x.type}]`):"";console.log(m.dim(` - ${x.title}${v} (${x.path})`))}console.log()}if($.live?.length){console.log(m.dim(" Read live at the source:"));for(let x of $.live)console.log(m.dim(` - ${x.line}`));console.log()}if(t.trace&&$.trace){if($.method==="summaries"&&console.log(m.dim(` method: summaries live reads: ${$.liveAsked??0} asked, ${$.live?.length??0} answered plan: ${$.trace.planMs??0}ms reads: ${$.trace.liveMs??0}ms`)),console.log(m.dim(` selector: ${$.trace.selectorMs}ms synthesis: ${$.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${$.candidates.map(x=>x.title).join(" | ")||"(none)"}`)),$.walked.length>$.candidates.length){let x=$.walked.filter(v=>!$.candidates.some(S=>S.path===v.path));console.log(m.dim(` followed: ${x.map(v=>`${v.title}@h${v.hop}`).join(" | ")}`))}console.log()}});X.command("score").description("score the wiki's answers to a question set; compare two reports").option("--dir <path>","wiki directory").option("--questions <file>","question set: JSON array or JSON lines of {id, question, expect: [facts]}").option("--agent <id>","ask as this agent (its own wiki first, then the shared wiki)").option("--own-only","search only the agent's own articles, to measure without the shared wiki").option("--out <file>","write the report as JSON to this file").option("--compare <files...>","compare two saved reports (before after) instead of running").option("--method <m>","how pages are picked: auto, summaries or catalog (default: wiki.query.method)").option("--no-live","skip the live read of the summaries method").option("--linked <n>","also open up to n pages linked from the picked pages (summaries method; default: wiki.query.linkedPages)").option("--no-notes","leave the agent's own notes out (wiki.query.notes)").option("--selector-model <m>","candidate-selection model (default haiku)").option("--synth-model <m>","synthesis model (default sonnet)").option("--json","print the report as JSON").action(async e=>{let{parseQuestionSet:t,buildReport:o,compareReports:n,runCost:s}=await import("./score-LNJ46A67.js"),r=S=>`${Math.round(S*100)}%`,i=S=>S===void 0?"?":`${(S/1e3).toFixed(1)}s`,a=S=>S===void 0?"?":`$${S.toFixed(3)}`,l=S=>`${i(S.meanMs)} and ${a(S.meanCostUsd)} per question${S.unpriced?` (${S.unpriced} without a cost)`:""}`;if(e.compare){if(e.compare.length!==2){console.log(m.red(" --compare takes two report files: before after")),process.exitCode=1;return}let[S,k]=e.compare.map(R=>JSON.parse(Dt(B(R),"utf-8"))),A=n(S,k);if(e.json){console.log(JSON.stringify(A,null,2));return}console.log(),console.log(m.bold(` ${r(A.before)} \u2192 ${r(A.after)}`)),console.log(m.dim(` before: ${l(A.cost.before)}`)),console.log(m.dim(` after: ${l(A.cost.after)}`)),A.changed==="unknown"?console.log(m.yellow(" ! A report records no settings, so what changed between the runs is unknown.")):(console.log(m.dim(` changed: ${A.changed.join("; ")||"nothing"}`)),A.changed.length>1&&console.log(m.yellow(" ! More than one setting changed: the difference can't be put down to one of them."))),(A.onlyBefore.length||A.onlyAfter.length)&&console.log(m.yellow(` ! The runs asked different questions. Only before: ${A.onlyBefore.join(", ")||"none"}. Only after: ${A.onlyAfter.join(", ")||"none"}.`));for(let R of A.deltas){if(R.before===R.after)continue;let T=R.after>R.before?m.green("\u25B2"):m.red("\u25BC");console.log(` ${T} ${R.id} ${r(R.before)} \u2192 ${r(R.after)} ${m.dim(R.question.slice(0,80))}`),R.gained.length&&console.log(m.green(` + ${R.gained.join(", ")}`)),R.lost.length&&console.log(m.red(` - ${R.lost.join(", ")}`))}console.log();return}if(!e.questions){console.log(m.red(" --questions <file> is required (or --compare before.json after.json).")),process.exitCode=1;return}let c=e.agent||process.env.AGENTX_AGENT_ID;if(!c){console.log(m.red(" --agent <id> is required: the score is for one agent's view of the wiki.")),process.exitCode=1;return}let u=t(Dt(B(e.questions),"utf-8")),{agenticQuery:d,CATALOG_SELECTOR_MODEL:p,CATALOG_SYNTH_MODEL:f}=await import("./query-RPZIRN3X.js"),{noteSourceFor:g}=await import("./query-settings-EBOBWOAL.js"),{meteredModelCall:h}=await import("./model-call-HMVMUAXS.js"),y=await nx(e);if(!y)return;let w=$e(e.dir),$=!e.ownOnly,x=[];for(let S of u){let k={calls:0,usd:0,unpriced:0},A=Date.now(),R=await d(S.question,w.getAgentWiki(c),c,{selectorModel:e.selectorModel,synthModel:e.synthModel,shared:$?w.sharedScope(c):void 0,method:y.method,summaries:y.summaries,notes:g(y,c),call:h(k)}),T=Date.now()-A,I=R.method==="summaries"&&k.unpriced===0?k.usd:void 0;x.push({q:S,answer:R.answer||R.error||"",status:R.status,citations:R.citations.map(M=>M.path),method:R.method??"catalog",ms:T,costUsd:I}),e.json||process.stderr.write(m.dim(` ${S.id} ${R.status} ${i(T)} ${a(I)}
|
|
734
734
|
`))}let v=o({questions:e.questions,agent:c,shared:$,settings:{method:y.method,linkedPages:y.summaries.linkedPages,linkedChars:y.summaries.linkedChars,live:y.summaries.live.enabled,notes:y.notes.enabled,navigatorModel:e.selectorModel??y.summaries.navigatorModel,answerModel:e.synthModel??y.summaries.answerModel,catalogSelectorModel:e.selectorModel??p,catalogSynthModel:e.synthModel??f}},x);if(e.out&&Jt(B(e.out),`${JSON.stringify(v,null,2)}
|
|
735
735
|
`),e.json){console.log(JSON.stringify(v,null,2));return}console.log(),console.log(m.bold(` ${c}: ${r(v.score)} \xB7 ${v.full}/${v.results.length} questions fully answered${$?"":" (own articles only)"}`)),console.log(m.dim(` ${l(s(v))}`));for(let S of v.results){let k=S.missing.length===0?m.green("\u2713"):S.found.length?m.yellow("~"):m.red("\u2717");console.log(` ${k} ${S.id} ${r(S.score)} ${m.dim(S.question.slice(0,80))}`),S.missing.length&&console.log(m.dim(` missing: ${S.missing.join(", ")}`))}e.out&&console.log(m.dim(`
|
|
736
|
-
report saved to ${e.out}`)),console.log()});X.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,t)=>{let o=$e(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let r of n){let a=await o.getAgentWiki(r).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(r)}:`));for(let l of a)console.log(` ${l.meta.title} [${(l.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${l.path} \u2014 ${l.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});X.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let t=$e(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=B(process.cwd(),".agentx/graph");if(!nt(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Jo({baseDir:n}),r=s.loadIndex(),i=new Map;for(let[d,p]of Object.entries(r.entries))i.set(d,p.path);if(i.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${i.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,l=0,c=0,u=0;for(let d of o){let p=t.getAgentWiki(d),f=p.listArticles(d),g=t.getSharedStore().listEntries(),h=new Map(g.map(x=>[x.id,x])),y=0,w=0,$=0;for(let x of f){if(a++,x.meta.graphPath?.length||!x.meta.sources?.length)continue;y++,l++;let v=new Map;for(let k of x.meta.sources){let A=h.get(k);if(!A)continue;let R=String(A.meta?.sender??""),T=s.fingerprint({text:A.content,channel:A.source,sender:R}),I=i.get(T);if(!I?.length)continue;let M=I.join("/"),D=v.get(M);D?D.n++:v.set(M,{path:I,n:1})}if(v.size===0)continue;w++,c++;let S;for(let k of v.values())(!S||k.n>S.n)&&(S=k);S&&(e.dryRun||(p.writeArticle(x.path,{...x.meta,graphPath:S.path},x.content,d),$++,u++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${w} matched \xB7 ${m.green($)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${l} missing graphPath, ${c} matched (${Math.round(c/Math.max(1,l)*100)}%), ${u} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});X.command("sync").description("pull raw entries from mesh peers into local wiki, or with --articles copy their agents' articles (read-only)").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--articles","copy the articles of agents this node does not run, instead of raw entries").option("--dry-run","show what would be synced without writing").action(async e=>{let t=$e(e.dir),o=t.getSharedStore(),n=await tx(e.peer?[e.peer]:void 0);if(n.length===0){console.log(m.dim(" No mesh peers configured")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(e.articles){let i=await ox();if(!i){console.log(m.red(" No agents in this node's daemon config; run it where agentx.json is.")),process.exitCode=1;return}let{syncPeerArticles:a}=await import("./article-sync-4NOPOQU7.js");for(let l of n){console.log(),console.log(m.bold(` Copying articles from ${l.url}...`));try{let c=await a({hub:t,peer:l,localAgents:i,dryRun:e.dryRun});console.log(m.dim(` Node: ${c.node}`));for(let u of c.agents){if(u.skipped==="local"){console.log(m.dim(` ${u.agentId}: runs here, not copied`));continue}if(u.skipped){console.log(m.yellow(` ${u.agentId}: skipped (${u.skipped})`));continue}let d=[`${u.copied} ${e.dryRun?"to copy":"copied"}`,`${u.unchanged} unchanged`];u.removed&&d.push(`${u.removed} removed (gone on the peer)`),u.rejected&&d.push(`${u.rejected} refused`),console.log(` ${m.cyan(u.agentId)}: ${d.join(", ")}${u.error?m.red(` \u2014 stopped: ${u.error}`):""}`),u.error&&(process.exitCode=1)}}catch(c){console.log(m.red(` ${c.cause?.code==="ECONNREFUSED"?"Connection refused":c.message}`)),process.exitCode=1}}console.log();return}let s=new Set(o.listEntries().map(i=>i.id)),r=0;for(let{url:i,token:a}of n){console.log(),console.log(m.bold(` Syncing from ${i}...`));let l=a?{Authorization:`Bearer ${a}`}:{};try{let c=await fetch(`${i}/wiki/entries`,{headers:l,signal:AbortSignal.timeout(12e4)});if(!c.ok){console.log(m.red(` HTTP ${c.status}`));continue}let u=await c.json(),d=u.entries||[],p=u.nodeId||"unknown";console.log(m.dim(` Node: ${p} \u2014 ${d.length} entries`));let f=0;for(let g of d)s.has(g.id)||(e.dryRun||(o.addEntry({id:g.id,date:g.date,agentId:g.agentId,source:`${g.source}@${p}`,sourceContext:g.sourceContext,content:g.content}),s.add(g.id)),f++);f>0?console.log(m.green(` ${f} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),r+=f;try{let g=await fetch(`${i}/wiki/agents`,{headers:l,signal:AbortSignal.timeout(5e3)});if(g.ok){let h=await g.json();for(let y of h.agents||[])y.totalEntries>0&&console.log(m.dim(` ${y.agentId}: ${y.totalEntries} entries, ${y.totalArticles} articles`))}}catch{}}catch(c){c.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${c.message}`))}}console.log(),r>0&&!e.dryRun?console.log(m.green(` ${r} entries synced.`)):r>0?console.log(m.dim(` ${r} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});X.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let t=e.dir||B(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(l=>{let c=new ic(t,void 0,l),d=c.getAgentWiki(o).rebuildIndex(),p=c.getAgentEntries(o),f=c.getUnabsorbedEntries(o),g=new Set,h=0,y=new Set;for(let $ of d.articles){for(let x of $.tags||[])g.add(x);h+=$.tags?.length||0;for(let x of $.sources||[])y.add(x)}let w=new Set(d.articles.map($=>$.path.includes("/")?$.path.split("/")[0]:"/"));return{mode:l,label:Vu(l),articles:d.articles.length,entries:p.length,unabsorbed:f.length,uniqueTags:g.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:w.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${o}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let r=22;console.log(` ${"".padEnd(20)} ${s.map(l=>l.label.padEnd(r)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(r)).join(" ")}`);let i=[["Articles",l=>String(l.articles)],["Unabsorbed",l=>String(l.unabsorbed)],["Unique tags",l=>String(l.uniqueTags)],["Avg tags/article",l=>l.avgTags],["Directories",l=>String(l.dirs)],["Entry coverage",l=>`${l.coverage}/${l.entries}`]];for(let[l,c]of i){let u=s.map(d=>c(d).padEnd(r));console.log(` ${l.padEnd(20)} ${u.join(" ")}`)}console.log();let a=(l,c)=>{let u=Math.max(...s.map(p=>p[l])),d=s.filter(p=>p[l]===u).map(p=>p.label);u>0&&console.log(m.dim(` Best ${c}: ${d.join(", ")} (${u})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});X.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,t)=>{let o=t.dir?B(process.cwd(),t.dir):B(process.cwd(),".agentx/wiki");nt(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?B(process.cwd(),e):B(process.cwd(),`agentx-wiki-${n}.tar.gz`),r=B(o,".."),i=o.split("/").pop()||"wiki",a=["-C",r,"-czf",s];t.includeRaw||a.push("--exclude="+i+"/raw"),a.push(i),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:l}=await import("child_process"),c=l("tar",a,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1));let{statSync:u}=await import("fs"),d=nt(s)?u(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${fN(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});X.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,nextActions:s,TIER_MEANING:r,ARTICLE_FIELDS_SEAT:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-5FTOWN5J.js"),{QuestionStore:l}=await import("./questions-ZATLU5AW.js"),c=$e(e.dir,e.mode),u=[],d=e.agent?[e.agent]:c.listAgents(),p=parseInt(e.limit),f=0,g=[];e:for(let k of d){let A=c.getAgentWiki(k);for(let R of A.listArticles(k)){if(f>=p)break e;let T=A.readArticle(R.path);if(!T||e.type&&T.meta.type!==e.type)continue;f++;let I=await a(i,n({title:T.meta.title,type:T.meta.type,body:T.content}),t(T.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:k,type:T.meta.type??"?"}});if(!I){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let M=o(T.meta.type,I.answers);for(let D of s(M,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&D.needsHuman||(e.ask&&D.needsHuman&&u.push({kind:"field",agentId:k,path:R.path,subject:T.meta.title,field:D.field,tier:D.tier,question:`${T.meta.title} (${T.meta.type??"?"}) \u2014 ${D.label}?`}),g.push({tier:D.tier,need:D.field,how:D.needsHuman?m.yellow("ask"):D.sources.join("/"),uncertain:D.uncertain?"?":"",agent:k,article:T.meta.title.slice(0,40)}))}}let h={added:0,skipped:0};if(e.ask&&u.length>0&&(h=new l(vt(e.dir)).add(u)),e.json){console.log(JSON.stringify(g,null,2));return}if(g.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],w=k=>String(k).replace(/\u001b\[[0-9;]*m/g,""),$=y.map(k=>Math.max(k.length,...g.map(A=>w(A[k]).length))),x=(k,A)=>String(k)+" ".repeat(Math.max(0,$[A]-w(k).length));console.log(),console.log(m.bold(y.map((k,A)=>x(k,A)).join(" ")));for(let k of g)console.log(y.map((A,R)=>x(k[A],R)).join(" "));let v=g.filter(k=>k.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${g.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${v} can be closed by a lookup; ${g.length-v} need a person.`));let S=g[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${r[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:k}=await import("./article-fields-PITN4NHA.js"),A=k[e.notifyTier]??k.pillar,R=u.filter(T=>(k[T.tier??"furniture"]??9)<=A);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:T}=await import("./config-LTXRWDRK.js"),I=T(),M=I?.notifications?.destination;if(!M?.channel||!M?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let D=R.slice(0,10).map(_=>`\u2022 ${_.question}`).join(`
|
|
736
|
+
report saved to ${e.out}`)),console.log()});X.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,t)=>{let o=$e(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let r of n){let a=await o.getAgentWiki(r).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(r)}:`));for(let l of a)console.log(` ${l.meta.title} [${(l.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${l.path} \u2014 ${l.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(m.dim(" No matching articles")),console.log()});X.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let t=$e(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=B(process.cwd(),".agentx/graph");if(!nt(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Jo({baseDir:n}),r=s.loadIndex(),i=new Map;for(let[d,p]of Object.entries(r.entries))i.set(d,p.path);if(i.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${i.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,l=0,c=0,u=0;for(let d of o){let p=t.getAgentWiki(d),f=p.listArticles(d),g=t.getSharedStore().listEntries(),h=new Map(g.map(x=>[x.id,x])),y=0,w=0,$=0;for(let x of f){if(a++,x.meta.graphPath?.length||!x.meta.sources?.length)continue;y++,l++;let v=new Map;for(let k of x.meta.sources){let A=h.get(k);if(!A)continue;let R=String(A.meta?.sender??""),T=s.fingerprint({text:A.content,channel:A.source,sender:R}),I=i.get(T);if(!I?.length)continue;let M=I.join("/"),D=v.get(M);D?D.n++:v.set(M,{path:I,n:1})}if(v.size===0)continue;w++,c++;let S;for(let k of v.values())(!S||k.n>S.n)&&(S=k);S&&(e.dryRun||(p.writeArticle(x.path,{...x.meta,graphPath:S.path},x.content,d),$++,u++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${y} eligible \xB7 ${w} matched \xB7 ${m.green($)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${l} missing graphPath, ${c} matched (${Math.round(c/Math.max(1,l)*100)}%), ${u} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});X.command("sync").description("pull raw entries from mesh peers into local wiki, or with --articles copy their agents' articles (read-only)").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--articles","copy the articles of agents this node does not run, instead of raw entries").option("--dry-run","show what would be synced without writing").action(async e=>{let t=$e(e.dir),o=t.getSharedStore(),n=await tx(e.peer?[e.peer]:void 0);if(n.length===0){console.log(m.dim(" No mesh peers configured")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(e.articles){let i=await ox();if(!i){console.log(m.red(" No agents in this node's daemon config; run it where agentx.json is.")),process.exitCode=1;return}let{syncPeerArticles:a}=await import("./article-sync-4NOPOQU7.js");for(let l of n){console.log(),console.log(m.bold(` Copying articles from ${l.url}...`));try{let c=await a({hub:t,peer:l,localAgents:i,dryRun:e.dryRun});console.log(m.dim(` Node: ${c.node}`));for(let u of c.agents){if(u.skipped==="local"){console.log(m.dim(` ${u.agentId}: runs here, not copied`));continue}if(u.skipped){console.log(m.yellow(` ${u.agentId}: skipped (${u.skipped})`));continue}let d=[`${u.copied} ${e.dryRun?"to copy":"copied"}`,`${u.unchanged} unchanged`];u.removed&&d.push(`${u.removed} removed (gone on the peer)`),u.rejected&&d.push(`${u.rejected} refused`),console.log(` ${m.cyan(u.agentId)}: ${d.join(", ")}${u.error?m.red(` \u2014 stopped: ${u.error}`):""}`),u.error&&(process.exitCode=1)}}catch(c){console.log(m.red(` ${c.cause?.code==="ECONNREFUSED"?"Connection refused":c.message}`)),process.exitCode=1}}console.log();return}let s=new Set(o.listEntries().map(i=>i.id)),r=0;for(let{url:i,token:a}of n){console.log(),console.log(m.bold(` Syncing from ${i}...`));let l=a?{Authorization:`Bearer ${a}`}:{};try{let c=await fetch(`${i}/wiki/entries`,{headers:l,signal:AbortSignal.timeout(12e4)});if(!c.ok){console.log(m.red(` HTTP ${c.status}`));continue}let u=await c.json(),d=u.entries||[],p=u.nodeId||"unknown";console.log(m.dim(` Node: ${p} \u2014 ${d.length} entries`));let f=0;for(let g of d)s.has(g.id)||(e.dryRun||(o.addEntry({id:g.id,date:g.date,agentId:g.agentId,source:`${g.source}@${p}`,sourceContext:g.sourceContext,content:g.content}),s.add(g.id)),f++);f>0?console.log(m.green(` ${f} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),r+=f;try{let g=await fetch(`${i}/wiki/agents`,{headers:l,signal:AbortSignal.timeout(5e3)});if(g.ok){let h=await g.json();for(let y of h.agents||[])y.totalEntries>0&&console.log(m.dim(` ${y.agentId}: ${y.totalEntries} entries, ${y.totalArticles} articles`))}}catch{}}catch(c){c.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${c.message}`))}}console.log(),r>0&&!e.dryRun?console.log(m.green(` ${r} entries synced.`)):r>0?console.log(m.dim(` ${r} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});X.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let t=e.dir||B(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(l=>{let c=new ic(t,void 0,l),d=c.getAgentWiki(o).rebuildIndex(),p=c.getAgentEntries(o),f=c.getUnabsorbedEntries(o),g=new Set,h=0,y=new Set;for(let $ of d.articles){for(let x of $.tags||[])g.add(x);h+=$.tags?.length||0;for(let x of $.sources||[])y.add(x)}let w=new Set(d.articles.map($=>$.path.includes("/")?$.path.split("/")[0]:"/"));return{mode:l,label:Vu(l),articles:d.articles.length,entries:p.length,unabsorbed:f.length,uniqueTags:g.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:w.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${o}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let r=22;console.log(` ${"".padEnd(20)} ${s.map(l=>l.label.padEnd(r)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(r)).join(" ")}`);let i=[["Articles",l=>String(l.articles)],["Unabsorbed",l=>String(l.unabsorbed)],["Unique tags",l=>String(l.uniqueTags)],["Avg tags/article",l=>l.avgTags],["Directories",l=>String(l.dirs)],["Entry coverage",l=>`${l.coverage}/${l.entries}`]];for(let[l,c]of i){let u=s.map(d=>c(d).padEnd(r));console.log(` ${l.padEnd(20)} ${u.join(" ")}`)}console.log();let a=(l,c)=>{let u=Math.max(...s.map(p=>p[l])),d=s.filter(p=>p[l]===u).map(p=>p.label);u>0&&console.log(m.dim(` Best ${c}: ${d.join(", ")} (${u})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});X.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,t)=>{let o=t.dir?B(process.cwd(),t.dir):B(process.cwd(),".agentx/wiki");nt(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?B(process.cwd(),e):B(process.cwd(),`agentx-wiki-${n}.tar.gz`),r=B(o,".."),i=o.split("/").pop()||"wiki",a=["-C",r,"-czf",s];t.includeRaw||a.push("--exclude="+i+"/raw"),a.push(i),console.log(m.dim(` tar ${a.join(" ")}`));let{spawnSync:l}=await import("child_process"),c=l("tar",a,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.status||1));let{statSync:u}=await import("fs"),d=nt(s)?u(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${fN(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});X.command("gaps").description("what each article still needs, most load-bearing first").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--type <t>","only articles of this type").option("--max-tier <tier>","stop at this layer: foundation|pillar|walls|openings|furniture","pillar").option("--limit <n>","articles to check","40").option("--auto","only gaps a system of record can close without asking anyone").option("--ask","queue the gaps that need a person onto the questions list").option("--notify","push the load-bearing ones to notifications.destination").option("--notify-tier <tier>","tier at or above which to push","pillar").option("--unclear","include fields the grader was unsure about").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,nextActions:s,TIER_MEANING:r,ARTICLE_FIELDS_SEAT:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-BSWBTNCP.js"),{QuestionStore:l}=await import("./questions-ZATLU5AW.js"),c=$e(e.dir,e.mode),u=[],d=e.agent?[e.agent]:c.listAgents(),p=parseInt(e.limit),f=0,g=[];e:for(let k of d){let A=c.getAgentWiki(k);for(let R of A.listArticles(k)){if(f>=p)break e;let T=A.readArticle(R.path);if(!T||e.type&&T.meta.type!==e.type)continue;f++;let I=await a(i,n({title:T.meta.title,type:T.meta.type,body:T.content}),t(T.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:k,type:T.meta.type??"?"}});if(!I){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let M=o(T.meta.type,I.answers);for(let D of s(M,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&D.needsHuman||(e.ask&&D.needsHuman&&u.push({kind:"field",agentId:k,path:R.path,subject:T.meta.title,field:D.field,tier:D.tier,question:`${T.meta.title} (${T.meta.type??"?"}) \u2014 ${D.label}?`}),g.push({tier:D.tier,need:D.field,how:D.needsHuman?m.yellow("ask"):D.sources.join("/"),uncertain:D.uncertain?"?":"",agent:k,article:T.meta.title.slice(0,40)}))}}let h={added:0,skipped:0};if(e.ask&&u.length>0&&(h=new l(vt(e.dir)).add(u)),e.json){console.log(JSON.stringify(g,null,2));return}if(g.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],w=k=>String(k).replace(/\u001b\[[0-9;]*m/g,""),$=y.map(k=>Math.max(k.length,...g.map(A=>w(A[k]).length))),x=(k,A)=>String(k)+" ".repeat(Math.max(0,$[A]-w(k).length));console.log(),console.log(m.bold(y.map((k,A)=>x(k,A)).join(" ")));for(let k of g)console.log(y.map((A,R)=>x(k[A],R)).join(" "));let v=g.filter(k=>k.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${g.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${v} can be closed by a lookup; ${g.length-v} need a person.`));let S=g[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${r[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:k}=await import("./article-fields-PITN4NHA.js"),A=k[e.notifyTier]??k.pillar,R=u.filter(T=>(k[T.tier??"furniture"]??9)<=A);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:T}=await import("./config-S522VXLI.js"),I=T(),M=I?.notifications?.destination;if(!M?.channel||!M?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let D=R.slice(0,10).map(_=>`\u2022 ${_.question}`).join(`
|
|
737
737
|
`),H=R.length>10?`
|
|
738
738
|
\u2026and ${R.length-10} more`:"",U=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
739
739
|
${D}${H}
|
|
740
740
|
|
|
741
|
-
agentx wiki questions`,E=I?.daemon?.port??I?.port??18800;try{let _=await fetch(`http://127.0.0.1:${E}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:M.channel,chatId:M.chatId,accountId:M.accountId,text:U})});console.log(_.ok?m.cyan(` Pushed ${R.length} question(s) to ${M.channel}.`):m.yellow(` Push failed (${_.status}) \u2014 questions are still queued.`))}catch(_){console.log(m.yellow(` Push failed (${String(_?.message??_).slice(0,80)}) \u2014 questions are still queued.`))}}}}});X.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:i}=await import("./seat-5FTOWN5J.js"),{resolveFacts:a,mergeRecords:l,installPrompts:c,defaultSources:u,recordsFromEntries:d}=await import("./facts-XGZWX6CR.js"),{backfillArticle:p}=await import("./backfill-7TCF4SHG.js"),f=$e(e.dir,e.mode),g=e.agent?[e.agent]:f.listAgents(),h=parseInt(e.limit),y=u(),w=l(d(f.getSharedStore().listEntries())),$=new Map(w.map(I=>[I.name.toLowerCase().trim(),I])),x=0,v=0,S=[],k=!1;e:for(let I of g){let M=f.getAgentWiki(I);for(let D of M.listArticles(I)){if(x>=h)break e;if(D.meta.type!=="person")continue;let H=M.readArticle(D.path);if(!H)continue;x++;let U=await i(s,n({title:H.meta.title,type:H.meta.type,body:H.content}),t(H.meta.type),{links:[{kind:"article",id:D.path}],features:{agent:I,op:"backfill"}});if(!U){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let _=o(H.meta.type,U.answers).missing.filter(j=>r.includes(j));if(_.length===0)continue;let{records:z,results:he}=await a([{name:H.meta.title,type:"person"}],{sources:y}),P=$.get(H.meta.title.toLowerCase().trim());if(!k){for(let j of c(he,y))console.log(m.yellow(` ! ${j.source} ${j.kind} \u2014 would supply ${j.provides.join(", ")}`)),console.log(m.dim(` ${j.hint}`));k=!0}let Q=l([...P?[{name:P.name,source:"entries",fields:Object.fromEntries(Object.entries(P.fields).map(([j,oe])=>[j,oe.value]))}]:[],...z]);if(Q.length===0)continue;let{content:ve,edits:ie}=p(H.content,Q[0],_);if(ie.length!==0){for(let j of ie)S.push({agent:I,article:H.meta.title.slice(0,32),field:j.field,action:j.replaced?"replace":"add",got:`${j.value.split(";").length} value(s)`});e.apply&&(M.writeArticle(D.path,H.meta,ve,I)?v++:console.log(m.red(` could not write ${D.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${x} person article(s) considered \u2014 nothing to backfill`));return}let A=["agent","article","field","action","got"],R=A.map(I=>Math.max(I.length,...S.map(M=>String(M[I]).length))),T=I=>I.map((M,D)=>String(M).padEnd(R[D])).join(" ");console.log(),console.log(m.bold(T(A)));for(let I of S)console.log(T(A.map(M=>I[M])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${v} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${x} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});X.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:t}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(vt(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,r)=>(o[s.tier??"furniture"]??9)-(o[r.tier??"furniture"]??9)),console.log();for(let s of n){let r=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${r} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});X.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,t,o)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:r}=await import("./article-fields-PITN4NHA.js"),i=new n(vt(o.dir)),a=i.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!i.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let h=i.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let l=i.list("open").find(h=>h.id===e||h.id.startsWith(e));if(l?.kind==="contradiction"&&l.factId){let{FactLedger:h}=await import("./ledger-5GMBLR7W.js"),y=new h(vt(o.dir));try{let w=y.get(l.factId);if(w){let $=y.write({subject:w.subject,attribute:w.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:w.volatility},{confirmedBy:"operator"});console.log(m.green(` ${$.status}: ${w.id} ${w.subject} \xB7 ${w.attribute}: ${$.fact.value}`))}else console.log(m.yellow(` fact ${l.factId} is gone; answer recorded only.`))}catch(w){w?.name!=="LedgerCorruptError"&&console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}i.resolve(l.id,"answered",t),console.log(m.green(` answered: ${l.question}`));return}let c;try{c=i.resolve(e,"answered",t)}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!c){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${c.question}`)),c.kind!=="field"||!c.field||!c.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!r[c.field]){console.log(m.dim(` recorded against ${c.path}. "${c.field}" has no fixed slot, so nothing was rewritten.`));return}let d=$e(o.dir,o.mode).getAgentWiki(c.agentId),p=d.readArticle(c.path);if(!p){console.log(m.yellow(` article gone: ${c.path}`));return}let f=s(p.content,c.field,`${t} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let g=d.writeArticle(c.path,p.meta,f.content,c.agentId);console.log(g?m.green(` wrote ${c.field} into ${c.path} (prior version kept)`):m.red(` could not write ${c.path}`))});X.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:r}=await import("./seat-5FTOWN5J.js"),{labelEntries:i,sample:a,scoreBacktest:l,toGradedRows:c,sweepPolicies:u}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=$e(e.dir,"graph").getSharedStore(),g=f.listEntries(),h=new Set(f.getUnabsorbedEntries().map(H=>H.id)),{labeled:y,backlog:w}=i(g,h),$=a(y,H=>H.absorbed,parseInt(e.n)),x={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},v=[],S=0,k=Date.now();if(e.load){let{readFileSync:H}=await import("fs");v.push(...JSON.parse(H(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${v.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${w} in backlog) \u2014 grading ${$.length}`));for(let H of e.load?[]:$){let U=await r(t,n(H),o,{features:{source:H.source??"",absorbed:H.absorbed}});if(!U){S++;continue}let E=U.answers;v.push({entry:H,verdict:s(U.answers,x),citeWorthy:E.citeWorthy?.noul})}if(v.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:H}=await import("fs");H(e.save,JSON.stringify(v)),console.log(m.dim(` saved ${v.length} outcome(s) to ${e.save}`))}let A=l(v,{minType:x.minTypeConfidence,minWorth:x.minWorth,minDurability:x.minDurability}),R=c(v,"seat","seat"),T=d(R,{minN:50}),I=((Date.now()-k)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:A,calibration:T,failures:S,elapsed:I},null,2));return}let M=H=>`${(H*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${A.n} (${A.positives} kept by absorb, ${A.negatives} passed over)`),console.log(` recall ${M(A.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${M(A.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${M(A.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${A.lostPositives>0?m.yellow(`lost ${A.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in T)||!T.insufficient)&&console.log(` ECE ${T.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),A.lostPositives>0){let H=A.droppedBy;console.log(m.dim(` dropped by: type ${H.type} \xB7 worth ${H.worth} \xB7 durability ${H.durability} (a positive can fail several)`))}let D=A.positiveMeans;if(console.log(m.dim(` positives avg: worth ${D.worth.toFixed(2)} \xB7 durability ${D.durability.toFixed(2)} \xB7 typeConf ${D.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${I}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let H=parseFloat(e.minRecall),{best:U,points:E}=u(v,{minRecall:H});if(console.log(),console.log(m.bold(` threshold sweep (${E.length} policies, recall floor ${M(H)})`)),U)console.log(` best: ${U.requireTyped?`typed & type>=${U.minType}`:"type gate OFF"} worth>=${U.minWorth} durability>=${U.minDurability}`),console.log(` recall ${M(U.recall)} \xB7 filtered ${M(U.filtered)} \xB7 precision ${M(U.precision)} \xB7 lost ${U.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${M(H)} recall \u2014 not even keeping everything typed.`));let _=E.slice().sort((z,he)=>he.recall-z.recall)[0];_&&console.log(m.dim(` Best recall available: ${M(_.recall)} at ${_.requireTyped?`type>=${_.minType}`:"type gate OFF"} worth>=${_.minWorth} dur>=${_.minDurability}, filtering ${M(_.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});X.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,t)=>{let o=B(process.cwd(),e);nt(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?B(process.cwd(),t.dir):B(process.cwd(),".agentx/wiki");nt(n)&&!t.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=B(n,".."),{mkdirSync:r}=await import("fs");r(s,{recursive:!0});let i=["-C",s,"-xzf",o];console.log(m.dim(` tar ${i.join(" ")}`));let{spawnSync:a}=await import("child_process"),l=a("tar",i,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function fN(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}cm();import{Command as hN}from"commander";import J from"chalk";import{resolve as El}from"path";import{existsSync as yN}from"fs";Z();var pr=new hN().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");pr.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let t=O();if(!t.graph?.enabled){console.log(J.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(J.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(J.red(` agent "${o}" not in config`));return}let n=(e.daemonUrl||t.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),r=new Jo({baseDir:El(process.cwd(),t.graph.baseDir)}),i=r.listPendingClassifications(s);if(i.length===0){console.log(J.dim(" no pending classifications \u2014 nothing to review"));return}let a=r.loadSchema(),l=r.loadNodes().nodes;console.log(),console.log(J.bold(` Graph review \u2014 ${i.length} pending`)),console.log(J.dim(` Reviewer: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let c=0,u=0,d=0,p=0;for(let g=0;g<i.length;g++){let h=i[g],y=qi(h.path,l)||h.path.join(" \u203A ");process.stdout.write(` [${g+1}/${i.length}] ${J.cyan(h.msgHash.slice(0,8))} ${J.dim(y)} ... `);let w=wN(h,a,l),$=null;try{$=await bN(n,o,w,t.dashboard?.token)}catch(S){p++,console.log(J.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!$||!$.decision){p++,console.log(J.red("ERR no decision"));continue}let x=String($.decision).toLowerCase().trim(),v=($.reason||"").toString().slice(0,180);if(x==="approve")if(console.log(J.green("APPROVE")+" "+J.dim(v)),e.dryRun)c++;else try{$N(r,h,a,l,o),r.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:o,reviewReason:v}),c++}catch(S){console.log(J.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),p++}else x==="reject"?(console.log(J.red("REJECT")+" "+J.dim(v)),e.dryRun||r.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:o,reviewReason:v}),u++):(console.log(J.yellow("SKIP")+" "+J.dim(v||x)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(J.dim(` Summary: ${f} approve ${c}, ${f} reject ${u}, ${d} skipped, ${p} errors.`)),e.dryRun&&(c>0||u>0)&&console.log(J.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});pr.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let t=O();if(!t.graph){console.log(J.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=El(process.cwd(),t.graph.baseDir);if(!yN(o)){console.log(J.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new Jo({baseDir:o,log:()=>{}}),r=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(J.dim(" "),...a)});console.log(),console.log(J.bold(" Pattern hits:"));let i=Object.entries(r.patternHits).sort((a,l)=>l[1]-a[1]);i.length===0&&console.log(J.dim(" (none)"));for(let[a,l]of i)console.log(` ${a.padEnd(28)} ${l}`);console.log(),e.dryRun?console.log(J.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(J.green(` Done. Backups: ${r.backups.length} file(s).`)),console.log()});pr.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let t=O();if(!t.graph?.enabled){console.log(J.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let o=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let r=new Jo({baseDir:El(process.cwd(),t.graph.baseDir)}),i=r.loadSchema(),a=r.loadNodes().nodes,l=new Set(a.map(A=>A.id));console.log(),console.log(J.bold(` graph pull \u2190 ${o}`));let c,u,d;try{let A=await fetch(`${o}/graph/schema`,{headers:s});if(!A.ok)throw new Error(`schema HTTP ${A.status}`);c=(await A.json()).schema;let T=await fetch(`${o}/graph/nodes`,{headers:s});if(!T.ok)throw new Error(`nodes HTTP ${T.status}`);u=(await T.json()).nodes||[];let I=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!I.ok)throw new Error(`classifications HTTP ${I.status}`);d=(await I.json()).classifications||[]}catch(A){console.log(J.red(` fetch failed: ${A.message}`));return}let p=i.levels.map(A=>A.id).join(","),f=c?.levels?.map(A=>A.id).join(","),g=p===f;g?console.log(J.dim(` schema matches (${i.levels.length} levels)`)):(console.log(J.yellow(" \u26A0 schema levels differ:")),console.log(J.dim(` local: ${p}`)),console.log(J.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(J.dim(" local is empty \u2014 adopting peer schema")),r.saveSchema(c)):console.log(J.yellow(" keeping local schema; node import may fail if levels disagree")));let h=g?i:c,y=new Map;h.levels.forEach((A,R)=>y.set(A.id,R));let w=[...u].sort((A,R)=>(y.get(A.level)??99)-(y.get(R.level)??99)),$=0,x=0,v=0;for(let A of w){if(l.has(A.id)){x++;continue}if(e.dryRun){$++,l.add(A.id);continue}try{r.addNode({...A,createdBy:A.createdBy?`${A.createdBy} (sync)`:`sync:${o}`}),l.add(A.id),$++}catch(R){v++,console.log(J.yellow(` skip node ${A.id}: ${R.message?.slice(0,100)}`))}}console.log(J.dim(` nodes: +${$} added \xB7 ${x} already-present \xB7 ${v} failed`));let S=0,k=0;for(let A of d)if(!(!A.msgHash||!Array.isArray(A.path))){if(r.getFingerprint(A.msgHash)){k++;continue}if(e.dryRun){S++;continue}r.setFingerprint(A.msgHash,{path:A.path,leaf:A.leaf||{}}),S++}console.log(J.dim(` fingerprints: +${S} cached \xB7 ${k} already-present`)),console.log(),e.dryRun?console.log(J.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(J.green(` \u2713 pulled from ${o}`)),console.log()});function wN(e,t,o){let n={};for(let i of o)(n[i.level]||=[]).push(`${i.id}${i.axes?.name?` (${i.axes.name})`:""}`);let s=t.levels.map(i=>` ${i.id}: [${(n[i.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
741
|
+
agentx wiki questions`,E=I?.daemon?.port??I?.port??18800;try{let _=await fetch(`http://127.0.0.1:${E}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:M.channel,chatId:M.chatId,accountId:M.accountId,text:U})});console.log(_.ok?m.cyan(` Pushed ${R.length} question(s) to ${M.channel}.`):m.yellow(` Push failed (${_.status}) \u2014 questions are still queued.`))}catch(_){console.log(m.yellow(` Push failed (${String(_?.message??_).slice(0,80)}) \u2014 questions are still queued.`))}}}}});X.command("backfill").description("write resolved identifiers into articles that are missing them").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--agent <id>","only this agent's wiki").option("--limit <n>","articles to consider","40").option("--apply","write the changes (default: show them only)").option("--json").action(async e=>{let{fieldQuestions:t,reportFields:o,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:i}=await import("./seat-BSWBTNCP.js"),{resolveFacts:a,mergeRecords:l,installPrompts:c,defaultSources:u,recordsFromEntries:d}=await import("./facts-XGZWX6CR.js"),{backfillArticle:p}=await import("./backfill-7TCF4SHG.js"),f=$e(e.dir,e.mode),g=e.agent?[e.agent]:f.listAgents(),h=parseInt(e.limit),y=u(),w=l(d(f.getSharedStore().listEntries())),$=new Map(w.map(I=>[I.name.toLowerCase().trim(),I])),x=0,v=0,S=[],k=!1;e:for(let I of g){let M=f.getAgentWiki(I);for(let D of M.listArticles(I)){if(x>=h)break e;if(D.meta.type!=="person")continue;let H=M.readArticle(D.path);if(!H)continue;x++;let U=await i(s,n({title:H.meta.title,type:H.meta.type,body:H.content}),t(H.meta.type),{links:[{kind:"article",id:D.path}],features:{agent:I,op:"backfill"}});if(!U){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let _=o(H.meta.type,U.answers).missing.filter(j=>r.includes(j));if(_.length===0)continue;let{records:z,results:he}=await a([{name:H.meta.title,type:"person"}],{sources:y}),P=$.get(H.meta.title.toLowerCase().trim());if(!k){for(let j of c(he,y))console.log(m.yellow(` ! ${j.source} ${j.kind} \u2014 would supply ${j.provides.join(", ")}`)),console.log(m.dim(` ${j.hint}`));k=!0}let Q=l([...P?[{name:P.name,source:"entries",fields:Object.fromEntries(Object.entries(P.fields).map(([j,oe])=>[j,oe.value]))}]:[],...z]);if(Q.length===0)continue;let{content:ve,edits:ie}=p(H.content,Q[0],_);if(ie.length!==0){for(let j of ie)S.push({agent:I,article:H.meta.title.slice(0,32),field:j.field,action:j.replaced?"replace":"add",got:`${j.value.split(";").length} value(s)`});e.apply&&(M.writeArticle(D.path,H.meta,ve,I)?v++:console.log(m.red(` could not write ${D.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${x} person article(s) considered \u2014 nothing to backfill`));return}let A=["agent","article","field","action","got"],R=A.map(I=>Math.max(I.length,...S.map(M=>String(M[I]).length))),T=I=>I.map((M,D)=>String(M).padEnd(R[D])).join(" ");console.log(),console.log(m.bold(T(A)));for(let I of S)console.log(T(A.map(M=>I[M])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${v} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${x} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});X.command("questions").alias("ask").description("gaps waiting on a person").option("--dir <path>","wiki directory").option("--status <s>","open | answered | dismissed","open").option("--json").action(async e=>{let{QuestionStore:t}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:o}=await import("./article-fields-PITN4NHA.js"),n=new t(vt(e.dir)).list(e.status);if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(m.green(` no ${e.status} questions`));return}n.sort((s,r)=>(o[s.tier??"furniture"]??9)-(o[r.tier??"furniture"]??9)),console.log();for(let s of n){let r=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${r} ${s.question}`),s.answer&&console.log(m.dim(` \u2192 ${s.answer}`))}console.log(),console.log(m.dim(` ${n.length} ${e.status}. agentx wiki answer <id> "<value>" \xB7 --dismiss to drop one`))});X.command("answer <id> [value]").description("answer a queued question; writes it into the article").option("--dir <path>","wiki directory").option("--mode <mode>","graph | unified | flat","graph").option("--dismiss","close the question without answering it").action(async(e,t,o)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:r}=await import("./article-fields-PITN4NHA.js"),i=new n(vt(o.dir)),a=i.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!i.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let h=i.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let l=i.list("open").find(h=>h.id===e||h.id.startsWith(e));if(l?.kind==="contradiction"&&l.factId){let{FactLedger:h}=await import("./ledger-5GMBLR7W.js"),y=new h(vt(o.dir));try{let w=y.get(l.factId);if(w){let $=y.write({subject:w.subject,attribute:w.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:w.volatility},{confirmedBy:"operator"});console.log(m.green(` ${$.status}: ${w.id} ${w.subject} \xB7 ${w.attribute}: ${$.fact.value}`))}else console.log(m.yellow(` fact ${l.factId} is gone; answer recorded only.`))}catch(w){w?.name!=="LedgerCorruptError"&&console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}i.resolve(l.id,"answered",t),console.log(m.green(` answered: ${l.question}`));return}let c;try{c=i.resolve(e,"answered",t)}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!c){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${c.question}`)),c.kind!=="field"||!c.field||!c.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!r[c.field]){console.log(m.dim(` recorded against ${c.path}. "${c.field}" has no fixed slot, so nothing was rewritten.`));return}let d=$e(o.dir,o.mode).getAgentWiki(c.agentId),p=d.readArticle(c.path);if(!p){console.log(m.yellow(` article gone: ${c.path}`));return}let f=s(p.content,c.field,`${t} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let g=d.writeArticle(c.path,p.meta,f.content,c.agentId);console.log(g?m.green(` wrote ${c.field} into ${c.path} (prior version kept)`):m.red(` could not write ${c.path}`))});X.command("triage-backtest").description("grade the entry-triage gate against what absorb actually kept").option("--dir <path>","wiki directory").option("--n <n>","entries to sample (half positive, half negative)","200").option("--min-worth <n>","P(useful in six months) required to keep").option("--min-durability <n>","expected durability required to keep").option("--min-type <n>","type confidence required to keep").option("--sweep","search thresholds for the most filtering that still keeps ~all positives").option("--min-recall <n>","recall floor for --sweep","0.95").option("--save <file>","write the graded outcomes so sweeps can be re-run for free").option("--load <file>","re-sweep saved outcomes without paying for the calls again").option("--json").action(async e=>{let{ENTRY_TRIAGE_SEAT:t,entryTriageQuestions:o,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:r}=await import("./seat-BSWBTNCP.js"),{labelEntries:i,sample:a,scoreBacktest:l,toGradedRows:c,sweepPolicies:u}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=$e(e.dir,"graph").getSharedStore(),g=f.listEntries(),h=new Set(f.getUnabsorbedEntries().map(H=>H.id)),{labeled:y,backlog:w}=i(g,h),$=a(y,H=>H.absorbed,parseInt(e.n)),x={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},v=[],S=0,k=Date.now();if(e.load){let{readFileSync:H}=await import("fs");v.push(...JSON.parse(H(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${v.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${w} in backlog) \u2014 grading ${$.length}`));for(let H of e.load?[]:$){let U=await r(t,n(H),o,{features:{source:H.source??"",absorbed:H.absorbed}});if(!U){S++;continue}let E=U.answers;v.push({entry:H,verdict:s(U.answers,x),citeWorthy:E.citeWorthy?.noul})}if(v.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:H}=await import("fs");H(e.save,JSON.stringify(v)),console.log(m.dim(` saved ${v.length} outcome(s) to ${e.save}`))}let A=l(v,{minType:x.minTypeConfidence,minWorth:x.minWorth,minDurability:x.minDurability}),R=c(v,"seat","seat"),T=d(R,{minN:50}),I=((Date.now()-k)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:A,calibration:T,failures:S,elapsed:I},null,2));return}let M=H=>`${(H*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${A.n} (${A.positives} kept by absorb, ${A.negatives} passed over)`),console.log(` recall ${M(A.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${M(A.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${M(A.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${A.lostPositives>0?m.yellow(`lost ${A.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in T)||!T.insufficient)&&console.log(` ECE ${T.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),A.lostPositives>0){let H=A.droppedBy;console.log(m.dim(` dropped by: type ${H.type} \xB7 worth ${H.worth} \xB7 durability ${H.durability} (a positive can fail several)`))}let D=A.positiveMeans;if(console.log(m.dim(` positives avg: worth ${D.worth.toFixed(2)} \xB7 durability ${D.durability.toFixed(2)} \xB7 typeConf ${D.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${I}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let H=parseFloat(e.minRecall),{best:U,points:E}=u(v,{minRecall:H});if(console.log(),console.log(m.bold(` threshold sweep (${E.length} policies, recall floor ${M(H)})`)),U)console.log(` best: ${U.requireTyped?`typed & type>=${U.minType}`:"type gate OFF"} worth>=${U.minWorth} durability>=${U.minDurability}`),console.log(` recall ${M(U.recall)} \xB7 filtered ${M(U.filtered)} \xB7 precision ${M(U.precision)} \xB7 lost ${U.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${M(H)} recall \u2014 not even keeping everything typed.`));let _=E.slice().sort((z,he)=>he.recall-z.recall)[0];_&&console.log(m.dim(` Best recall available: ${M(_.recall)} at ${_.requireTyped?`type>=${_.minType}`:"type gate OFF"} worth>=${_.minWorth} dur>=${_.minDurability}, filtering ${M(_.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});X.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,t)=>{let o=B(process.cwd(),e);nt(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?B(process.cwd(),t.dir):B(process.cwd(),".agentx/wiki");nt(n)&&!t.force&&(console.log(m.yellow(` ${n} already exists.`)),console.log(m.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=B(n,".."),{mkdirSync:r}=await import("fs");r(s,{recursive:!0});let i=["-C",s,"-xzf",o];console.log(m.dim(` tar ${i.join(" ")}`));let{spawnSync:a}=await import("child_process"),l=a("tar",i,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1)),console.log(),console.log(m.green(` \u2713 restored to ${n}`)),console.log(m.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function fN(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}cm();import{Command as hN}from"commander";import J from"chalk";import{resolve as El}from"path";import{existsSync as yN}from"fs";Z();var pr=new hN().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");pr.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let t=O();if(!t.graph?.enabled){console.log(J.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(J.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(J.red(` agent "${o}" not in config`));return}let n=(e.daemonUrl||t.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),r=new Jo({baseDir:El(process.cwd(),t.graph.baseDir)}),i=r.listPendingClassifications(s);if(i.length===0){console.log(J.dim(" no pending classifications \u2014 nothing to review"));return}let a=r.loadSchema(),l=r.loadNodes().nodes;console.log(),console.log(J.bold(` Graph review \u2014 ${i.length} pending`)),console.log(J.dim(` Reviewer: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let c=0,u=0,d=0,p=0;for(let g=0;g<i.length;g++){let h=i[g],y=qi(h.path,l)||h.path.join(" \u203A ");process.stdout.write(` [${g+1}/${i.length}] ${J.cyan(h.msgHash.slice(0,8))} ${J.dim(y)} ... `);let w=wN(h,a,l),$=null;try{$=await bN(n,o,w,t.dashboard?.token)}catch(S){p++,console.log(J.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!$||!$.decision){p++,console.log(J.red("ERR no decision"));continue}let x=String($.decision).toLowerCase().trim(),v=($.reason||"").toString().slice(0,180);if(x==="approve")if(console.log(J.green("APPROVE")+" "+J.dim(v)),e.dryRun)c++;else try{$N(r,h,a,l,o),r.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:o,reviewReason:v}),c++}catch(S){console.log(J.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),p++}else x==="reject"?(console.log(J.red("REJECT")+" "+J.dim(v)),e.dryRun||r.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:o,reviewReason:v}),u++):(console.log(J.yellow("SKIP")+" "+J.dim(v||x)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(J.dim(` Summary: ${f} approve ${c}, ${f} reject ${u}, ${d} skipped, ${p} errors.`)),e.dryRun&&(c>0||u>0)&&console.log(J.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});pr.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let t=O();if(!t.graph){console.log(J.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=El(process.cwd(),t.graph.baseDir);if(!yN(o)){console.log(J.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new Jo({baseDir:o,log:()=>{}}),r=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(J.dim(" "),...a)});console.log(),console.log(J.bold(" Pattern hits:"));let i=Object.entries(r.patternHits).sort((a,l)=>l[1]-a[1]);i.length===0&&console.log(J.dim(" (none)"));for(let[a,l]of i)console.log(` ${a.padEnd(28)} ${l}`);console.log(),e.dryRun?console.log(J.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(J.green(` Done. Backups: ${r.backups.length} file(s).`)),console.log()});pr.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://peer.example.com:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let t=O();if(!t.graph?.enabled){console.log(J.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let o=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let r=new Jo({baseDir:El(process.cwd(),t.graph.baseDir)}),i=r.loadSchema(),a=r.loadNodes().nodes,l=new Set(a.map(A=>A.id));console.log(),console.log(J.bold(` graph pull \u2190 ${o}`));let c,u,d;try{let A=await fetch(`${o}/graph/schema`,{headers:s});if(!A.ok)throw new Error(`schema HTTP ${A.status}`);c=(await A.json()).schema;let T=await fetch(`${o}/graph/nodes`,{headers:s});if(!T.ok)throw new Error(`nodes HTTP ${T.status}`);u=(await T.json()).nodes||[];let I=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!I.ok)throw new Error(`classifications HTTP ${I.status}`);d=(await I.json()).classifications||[]}catch(A){console.log(J.red(` fetch failed: ${A.message}`));return}let p=i.levels.map(A=>A.id).join(","),f=c?.levels?.map(A=>A.id).join(","),g=p===f;g?console.log(J.dim(` schema matches (${i.levels.length} levels)`)):(console.log(J.yellow(" \u26A0 schema levels differ:")),console.log(J.dim(` local: ${p}`)),console.log(J.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(J.dim(" local is empty \u2014 adopting peer schema")),r.saveSchema(c)):console.log(J.yellow(" keeping local schema; node import may fail if levels disagree")));let h=g?i:c,y=new Map;h.levels.forEach((A,R)=>y.set(A.id,R));let w=[...u].sort((A,R)=>(y.get(A.level)??99)-(y.get(R.level)??99)),$=0,x=0,v=0;for(let A of w){if(l.has(A.id)){x++;continue}if(e.dryRun){$++,l.add(A.id);continue}try{r.addNode({...A,createdBy:A.createdBy?`${A.createdBy} (sync)`:`sync:${o}`}),l.add(A.id),$++}catch(R){v++,console.log(J.yellow(` skip node ${A.id}: ${R.message?.slice(0,100)}`))}}console.log(J.dim(` nodes: +${$} added \xB7 ${x} already-present \xB7 ${v} failed`));let S=0,k=0;for(let A of d)if(!(!A.msgHash||!Array.isArray(A.path))){if(r.getFingerprint(A.msgHash)){k++;continue}if(e.dryRun){S++;continue}r.setFingerprint(A.msgHash,{path:A.path,leaf:A.leaf||{}}),S++}console.log(J.dim(` fingerprints: +${S} cached \xB7 ${k} already-present`)),console.log(),e.dryRun?console.log(J.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(J.green(` \u2713 pulled from ${o}`)),console.log()});function wN(e,t,o){let n={};for(let i of o)(n[i.level]||=[]).push(`${i.id}${i.axes?.name?` (${i.axes.name})`:""}`);let s=t.levels.map(i=>` ${i.id}: [${(n[i.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
742
742
|
`),r=JSON.stringify(e.proposedAxes||{},null,2);return["You are reviewing a pending intent classification. Decide whether it is reasonable.","","--- MESSAGE (first 500 chars) ---",(e.preview||"").slice(0,500),`channel: ${e.channel||"?"} \xB7 sender: ${e.sender||"?"}`,"","--- PROPOSED PATH ---",e.path.join(" \u203A "),"","--- PROPOSED AXES (per new node) ---",r,"","--- CURRENT NODES BY LEVEL (first 10 per level) ---",s,"","--- YOUR JOB ---","Decide one of:"," approve \u2014 the path is right and the axes make sense for the message"," reject \u2014 the path is wrong (e.g. the message is NOT about the proposed org/topic, or the axes are bogus)"," skip \u2014 you can't confidently decide; leave it for a human","",'BEFORE you decide, you MAY call `agentx wiki query` (via Bash) to check institutional context \u2014 e.g. "is there an article for this project" or "who is this person". This is optional; don\'t call it for obvious cases.',"","Bias toward reject over approve when uncertain. A wrong approval pollutes the graph; a wrong rejection just keeps the entry pending.","","Return EXACTLY one JSON object on one line, no prose, no fences:",' {"decision":"approve"|"reject"|"skip","reason":"one sentence"}'].join(`
|
|
743
743
|
`)}async function bN(e,t,o,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let r=new AbortController,i=setTimeout(()=>r.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:t,message:o,context:{channel:"a2a",sender:"graph-review"}}),signal:r.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let l=await a.json();if(l?.error)throw new Error(String(l.error));return Pi((l?.content||"").toString())}finally{clearTimeout(i)}}function $N(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function Qu(){let e=O();if(!e.graph?.baseDir)return console.log(J.red(" graph.baseDir is not configured")),null;let t=El(process.cwd(),e.graph.baseDir);return{store:new Jo({baseDir:t}),baseDir:t}}var Zu=pr.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Zu.command("next").alias("list").description("what to check next, spread across the confidence range").option("--n <n>","how many","10").option("--strategy <s>","stratified | uncertain","stratified").option("--json").action(async e=>{let t=Qu();if(!t)return;let{ReviewStore:o,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),r=new o(t.baseDir).load(),i=n(s,new Set(r.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(J.green(" nothing left unreviewed"));return}let a=t.store.loadNodes().nodes;console.log();for(let l of i){let c=typeof l.confidence=="number"?l.confidence.toFixed(2):J.dim("cache");console.log(` ${J.cyan(l.msgHash.slice(0,8))} ${c.padStart(5)} ${J.bold(qi(l.path,a)||l.path.join(" \u203A "))}`),l.preview&&console.log(J.dim(` ${String(l.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(J.dim(` ${i.length} to check (${e.strategy}).`)),console.log(J.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});Zu.command("mark <hash> <verdict>").description("record a verdict: correct | wrong | unsure").option("--path <p>","for `wrong`: the path it should have been, slash-separated").option("--note <t>","why, when it is worth remembering").option("--by <who>","reviewer","operator").action(async(e,t,o)=>{if(!["correct","wrong","unsure"].includes(t)){console.log(J.red(" verdict must be correct | wrong | unsure"));return}let n=Qu();if(!n)return;let{ReviewStore:s}=await import("./review-store-PW3OBGZQ.js"),i=n.store.listAllClassifications().filter(c=>c.msgHash===e||c.msgHash.startsWith(e));if(i.length===0){console.log(J.red(` no classification matching "${e}"`));return}if(i.length>1){console.log(J.red(` "${e}" matches ${i.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:i[0].msgHash,verdict:t,correctPath:o.path?String(o.path).split("/").filter(Boolean):void 0,note:o.note,reviewer:o.by});let l=n.store.loadNodes().nodes;console.log(J.green(` ${t}: ${qi(i[0].path,l)||i[0].path.join(" \u203A ")}`)),o.path&&console.log(J.dim(` should have been: ${o.path}`))});Zu.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let t=Qu();if(!t)return;let{ReviewStore:o,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=t.store.listAllClassifications(),r=new o(t.baseDir).load(),i=n(s,r);if(e.json){console.log(JSON.stringify(i,null,2));return}let a=l=>`${(l*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${i.classifications}`),console.log(` reviewed ${i.reviewed} (${i.correct} correct \xB7 ${i.wrong} wrong \xB7 ${i.unsure} unsure)`),i.correct+i.wrong>0&&console.log(` accuracy ${a(i.accuracy)}`),console.log(` calibratable ${i.calibratable} ${J.dim("reviewed rows that carry a confidence")}`),i.byBin.length>0){console.log(),console.log(J.bold(" reliability \u2014 confidence vs how often it was right"));for(let l of i.byBin){let c=Math.abs(parseFloat(l.bin.split("-")[0])+.05-l.accuracy),u=l.n>=5&&c>.15?J.yellow(" \u2190 miscalibrated"):"";console.log(` ${l.bin} n=${String(l.n).padStart(3)} right ${a(l.accuracy).padStart(6)}${u}`)}}console.log(),i.calibratable<100?console.log(J.dim(` ${100-i.calibratable} more labelled rows before a calibration report means anything.`)):console.log(J.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as AN}from"commander";import ge from"chalk";import{Command as rx}from"commander";import _e from"chalk";import{existsSync as kN}from"fs";import{resolve as vN}from"path";import xN from"better-sqlite3";function SN(e){if(!e)return;let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(t){let n=Number(t[1]),s=t[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(_e.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function EN(e){let t=vN(process.cwd(),e);return kN(t)||(console.log(_e.red(` No db at ${t}`)),process.exit(1)),new xN(t,{readonly:!0})}var ix=new rx().name("extract").description("mine recurring user activity into procedure drafts (dry-run by default)").option("--path <path>","SQLite db path",".agentx/db.sqlite").option("--since <duration>","activity window, e.g. 24h, 7d, or ms epoch","7d").option("--agent <id>","only mine one agent's activity").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(Cr)).option("--max <n>","max clusters distilled per run",String(Gi)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(_e.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let t=EN(e.path),o=await Dp(t,{since:SN(e.since),agentId:e.agent,sessions:new xm(process.cwd()),minOccurrences:Number(e.minOccurrences)||Cr,max:Number(e.max)||Gi,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(_e.dim(` ${n}`))});console.log(),console.log(` ${o.episodes} episode(s) \u2192 ${o.clusters} cluster(s), ${o.ready.length} at threshold`);for(let n of o.ready)console.log(` ${_e.cyan(n.key)} ${_e.bold(`\xD7${n.count}`)} ${_e.dim(n.status)}`),n.sampleMessage&&console.log(_e.dim(` "${n.sampleMessage.slice(0,100)}"`));if(o.nearMisses.length){console.log(_e.dim(`
|
|
744
744
|
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of o.nearMisses.slice(0,5))console.log(_e.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of o.drafted)console.log(_e.green(` \u2713 draft written: ${n.id}`)+_e.dim(` (${n.count} occurrences)`));for(let n of o.skipped)console.log(_e.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of o.warnings)console.log(_e.yellow(` \u26A0 ${n}`));o.dryRun?console.log(_e.dim(`
|
|
@@ -809,7 +809,7 @@ ${e.body||""}`)}function uj(e){return e.startsWith("test/")||/\.test\.[cm]?[jt]s
|
|
|
809
809
|
|
|
810
810
|
`))>=0;){let f=c.slice(0,p);c=c.slice(p+2),Ej(f)}}}catch(i){console.error(Ae.red(` disconnected: ${i.message||i}`)),process.exit(1)}});function Ej(e){let t="message",o="";for(let r of e.split(`
|
|
811
811
|
`))r.startsWith("event: ")?t=r.slice(7):r.startsWith("data: ")&&(o=r.slice(6));if(!o)return;let n={};try{n=JSON.parse(o)}catch{console.log(`${t}: ${o}`);return}let s=n.at?Ae.dim(new Date(n.at).toLocaleTimeString()):"";switch(t){case"run":{let r=Ae.cyan(n.phase?.padEnd(9)??"run"),i=Ae.bold(n.workflowId??""),a=Ae.dim((n.runId??"").slice(0,8)),l=n.nodeId?Ae.yellow(n.nodeId):"",c=n.note?Ae.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${r} ${i} ${a} ${l} ${c}`);break}case"task":{let r=Ae.magenta(`task.${n.phase}`.padEnd(14)),i=Ae.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",l=n.title?Ae.dim(`"${n.title}"`):"";console.log(`${s} ${r} ${i} ${Ae.cyan(a)} ${l}`);break}case"signal":{let r=Ae.green("signal".padEnd(9)),i=Ae.bold(n.name),a=Ae.dim(`(${n.scope})`),l=n.workflowId?Ae.dim(n.workflowId):"";console.log(`${s} ${r} ${i} ${a} ${l}`);break}case"mesh":{let r=Ae.blue("mesh".padEnd(9)),i=Ae.bold(n.peer),a=n.healthy?Ae.green("\u2713 healthy"):Ae.red("\u2717 lost");console.log(`${s} ${r} ${i} ${a} ${Ae.dim(n.delta??"")}`);break}case"channel":{let r=Ae.yellow("channel".padEnd(9)),i=n.direction==="in"?Ae.cyan("\u2190"):Ae.magenta("\u2192"),a=Ae.bold(`${n.channel}:${n.chatId??""}`),l=n.textPreview?Ae.dim(n.textPreview):"";console.log(`${s} ${r} ${i} ${a} ${l}`);break}case"status":{console.log(Ae.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${t} ${JSON.stringify(n)}`)}}Z();import{Command as g0}from"commander";import Ao from"chalk";function Aj(e,t){let o=e.replace(/\/+$/,""),n=new URLSearchParams;if(t.since&&n.set("since",t.since),t.limit&&n.set("limit",t.limit),t.agent){let s=n.toString();return`${o}/agents/${encodeURIComponent(t.agent)}/events${s?`?${s}`:""}`}return t.kind&&n.set("kind",t.kind),t.limit||n.set("limit","50"),`${o}/events/recent?${n}`}function Rj(e,t,o=process.env){let n={name:e};t.summary&&(n.summary=t.summary),t.ref&&(n.ref=t.ref),t.expiresIn&&(n.expiresIn=t.expiresIn);let s=t.by||o.AGENTX_AGENT_ID;return s&&(n.by=s),o.AGENTX_AGENT_ID&&(n.senderAgentId=o.AGENTX_AGENT_ID),o.AGENTX_TASK_ID&&(n.callerTaskId=o.AGENTX_TASK_ID),o.AGENTX_CHANNEL&&(n.callerChannel=o.AGENTX_CHANNEL),o.AGENTX_CHAT_ID&&(n.callerChatId=o.AGENTX_CHAT_ID),n}function m0(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=O(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return{baseUrl:(t||"http://localhost:18800").replace(/\/+$/,""),token:o}}var Tj=new g0().name("emit").description("publish a named event (for example render:ready) that wakes the agents subscribed to it").argument("<name>","event name: letters, digits and : . _ -").option("--summary <text>","one short line on what happened").option("--ref <ref>","pointer to the details: an issue, a path, a run id").option("--by <name>","who emitted it (an agent id or a person's name; default: the running agent)").option("--expires-in <duration>","drop wakes not started within this time, for example 90s, 5m or 2h").action(async(e,t,o)=>{let n=o.optsWithGlobals(),{baseUrl:s,token:r}=m0(n),i={"Content-Type":"application/json"};r&&(i.Authorization=`Bearer ${r}`);try{let a=await fetch(`${s}/events`,{method:"POST",headers:i,body:JSON.stringify(Rj(e,n)),signal:AbortSignal.timeout(1e4)}),l=await a.json().catch(()=>({}));if(!a.ok){console.error(Ao.red(` Event refused (${a.status}): ${l.error||"unknown error"}`)),process.exitCode=1;return}if(n.json){console.log(JSON.stringify(l,null,2));return}console.log(Ao.green(` \u2713 Emitted ${l.event?.type??e} on ${l.event?.node??"this machine"}`)+Ao.dim(` (event ${l.event?.id??"?"})`))}catch(a){console.error(Ao.red(` daemon unreachable at ${s}: ${a?.message||a}`)),process.exitCode=1}}),p0=new g0().name("events").description("recent events on this node, or those matching one agent's subscriptions").option("-c, --config <path>","daemon config file").option("-a, --agent <id>","only events matching this agent's subscriptions").option("-s, --since <id|iso>","only events after this event id or ISO time").option("-k, --kind <kind>","only this event kind (without --agent)").option("-n, --limit <n>","most events to show (with --agent: default 20, max 50)").option("--json","machine-readable output").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").addCommand(Tj).action(async e=>{let{baseUrl:t,token:o}=m0(e),n={};o&&(n.Authorization=`Bearer ${o}`);let s;try{let a=await fetch(Aj(t,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(Ao.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(Ao.red(` daemon unreachable at ${t}: ${a?.message||a}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(s,null,2));return}let r=s.events??[];if(e.agent&&!s.subscriptions){console.log(Ao.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(r.length===0){console.log(Ao.dim(" no events"));return}for(let a of r)console.log(` ${Im(a)} ${Ao.dim(a.id)}`);let i=s.next??r[r.length-1].id;console.log(Ao.dim(`
|
|
812
|
-
${r.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${i}`))});import{Command as Oj}from"commander";import $i from"chalk";import{spawn as Ij}from"node:child_process";import{execFileSync as Cj}from"node:child_process";function f0(e=()=>Cj("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let t;try{t=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let o=t.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return o?Number(o[1])<2?{ok:!1,reason:`OpenCode ${t} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:t}:{ok:!1,reason:`Could not recognize the OpenCode version: ${t||"empty output"}`}}var h0=new Oj().name("tui").description("open the AgentX console in OpenCode").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","daemon mesh bearer token for remote nodes").option("--agent <id>","AgentX agent to use as the OpenCode model").option("--legacy","open the built-in Ink terminal UI").option("--poll <ms>","legacy UI snapshot poll interval in ms","3000").action(async e=>{process.stdout.isTTY||(console.error($i.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-
|
|
812
|
+
${r.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${i}`))});import{Command as Oj}from"commander";import $i from"chalk";import{spawn as Ij}from"node:child_process";import{execFileSync as Cj}from"node:child_process";function f0(e=()=>Cj("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let t;try{t=e().trim()}catch(n){return{ok:!1,reason:n?.code==="ENOENT"?"OpenCode is not installed or is not on PATH.":`Could not run opencode --version: ${n?.message||String(n)}`}}let o=t.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return o?Number(o[1])<2?{ok:!1,reason:`OpenCode ${t} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:t}:{ok:!1,reason:`Could not recognize the OpenCode version: ${t||"empty output"}`}}var h0=new Oj().name("tui").description("open the AgentX console in OpenCode").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","daemon mesh bearer token for remote nodes").option("--agent <id>","AgentX agent to use as the OpenCode model").option("--legacy","open the built-in Ink terminal UI").option("--poll <ms>","legacy UI snapshot poll interval in ms","3000").action(async e=>{process.stdout.isTTY||(console.error($i.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-U3OFNJ5W.js"),o=t({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:f0();if(n?.ok){let{fetchAgents:c}=await import("./client-U3OFNJ5W.js"),u=await c(o);if(!u.length)throw new Error(`No AgentX agents returned by ${o.baseUrl}`);let d=e.agent||u[0].id;if(!u.some(w=>w.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let p={};try{p=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(u.map(w=>[w.id,{name:`AgentX ${w.name||w.id}`}])),g={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...p,model:`agentx/${d}`,providers:{...p.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${o.baseUrl}/v1`},models:f}}})};console.error($i.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:h}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:y}=await import("./opencode-launch-ECMEY2QZ.js");await y({agentId:d,env:g,cwd:process.cwd(),pool:h,spawnImpl:Ij,log:w=>console.error($i.dim(w))});return}n&&!n.ok&&(console.error($i.yellow(n.reason)),console.error($i.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-OUWMH6QG.js"),{render:r}=await import("ink"),i=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await r(i.createElement(s,{conn:o,pollMs:a})).waitUntilExit()});import{Command as Nj}from"commander";import fe from"chalk";import{randomUUID as b0}from"crypto";import{createInterface as jj}from"node:readline/promises";import _j from"ora";import ql from"chalk";function y0(e){console.error(),console.error(ql.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(ql.dim(` ${e.why}`)),console.error(),console.error(` Use ${ql.cyan(e.instead)} instead.`),e.note&&console.error(ql.dim(` ${e.note}`)),console.error()}var w0={why:"No recorded use on any node since 2026-07-03.",instead:"agentx attach <agent>",note:"Wears the identity in the Claude Code session you already have open \u2014 see docs/reference/attach.md"};var $0=new Nj().name("chat").description("[deprecated \u2014 see agentx attach] interactive chat with a daemon-registered agent").argument("[agent]","agent id to talk to (with or without leading @)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--channel <name>","logical channel name passed in context","chat-cli").option("--chat-id <id>","resume an existing chatId (otherwise a fresh one is generated)").action(async(e,t)=>{y0({what:"agentx chat",...w0});let o=by({node:t.node,token:t.token,config:t.config}),n=(e??"").replace(/^@/,"").trim(),s=t.channel,r=t.chatId||`chat-cli:${b0().slice(0,12)}`,i=[];try{i=await ga(o)}catch(u){console.error(fe.red(` cannot reach daemon at ${o.baseUrl}: ${u?.message||u}`)),console.error(fe.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(i.length===0&&(console.error(fe.red(" no agents registered with the daemon")),process.exit(1)),n?i.find(u=>u.id===n)||(console.error(fe.red(` unknown agent: @${n}`)),console.error(fe.dim(` registered: ${i.map(u=>`@${u.id}`).join(", ")}`)),process.exit(1)):(n=i[0].id,console.log(fe.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:u}=await import("ink"),{ChatApp:d}=await import("./ChatApp-EZ5A47FV.js"),p=(await import("react")).default;await u(p.createElement(d,{conn:o,agentId:n,channel:s,chatId:r,agents:i})).waitUntilExit();return}Pj(o.baseUrl,n,r,s);let a=jj({input:process.stdin,output:process.stdout}),l=!1,c=!1;for(a.on("close",()=>{if(l){c=!0;return}console.log(fe.dim(`
|
|
813
813
|
bye`)),process.exit(0)});;){let u;try{u=(await a.question(fe.cyan("you \u203A "))).trim()}catch{a.close();return}if(!u)continue;if(u==="/exit"||u==="/quit"){a.close();return}if(u==="/who"){console.log(fe.dim(` @${n} chatId=${r} channel=${s}`));continue}if(u==="/clear"){r=`chat-cli:${b0().slice(0,12)}`,console.log(fe.dim(` fresh chatId=${r} (warm process dropped)`));continue}if(u==="/agents"){try{let g=await ga(o);for(let h of g){let y=h.id===n?fe.green("\u25CF"):fe.dim("\u25CB");console.log(` ${y} @${h.id} ${fe.dim(h.tier)} ${h.model??""}`)}}catch(g){console.error(fe.red(` failed to list agents: ${g?.message||g}`))}continue}if(u.startsWith("/agent ")){let g=u.slice(7).replace(/^@/,"").trim();if(!g){console.log(fe.red(" usage: /agent <id>"));continue}try{if(!(await ga(o)).find(y=>y.id===g)){console.log(fe.red(` unknown agent: @${g}`));continue}n=g,console.log(fe.dim(` now talking to @${n}`))}catch(h){console.error(fe.red(` failed to switch agent: ${h?.message||h}`))}continue}if(u.startsWith("/")){console.log(fe.red(` unknown command: ${u.split(/\s+/)[0]}`)),console.log(fe.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}l=!0;let d=_j({text:`@${n}\u2026`,color:"cyan"}).start(),p=Date.now(),f=Dj(n);try{let g=await $y(o,n,u,{channel:s,chatId:r,onText:y=>{d.stop(),f.text(y)},onThinking:()=>{},onTool:y=>{d.stop(),f.tool(y)}});d.stop();let h=Math.round((Date.now()-p)/100)/10;g.error?f.finishError(g.error):f.finish(h,g.usage)}catch(g){d.stop(),f.finishError(g?.message||String(g))}finally{l=!1}if(c){console.log(fe.dim(" bye"));return}}});function Dj(e){let t=!1,o=!0,n=!1,s=new Set,r=()=>{t||(process.stdout.write(`${fe.green(`@${e}`)}
|
|
814
814
|
`),t=!0)};return{text(i){if(i){r(),n=!0;for(let a of i)o&&a!==`
|
|
815
815
|
`&&(process.stdout.write(" "),o=!1),process.stdout.write(a),a===`
|
|
@@ -909,7 +909,7 @@ Restart the daemon to activate.
|
|
|
909
909
|
dist/
|
|
910
910
|
*.log
|
|
911
911
|
.env
|
|
912
|
-
`}import{Command as b_}from"commander";import dt from"chalk";import{writeFileSync as $_,mkdirSync as k_,existsSync as Jl,readFileSync as D0,appendFileSync as P0}from"fs";import{resolve as kr,dirname as q0}from"path";import{homedir as Rg}from"os";var F0=new b_().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-
|
|
912
|
+
`}import{Command as b_}from"commander";import dt from"chalk";import{writeFileSync as $_,mkdirSync as k_,existsSync as Jl,readFileSync as D0,appendFileSync as P0}from"fs";import{resolve as kr,dirname as q0}from"path";import{homedir as Rg}from"os";var F0=new b_().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-VCNJHSWN.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=S_(o);break;case"bash":s=C_(o);break;case"fish":s=O_(o);break;default:console.error(dt.red(`unsupported shell: ${n}`)),console.error(dt.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?kr(String(e.output)):v_(n);k_(q0(r),{recursive:!0}),$_(r,s),console.log(dt.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),x_(n,r,!!e.yes)});function v_(e){let t=Rg();switch(e){case"zsh":return kr(t,".zsh","completions","_agentx");case"bash":return kr(t,".bash_completion.d","agentx.bash");case"fish":return kr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function x_(e,t,o){if(e==="zsh"){let n=kr(Rg(),".zshrc"),s=q0(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Jl(n)?D0(n,"utf-8"):"",l=!a.includes(s),c=!/autoload\s+-U\s+compinit/.test(a);if(!l&&!c){console.log(dt.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Jl(n)){let u=["","# agentx completion"];l&&u.push(r),c&&u.push(i),P0(n,u.join(`
|
|
913
913
|
`)+`
|
|
914
914
|
`),console.log(dt.green("\u2713 Patched ~/.zshrc")),console.log(dt.dim("Reload your shell: exec zsh"));return}console.log(dt.dim("Add this to ~/.zshrc if not already present:")),l&&console.log(dt.cyan(` ${r}`)),c&&console.log(dt.cyan(` ${i}`)),console.log(),console.log(dt.dim("Then reload: exec zsh")),console.log(dt.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=kr(Rg(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Jl(n)?D0(n,"utf-8"):"").includes(t)){console.log(dt.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&Jl(n)){P0(n,`
|
|
915
915
|
# agentx completion
|
|
@@ -925,4 +925,4 @@ ${I_({...t,category:e.category})}`),u&&a.set(c.id,u)}let l=`https://github.com/$
|
|
|
925
925
|
${o.url}`)}catch(t){console.error(xr.red(` ${t.message}`)),process.exitCode=1}});Ri.command("draft <file>").description("turn a draft JSON file ({category, title, fields}) into a pre-filled issue form link; '-' reads stdin").requiredOption("--model <model>","the model that wrote the draft").option("--models <pathOrUrl>","model list to read",Cg).action(async(e,t)=>{try{let o=await Ng(t.models);if(!Og(t.model,o)){console.log(Ig(t.model,o)),process.exitCode=1;return}let n=e==="-"?await __():await j_(e,"utf8"),s=JSON.parse(n),{version:r}=await Ji(),i=H0({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(xr.red(` ${o.message}`)),process.exitCode=1}});async function __(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function o5(){let e=await Ji(),t=new D_().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");t.hook("preAction",(o,n)=>{let s=Zh(n);ey(s)&&Qh("cli",s)});for(let o of[eb,mw,gw,rs,Ms,po,qt,jh,Ek,Rk,yo,Ca,Do,In,Qn,ko,Mo,Qr,vv,gn,$a,h0,ln,d$,u$,$$,ii,I$,P$,a$,q$,F$,nk,ak,lk,Ht,is,v0,Hr,tn,F0,Ri])t.addCommand(o);for(let o of G0)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=G0.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,P_(o,74," "),""].join(`
|
|
926
926
|
`)}),t}var G0=[X,pr,Fo,ro,Gr,sr,st,qo,mn,Vn,us,hr,sn,St,Ks,Ga,al,Kn,ll,cl,u0,p0,_o,bi,Ut,ky,Pn,Ei,Ed,yn,kt,zs,Ad,_l,Eo,rg,Uo,T0,br,C0,$0];function P_(e,t,o){let n=[],s="";for(let r of e)s&&s.length+r.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+r;return s&&n.push(o+s),n.join(`
|
|
927
927
|
`)}export{o5 as buildProgram};
|
|
928
|
-
//# sourceMappingURL=program-
|
|
928
|
+
//# sourceMappingURL=program-VCNJHSWN.js.map
|