agentix-cli 0.200.1 → 0.201.0
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/apps/mac-voice/Sources/AgentXVoice/Brand.swift +1 -0
- package/apps/mac-voice/Sources/AgentXVoice/Markdown.swift +67 -2
- package/dist/{App-AUKNCAVD.js → App-UHSMBGRE.js} +2 -2
- package/dist/{ChatApp-KYQIQZ6Q.js → ChatApp-Z6YVST7J.js} +2 -2
- package/dist/{absorb-eval-TJN5WUYZ.js → absorb-eval-4GDAAYBL.js} +2 -2
- package/dist/{adapter-VLNSNP6C.js → adapter-IITFGDOV.js} +2 -2
- package/dist/{agent-KXHSNUNY.js → agent-T7HRXIBL.js} +2 -2
- package/dist/{board-dashboard-QKOJEHXS.js → board-dashboard-QXYD62AT.js} +4 -4
- package/dist/{chunk-TBSPEM7I.js → chunk-2BK25FAQ.js} +2 -2
- package/dist/{chunk-QISI5WM2.js → chunk-2N6LROEF.js} +2 -2
- package/dist/{chunk-ORAQRC6A.js → chunk-4LUZO3AP.js} +2 -2
- package/dist/{chunk-3I3TBJZV.js → chunk-5OREKHSP.js} +6 -6
- package/dist/{chunk-64UGFZPX.js → chunk-5TW7QEVK.js} +2 -2
- package/dist/{chunk-KE4SLJTC.js → chunk-6YWB3XTT.js} +2 -2
- package/dist/{chunk-EM72LW2F.js → chunk-7TO4QLFS.js} +2 -2
- package/dist/{chunk-K34LYNGN.js → chunk-BTI3OUFH.js} +2 -2
- package/dist/{chunk-6RJ7ERGC.js → chunk-EVRLNHIC.js} +2 -2
- package/dist/{chunk-4MJOSO7T.js → chunk-FLSEPYM3.js} +2 -2
- package/dist/{chunk-J4AMQF7D.js → chunk-H6FFWHJH.js} +2 -2
- package/dist/{chunk-SXL6R3HH.js → chunk-HUN2UIYB.js} +2 -2
- package/dist/{chunk-LBIU3OWW.js → chunk-KAAAB3W3.js} +5 -5
- package/dist/{chunk-O672XL5L.js → chunk-KUAJUHMB.js} +2 -2
- package/dist/{chunk-W764F42W.js → chunk-LCVKEIG2.js} +2 -2
- package/dist/{chunk-APULKE2J.js → chunk-LPSDAS22.js} +2 -2
- package/dist/{chunk-AHJ6FEHW.js → chunk-MXB47GPG.js} +2 -2
- package/dist/{chunk-M6EQBW2F.js → chunk-NDBM7DTN.js} +2 -2
- package/dist/{chunk-RW2JLP5P.js → chunk-O62HITS4.js} +2 -2
- package/dist/{chunk-25U5MNNF.js → chunk-OD2GONCQ.js} +2 -2
- package/dist/{chunk-AKDJGDLN.js → chunk-ORICHN2H.js} +2 -2
- package/dist/{chunk-UBLPD6DK.js → chunk-QCCVHEKZ.js} +2 -2
- package/dist/{chunk-KOZSBUXJ.js → chunk-T4BWPILH.js} +2 -2
- package/dist/{chunk-QMFNIUW7.js → chunk-TTHY22I4.js} +2 -2
- package/dist/{chunk-BNTN3LKN.js → chunk-VVFJCGX7.js} +2 -2
- package/dist/{chunk-7VHE7WLJ.js → chunk-XDFPXEXU.js} +3 -3
- package/dist/{chunk-R5TCPLWF.js → chunk-XPL6F4HL.js} +2 -2
- package/dist/{chunk-6QVUXEVK.js → chunk-YHLKEGIC.js} +2 -2
- package/dist/{chunk-QTOOFB4N.js → chunk-YV2SLQIL.js} +2 -2
- package/dist/{chunk-QTOOFB4N.js.map → chunk-YV2SLQIL.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/{client-FXU56BIM.js → client-HJBH2DVH.js} +2 -2
- package/dist/{config-IOQKEH47.js → config-QBTOYJA7.js} +2 -2
- package/dist/{config-mutate-633Q77K3.js → config-mutate-G46QCYCR.js} +2 -2
- package/dist/{config-mutator-LRZHJ3UN.js → config-mutator-3FGEZPF3.js} +2 -2
- package/dist/{contributions-3AE43OSI.js → contributions-OOPYQSLO.js} +2 -2
- package/dist/{doctor-KCRL67QL.js → doctor-2KOQNH44.js} +2 -2
- package/dist/{follow-up-tool-WLDWTZRW.js → follow-up-tool-K252F4QA.js} +2 -2
- package/dist/{hub-PG4OFRIQ.js → hub-E56MSG7W.js} +2 -2
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/{program-QHE7PH65.js → program-3NLSKRKW.js} +23 -23
- package/dist/{promote-DLM7N6V2.js → promote-GWDQR2DT.js} +2 -2
- package/dist/{query-TBQGAIZG.js → query-PYJN4G32.js} +2 -2
- package/dist/{query-settings-U6XNO5V4.js → query-settings-XFOY343Z.js} +2 -2
- package/dist/{registry-DGGJJOVA.js → registry-EMB3QRRL.js} +2 -2
- package/dist/{request-planner-YQ4RTZNU.js → request-planner-DP3PIMNQ.js} +2 -2
- package/dist/{review-candidates-OE5HDVWI.js → review-candidates-5HRRFPEG.js} +2 -2
- package/dist/{routing-RAG6I37K.js → routing-LX5QYMZW.js} +2 -2
- package/dist/schedule-tool-HD72JVUS.js +2 -0
- package/dist/{scheduler-TGP4B5KZ.js → scheduler-UN5ZPEK4.js} +2 -2
- package/dist/{seat-74G2KLZQ.js → seat-2RFBH5N2.js} +2 -2
- package/dist/{select-P7565K5D.js → select-MOZ2GNNR.js} +2 -2
- package/dist/{set-enabled-DE3TKKEK.js → set-enabled-IFK2TCH5.js} +2 -2
- package/dist/{sprint-tool-CK3SD4NZ.js → sprint-tool-WB2M7RHX.js} +2 -2
- package/dist/{tool-X6DAR3KL.js → tool-57ZGZ7BD.js} +2 -2
- package/dist/{tool-XGB3PMXA.js → tool-CMHNG2PN.js} +2 -2
- package/dist/{tool-DWKCESVE.js → tool-SKQNMJP2.js} +2 -2
- package/dist/{wiki-E45S2K6F.js → wiki-K77I5LJP.js} +2 -2
- package/dist/wiki-enrich-PK5XQCV3.js +2 -0
- package/package.json +1 -1
- package/dist/schedule-tool-O5FJXSKO.js +0 -2
- package/dist/wiki-enrich-LREINNTK.js +0 -2
- /package/dist/{App-AUKNCAVD.js.map → App-UHSMBGRE.js.map} +0 -0
- /package/dist/{ChatApp-KYQIQZ6Q.js.map → ChatApp-Z6YVST7J.js.map} +0 -0
- /package/dist/{absorb-eval-TJN5WUYZ.js.map → absorb-eval-4GDAAYBL.js.map} +0 -0
- /package/dist/{adapter-VLNSNP6C.js.map → adapter-IITFGDOV.js.map} +0 -0
- /package/dist/{agent-KXHSNUNY.js.map → agent-T7HRXIBL.js.map} +0 -0
- /package/dist/{board-dashboard-QKOJEHXS.js.map → board-dashboard-QXYD62AT.js.map} +0 -0
- /package/dist/{chunk-TBSPEM7I.js.map → chunk-2BK25FAQ.js.map} +0 -0
- /package/dist/{chunk-QISI5WM2.js.map → chunk-2N6LROEF.js.map} +0 -0
- /package/dist/{chunk-ORAQRC6A.js.map → chunk-4LUZO3AP.js.map} +0 -0
- /package/dist/{chunk-3I3TBJZV.js.map → chunk-5OREKHSP.js.map} +0 -0
- /package/dist/{chunk-64UGFZPX.js.map → chunk-5TW7QEVK.js.map} +0 -0
- /package/dist/{chunk-KE4SLJTC.js.map → chunk-6YWB3XTT.js.map} +0 -0
- /package/dist/{chunk-EM72LW2F.js.map → chunk-7TO4QLFS.js.map} +0 -0
- /package/dist/{chunk-K34LYNGN.js.map → chunk-BTI3OUFH.js.map} +0 -0
- /package/dist/{chunk-6RJ7ERGC.js.map → chunk-EVRLNHIC.js.map} +0 -0
- /package/dist/{chunk-4MJOSO7T.js.map → chunk-FLSEPYM3.js.map} +0 -0
- /package/dist/{chunk-J4AMQF7D.js.map → chunk-H6FFWHJH.js.map} +0 -0
- /package/dist/{chunk-SXL6R3HH.js.map → chunk-HUN2UIYB.js.map} +0 -0
- /package/dist/{chunk-LBIU3OWW.js.map → chunk-KAAAB3W3.js.map} +0 -0
- /package/dist/{chunk-O672XL5L.js.map → chunk-KUAJUHMB.js.map} +0 -0
- /package/dist/{chunk-W764F42W.js.map → chunk-LCVKEIG2.js.map} +0 -0
- /package/dist/{chunk-APULKE2J.js.map → chunk-LPSDAS22.js.map} +0 -0
- /package/dist/{chunk-AHJ6FEHW.js.map → chunk-MXB47GPG.js.map} +0 -0
- /package/dist/{chunk-M6EQBW2F.js.map → chunk-NDBM7DTN.js.map} +0 -0
- /package/dist/{chunk-RW2JLP5P.js.map → chunk-O62HITS4.js.map} +0 -0
- /package/dist/{chunk-25U5MNNF.js.map → chunk-OD2GONCQ.js.map} +0 -0
- /package/dist/{chunk-AKDJGDLN.js.map → chunk-ORICHN2H.js.map} +0 -0
- /package/dist/{chunk-UBLPD6DK.js.map → chunk-QCCVHEKZ.js.map} +0 -0
- /package/dist/{chunk-KOZSBUXJ.js.map → chunk-T4BWPILH.js.map} +0 -0
- /package/dist/{chunk-QMFNIUW7.js.map → chunk-TTHY22I4.js.map} +0 -0
- /package/dist/{chunk-BNTN3LKN.js.map → chunk-VVFJCGX7.js.map} +0 -0
- /package/dist/{chunk-7VHE7WLJ.js.map → chunk-XDFPXEXU.js.map} +0 -0
- /package/dist/{chunk-R5TCPLWF.js.map → chunk-XPL6F4HL.js.map} +0 -0
- /package/dist/{chunk-6QVUXEVK.js.map → chunk-YHLKEGIC.js.map} +0 -0
- /package/dist/{client-FXU56BIM.js.map → client-HJBH2DVH.js.map} +0 -0
- /package/dist/{config-IOQKEH47.js.map → config-QBTOYJA7.js.map} +0 -0
- /package/dist/{config-mutate-633Q77K3.js.map → config-mutate-G46QCYCR.js.map} +0 -0
- /package/dist/{config-mutator-LRZHJ3UN.js.map → config-mutator-3FGEZPF3.js.map} +0 -0
- /package/dist/{contributions-3AE43OSI.js.map → contributions-OOPYQSLO.js.map} +0 -0
- /package/dist/{doctor-KCRL67QL.js.map → doctor-2KOQNH44.js.map} +0 -0
- /package/dist/{follow-up-tool-WLDWTZRW.js.map → follow-up-tool-K252F4QA.js.map} +0 -0
- /package/dist/{hub-PG4OFRIQ.js.map → hub-E56MSG7W.js.map} +0 -0
- /package/dist/{program-QHE7PH65.js.map → program-3NLSKRKW.js.map} +0 -0
- /package/dist/{promote-DLM7N6V2.js.map → promote-GWDQR2DT.js.map} +0 -0
- /package/dist/{query-TBQGAIZG.js.map → query-PYJN4G32.js.map} +0 -0
- /package/dist/{query-settings-U6XNO5V4.js.map → query-settings-XFOY343Z.js.map} +0 -0
- /package/dist/{registry-DGGJJOVA.js.map → registry-EMB3QRRL.js.map} +0 -0
- /package/dist/{request-planner-YQ4RTZNU.js.map → request-planner-DP3PIMNQ.js.map} +0 -0
- /package/dist/{review-candidates-OE5HDVWI.js.map → review-candidates-5HRRFPEG.js.map} +0 -0
- /package/dist/{routing-RAG6I37K.js.map → routing-LX5QYMZW.js.map} +0 -0
- /package/dist/{schedule-tool-O5FJXSKO.js.map → schedule-tool-HD72JVUS.js.map} +0 -0
- /package/dist/{scheduler-TGP4B5KZ.js.map → scheduler-UN5ZPEK4.js.map} +0 -0
- /package/dist/{seat-74G2KLZQ.js.map → seat-2RFBH5N2.js.map} +0 -0
- /package/dist/{select-P7565K5D.js.map → select-MOZ2GNNR.js.map} +0 -0
- /package/dist/{set-enabled-DE3TKKEK.js.map → set-enabled-IFK2TCH5.js.map} +0 -0
- /package/dist/{sprint-tool-CK3SD4NZ.js.map → sprint-tool-WB2M7RHX.js.map} +0 -0
- /package/dist/{tool-X6DAR3KL.js.map → tool-57ZGZ7BD.js.map} +0 -0
- /package/dist/{tool-XGB3PMXA.js.map → tool-CMHNG2PN.js.map} +0 -0
- /package/dist/{tool-DWKCESVE.js.map → tool-SKQNMJP2.js.map} +0 -0
- /package/dist/{wiki-E45S2K6F.js.map → wiki-K77I5LJP.js.map} +0 -0
- /package/dist/{wiki-enrich-LREINNTK.js.map → wiki-enrich-PK5XQCV3.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Uh,b as Zi,g as Wh}from"./chunk-
|
|
1
|
+
import{a as Uh,b as Zi,g as Wh}from"./chunk-2N6LROEF.js";import{b as Lh}from"./chunk-YHLKEGIC.js";import{B as sh,C as rh,D as lh,E as dh,G as uh,I as gh,J as mh,K as xl,L as ph,W as fh,X as hh,Y as Sl,Z as wh,aa as yh,ba as $h,ca as bh,da as kh,ea as Ah,fa as Eh,g as Hf,ga as Rh,h as Gf,ha as Ch,ia as Th,ja as Oh,l as zf,la as Al,m as Yf,ma as Ih,o as Kf,oa as Nh,pa as jh,q as Rs,qa as _h,r as Cs,s as Xf,t as Vf,u as Qf,v as Zf,w as eh,x as th,z as co}from"./chunk-7TO4QLFS.js";import{n as El}from"./chunk-LCVKEIG2.js";import{a as Ph,b as Dh,d as Ar,e as Mh}from"./chunk-HUN2UIYB.js";import{a as qh,b as Fh}from"./chunk-MXB47GPG.js";import"./chunk-EFGAPAYZ.js";import{d as ih,e as vl,h as ah,i as ch}from"./chunk-CTN4KYE6.js";import{a as vh,c as xh,d as Sh}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as Pt}from"./chunk-FLSEPYM3.js";import{a as oh,c as nh}from"./chunk-6YWB3XTT.js";import{a as bl}from"./chunk-LNY6N73E.js";import{a as Wm,b as Qc}from"./chunk-GMP2IB4E.js";import{a as zc,b as xm}from"./chunk-RKPAVWXF.js";import{$ as hf,A as Wp,Aa as ut,B as il,Ba as Ki,C as Bp,Ca as Xi,D as Jp,Da as Sr,E as Hp,Ea as wl,F as Gp,Fa as qf,G as zp,Ga as Uf,H as Yp,Ha as $l,I as al,Ia as Bf,J as Kp,Ja as Vi,K as Wi,Ka as Es,L as Xp,La as Qi,M as cl,Ma as kl,N as Vp,Na as Jf,O as Qp,P as Zp,Q as ef,R as tf,S as Bi,T as af,U as df,V as uf,W as gf,X as mf,Y as pf,Z as dl,_ as ff,a as zm,aa as wf,b as Ym,ba as yf,ca as $f,da as bf,ea as kf,fa as vf,ga as xf,h as Ti,ha as Of,i as Qm,ia as Gi,j as $r,ja as Co,k as Oi,ka as Ho,l as ep,la as xs,m as op,ma as zi,n as wp,na as Yi,o as yp,oa as hl,p as Di,pa as If,q as nl,qa as Nf,r as Ap,ra as jf,s as Dp,sa as _f,t as Mp,ta as Pf,u as Lp,ua as Df,v as qp,va as Ss,w as Ui,wa as As,x as Fp,xa as Mf,y as Up,ya as xr,z as rl,za as Lf}from"./chunk-5OREKHSP.js";import{$a as Jo,$b as ao,Mb as Ff,Nb as yl,Pa as kr,Q as Ip,S as br,Sa as ul,T as Np,Ta as Ji,Ua as Sf,W as jp,X as Fi,ab as Af,bb as gl,bc as Wf,db as ml,ea as of,fa as nf,fb as Ef,ga as sf,gb as Rf,ha as ll,hb as vr,ka as rf,lb as Hi,ob as Cf,pb as Tf,qb as pl,v as tp,xb as fl}from"./chunk-ORICHN2H.js";import"./chunk-GTJIKXDB.js";import{a as Km,c as el,e as Xm,f as Vm}from"./chunk-VVFJCGX7.js";import"./chunk-ZVP6GB4G.js";import{A as lp,B as dp,C as up,D as gp,E as mp,F as pp,K as ji,L as fp,M as hp,Q as _p,R as Pp,a as Hc,b as wm,e as ym,f as $m,o as np,s as Ii,t as Ni,u as sp,v as rp,w as ip,y as ap,z as cp}from"./chunk-OD2GONCQ.js";import"./chunk-IMLAPB7G.js";import"./chunk-VZLIBDLH.js";import{a as cf,b as lf}from"./chunk-EKJG63EJ.js";import"./chunk-T4BWPILH.js";import{c as $p}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import{c as ol}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as bp,e as _i,g as Pi}from"./chunk-LQE73AZR.js";import{a as kp,b as vp,c as xp,d as Sp}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-BIYEGA7Q.js";import{d as Ep,e as bn,f as Rp,g as Mi,j as Cp,k as Tp,m as Op,n as sl,q as Li,r as Ro,s as qi}from"./chunk-XPZSEDE3.js";import"./chunk-PPUN7YHA.js";import"./chunk-A5GYG56I.js";import{a as tl,p as Zm}from"./chunk-KUAJUHMB.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as _t}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-6TTGRTDO.js";import{a as io}from"./chunk-MNG2AMKZ.js";import{a as Im,b as Nm,c as jm,d as _m,e as Kc,f as Pm,g as Xc,h as Vc,l as Dm,m as Mm}from"./chunk-RX5O5637.js";import{f as Lm,i as qm,l as Fm,m as Um}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{m as Bm,n as Jm,o as Zc,p as Ci,q as Hm,r as Gm}from"./chunk-2BK25FAQ.js";import{a as Gc,d as bm,e as Ri}from"./chunk-QPABR72X.js";import{a as yr,e as Sm,f as Am,g as Yc,i as Em,j as Rm,l as Cm,m as Tm,n as Om}from"./chunk-4LUZO3AP.js";import{b as vs,e as vm}from"./chunk-IFUAP7UD.js";import{c as km}from"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{$ as pm,Ca as hm,D as Fc,E as Vg,S as Bo,Y as gm,aa as fm,g as Ug,r as Wg,s as Bg,t as Jg}from"./chunk-KAAAB3W3.js";import{I as ws,J as Ai,K as Ei,L as ys,M as Zg,N as Uo,P as Wo,b as hs,fa as dm,r as Ao,s as Uc,t as Qg,u as Wc,ua as um,w as Eo,wa as mm,x as Si}from"./chunk-BTI3OUFH.js";import{b as yn}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-5TW7QEVK.js";import"./chunk-SFQUP3BP.js";import{a as $s}from"./chunk-GV7S5BAX.js";import{c as tm}from"./chunk-SZDACK6O.js";import{f as om,g as nm,h as Bc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as rm,f as $n,k as bs}from"./chunk-VJVXEVZ7.js";import{a as Kg,l as sm,o as lm}from"./chunk-TTHY22I4.js";import{a as wt,b as me,c as We,d as ks,e as im}from"./chunk-O62HITS4.js";import{a as am,b as Jc,h as cm}from"./chunk-3UOTLMXD.js";import"./chunk-VWTBHLMX.js";import{i as Gg,j as zg}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as qc,b as Yg}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Xg}from"./chunk-X5C5W3E4.js";import{e as em}from"./chunk-GSX4NK2N.js";import"./chunk-HPRLRD4P.js";import{a as Lc}from"./chunk-XPL6F4HL.js";import"./chunk-QCCVHEKZ.js";import{c as Hg}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-XDFPXEXU.js";import"./chunk-JTFCU5LH.js";import{g as Fo,i as xi}from"./chunk-NDBM7DTN.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-H6FFWHJH.js";import{a as Ic,b as lg,c as n0,d as fi,e as dg,f as jg,g as m0,h as _g,i as p0,m as fs,n as Dg,q as Mg,u as Lg,y as ro,z as wr}from"./chunk-EVRLNHIC.js";import{a as So,b as ps,e as Og,f as hr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as vi,b as Pg}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as qo,j as qg}from"./chunk-QUFIUXMQ.js";import{n as Fg}from"./chunk-AV7T3SYT.js";import"./chunk-2HBEZV7L.js";import"./chunk-A7JSRDJL.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as so,b as o0}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{A as i0,Cb as bi,Db as fr,Eb as O,Hb as ki,J as jc,Ja as Ag,K as a0,Na as l0,Ob as te,Wa as Eg,Xa as wn,Y as $g,Z as c0,Za as Pc,ca as yi,da as $i,eb as Dc,f as hi,fb as Mc,g as ug,ga as bg,h as fn,hb as Rg,i as Nc,ia as kg,ib as d0,ja as ms,k as gg,ka as _c,l as wi,m as s0,ob as Tg,ra as vg,ta as xg,u as pg,ua as Sg,v as fg,w as hg,y as wg,z as yg}from"./chunk-YV2SLQIL.js";import"./chunk-VJ5HC63R.js";import{j as dt,r as hn}from"./chunk-UEEB3UTU.js";import{a as Cg,c as u0}from"./chunk-YSCT6DPR.js";import{a as mg,e as r0}from"./chunk-VQRY4IDI.js";import{g as Ig,k as Ng,l as g0}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as f0}from"commander";var Bh=new f0().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 Ym({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()});te();import{Command as h0}from"commander";import{execFileSync as lo}from"node:child_process";import{cpSync as Jh,existsSync as Tl,mkdirSync as Rl,mkdtempSync as w0,readdirSync as y0,rmSync as Hh,writeFileSync as Gh}from"node:fs";import{dirname as zh,join as gt}from"node:path";import{homedir as ea,release as $0,tmpdir as b0}from"node:os";import{setTimeout as k0}from"node:timers/promises";function ta(){let e=sp(process.platform,process.arch,$0());if(e)throw new Error(e)}function oa(){let e=gt(ea(),"Library/LaunchAgents"),t=[];try{t=y0(e).filter(ap)}catch{}let o=t.flatMap(n=>{let s=gt(e,n);try{return[{file:s,plist:lo("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return cp(e,o)}function Er(e){return`gui/${process.getuid()}/${e.label}`}async function Cl(e){try{lo("launchctl",["bootout",Er(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{lo("launchctl",["print",Er(e)],{stdio:"pipe"})}catch{return}await k0(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Yh(e){if(!Tl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{lo("launchctl",["print",Er(e)],{stdio:"pipe"})}catch{t=!1}t||lo("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),lo("launchctl",["kickstart",Er(e)],{stdio:"pipe"})}function v0(){let e=pp();if(e&&Tl(gt(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 Ts=new h0("desktop").description("install and control the macOS desktop assistant");Ts.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=>{ta();let t=O(),o=rp(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=v0(),i=gt(ea(),"Applications"),{keep:a,remove:c}=oa();if(console.log(`Desktop assistant \u2192 ${gt(i,Ii)}
|
|
2
2
|
Computer-use helper \u2192 ${gt(i,Ni)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -65,7 +65,7 @@ Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choos
|
|
|
65
65
|
`)[0]}. Run this from the folder that holds agentx.json.`),!1}let n=e==="agent"?!!o.agents?.[t]:t===wn||(o.people??[]).some(s=>s.id===t);return n||Tn(e==="agent"?`No agent "${t}" in agentx.json.`:`No person "${t}" in agentx.json: agentx people list`),n}async function Ny(e,t,o){if(Iy(e,t))try{await Fm(process.cwd(),e,t,Wm(o)),console.log(Cn.green(` \u2713 picture set for ${e} "${t}". Pages show it on their next load.`))}catch(n){if(n instanceof Lm){Tn(n.message);return}throw n}}function jy(e,t){Iy(e,t)&&console.log(Um(process.cwd(),e,t)?Cn.green(` \u2713 picture removed for ${e} "${t}"; the initials show again.`):Cn.dim(` ${e} "${t}" has no picture.`))}function td(e){let t=e.agent?.trim()||Eo();return t||Tn("Say which agent: --agent <id>"),t}function _y(){let e=new Oy("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(Eo()){let s=await Qc(t,o.agent?.trim(),{daemonUrl:Ty()});return s.ok?console.log(Cn.green(` \u2713 ${s.message}`)):Tn(s.message)}let n=td(o);n&&await Ny("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(Eo()){let n=await Qc(null,t.agent?.trim(),{daemonUrl:Ty()});return n.ok?console.log(Cn.green(` \u2713 ${n.message}`)):Tn(n.message)}let o=td(t);o&&jy("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=td(t);if(!o)return;let n=qm(process.cwd(),"agent",o);console.log(n?` ${o}: picture set (.agentx/pictures/agent/${o}.${n}.webp)`:Cn.dim(` ${o}: no picture, the initials show`))}),e}function Py(){let e=new Oy("picture").description("a person's profile picture: set or remove (the owner only)"),t=()=>{let o=Eo();return o&&Tn(`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 Ny("person",o,n)}),e.command("remove <id>").alias("rm").description("remove the picture: the initials show again").action(o=>{t()&&jy("person",o)}),e}function Ie(){let e=de(process.cwd(),"agentx.json");if(!ze(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Yo(e,"utf-8"))}function yt(e){return me(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error($.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error($.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error($.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var po=new mo().name("agent").description("manage agents \u2014 add, list, remove, pause, resume");po.command("list").alias("ls").description("list configured agents").action(()=>{let e=Ie();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${$.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log($.dim(` workspace: ${o.workspace}`)),n&&console.log($.dim(` mentions: ${n}`))}console.log()});po.command("add").description("add a new agent interactively").action(async()=>{let e=Ie(),t=await ct([{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:de(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:zo(t.workspace,t.id);go(de(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-HAV4CQV7.js"),r=s(t.id,n,"19900",(...u)=>{console.log($.dim(` ${u.join(" ")}`))}),i=de(process.cwd(),"src/wiki/SKILL.md"),a=de(AA(EA(import.meta.url)),"../wiki/SKILL.md"),c=ze(i)?i:a;ze(c)&&(go(de(o,".claude/skills/wiki"),{recursive:!0}),od(c,de(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await yt(e),console.log($.green(`
|
|
66
66
|
Agent "${t.id}" added`)),console.log($.dim(` Workspace: ${o}`)),console.log($.dim(` Created: ${r.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`));let l=Si(Ao(),[t.id]);l&&console.log($.yellow(` Created by agent "${l}": it starts once the owner approves it (agentx approvals approve agent:${t.id}).`)),console.log()});po.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=Ie();if(!t.agents?.[e]){console.log($.red(` Agent "${e}" not found`));return}delete t.agents[e],await yt(t),Wc(Ao(),e),console.log($.green(` Agent "${e}" removed from config (workspace preserved)`))});po.addCommand(_y());function Dy(e){let t=Eo();return t?(console.log($.red(` Only the owner can ${e}; agent "${t}" asked. Ask the owner, or raise a card.`)),process.exitCode=1,!1):!0}po.command("pause <id>").description("pause an agent: it starts no run until resumed (applies at once)").action(e=>{if(Dy("pause an agent")){if(!Ie().agents?.[e]){console.log($.red(` Agent "${e}" not found`)),process.exitCode=1;return}if(Uc(Ao())[e]?.kind==="approval"){console.log($.yellow(` "${e}" waits for your approval and does not run yet: agentx approvals list`));return}Qg(Ao(),e,"paused","the owner"),console.log($.green(` "${e}" paused. Messages and schedules for it are refused until you run: agentx agent resume ${e}`))}});po.command("resume <id>").description("resume a paused agent").action(e=>{if(!Dy("resume an agent"))return;let t=Uc(Ao())[e];if(t?.kind==="approval"){console.log($.yellow(` "${e}" was created by ${t.by} and waits for your approval: agentx approvals approve agent:${e}`));return}console.log(Wc(Ao(),e,"paused")?$.green(` "${e}" resumed`):$.dim(` "${e}" was not paused`))});po.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=Ie(),n=o.agents?.[e];if(n||(console.log($.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log($.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):$.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":$.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||$.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($.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($.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($.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($.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=r,s.push(`maxExecutionMinutes=${r}`)}s.length===0&&(console.log($.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await yt(o),console.log($.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log($.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Dr=new mo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Dr.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,t)=>{let n=Ie().agents?.[e];n||(console.log($.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($.dim(`
|
|
67
67
|
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
68
|
-
`));return}console.log(),console.log($.bold(` ${e}`));for(let r of s){let i=r.enabled!==!1,a=[],c=r.credentials??{};for(let[u,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?$.green(`${u}:${d}=set`):$.yellow(`${u}:${d}=UNSET`)):u==="auth"&&d==="keyring"?a.push($.dim("auth:keyring")):u==="sessionDir"&&typeof d=="string"&&a.push($.dim(`sessionDir:${d}`));let l=Object.entries(r.metadata??{}).map(([u,d])=>`${u}=${d}`).join(" ");console.log(` ${i?$.cyan(r.kind.padEnd(14)):$.dim(r.kind.padEnd(14))} ${$.bold(r.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${$.dim(l)}`),i||console.log(` ${$.dim("(disabled)")}`)}console.log()});Dr.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=Ie();o.agents?.[e]||(console.log($.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-IOQKEH47.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await ct({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),r||(console.log($.red(" --kind is required")),process.exit(1));let i=String(t.label||"").trim();!i&&n&&(i=((await ct({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),i||(console.log($.red(" --label is required")),process.exit(1));let a=String(t.tokenEnv||"").trim(),c=String(t.auth||"").trim(),l=String(t.sessionDir||"").trim();if(!a&&!c&&!l&&n){let p=await ct({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 ct({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():p.scheme==="keyring"?c="keyring":p.scheme==="sessionDir"&&(l=((await ct({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 ct({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,...w]=f.split("=");g&&(u[g.trim()]=w.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log($.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log($.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($.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 yt(o),console.log($.green(` \u2713 ${e}: added ${r} integration "${i}"`)),a&&!process.env[a]&&console.log($.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Dr.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=Ie(),n=o.agents?.[e];n||(console.log($.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[r,i]=t.includes(":")?t.split(":",2):[t,""],a=s.findIndex(l=>l.kind===r&&(!i||l.label===i)||l.label===t);a===-1&&(console.log($.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await yt(o),console.log($.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Dr.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=Ie().agents?.[e];n||(console.log($.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($.yellow(" no integrations to test"));return}let i=0;console.log();for(let a of r){let c=a.credentials??{},l=[];for(let[u,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${u}: env var ${d} is unset`);if(l.length){i+=1,console.log(` ${$.red("\u2717")} ${a.kind} "${a.label}"`);for(let u of l)console.log(` ${$.dim(u)}`)}else console.log(` ${$.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),i>0&&process.exit(1)});po.addCommand(Dr);var ha=new mo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");ha.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Ie();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log($.bold(" Telegram:"));for(let[r,i]of Object.entries(t.accounts||{}))console.log(` ${$.cyan(r)} -> agent: ${i.agentBinding}`)}else console.log($.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log($.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let r of o.routes||[]){let i=r.contact?`contact ${r.contact}`:`group "${r.group}"`;console.log(` ${i} -> agent: ${r.agent}`)}}else console.log($.dim(" WhatsApp: disabled"));let n=e.channels?.email;if(n?.enabled&&Object.keys(n.accounts||{}).length){console.log($.bold(" Email:"));for(let[r,i]of Object.entries(n.accounts))console.log(` ${r}: ${i.address} -> agent: ${i.agent}, replies ${i.send==="auto"?"sent at once":"wait for approval"}`)}else console.log($.dim(" Email: disabled (agentx connect email)"));let s=e.channels?.gitlab;if(s?.enabled){console.log($.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let r of s.routes||[])console.log(` ${r.project} -> agent: ${r.agent}`)}else console.log($.dim(" GitLab: disabled"));console.log()});ha.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=Ie(),t=Object.keys(e.agents||{});if(!t.length){console.log($.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await ct({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await ct([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:o}]);if(!s.accountName||!s.token)return;try{let i=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!i.ok)throw new Error(i.description);console.log($.green(` Bot verified: @${i.result.username}`));let a=`@${i.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,i.result.username),e.agents[s.agentBinding].mentions=c)}catch(r){console.log($.red(` Invalid token: ${r.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await yt(e),console.log($.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await ct([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let r=[],i=s.addRoute;for(;i;){let a=await ct([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&r.push({[a.type]:a.value,agent:a.agent}),i=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:r},await yt(e),go(de(process.cwd(),s.sessionDir),{recursive:!0}),console.log($.green(` WhatsApp enabled (${r.length} routes, default: ${s.defaultAgent})`)),console.log($.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await ct([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let r=[],i=s.addRoute;for(;i;){let a=await ct([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&r.push({project:a.project,agent:a.agent}),i=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:r},await yt(e),console.log($.green(` GitLab enabled (${r.length} routes, webhook :${s.webhookPort})`)),console.log($.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log($.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log($.dim(` Secret token: ${s.webhookSecret}`)),console.log($.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log($.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var qs=new mo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");qs.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Ie();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?$.green("\u25CF"):$.dim("\u25CB");console.log(` ${n} ${$.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log($.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log($.dim(" No cron jobs configured")),console.log()});qs.command("add").description("add a cron job").action(async()=>{let e=Ie(),t=Object.keys(e.agents||{}),o=await ct([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:t.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await yt(e),console.log($.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});qs.command("enable <id>").description("enable a cron job").action(async e=>{let t=Ie();if(!t.crons?.[e]){console.log($.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log($.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await yt(t),console.log($.green(` Cron "${e}" enabled`))});qs.command("disable <id>").description("disable a cron job").action(async e=>{let t=Ie();if(!t.crons?.[e]){console.log($.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await yt(t),console.log($.green(` Cron "${e}" disabled`))});var Lt=new mo().name("mesh").description("manage mesh peers \u2014 add, list, remove");Lt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Ie();if(console.log(),!e.mesh?.enabled)console.log($.dim(" Mesh: disabled"));else{console.log($.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=$.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=$.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${$.cyan(t.name)} ${$.dim(t.url)} ${o}`)}}console.log()});Lt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Ie(),t=await ct([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log($.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log($.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:t.url,name:t.name,...t.token?{token:t.token}:{}}),await yt(e),console.log($.green(` Peer "${t.name}" added`)),console.log()}});Lt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=Ie();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await yt(t),console.log($.green(` Peer "${e}" removed`)))});Lt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let t=Ie();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log($.red(" --interval must be 5..3600 seconds")),process.exit(1)),t.mesh.healthCheck.interval=n,o.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log($.red(" --timeout must be 1..60 seconds")),process.exit(1)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log($.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await yt(t),console.log($.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log($.dim(" Restart the daemon for the new cadence to take effect."))});Lt.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,t)=>{let o=t.node||"";if(!o)try{o=O().dashboard?.daemonUrl||""}catch{}o=(o||"http://localhost:18800").replace(/\/+$/,"");let n=t.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let r=await fetch(`${o}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...t.by?{by:t.by}:{}}),signal:AbortSignal.timeout(1e4)}),i=await r.json().catch(()=>({}));r.ok||(console.log($.red(` Announcement refused (${r.status}): ${i.error||"unknown error"}`)),process.exit(1)),console.log($.green(` \u2713 Announced from ${i.event?.node??"this machine"}`)+$.dim(` (event ${i.event?.id??"?"})`))}catch(r){console.log($.red(` Could not reach the daemon at ${o}: ${r?.message||r}`)),process.exit(1)}});var My=e=>{let t=e||"";if(!t)try{t=O().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function wa(e,t,o={}){let n=My(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let r=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:s,body:JSON.stringify(o),signal:AbortSignal.timeout(15e3)}),i=await r.json().catch(()=>({}));r.ok||(console.log($.red(` ${i.error||`HTTP ${r.status}`}`)),process.exit(1));let a=i.grant;console.log($.green(` \u2713 ${a?.name??e}: ${a?.state}${i.stopped?`, ${i.stopped} running turn(s) stopped`:""}`))}catch(r){console.log($.red(` Could not reach the daemon at ${n}: ${r?.message||r}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var On=Lt.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");On.command("invite").description("open a grant to a guest mesh and print the one-time code it joins with").requiredOption("--name <name>",'what you call it, e.g. "Support session for company X"').requiredOption("--guest <name>","the other organisation's name").requiredOption("--agent <id>","the agent of this node that works for them").option("--folders <list>","folders that agent may touch for them, comma-separated").option("--skills <list>","skills it may use for them, comma-separated").option("--commands <list>","commands it may run for them, comma-separated").option("--level <level>","report (read only) | propose (no merge, deploy or delete) | act","propose").option("--days <n>","how long the grant lasts (1 to 365)","7").option("--url <origin>","the address the guest reaches this node on (default: dashboard.daemonUrl)").action(async e=>{let{TokenStore:t}=await import("./token-store-F2PHHO5A.js"),{PairCodeStore:o,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:r}=await import("./grants-3UVDASRI.js"),i=O(),a=r({tokens:new t,codes:new o,guests:new s,hasAgent:l=>!!i.agents[l]},{name:e.name,guest:e.guest,agentId:e.agent,folders:e.folders?.split(","),skills:e.skills?.split(","),commands:e.commands?.split(","),level:e.level,days:Number(e.days)});a.ok||(console.log($.red(` ${a.error}`)),process.exit(1));let c=(e.url||My()).replace(/\/+$/,"");console.log(),console.log(` Grant ${$.bold(a.grant.name)} for ${$.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log($.dim(` id ${a.grant.id} \xB7 folders: ${a.grant.folders.join(", ")||"none"} \xB7 skills: ${a.grant.skills.join(", ")||"none"} \xB7 commands: ${a.grant.commands.join(", ")||"none"}`)),console.log(),console.log(" Send the guest this address and code. The code works once, for 10 minutes:"),console.log(),console.log(` ${$.cyan(c)}`),console.log(` ${$.bold(n(a.code))}`),console.log(),console.log(` They run: ${$.cyan(`agentx mesh join ${c} --code ${n(a.code)} --name <what-they-call-you>`)}`),console.log(` When they join, a card "Guest mesh: ${a.grant.guest} wants to join" asks you to approve it.`),console.log()});On.command("list",{isDefault:!0}).alias("ls").description("every grant: state, guest, agent, level, end date, usage").option("--json","machine-readable output").action(async e=>{let{GuestStore:t}=await import("./store-7W2AP5H4.js"),o=new t().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log($.dim(`
|
|
68
|
+
`));return}console.log(),console.log($.bold(` ${e}`));for(let r of s){let i=r.enabled!==!1,a=[],c=r.credentials??{};for(let[u,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?$.green(`${u}:${d}=set`):$.yellow(`${u}:${d}=UNSET`)):u==="auth"&&d==="keyring"?a.push($.dim("auth:keyring")):u==="sessionDir"&&typeof d=="string"&&a.push($.dim(`sessionDir:${d}`));let l=Object.entries(r.metadata??{}).map(([u,d])=>`${u}=${d}`).join(" ");console.log(` ${i?$.cyan(r.kind.padEnd(14)):$.dim(r.kind.padEnd(14))} ${$.bold(r.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${$.dim(l)}`),i||console.log(` ${$.dim("(disabled)")}`)}console.log()});Dr.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=Ie();o.agents?.[e]||(console.log($.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-QBTOYJA7.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await ct({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),r||(console.log($.red(" --kind is required")),process.exit(1));let i=String(t.label||"").trim();!i&&n&&(i=((await ct({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),i||(console.log($.red(" --label is required")),process.exit(1));let a=String(t.tokenEnv||"").trim(),c=String(t.auth||"").trim(),l=String(t.sessionDir||"").trim();if(!a&&!c&&!l&&n){let p=await ct({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 ct({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():p.scheme==="keyring"?c="keyring":p.scheme==="sessionDir"&&(l=((await ct({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 ct({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,...w]=f.split("=");g&&(u[g.trim()]=w.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log($.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log($.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($.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 yt(o),console.log($.green(` \u2713 ${e}: added ${r} integration "${i}"`)),a&&!process.env[a]&&console.log($.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Dr.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=Ie(),n=o.agents?.[e];n||(console.log($.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[r,i]=t.includes(":")?t.split(":",2):[t,""],a=s.findIndex(l=>l.kind===r&&(!i||l.label===i)||l.label===t);a===-1&&(console.log($.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await yt(o),console.log($.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Dr.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=Ie().agents?.[e];n||(console.log($.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($.yellow(" no integrations to test"));return}let i=0;console.log();for(let a of r){let c=a.credentials??{},l=[];for(let[u,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${u}: env var ${d} is unset`);if(l.length){i+=1,console.log(` ${$.red("\u2717")} ${a.kind} "${a.label}"`);for(let u of l)console.log(` ${$.dim(u)}`)}else console.log(` ${$.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),i>0&&process.exit(1)});po.addCommand(Dr);var ha=new mo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");ha.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Ie();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log($.bold(" Telegram:"));for(let[r,i]of Object.entries(t.accounts||{}))console.log(` ${$.cyan(r)} -> agent: ${i.agentBinding}`)}else console.log($.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log($.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let r of o.routes||[]){let i=r.contact?`contact ${r.contact}`:`group "${r.group}"`;console.log(` ${i} -> agent: ${r.agent}`)}}else console.log($.dim(" WhatsApp: disabled"));let n=e.channels?.email;if(n?.enabled&&Object.keys(n.accounts||{}).length){console.log($.bold(" Email:"));for(let[r,i]of Object.entries(n.accounts))console.log(` ${r}: ${i.address} -> agent: ${i.agent}, replies ${i.send==="auto"?"sent at once":"wait for approval"}`)}else console.log($.dim(" Email: disabled (agentx connect email)"));let s=e.channels?.gitlab;if(s?.enabled){console.log($.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let r of s.routes||[])console.log(` ${r.project} -> agent: ${r.agent}`)}else console.log($.dim(" GitLab: disabled"));console.log()});ha.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=Ie(),t=Object.keys(e.agents||{});if(!t.length){console.log($.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await ct({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await ct([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:o}]);if(!s.accountName||!s.token)return;try{let i=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!i.ok)throw new Error(i.description);console.log($.green(` Bot verified: @${i.result.username}`));let a=`@${i.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,i.result.username),e.agents[s.agentBinding].mentions=c)}catch(r){console.log($.red(` Invalid token: ${r.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await yt(e),console.log($.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await ct([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let r=[],i=s.addRoute;for(;i;){let a=await ct([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&r.push({[a.type]:a.value,agent:a.agent}),i=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:r},await yt(e),go(de(process.cwd(),s.sessionDir),{recursive:!0}),console.log($.green(` WhatsApp enabled (${r.length} routes, default: ${s.defaultAgent})`)),console.log($.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await ct([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let r=[],i=s.addRoute;for(;i;){let a=await ct([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&r.push({project:a.project,agent:a.agent}),i=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:r},await yt(e),console.log($.green(` GitLab enabled (${r.length} routes, webhook :${s.webhookPort})`)),console.log($.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log($.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log($.dim(` Secret token: ${s.webhookSecret}`)),console.log($.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log($.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var qs=new mo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");qs.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Ie();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?$.green("\u25CF"):$.dim("\u25CB");console.log(` ${n} ${$.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log($.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log($.dim(" No cron jobs configured")),console.log()});qs.command("add").description("add a cron job").action(async()=>{let e=Ie(),t=Object.keys(e.agents||{}),o=await ct([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:t.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await yt(e),console.log($.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});qs.command("enable <id>").description("enable a cron job").action(async e=>{let t=Ie();if(!t.crons?.[e]){console.log($.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log($.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await yt(t),console.log($.green(` Cron "${e}" enabled`))});qs.command("disable <id>").description("disable a cron job").action(async e=>{let t=Ie();if(!t.crons?.[e]){console.log($.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await yt(t),console.log($.green(` Cron "${e}" disabled`))});var Lt=new mo().name("mesh").description("manage mesh peers \u2014 add, list, remove");Lt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Ie();if(console.log(),!e.mesh?.enabled)console.log($.dim(" Mesh: disabled"));else{console.log($.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=$.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=$.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${$.cyan(t.name)} ${$.dim(t.url)} ${o}`)}}console.log()});Lt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Ie(),t=await ct([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log($.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log($.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:t.url,name:t.name,...t.token?{token:t.token}:{}}),await yt(e),console.log($.green(` Peer "${t.name}" added`)),console.log()}});Lt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=Ie();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await yt(t),console.log($.green(` Peer "${e}" removed`)))});Lt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let t=Ie();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log($.red(" --interval must be 5..3600 seconds")),process.exit(1)),t.mesh.healthCheck.interval=n,o.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log($.red(" --timeout must be 1..60 seconds")),process.exit(1)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log($.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await yt(t),console.log($.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log($.dim(" Restart the daemon for the new cadence to take effect."))});Lt.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,t)=>{let o=t.node||"";if(!o)try{o=O().dashboard?.daemonUrl||""}catch{}o=(o||"http://localhost:18800").replace(/\/+$/,"");let n=t.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let r=await fetch(`${o}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...t.by?{by:t.by}:{}}),signal:AbortSignal.timeout(1e4)}),i=await r.json().catch(()=>({}));r.ok||(console.log($.red(` Announcement refused (${r.status}): ${i.error||"unknown error"}`)),process.exit(1)),console.log($.green(` \u2713 Announced from ${i.event?.node??"this machine"}`)+$.dim(` (event ${i.event?.id??"?"})`))}catch(r){console.log($.red(` Could not reach the daemon at ${o}: ${r?.message||r}`)),process.exit(1)}});var My=e=>{let t=e||"";if(!t)try{t=O().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function wa(e,t,o={}){let n=My(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let r=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:s,body:JSON.stringify(o),signal:AbortSignal.timeout(15e3)}),i=await r.json().catch(()=>({}));r.ok||(console.log($.red(` ${i.error||`HTTP ${r.status}`}`)),process.exit(1));let a=i.grant;console.log($.green(` \u2713 ${a?.name??e}: ${a?.state}${i.stopped?`, ${i.stopped} running turn(s) stopped`:""}`))}catch(r){console.log($.red(` Could not reach the daemon at ${n}: ${r?.message||r}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var On=Lt.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");On.command("invite").description("open a grant to a guest mesh and print the one-time code it joins with").requiredOption("--name <name>",'what you call it, e.g. "Support session for company X"').requiredOption("--guest <name>","the other organisation's name").requiredOption("--agent <id>","the agent of this node that works for them").option("--folders <list>","folders that agent may touch for them, comma-separated").option("--skills <list>","skills it may use for them, comma-separated").option("--commands <list>","commands it may run for them, comma-separated").option("--level <level>","report (read only) | propose (no merge, deploy or delete) | act","propose").option("--days <n>","how long the grant lasts (1 to 365)","7").option("--url <origin>","the address the guest reaches this node on (default: dashboard.daemonUrl)").action(async e=>{let{TokenStore:t}=await import("./token-store-F2PHHO5A.js"),{PairCodeStore:o,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:r}=await import("./grants-3UVDASRI.js"),i=O(),a=r({tokens:new t,codes:new o,guests:new s,hasAgent:l=>!!i.agents[l]},{name:e.name,guest:e.guest,agentId:e.agent,folders:e.folders?.split(","),skills:e.skills?.split(","),commands:e.commands?.split(","),level:e.level,days:Number(e.days)});a.ok||(console.log($.red(` ${a.error}`)),process.exit(1));let c=(e.url||My()).replace(/\/+$/,"");console.log(),console.log(` Grant ${$.bold(a.grant.name)} for ${$.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log($.dim(` id ${a.grant.id} \xB7 folders: ${a.grant.folders.join(", ")||"none"} \xB7 skills: ${a.grant.skills.join(", ")||"none"} \xB7 commands: ${a.grant.commands.join(", ")||"none"}`)),console.log(),console.log(" Send the guest this address and code. The code works once, for 10 minutes:"),console.log(),console.log(` ${$.cyan(c)}`),console.log(` ${$.bold(n(a.code))}`),console.log(),console.log(` They run: ${$.cyan(`agentx mesh join ${c} --code ${n(a.code)} --name <what-they-call-you>`)}`),console.log(` When they join, a card "Guest mesh: ${a.grant.guest} wants to join" asks you to approve it.`),console.log()});On.command("list",{isDefault:!0}).alias("ls").description("every grant: state, guest, agent, level, end date, usage").option("--json","machine-readable output").action(async e=>{let{GuestStore:t}=await import("./store-7W2AP5H4.js"),o=new t().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log($.dim(`
|
|
69
69
|
No guest grants. Open one: agentx mesh guests invite --name \u2026 --guest \u2026 --agent \u2026
|
|
70
70
|
`));return}console.log();for(let n of o){let s=n.state==="active"?$.green("active"):n.state==="pending"?$.yellow(n.guestNode?"waiting for your approval":"not joined yet"):n.state==="paused"?$.yellow("paused"):$.red(`ended${n.endedReason?`: ${n.endedReason}`:""}`);console.log(` ${$.cyan(n.id)} ${$.bold(n.name)} ${n.guest} \u2192 ${n.agentId} ${n.level} ${s}`),console.log($.dim(` until ${n.expiresAt.slice(0,10)} \xB7 ${n.usage.turns} turn(s), ${n.usage.tokens} tokens${n.usage.lastAt?` \xB7 last ${n.usage.lastAt.slice(0,16).replace("T"," ")} UTC`:""}${n.guestNode?.name?` \xB7 node ${n.guestNode.name}`:""}`))}console.log()});On.command("show <id>").description("one grant, what it opens and what the guest did").action(async e=>{let{GuestStore:t}=await import("./store-7W2AP5H4.js"),o=new t,n=o.get(e);n||(console.log($.red(` No grant "${e}". See \`agentx mesh guests\`.`)),process.exit(1)),console.log(),console.log(` ${$.bold(n.name)} (${n.id}) \xB7 ${n.state}`),console.log(` guest: ${n.guest}${n.guestNode?` \xB7 node ${n.guestNode.name??n.guestNode.id??"?"} at ${n.guestNode.address??"?"}`:""}`),console.log(` agent: ${n.agentId} \xB7 level: ${n.level} \xB7 until ${n.expiresAt.slice(0,10)}`),console.log(` folders: ${n.folders.join(", ")||"none"}
|
|
71
71
|
skills: ${n.skills.join(", ")||"none"}
|
|
@@ -76,7 +76,7 @@ Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choos
|
|
|
76
76
|
Not a guest anywhere. Join with: agentx mesh join <url> --code \u2026 --name \u2026
|
|
77
77
|
`));return}console.log();for(let n of o){let s=await t(n),r=s.ok?s.grant.state==="active"?$.green("active"):$.yellow(String(s.grant.state)):s.status===403?$.yellow(s.error):$.red(s.error);console.log(` ${$.cyan(n.name)} ${$.dim(n.url)} ${n.agentId} until ${n.expiresAt.slice(0,10)} ${r}`)}console.log()});Lt.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($.red(` No host "${e}". See \`agentx mesh hosts\`.`)),process.exit(1));let r=await n(s,t.join(" "));r.error&&(console.log($.red(` ${r.error}`)),process.exit(1)),console.log(`
|
|
78
78
|
${r.content}
|
|
79
|
-
`)});Lt.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($.red(` No host "${e}".`)),process.exit(1)),console.log($.green(` \u2713 Left ${e}`))});var In=new mo().name("skill").description("manage skills \u2014 add to agent(s), list");In.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=Ie(),n=de(e);if(!ze(n)){console.log($.red(` Skill not found: ${n}`));return}let s=ze(zo(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 ct({type:"multiselect",name:"agents",message:"Install to which agents?",choices:i.map(c=>({title:`${c} (${o.agents[c].name})`,value:c}))})).agents||[]}for(let i of r){let a=o.agents[i];if(!a){console.log($.yellow(` Agent "${i}" not found, skipping`));continue}let c=Rs(a.tier,a.workspace);if(!c){console.log($.yellow(` ${i}: its runtime (${a.tier}) does not use skills, skipping`));continue}let l=de(c,s);go(l,{recursive:!0}),ze(zo(n,"SKILL.md"))?od(n,l,{recursive:!0}):n.endsWith(".md")&&od(n,zo(l,"SKILL.md")),console.log($.green(` ${s} -> ${i} (${a.workspace})`))}console.log()});In.command("list").alias("ls").description("list skills per agent").action(()=>{let e=Ie();console.log();for(let[t,o]of Object.entries(e.agents||{})){if(!Rs(o.tier,o.workspace)){console.log(` ${$.cyan(t)}: ${$.dim(`(${o.tier} does not use skills)`)}`);continue}let n=Cs(o.tier,o.workspace).map(s=>s.name);console.log(` ${$.cyan(t)}: ${n.length?n.join(", "):$.dim("(none)")}`)}console.log()});In.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]:[de(n,"src",e,"SKILL.md"),de(n,"skills",e,"SKILL.md")],r=s.find(y=>ze(y));if(!r){console.log($.red(` No SKILL.md found for "${e}". Searched:`));for(let y of s)console.log($.dim(` ${y}`));return}let i=Yo(r,"utf-8"),a=o("sha256").update(i).digest("hex").slice(0,12),c=(i.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=O()}catch(y){console.log($.red(` Can't load agentx.json: ${y.message}`));return}let u=Object.entries(l.agents||{}),d=t.agent?u.filter(([y])=>y===t.agent):u;if(d.length===0){console.log($.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log($.bold(` Skill sync \u2014 ${e}`)),console.log($.dim(` Source: ${r}`)),console.log($.dim(` Version: ${c} \xB7 hash ${a}`)),console.log($.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,f=0,g=0,w=0;for(let[y,b]of d){let v=b.workspace;if(!v||!ze(v)){console.log(` ${$.yellow("\u2717")} ${y.padEnd(22)} ${$.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let x=Rs(b.tier,v);if(!x){console.log(` ${$.dim("\xB7")} ${y.padEnd(22)} ${$.dim(`(skipped \u2014 ${b.tier} does not use skills)`)}`),w++;continue}let S=Cs(b.tier,v).find(N=>N.name===e)?.dir??de(x,e),k=de(S,"SKILL.md");if(!ze(k)){if(!t.allWorkspaces){console.log(` ${$.dim("\xB7")} ${y.padEnd(22)} ${$.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}t.dryRun||(go(S,{recursive:!0}),Ls(k,i)),console.log(` ${$.green("+")} ${y.padEnd(22)} ${$.dim("\u2192 seeded v"+c)}`),p++;continue}let E=Yo(k,"utf-8");if(o("sha256").update(E).digest("hex").slice(0,12)===a){console.log(` ${$.dim("=")} ${y.padEnd(22)} ${$.dim("up to date (v"+c+")")}`),g++;continue}let T=(E.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||Ls(k,i),console.log(` ${$.yellow("\u21BB")} ${y.padEnd(22)} ${$.dim(`v${T} \u2192 v${c}`)}`),f++}console.log();let h=t.dryRun?"would":"did";console.log($.dim(` Summary: ${h} seed ${p}, ${h} update ${f}, ${g} already current, ${w} skipped.`)),t.dryRun&&(p>0||f>0)&&console.log($.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});In.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=Ie().agents?.[e.workspace];f||(console.log($.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),r.push(de(f.workspace))}else if(e.allWorkspaces){let p=Ie();for(let f of Object.values(p.agents||{}))f?.workspace&&r.push(de(f.workspace))}else r.push(de(e.cwd));let i=de(e.referencesCwd||e.cwd),c=(await Promise.all(r.map(p=>t(p)))).flat(),[l,u]=await Promise.all([n(i),s(i)]),d=o({skills:c,references:l,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"?$.green("PASS "):f.verdict==="REVIEW"?$.yellow("REVIEW "):$.red("FAILING");console.log(` ${g} ${$.bold(f.name)}${f.skill?.path?$.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${$.dim("\xB7")} ${w}`)}console.log(),console.log(` ${$.green(`${p.PASS} PASS`)} ${$.yellow(`${p.REVIEW} REVIEW`)} ${$.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(d.some(p=>p.verdict==="FAILING")?1:0)});In.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=Ie(),n=Object.entries(o.agents||{}),[s,r]=t.agent?n.find(([u])=>u===t.agent)??[]:n[0]??[];r||(console.log($.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:i}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-
|
|
79
|
+
`)});Lt.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($.red(` No host "${e}".`)),process.exit(1)),console.log($.green(` \u2713 Left ${e}`))});var In=new mo().name("skill").description("manage skills \u2014 add to agent(s), list");In.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=Ie(),n=de(e);if(!ze(n)){console.log($.red(` Skill not found: ${n}`));return}let s=ze(zo(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 ct({type:"multiselect",name:"agents",message:"Install to which agents?",choices:i.map(c=>({title:`${c} (${o.agents[c].name})`,value:c}))})).agents||[]}for(let i of r){let a=o.agents[i];if(!a){console.log($.yellow(` Agent "${i}" not found, skipping`));continue}let c=Rs(a.tier,a.workspace);if(!c){console.log($.yellow(` ${i}: its runtime (${a.tier}) does not use skills, skipping`));continue}let l=de(c,s);go(l,{recursive:!0}),ze(zo(n,"SKILL.md"))?od(n,l,{recursive:!0}):n.endsWith(".md")&&od(n,zo(l,"SKILL.md")),console.log($.green(` ${s} -> ${i} (${a.workspace})`))}console.log()});In.command("list").alias("ls").description("list skills per agent").action(()=>{let e=Ie();console.log();for(let[t,o]of Object.entries(e.agents||{})){if(!Rs(o.tier,o.workspace)){console.log(` ${$.cyan(t)}: ${$.dim(`(${o.tier} does not use skills)`)}`);continue}let n=Cs(o.tier,o.workspace).map(s=>s.name);console.log(` ${$.cyan(t)}: ${n.length?n.join(", "):$.dim("(none)")}`)}console.log()});In.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]:[de(n,"src",e,"SKILL.md"),de(n,"skills",e,"SKILL.md")],r=s.find(y=>ze(y));if(!r){console.log($.red(` No SKILL.md found for "${e}". Searched:`));for(let y of s)console.log($.dim(` ${y}`));return}let i=Yo(r,"utf-8"),a=o("sha256").update(i).digest("hex").slice(0,12),c=(i.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=O()}catch(y){console.log($.red(` Can't load agentx.json: ${y.message}`));return}let u=Object.entries(l.agents||{}),d=t.agent?u.filter(([y])=>y===t.agent):u;if(d.length===0){console.log($.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log($.bold(` Skill sync \u2014 ${e}`)),console.log($.dim(` Source: ${r}`)),console.log($.dim(` Version: ${c} \xB7 hash ${a}`)),console.log($.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let p=0,f=0,g=0,w=0;for(let[y,b]of d){let v=b.workspace;if(!v||!ze(v)){console.log(` ${$.yellow("\u2717")} ${y.padEnd(22)} ${$.dim("(workspace missing: "+(v||"undefined")+")")}`),w++;continue}let x=Rs(b.tier,v);if(!x){console.log(` ${$.dim("\xB7")} ${y.padEnd(22)} ${$.dim(`(skipped \u2014 ${b.tier} does not use skills)`)}`),w++;continue}let S=Cs(b.tier,v).find(N=>N.name===e)?.dir??de(x,e),k=de(S,"SKILL.md");if(!ze(k)){if(!t.allWorkspaces){console.log(` ${$.dim("\xB7")} ${y.padEnd(22)} ${$.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}t.dryRun||(go(S,{recursive:!0}),Ls(k,i)),console.log(` ${$.green("+")} ${y.padEnd(22)} ${$.dim("\u2192 seeded v"+c)}`),p++;continue}let E=Yo(k,"utf-8");if(o("sha256").update(E).digest("hex").slice(0,12)===a){console.log(` ${$.dim("=")} ${y.padEnd(22)} ${$.dim("up to date (v"+c+")")}`),g++;continue}let T=(E.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||Ls(k,i),console.log(` ${$.yellow("\u21BB")} ${y.padEnd(22)} ${$.dim(`v${T} \u2192 v${c}`)}`),f++}console.log();let h=t.dryRun?"would":"did";console.log($.dim(` Summary: ${h} seed ${p}, ${h} update ${f}, ${g} already current, ${w} skipped.`)),t.dryRun&&(p>0||f>0)&&console.log($.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});In.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=Ie().agents?.[e.workspace];f||(console.log($.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),r.push(de(f.workspace))}else if(e.allWorkspaces){let p=Ie();for(let f of Object.values(p.agents||{}))f?.workspace&&r.push(de(f.workspace))}else r.push(de(e.cwd));let i=de(e.referencesCwd||e.cwd),c=(await Promise.all(r.map(p=>t(p)))).flat(),[l,u]=await Promise.all([n(i),s(i)]),d=o({skills:c,references:l,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"?$.green("PASS "):f.verdict==="REVIEW"?$.yellow("REVIEW "):$.red("FAILING");console.log(` ${g} ${$.bold(f.name)}${f.skill?.path?$.dim(` (${f.skill.path})`):""}`);for(let w of f.reasons)console.log(` ${$.dim("\xB7")} ${w}`)}console.log(),console.log(` ${$.green(`${p.PASS} PASS`)} ${$.yellow(`${p.REVIEW} REVIEW`)} ${$.red(`${p.FAILING} FAILING`)}`),console.log()}process.exit(d.some(p=>p.verdict==="FAILING")?1:0)});In.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=Ie(),n=Object.entries(o.agents||{}),[s,r]=t.agent?n.find(([u])=>u===t.agent)??[]:n[0]??[];r||(console.log($.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:i}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-MOZ2GNNR.js"),c=await i(r.workspace);if(c.length===0){console.log($.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(t.min)||.6});if(t.json){console.log(JSON.stringify({task:e,agent:s,skillsSeen:c.length,picked:l.skill?.frontmatter.name??null,anyRelevant:l.anyRelevant,confidence:l.confidence,judged:l.judged,reason:l.reason,shortlist:l.shortlist},null,2));return}if(console.log(),l.skill?(console.log(` ${$.green("\u2192")} ${$.bold(l.skill.frontmatter.name)} ${$.dim(`\xB7 ${l.reason}`)}`),console.log(` ${$.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${$.yellow("\xB7")} no skill for this ${$.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log($.dim(`
|
|
80
80
|
shortlist (lexical -> judged)`));for(let u of l.shortlist.slice(0,6)){let d=u.p===void 0?" - ":u.p.toFixed(2);console.log($.dim(` ${u.lexical.toFixed(2)} -> ${d} ${u.name}`))}}l.judged||console.log($.dim(`
|
|
81
81
|
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Mr=new mo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Mr.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($.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let o=de(t.cwd),n=de(o,"references/example"),s=de(o,"references/recipes/example.yaml");ze(n)||(console.log($.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let r=de(o,".agentx/references",e),i=de(o,".agentx/references/recipes");go(r,{recursive:!0}),go(i,{recursive:!0});let a=SA(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let p=zo(r,d);if(ze(p)&&!t.force){console.log($.dim(` skip ${p} (exists; --force to overwrite)`)),l++;continue}let g=Yo(zo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Ls(p,g),console.log($.green(` + ${p}`)),c++}let u=zo(i,`${e}.yaml`);if(ze(u)&&!t.force)console.log($.dim(` skip ${u} (exists; --force to overwrite)`)),l++;else if(ze(s)){let d=Yo(s,"utf-8").replaceAll("example.",`${e}.`);Ls(u,d),console.log($.green(` + ${u}`)),c++}console.log(),console.log($.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log($.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log($.dim(" 2. agentx skill audit # verify references resolve")),console.log($.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Mr.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($.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=de(t.cwd),i=t.from?String(t.from).split(",").map(w=>w.trim()).filter(Boolean):[e],a=await o(r),c=n(a,{namespace:e,filter:i,gitlabHost:t.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log($.yellow(` No skills matched filter [${i.join(", ")}] under ${r}`)),console.log($.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log($.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([w,h])=>[w,h.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let u=s(c,e),d=de(t.referencesCwd||t.cwd),p=de(d,".agentx/references",e);if(!t.write){console.log(),console.log($.dim(` Dry-run \u2014 would write to ${p}/`));for(let[w,h]of Object.entries(u))console.log($.cyan(`
|
|
82
82
|
--- ${w} ---`)),console.log(h.split(`
|
|
@@ -85,7 +85,7 @@ ${r.content}
|
|
|
85
85
|
`).length>30&&console.log($.dim(` \u2026 (${h.split(`
|
|
86
86
|
`).length-30} more lines truncated in preview)`));console.log(),console.log($.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}go(p,{recursive:!0});let f=0,g=0;for(let[w,h]of Object.entries(u)){let y=zo(p,w);if(ze(y)&&!t.force){console.log($.dim(` skip ${y} (exists; --force to overwrite)`)),g++;continue}Ls(y,h),console.log($.green(` + ${y}`)),f++}console.log(),console.log($.dim(` ${f} written, ${g} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log($.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Mr.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(de(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($.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(` ${$.cyan(s.id)} ${$.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),r&&console.log($.dim(` ${r}`))}console.log(),console.log($.dim(` ${n.length} reference(s) loaded.`)),console.log()});var sd=new mo().name("hook").description("manage hooks \u2014 add to agent workspace");sd.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=Ie().agents?.[e];if(!o){console.log($.red(` Agent "${e}" not found`));return}let n=de(o.workspace,".claude/settings.json"),s=ze(n)?JSON.parse(Yo(n,"utf-8")):{},r=await ct([{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:c=>c==="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),go(de(o.workspace,".claude"),{recursive:!0}),Ls(n,JSON.stringify(s,null,2)),console.log($.green(` Hook added to ${e}: ${r.event} -> ${r.type}`)),console.log()});var rd=new mo().name("migrate").description("import configuration from OpenClaw or other tools");rd.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,de(process.env.HOME||"",".openclaw/openclaw.json"),de(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of o)if(f&&ze(f)){n=f;break}if(!n){console.log($.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log($.dim(` Reading: ${n}`));let s=JSON.parse(Yo(n,"utf-8")),r=ze(de(process.cwd(),"agentx.json"))?Ie():{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||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);i.find(f=>f.id==="main"||f.default)&&(c.default="main");let l=0;for(let f of i){if(f.workspace?.startsWith("/data"))continue;let g=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=f.groupChat?.mentionPatterns||[];if(w.some(h=>h===g)||w.push(g),r.agents[g]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!t.dryRun){go(de(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:h}=await import("./workspace-setup-HAV4CQV7.js");h(g,r.agents[g])}}console.log(` ${$.green(l)} 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 h=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.channels.telegram.accounts[f]={token:g.botToken,agentBinding:h},r.channels.telegram.enabled=!0,d++}console.log(` ${$.green(d)} Telegram accounts imported`);let p=de(n,"../cron/jobs.json");if(ze(p)){let f=JSON.parse(Yo(p,"utf-8")),g=0;for(let w of f.jobs||[]){let h=w.name||w.id,y=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.crons[h]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:y,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},g++}console.log(` ${$.green(g)} cron jobs imported`)}t.dryRun?(console.log($.yellow(`
|
|
87
87
|
Dry run \u2014 nothing written`)),console.log(JSON.stringify(r,null,2))):(await yt(r),console.log($.green(`
|
|
88
|
-
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Ko=new mo().name("config").description("validate and inspect configuration");Ko.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($.green(" \u2713 Config valid")),console.log($.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log($.dim(` Bind: ${t.node.bind}`)),console.log($.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log($.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log($.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log($.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log($.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=ki(t);if(n.length){console.log(),console.log($.yellow(" Warnings:"));for(let s of n)console.log($.yellow(` \u26A0 ${s}`))}else console.log($.green(" \u2713 All workspaces valid"));console.log();for(let[s,r]of Object.entries(t.agents)){let i=r.workspace,a=ze(de(i,".claude")),c=ze(de(i,"CLAUDE.md")),l=ze(de(i,".claude/settings.json")),u=Cs(r.tier,i).length,d=[a?$.green("\u2713"):$.red("\u2717"),".claude",c?$.green("\u2713"):$.yellow("\u25CB"),"CLAUDE.md",l?$.green("\u2713"):$.yellow("\u25CB"),"settings",`${u} skills`];console.log(` ${$.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log($.red(` \u2717 ${t.message}`))}console.log()});Ko.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($.red(t.message))}});function RA(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 nd(e){return e===void 0?$.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Ko.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-
|
|
88
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Ko=new mo().name("config").description("validate and inspect configuration");Ko.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($.green(" \u2713 Config valid")),console.log($.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log($.dim(` Bind: ${t.node.bind}`)),console.log($.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log($.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log($.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log($.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log($.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=ki(t);if(n.length){console.log(),console.log($.yellow(" Warnings:"));for(let s of n)console.log($.yellow(` \u26A0 ${s}`))}else console.log($.green(" \u2713 All workspaces valid"));console.log();for(let[s,r]of Object.entries(t.agents)){let i=r.workspace,a=ze(de(i,".claude")),c=ze(de(i,"CLAUDE.md")),l=ze(de(i,".claude/settings.json")),u=Cs(r.tier,i).length,d=[a?$.green("\u2713"):$.red("\u2717"),".claude",c?$.green("\u2713"):$.yellow("\u25CB"),"CLAUDE.md",l?$.green("\u2713"):$.yellow("\u25CB"),"settings",`${u} skills`];console.log(` ${$.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log($.red(` \u2717 ${t.message}`))}console.log()});Ko.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($.red(t.message))}});function RA(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 nd(e){return e===void 0?$.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Ko.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-3FGEZPF3.js"),{expandEnvVars:i}=await import("./config-QBTOYJA7.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log($.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(o(a,"utf-8")),l=t.raw?c:i(c),u=r(l,e);t.json?console.log(JSON.stringify(u)):console.log(nd(u))});Ko.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-3FGEZPF3.js"),i=RA(t,!!o.string),a=await n(l=>{s(l,e,i)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log($.red(` \u2717 ${a.error}`)),process.exit(1));let c=r(a.after,e);o.dryRun?console.log($.yellow(` (dry-run) ${$.cyan(e)} would become: ${nd(c)}`)):(console.log($.green(` \u2713 ${$.cyan(e)} = ${nd(c)}`)),a.reloaded?console.log($.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log($.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Ko.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-3FGEZPF3.js"),r=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(r.success||(console.log($.red(` \u2717 ${r.error}`)),process.exit(1)),n(r.after,e)!==void 0){console.log($.dim(` (no-op) ${$.cyan(e)} was not set`));return}t.dryRun?console.log($.yellow(` (dry-run) ${$.cyan(e)} would be removed`)):(console.log($.green(` \u2713 ${$.cyan(e)} removed`)),r.reloaded&&console.log($.dim(" Daemon hot-reloaded.")))});Ko.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,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:i,businessEnabled:t,active:a,projects:o},configError:n},null,2));return}console.log(),console.log($.bold(" Governance flags")),console.log(),n&&(console.log($.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?$.green:s==="shadow"?$.cyan:s==="off"?$.dim:$.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":$.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let u=a?$.green("active"):i?$.yellow("env=true but business.enabled=false \u2192 inactive"):$.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${u}`),console.log($.dim(` business.enabled ${t?$.green("true"):$.dim("false")}`)),console.log($.dim(` business.projects[] ${o}`)),console.log(),console.log($.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log($.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});hn();import{Command as CA}from"commander";import Xo from"chalk";import{resolve as Vo}from"path";import{existsSync as TA}from"fs";var Oo=new CA().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Nn(e){let t=Vo(e,".agentx/db.sqlite");TA(t)||(console.log(Xo.red(` No SQLite at ${t}`)),console.log(Xo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=dt({path:t});return o||(console.log(Xo.red(` Could not open ${t}`)),console.log(Xo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function jn(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Xo.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])))}Oo.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=Nn(Vo(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=`
|
|
89
89
|
SELECT agent_id, channel, status, duration_ms,
|
|
90
90
|
input_tokens, output_tokens,
|
|
91
91
|
substr(message_preview, 1, 60) AS message,
|
|
@@ -515,7 +515,7 @@ return aid ?? null`}function pC(e,t){if(e.kind==="path"){let s=e.pts,r=s[Math.fl
|
|
|
515
515
|
`):" not written yet"),n.builders){console.log(Y.dim(`
|
|
516
516
|
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}`)}}});zr(Jn.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 Bn(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}`))});zr(Jn.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 Bn(t,"POST","/api/signals/drop",{id:e,node:t.peer});console.log(Y.green(` dropped ${o.agentId} task ${o.id}`))});te();import{Command as pT}from"commander";import Nb from"chalk";function Ud(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 Wd(e){return e.chatId?`${e.channel}:${e.chatId}`:e.channel}function Ib(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,c])=>`${a} ${c.running}/${c.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 ${Ud(a)} more`)}o.push(""),o.push(`Running (${e.running.length})`),e.running.length||o.push(" none");for(let a of e.running){let c=Math.max(0,Math.round((t-Date.parse(a.startedAt))/1e3));o.push(` ${a.agentId} ${a.priority}${a.class?` [${a.class}]`:""} ${Wd(a)} for ${Ud(c)}`)}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}]`:""} ${Wd(a)} waiting ${Ud(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}, ${Wd(e.next)})`:"Next: nothing waiting"),o.join(`
|
|
517
517
|
`)}var jb=new pT().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(Nb.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(Nb.red(` could not reach daemon at ${t}: ${s?.message||s}`)),process.exit(1)}console.log(e.json?JSON.stringify(n,null,2):Ib(n))});te();import{Command as fT}from"commander";import _b from"chalk";var Pb=new fT().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(_b.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(_b.red(` could not reach daemon at ${t}: ${s?.message||s}`)),process.exit(1)}console.log(e.json?JSON.stringify(n,null,2):hf(n))});te();import{Command as hT}from"commander";import $t from"chalk";var Ga=new hT().name("review-gate").description("independent pre-merge review of agent PRs against their linked issue");function wT(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 Db(e,t,o,n){let{baseUrl:s,headers:r}=wT(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 Mb=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)"),Lb=e=>e==="success"?$t.green(e):e==="failure"?$t.red(e):$t.yellow(e);Mb(Ga.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 Db(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)} ${Lb(s.state)} ${$t.dim(s.reason)}${s.replay?$t.dim(" (replay)"):""}`)});Mb(Ga.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 Db(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:c}=await s.read();c&&(i+=r.decode(c,{stream:!0}));let l;for(;(l=i.indexOf(`
|
|
518
|
-
`))>=0;){let u=i.slice(0,l).trim();if(i=i.slice(l+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} ${Lb(d.state)}${d.flagged?$t.red(" flagged"):""} ${$t.dim(d.reason)}`)}if(a)break}});te();import{Command as yT}from"commander";import Hn from"chalk";import{resolve as $T}from"path";var za=new yT().name("cloud-sessions").description("list and close the Claude cloud sessions that block their GitHub issue"),qb=e=>e.option("--file <path>","session file",".agentx/cloud-sessions.json").option("-c, --config <path>","daemon config file, for each agent's openHours");function Fb(e){return new fm($T(process.cwd(),e.file||".agentx/cloud-sessions.json"))}function bT(e){let t={};try{t=O(e.config).agents}catch{}return o=>t[o]?.cloudSessions?.openHours??pm.openHours}function kT(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}qb(za.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=bT(e),o=Date.now(),n=Fb(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(Hn.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} ${Hn.dim(`${s.agentId}, started ${i}`)} ${r?Hn.yellow("open"):Hn.dim("over")}`)}});qb(za.command("close <refs...>").description("forget the session for each issue (owner/repo#42), so its next comment runs normally")).action((e,t)=>{let o=Fb(t),n=!1;for(let s of e){let r=kT(s);if(!r){console.log(Hn.red(` ${s}: expected owner/repo#number`)),n=!0;continue}o.close(r.repo,r.number)?console.log(Hn.green(` closed ${r.repo}#${r.number}`)):console.log(Hn.dim(` ${r.repo}#${r.number}: no session recorded`))}n&&(process.exitCode=1)});import{Command as vT}from"commander";import pt from"chalk";import{existsSync as Bd,rmSync as xT}from"fs";import{resolve as Jd}from"path";var Ks=new vT().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Ks.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(pt.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),r=await om(e,t,{verbose:n}),i=Date.now()-s;console.log(pt.green(` \u2713 indexed ${r.docs} doc(s) for ${pt.bold(e)} in ${i}ms`)),console.log(pt.dim(` \u2192 ${r.path}`))});Ks.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=Jd(e.cwd,".agentx","rag");if(!Bd(t)){console.log(pt.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>Bd(Jd(t,s,"index.json")));if(n.length===0){console.log(pt.dim(" (no indexes)"));return}for(let s of n.sort()){let r=Bc(s);console.log(` ${pt.bold(s)} ${r.docs} doc(s) ${pt.dim(r.path)}`)}});Ks.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=nm(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let r=Bc(e);r.exists?console.log(pt.dim(` (no hits in ${r.docs} indexed docs)`)):console.log(pt.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let r of s)console.log(` ${pt.bold(r.title)} ${pt.dim(`(${r.score.toFixed(2)})`)}`),console.log(` ${pt.dim(r.path)}`),console.log(` ${pt.dim(r.snippet.slice(0,200))}`)});Ks.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=Jd(process.cwd(),".agentx","rag",e);if(!Bd(t)){console.log(pt.dim(` no index for ${e} \u2014 nothing to clear`));return}xT(t,{recursive:!0,force:!0}),console.log(pt.green(` \u2713 cleared index for ${e}`))});te();import{Command as ST}from"commander";import we from"chalk";import Xs from"prompts";var Gn=new ST().name("backlog").description("manage the local backlog used by business workSource=backlog");function Yr(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 Ff(n)}}function AT(e){return e?we.cyan(`${e.type}:${e.project}#${e.iid}`):we.dim("manual")}function ET(e){return{todo:we.gray("todo"),doing:we.yellow("doing"),blocked:we.red("blocked"),done:we.green("done")}[e]}Gn.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}=Yr(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(` ${ET(n.status).padEnd(7)} ${AT(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()}`))});Gn.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=Yr(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=sf([t],r.source,n.config),a=await ll(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(we.dim(" sync:"),...c));console.log(a.ok?we.dim(` synced -> ${a.url??r.source.type}`):we.yellow(` sync failed: ${a.error}`))}});Gn.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=Yr(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 ll(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}`))}});Gn.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}=Yr(t.config);o.remove(e)||(console.error(we.red(` item ${e} not found`)),process.exit(1)),console.log(we.green(` removed ${e}`))});Gn.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=Yr(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 h=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Xs({type:"select",name:"source",message:"Source",choices:h})).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 h=s==="gitlab"?CT(t.config):TT(t.config);h.length?(r=(await Xs({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...h.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,r==="__CUSTOM__"&&(r=(await Xs({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):r=(await Xs({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!r)return;let a=((await Xs({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 c=s==="gitlab"?await OT(t.config,r,a):await IT(t.config,r,a);if(!c.length){console.log(we.yellow(" no open issues matched"));return}console.log(we.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=r,u=new Set(t.store.list().map(h=>h.id)),d=c.map(h=>{let y=yl({type:s,project:l,iid:h.iid,url:h.url}),b=u.has(y),v=h.labels.length?` [${h.labels.slice(0,3).join(",")}]`:"";return{title:`#${h.iid} ${h.title}${v}${b?we.dim(" (already imported)"):""}`,value:h,disabled:b}}),f=(await Xs({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(h=>{let y={type:s,host:s==="gitlab"?RT(t.config):void 0,project:l,iid:h.iid,url:h.url};return{id:yl(y),title:h.title,description:h.description,assignee:e.assignee||h.assignee,labels:h.labels,milestone:h.milestone,status:"todo",source:y,importedAt:new Date().toISOString()}}),w=t.store.addMany(g);console.log(we.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let h of w)console.log(we.dim(` ${h.id} \u2014 ${h.title}`))});function RT(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function CT(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 TT(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 OT(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(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function IT(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 c=`repo:${t} is:issue is:open ${o}`;r=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(r,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(Ub)}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(c=>!c.pull_request).map(Ub):[]}function Ub(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 NT}from"commander";import ee from"chalk";import{existsSync as jT,readFileSync as _T}from"fs";import{resolve as PT}from"path";import DT from"prompts";te();function Wb(e){let t=e||PT(process.cwd(),"agentx.json");return jT(t)||(console.log(ee.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(_T(t,"utf-8"))}async function MT(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(ee.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:r,accountId:i}=await DT([{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(ee.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Io=new NT().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Io.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: ${yr})`,yr).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){Io.help();return}t.agent||(console.log(ee.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(ee.red(' --do "<prompt>" is required')),process.exit(1));let o=zc(e);o||(console.log(ee.red(` Couldn't parse: "${e}"`)),console.log(ee.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(ee.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(ee.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Wb(t.config),s=fr(n);n.agents?.[t.agent]||(console.log(ee.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(ee.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let r=await MT(t.notify,s),i=t.id||xm(o.matched,t.agent),a=Am({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:Sm(t.onError),enabled:!t.disabled}),c=a.onError,l=await me(d=>We(d,`crons.${i}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(ee.red(` \u2717 ${l.error}`)),process.exit(1));let u=t.dryRun?"would add":"Added";console.log(ee.green(` \u2713 ${u} cron ${ee.cyan(i)}`)),console.log(ee.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(ee.dim(` Agent: ${t.agent}`)),r&&console.log(ee.dim(` Notify: ${r.channel} ${r.chatId} ${Yc(a)}`)),c.length&&console.log(ee.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(ee.dim(" Daemon hot-reloaded."))});Io.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=Wb(e.config).crons||{},n=Object.entries(o),s=new Set;try{let{loadDaemonConfig:r}=await import("./config-IOQKEH47.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(ee.dim(" No scheduled jobs"));return}console.log();for(let[r,i]of n){let a=i.approval?ee.yellow("\u25D0"):i.enabled?ee.green("\u25CF"):ee.dim("\u25CB"),c=i.schedule;try{c=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${a} ${ee.cyan(r.padEnd(32))} ${ee.dim(i.schedule.padEnd(14))} ${ee.dim("\u2192")} ${i.agent}`),console.log(ee.dim(` ${c} (${i.timezone||"UTC"})`)),i.notify&&console.log(ee.dim(` notify: ${i.notify.channel} ${i.notify.chatId} ${Yc(i)}`)),i.createdBy&&console.log(ee.dim(` created by agent: ${i.createdBy}`)),s.has(r)&&console.log(ee.dim(" built in: added by AgentX from your settings; a job of the same id in crons replaces it")),i.approval){let l=i.timezone||"UTC",u=Rm(Em(i.schedule,l),l);console.log(ee.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${u}`)),console.log(ee.dim(` agentx schedule approve ${r} | agentx schedule reject ${r}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])Io.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await Om(o,t);n.success||(console.log(ee.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(ee.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(ee.dim(" Daemon hot-reloaded."))});Io.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await me(o=>{if(!ks(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);im(o,`crons.${e}`)});t.success||(console.log(ee.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(ee.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(ee.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",Cm,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Tm,"reject an agent's pending create/delete request (drops the request)"]])Io.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(ee.red(` \u2717 ${r.message}`)),process.exit(1)),console.log(ee.green(` \u2713 ${r.message}`)),r.result?.reloaded&&console.log(ee.dim(" Daemon hot-reloaded."))});Io.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=zc(t);o||(console.log(ee.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(ee.green(` "${t}"`)),console.log(ee.dim(` \u2192 ${o.cron}`)),console.log(ee.dim(` \u2192 ${o.human}`))});import{Command as nO}from"commander";import nk from"chalk";import{existsSync as sO,readFileSync as rO}from"fs";import{resolve as rk}from"path";import{existsSync as LT,readFileSync as qT,writeFileSync as FT}from"fs";import{join as zd}from"path";var Hd="leads.md",Bb="opt-outs.md",Jb=864e5,Gd=/\d{4}-\d{2}-\d{2}/;function UT(e){return e.split(`
|
|
518
|
+
`))>=0;){let u=i.slice(0,l).trim();if(i=i.slice(l+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} ${Lb(d.state)}${d.flagged?$t.red(" flagged"):""} ${$t.dim(d.reason)}`)}if(a)break}});te();import{Command as yT}from"commander";import Hn from"chalk";import{resolve as $T}from"path";var za=new yT().name("cloud-sessions").description("list and close the Claude cloud sessions that block their GitHub issue"),qb=e=>e.option("--file <path>","session file",".agentx/cloud-sessions.json").option("-c, --config <path>","daemon config file, for each agent's openHours");function Fb(e){return new fm($T(process.cwd(),e.file||".agentx/cloud-sessions.json"))}function bT(e){let t={};try{t=O(e.config).agents}catch{}return o=>t[o]?.cloudSessions?.openHours??pm.openHours}function kT(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}qb(za.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=bT(e),o=Date.now(),n=Fb(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(Hn.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} ${Hn.dim(`${s.agentId}, started ${i}`)} ${r?Hn.yellow("open"):Hn.dim("over")}`)}});qb(za.command("close <refs...>").description("forget the session for each issue (owner/repo#42), so its next comment runs normally")).action((e,t)=>{let o=Fb(t),n=!1;for(let s of e){let r=kT(s);if(!r){console.log(Hn.red(` ${s}: expected owner/repo#number`)),n=!0;continue}o.close(r.repo,r.number)?console.log(Hn.green(` closed ${r.repo}#${r.number}`)):console.log(Hn.dim(` ${r.repo}#${r.number}: no session recorded`))}n&&(process.exitCode=1)});import{Command as vT}from"commander";import pt from"chalk";import{existsSync as Bd,rmSync as xT}from"fs";import{resolve as Jd}from"path";var Ks=new vT().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Ks.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(pt.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),r=await om(e,t,{verbose:n}),i=Date.now()-s;console.log(pt.green(` \u2713 indexed ${r.docs} doc(s) for ${pt.bold(e)} in ${i}ms`)),console.log(pt.dim(` \u2192 ${r.path}`))});Ks.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=Jd(e.cwd,".agentx","rag");if(!Bd(t)){console.log(pt.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>Bd(Jd(t,s,"index.json")));if(n.length===0){console.log(pt.dim(" (no indexes)"));return}for(let s of n.sort()){let r=Bc(s);console.log(` ${pt.bold(s)} ${r.docs} doc(s) ${pt.dim(r.path)}`)}});Ks.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=nm(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let r=Bc(e);r.exists?console.log(pt.dim(` (no hits in ${r.docs} indexed docs)`)):console.log(pt.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let r of s)console.log(` ${pt.bold(r.title)} ${pt.dim(`(${r.score.toFixed(2)})`)}`),console.log(` ${pt.dim(r.path)}`),console.log(` ${pt.dim(r.snippet.slice(0,200))}`)});Ks.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=Jd(process.cwd(),".agentx","rag",e);if(!Bd(t)){console.log(pt.dim(` no index for ${e} \u2014 nothing to clear`));return}xT(t,{recursive:!0,force:!0}),console.log(pt.green(` \u2713 cleared index for ${e}`))});te();import{Command as ST}from"commander";import we from"chalk";import Xs from"prompts";var Gn=new ST().name("backlog").description("manage the local backlog used by business workSource=backlog");function Yr(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 Ff(n)}}function AT(e){return e?we.cyan(`${e.type}:${e.project}#${e.iid}`):we.dim("manual")}function ET(e){return{todo:we.gray("todo"),doing:we.yellow("doing"),blocked:we.red("blocked"),done:we.green("done")}[e]}Gn.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}=Yr(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(` ${ET(n.status).padEnd(7)} ${AT(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()}`))});Gn.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=Yr(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=sf([t],r.source,n.config),a=await ll(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(we.dim(" sync:"),...c));console.log(a.ok?we.dim(` synced -> ${a.url??r.source.type}`):we.yellow(` sync failed: ${a.error}`))}});Gn.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=Yr(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 ll(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}`))}});Gn.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}=Yr(t.config);o.remove(e)||(console.error(we.red(` item ${e} not found`)),process.exit(1)),console.log(we.green(` removed ${e}`))});Gn.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=Yr(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 h=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Xs({type:"select",name:"source",message:"Source",choices:h})).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 h=s==="gitlab"?CT(t.config):TT(t.config);h.length?(r=(await Xs({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...h.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,r==="__CUSTOM__"&&(r=(await Xs({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):r=(await Xs({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!r)return;let a=((await Xs({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 c=s==="gitlab"?await OT(t.config,r,a):await IT(t.config,r,a);if(!c.length){console.log(we.yellow(" no open issues matched"));return}console.log(we.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=r,u=new Set(t.store.list().map(h=>h.id)),d=c.map(h=>{let y=yl({type:s,project:l,iid:h.iid,url:h.url}),b=u.has(y),v=h.labels.length?` [${h.labels.slice(0,3).join(",")}]`:"";return{title:`#${h.iid} ${h.title}${v}${b?we.dim(" (already imported)"):""}`,value:h,disabled:b}}),f=(await Xs({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(h=>{let y={type:s,host:s==="gitlab"?RT(t.config):void 0,project:l,iid:h.iid,url:h.url};return{id:yl(y),title:h.title,description:h.description,assignee:e.assignee||h.assignee,labels:h.labels,milestone:h.milestone,status:"todo",source:y,importedAt:new Date().toISOString()}}),w=t.store.addMany(g);console.log(we.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let h of w)console.log(we.dim(` ${h.id} \u2014 ${h.title}`))});function RT(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function CT(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 TT(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 OT(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(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function IT(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 c=`repo:${t} is:issue is:open ${o}`;r=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(r,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(Ub)}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(c=>!c.pull_request).map(Ub):[]}function Ub(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 NT}from"commander";import ee from"chalk";import{existsSync as jT,readFileSync as _T}from"fs";import{resolve as PT}from"path";import DT from"prompts";te();function Wb(e){let t=e||PT(process.cwd(),"agentx.json");return jT(t)||(console.log(ee.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(_T(t,"utf-8"))}async function MT(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(ee.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:r,accountId:i}=await DT([{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(ee.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Io=new NT().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Io.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: ${yr})`,yr).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){Io.help();return}t.agent||(console.log(ee.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(ee.red(' --do "<prompt>" is required')),process.exit(1));let o=zc(e);o||(console.log(ee.red(` Couldn't parse: "${e}"`)),console.log(ee.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(ee.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(ee.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Wb(t.config),s=fr(n);n.agents?.[t.agent]||(console.log(ee.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(ee.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let r=await MT(t.notify,s),i=t.id||xm(o.matched,t.agent),a=Am({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:Sm(t.onError),enabled:!t.disabled}),c=a.onError,l=await me(d=>We(d,`crons.${i}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(ee.red(` \u2717 ${l.error}`)),process.exit(1));let u=t.dryRun?"would add":"Added";console.log(ee.green(` \u2713 ${u} cron ${ee.cyan(i)}`)),console.log(ee.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(ee.dim(` Agent: ${t.agent}`)),r&&console.log(ee.dim(` Notify: ${r.channel} ${r.chatId} ${Yc(a)}`)),c.length&&console.log(ee.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(ee.dim(" Daemon hot-reloaded."))});Io.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=Wb(e.config).crons||{},n=Object.entries(o),s=new Set;try{let{loadDaemonConfig:r}=await import("./config-QBTOYJA7.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(ee.dim(" No scheduled jobs"));return}console.log();for(let[r,i]of n){let a=i.approval?ee.yellow("\u25D0"):i.enabled?ee.green("\u25CF"):ee.dim("\u25CB"),c=i.schedule;try{c=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${a} ${ee.cyan(r.padEnd(32))} ${ee.dim(i.schedule.padEnd(14))} ${ee.dim("\u2192")} ${i.agent}`),console.log(ee.dim(` ${c} (${i.timezone||"UTC"})`)),i.notify&&console.log(ee.dim(` notify: ${i.notify.channel} ${i.notify.chatId} ${Yc(i)}`)),i.createdBy&&console.log(ee.dim(` created by agent: ${i.createdBy}`)),s.has(r)&&console.log(ee.dim(" built in: added by AgentX from your settings; a job of the same id in crons replaces it")),i.approval){let l=i.timezone||"UTC",u=Rm(Em(i.schedule,l),l);console.log(ee.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${u}`)),console.log(ee.dim(` agentx schedule approve ${r} | agentx schedule reject ${r}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])Io.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await Om(o,t);n.success||(console.log(ee.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(ee.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(ee.dim(" Daemon hot-reloaded."))});Io.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await me(o=>{if(!ks(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);im(o,`crons.${e}`)});t.success||(console.log(ee.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(ee.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(ee.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",Cm,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Tm,"reject an agent's pending create/delete request (drops the request)"]])Io.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(ee.red(` \u2717 ${r.message}`)),process.exit(1)),console.log(ee.green(` \u2713 ${r.message}`)),r.result?.reloaded&&console.log(ee.dim(" Daemon hot-reloaded."))});Io.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=zc(t);o||(console.log(ee.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(ee.green(` "${t}"`)),console.log(ee.dim(` \u2192 ${o.cron}`)),console.log(ee.dim(` \u2192 ${o.human}`))});import{Command as nO}from"commander";import nk from"chalk";import{existsSync as sO,readFileSync as rO}from"fs";import{resolve as rk}from"path";import{existsSync as LT,readFileSync as qT,writeFileSync as FT}from"fs";import{join as zd}from"path";var Hd="leads.md",Bb="opt-outs.md",Jb=864e5,Gd=/\d{4}-\d{2}-\d{2}/;function UT(e){return e.split(`
|
|
519
519
|
`).map(t=>t.trim()).filter(t=>/^[-*]\s+\S/.test(t)).map(t=>t.replace(/^[-*]\s+/,"").split("|").map(o=>o.trim()))}function WT(e){return e.split(`
|
|
520
520
|
`).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(Gd)?.[0]:a.startsWith("added")?r.added=i.match(Gd)?.[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 Hb(e){return UT(e).map(([t="",o="",n,s])=>({name:t,company:o,date:n?.match(Gd)?.[0],reason:s||void 0})).filter(t=>t.name)}var Ya=e=>e.trim().toLowerCase().replace(/\s+/g," ");function Kr(e,t){return t.some(o=>Ya(o.name)===Ya(e.name)&&(!o.company||Ya(o.company)===Ya(e.company)))}var BT=e=>/^done\b/i.test(e.next??""),Vs=e=>Date.parse(`${e}T00:00:00Z`);function Gb(e,t,o,n=7){let s=Vs(o)-n*Jb;return e.filter(r=>{if(BT(r)||Kr(r,t))return!1;let i=r.lastContact??r.added;return!i||Vs(i)<=s})}function zb(e,t,o,n=1){let s=Vs(o)-(n-1)*Jb;return e.filter(r=>r.added&&Vs(r.added)>=s&&Vs(r.added)<=Vs(o)&&!Kr(r,t))}function Yd(e){return LT(e)?qT(e,"utf-8"):""}function Yb(e){return WT(Yd(zd(e,Hd)))}function Kb(e){return Hb(Yd(zd(e,Bb)))}var JT=`# Opt-outs
|
|
521
521
|
|
|
@@ -566,7 +566,7 @@ ${oe.text}`));T.delivery.reached.of++,ie&&T.delivery.reached.n++;let j=P[0]??Q[0
|
|
|
566
566
|
Plan ${L.dim(`[${r.state}] by ${r.createdBy}, ${Vn(r.createdAt)}`)}`),Ck(s.steps(e)),console.log(`
|
|
567
567
|
Log`);for(let i of s.events(e))console.log(L.dim(` ${Vn(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});jo.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(c=>o[c]);if(n.length!==1){console.error(L.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=er();if(!s)return;let r=Za();if(!r){process.exitCode=1;return}let i=Number(t),a=Xp(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(L.red(` ${a}`)),process.exitCode=1;return}console.log(L.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+L.dim(" (the daemon goes on within a minute)")),Ck(r.steps(e))});function Tk(e,t,o,n){let s=jo.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=er();if(!a)return;let c=e==="done"?i.evidence??(i.reason?`closed by owner: ${i.reason}`:void 0):i.reason??"dropped by the owner";if(!c){console.error(L.red(` ${n}`)),process.exitCode=1;return}let l=a.get(r);if(!l||l.state==="candidate"){console.error(L.red(` no request "${r}"`)),process.exitCode=1;return}if(!a.close(r,e==="done"?"done":"dropped",c,Date.now())){console.error(L.red(` ${r} is already closed (${cu[l.state]??l.state})`)),process.exitCode=1;return}console.log(L.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}Tk("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>");Tk("drop","drop a request you no longer want","--reason <text>","");jo.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 (${yi.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=(h,y)=>{if(y===void 0)return;let b=Number(y);if(!(b>0))throw new Error(`${h} must be a positive number`);return b},d=(h,y)=>h===void 0?void 0:h===y?[]:h.split(",").map(b=>b.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 h=u("--catch-cap",e.catchCap);if(h!==void 0&&!Number.isInteger(h))throw new Error("--catch-cap must be a whole number");t.catchPromises={...e.catch!==void 0?{enabled:e.catch==="on"}:{},...h!==void 0?{dailyCap:h}:{}}}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 h=Number(e.maxNudges);if(!Number.isInteger(h)||h<0)throw new Error("--max-nudges must be a whole number, 0 or more");p.maxNudges=h}if(p.approveKinds=d(e.approveKinds,"none"),p.disabledAgents=d(e.plansOffFor,"none"),p.requireForWork=d(e.planFor,"none"),e.planOver!==void 0){let h=Number(e.planOver);if(!(h>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");p.requireOverMinutes=h}Object.values(p).some(h=>h!==void 0)&&(t.plans=p);let f={},g=d(e.checks,"none");if(g){let h=g.filter(y=>!yi.includes(y));if(h.length)throw new Error(`unknown check ${h.join(", ")}: use ${yi.join(", ")}`);f.enabled=g}f.checkEveryMinutes=u("--check-every",e.checkEvery),Object.values(f).some(h=>h!==void 0)&&(t.checkers=f);let w={};if(e.autoResend!==void 0){if(e.autoResend!=="on"&&e.autoResend!=="off")throw new Error("--auto-resend takes on or off");w.enabled=e.autoResend==="on"}if(e.resendAfter!==void 0){let h=Number(e.resendAfter);if(!(h>=0))throw new Error("--resend-after must be a number of minutes, 0 or more");w.afterMinutes=h}w.holdMaxHours=u("--resend-hold-hours",e.resendHoldHours),Object.values(w).some(h=>h!==void 0)&&(t.autoResend=w),e.flowZone!==void 0&&(t.flow={timeZone:e.flowZone})}catch(u){console.error(L.red(` ${u.message}`)),process.exitCode=1;return}if(Object.values(t).some(u=>u!==void 0)){let u=await Np(t);if(!u.success){console.error(L.red(` ${u.error}`)),process.exitCode=1;return}console.log(L.green(" \u2713 saved")+(u.reloaded?L.dim(" (daemon reloaded)"):""))}let o=br();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??Wi;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??Wi.requireOverMinutes,i=s.requireForWork??Wi.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??Kp;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??Zc).timeZone} days`);let c=o.checkers??$i;console.log(` Loop checks ${c.enabled.length?c.enabled.join(", "):"off"}, every ${c.checkEveryMinutes} minute(s)`);let l=Object.keys(c.repos);console.log(` Repos for git-ancestor ${l.length?l.join(", "):"none (requests.checkers.repos in agentx.json)"}`)});import{Command as WO}from"commander";import tr from"chalk";te();var Ok=new WO("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Sl.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(tr.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await me(r=>{n=wh(r,e,t==="on")});s.success||(console.error(tr.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(tr.green(`\u2713 ${n}`)),s.reloaded&&console.log(tr.dim(" daemon hot-reloaded"))}let o=O().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Sl)console.log(` ${n.padEnd(8)} ${o.includes(n)?tr.green("on"):tr.dim("off")}`)});import{Command as w1}from"commander";import or from"chalk";import ve from"chalk";import Vr from"prompts";import{readFileSync as BO,writeFileSync as JO,existsSync as HO}from"fs";import{resolve as Ik}from"path";var GO=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function zO(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function du(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Nk(e=".env"){let t=Ik(e);if(!HO(t))return[];let o=BO(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(GO);r?n.push({kind:"kv",key:r[1],value:zO(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function YO(e){return e.map(t=>t.kind==="kv"?`${t.key}=${du(t.value)}`:t.raw).join(`
|
|
568
568
|
`)+`
|
|
569
|
-
`}function Qn(e,t,o=".env"){let n=Ik(o),s=Nk(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${du(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${du(t)}`})),JO(n,YO(s))}function uu(e,t=".env"){return Nk(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var jk="https://t.me/BotFather";async function KO(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 XO(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 _k(e={}){console.log(),console.log(ve.bold(" Connect Telegram")),console.log(),console.log(ve.dim(` 1. Open ${jk}`)),console.log(ve.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ve.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Vr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&To(jk);let{token:o}=await Vr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:x=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(x.trim())||"That doesn't look like a Telegram token"});o||(console.log(ve.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await KO(o.trim());n||(console.log(ve.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ve.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(ve.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await Vr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),u||(console.log(ve.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await Vr({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(ve.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Qn(f,o.trim()),process.env[f]=o.trim();let g=await me(x=>{We(x,"channels.telegram.enabled",!0),We(x,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let S=ks(x,`agents.${u}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),We(x,`agents.${u}.mentions`,S))},{configPath:e.configPath});if(g.success||(console.log(ve.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(ve.dim(` Token stored in .env as ${f}`)),console.log(ve.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(ve.dim(" Daemon hot-reloaded.")):console.log(ve.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Vr({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(ve.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ve.dim(" Waiting up to 90s..."));let h=await XO(o.trim(),9e4);if(!h){console.log(ve.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ve.dim(" agentx config set notifications.destination.channel telegram")),console.log(ve.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ve.dim(` agentx config set notifications.destination.accountId ${p}`));return}let y={channel:"telegram",chatId:String(h.chatId),accountId:p},b=[],v=await me(x=>{We(x,"notifications.destination",y),b=da(x,y)},{configPath:e.configPath});if(!v.success){console.log(ve.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(ve.green(" \u2713 Default --notify target set")),console.log(ve.dim(` Chat: ${h.chatTitle||h.chatId} (from ${h.from})`)),console.log(ve.dim(" From now on, --notify me resolves to this chat.")),b.length&&console.log(ve.dim(` Schedules that now report here: ${b.join(", ")}`)),v.reloaded&&console.log(ve.dim(" Daemon hot-reloaded."))}import Me from"chalk";import gu from"prompts";import{existsSync as pu,mkdirSync as VO,readdirSync as QO,readFileSync as Pk}from"fs";import{resolve as mu}from"path";var ZO=".agentx/whatsapp-sessions";function e1(){let e=mu(process.cwd(),".agentx/daemon.pid");if(!pu(e))return!1;try{let t=parseInt(Pk(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function t1(e){if(!pu(e))return!1;try{return QO(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function o1(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Me.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Me.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;VO(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(u=>{let p=setTimeout(()=>{t(Me.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}u(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){t(Me.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(Me.green(" \u2713 Paired"));try{l.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(Me.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Dk(e={}){if(console.log(),console.log(Me.bold(" Connect WhatsApp")),console.log(),e1()){console.log(Me.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Me.dim(" agentx daemon stop")),console.log();let{cont:l}=await gu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Me.red(" Aborted")),process.exit(1))}let t=e.configPath||mu(process.cwd(),"agentx.json");pu(t)||(console.log(Me.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Pk(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||ZO,s=mu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Me.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await gu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(Me.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(t1(s)&&a){let{keep:l}=await gu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(Me.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await o1(s,u=>console.log(u))||(console.log(Me.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await me(l=>{We(l,"channels.whatsapp.enabled",!0),We(l,"channels.whatsapp.sessionDir",n),We(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Me.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Me.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Me.dim(` Session: ${n}`)),console.log(Me.dim(" Start the daemon to begin receiving:")),console.log(Me.dim(" agentx daemon start")),console.log(Me.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Me.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Me.dim(" Add routes later with:")),console.log(Me.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Rt from"chalk";import n1 from"prompts";import{existsSync as s1,readFileSync as r1}from"fs";import{resolve as i1}from"path";async function a1(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 c1(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 _o(e){console.log(Rt.red(` ${e}`)),process.exit(1)}async function Zn(e){return(await n1(e,{onCancel:()=>_o("Aborted")}))[e.name]}async function Mk(e={}){console.log(),console.log(Rt.bold(" Connect email")),console.log();let t=e.configPath||i1(process.cwd(),"agentx.json");s1(t)||_o(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(r1(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&_o("No agents configured. Run: agentx agent add");let s=e.agent??await Zn({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(y=>({title:y,value:y}))});o.agents?.[s]||_o(`No agent "${s}" in ${t}`);let r=(e.address??await Zn({type:"text",name:"address",message:"Email address customers write to:",validate:y=>/^\S+@\S+\.\S+$/.test(y.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=$h(r),c=e.imapHost??a?.imapHost??await Zn({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await Zn({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await Zn({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await Zn({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&_o("Ports must be numbers.");let p=e.passwordEnv||kh(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&_o(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Rt.dim(` Gmail needs an app password, not your account password: ${yh}`)),console.log(Rt.dim(" (2-step verification must be on for that page to show.)"))),f=(await Zn({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||_o("Aborted");let g={agent:s,address:r,imapHost:c,imapPort:l,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 y=await a1(g,f);y&&(console.log(Rt.red("\u2717")),_o(y)),console.log(Rt.green("\u2713"))}e.passwordEnv||(Qn(p,f),process.env[p]=f);let w=await me(y=>{We(y,"channels.email.enabled",!0),We(y,`channels.email.accounts.${i}`,bh(g))},{configPath:e.configPath});w.success||_o(`Config save failed: ${w.error}`),console.log(),console.log(Rt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Rt.dim(` Password stored in .env as ${p}`)),console.log(Rt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let h=c1(o.agents[s]?.tier,g.allowFrom);h&&console.log(Rt.yellow(` ${h}`)),console.log(g.send==="auto"?Rt.yellow(" Replies are sent as soon as the agent writes them."):Rt.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Rt.dim(" Only mail that arrives from now on is answered.")),console.log(Rt.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as l1}from"crypto";import Ke from"chalk";import Lk from"prompts";var ec="agentx-mesh:",tc="//join/";function d1(e){return Buffer.from(e,"utf-8").toString("base64url")}function u1(e){return Buffer.from(e,"base64url").toString("utf-8")}function g1(e){return`${ec}${tc}${d1(JSON.stringify(e))}`}function m1(e){if(!e.startsWith(`${ec}${tc}`))throw new Error(`Not a mesh invite link \u2014 expected ${ec}${tc}\u2026`);let t=e.slice(ec.length+tc.length),o=JSON.parse(u1(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 p1(){return l1(32).toString("hex")}function f1(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function h1(e){return e?.node?.name||e?.node?.id||"node"}async function qk(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(Ke.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=uu("MESH_TOKEN");i||(i=p1(),Qn("MESH_TOKEN",i),console.log(Ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||f1(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Lk({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(Ke.red(" Aborted")),process.exit(1)),a=d}let l=await me(d=>{We(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ke.red(` \u2717 ${l.error}`)),process.exit(1));let u=g1({url:a,token:i,name:h1(r),version:1});console.log(),console.log(Ke.bold(" Mesh invite")),console.log(),console.log(` ${Ke.cyan(u)}`),console.log(),console.log(Ke.dim(" Run on the other node:")),console.log(Ke.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ke.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Fk(e,t={}){let o;try{o=m1(e)}catch(r){console.log(Ke.red(` \u2717 ${r.message}`)),process.exit(1)}let n=uu("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Lk({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ke.red(" Aborted (keeping existing .env)")),process.exit(1))}Qn("MESH_TOKEN",o.token);let s=await me(r=>{We(r,"mesh.enabled",!0);let i=ks(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),We(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ke.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ke.green(" \u2713 Joined mesh")),console.log(Ke.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ke.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ke.dim(" Daemon hot-reloaded.")):console.log(Ke.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(Ke.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ke.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ke.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var es=new w1().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");es.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 _k({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});es.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 Dk({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});es.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 Mk({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 Uk=es.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Uk.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 qk({url:e.url,configPath:e.config})});Uk.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 Fk(e,{configPath:t.config})});es.action(()=>{console.log(),console.log(or.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${or.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${or.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${or.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${or.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(or.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as y1}from"commander";import ce from"chalk";var ts=new y1().name("usage").description("token usage analysis and reporting");ts.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,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),u=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ce.cyan(a)}: ${l} tokens (${c.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}`))}});ts.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 c=i.now,l=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-c)/6e4)),w=d.resetsAt>c?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",h=l.has(d.window)?ce.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${p.padEnd(12)} ${[f,w,h].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`),l.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}`))}});ts.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?"))}});ts.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 c=null;if(e.baseline)try{c=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(c?{baseline:c,current:a}:a,null,2));return}let l=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)`)),c&&console.log(ce.dim(` Baseline: ${c.from} to ${c.to} (${c.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(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(g=>[g,a.channels[g],c?.channels[g]]).sort((g,w)=>(w[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,c?.total]);for(let[g,w,h]of f){let y=r(w),b=` ${g.padEnd(14)} ${String(w?.tasks||0).padStart(6)} ${u(w?.cacheRead||0).padStart(11)} ${u(w?.cacheCreate||0).padStart(11)} ${u(w?.output||0).padStart(8)} ${l(w?.cost||0).padStart(10)} ${l(y).padStart(9)}`;if(c){let v=r(h),x=y!==null&&v?`${((y-v)/v*100).toFixed(0)}%`:"-";b+=` ${l(v).padStart(9)} ${x.padStart(7)}`}console.log(b)}console.log(),c&&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()});ts.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-Y7D5W52I.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-QHE7PH65.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();c.push(g),l(f,g)}};l(i,"");let u=c.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}/${c.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 $1}from"commander";import He from"chalk";import{readFileSync as b1}from"fs";import{resolve as k1}from"path";te();var rn=new $1().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");rn.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{qg(k1(process.cwd(),".env"))}catch{}let t=v1(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-QKOJEHXS.js");o(t)}catch(t){console.log(He.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(He.dim(t.stack)),process.exit(1)}});function v1(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(He.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(He.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
569
|
+
`}function Qn(e,t,o=".env"){let n=Ik(o),s=Nk(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${du(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${du(t)}`})),JO(n,YO(s))}function uu(e,t=".env"){return Nk(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var jk="https://t.me/BotFather";async function KO(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 XO(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 _k(e={}){console.log(),console.log(ve.bold(" Connect Telegram")),console.log(),console.log(ve.dim(` 1. Open ${jk}`)),console.log(ve.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ve.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Vr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&To(jk);let{token:o}=await Vr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:x=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(x.trim())||"That doesn't look like a Telegram token"});o||(console.log(ve.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await KO(o.trim());n||(console.log(ve.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ve.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(ve.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await Vr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),u||(console.log(ve.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await Vr({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(ve.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Qn(f,o.trim()),process.env[f]=o.trim();let g=await me(x=>{We(x,"channels.telegram.enabled",!0),We(x,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let S=ks(x,`agents.${u}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),We(x,`agents.${u}.mentions`,S))},{configPath:e.configPath});if(g.success||(console.log(ve.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(ve.dim(` Token stored in .env as ${f}`)),console.log(ve.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(ve.dim(" Daemon hot-reloaded.")):console.log(ve.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Vr({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(ve.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ve.dim(" Waiting up to 90s..."));let h=await XO(o.trim(),9e4);if(!h){console.log(ve.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ve.dim(" agentx config set notifications.destination.channel telegram")),console.log(ve.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ve.dim(` agentx config set notifications.destination.accountId ${p}`));return}let y={channel:"telegram",chatId:String(h.chatId),accountId:p},b=[],v=await me(x=>{We(x,"notifications.destination",y),b=da(x,y)},{configPath:e.configPath});if(!v.success){console.log(ve.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(ve.green(" \u2713 Default --notify target set")),console.log(ve.dim(` Chat: ${h.chatTitle||h.chatId} (from ${h.from})`)),console.log(ve.dim(" From now on, --notify me resolves to this chat.")),b.length&&console.log(ve.dim(` Schedules that now report here: ${b.join(", ")}`)),v.reloaded&&console.log(ve.dim(" Daemon hot-reloaded."))}import Me from"chalk";import gu from"prompts";import{existsSync as pu,mkdirSync as VO,readdirSync as QO,readFileSync as Pk}from"fs";import{resolve as mu}from"path";var ZO=".agentx/whatsapp-sessions";function e1(){let e=mu(process.cwd(),".agentx/daemon.pid");if(!pu(e))return!1;try{let t=parseInt(Pk(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function t1(e){if(!pu(e))return!1;try{return QO(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function o1(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Me.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Me.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;VO(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(u=>{let p=setTimeout(()=>{t(Me.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}u(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){t(Me.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(Me.green(" \u2713 Paired"));try{l.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(Me.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Dk(e={}){if(console.log(),console.log(Me.bold(" Connect WhatsApp")),console.log(),e1()){console.log(Me.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Me.dim(" agentx daemon stop")),console.log();let{cont:l}=await gu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Me.red(" Aborted")),process.exit(1))}let t=e.configPath||mu(process.cwd(),"agentx.json");pu(t)||(console.log(Me.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Pk(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||ZO,s=mu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Me.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await gu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(Me.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(t1(s)&&a){let{keep:l}=await gu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(Me.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await o1(s,u=>console.log(u))||(console.log(Me.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await me(l=>{We(l,"channels.whatsapp.enabled",!0),We(l,"channels.whatsapp.sessionDir",n),We(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Me.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Me.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Me.dim(` Session: ${n}`)),console.log(Me.dim(" Start the daemon to begin receiving:")),console.log(Me.dim(" agentx daemon start")),console.log(Me.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Me.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Me.dim(" Add routes later with:")),console.log(Me.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Rt from"chalk";import n1 from"prompts";import{existsSync as s1,readFileSync as r1}from"fs";import{resolve as i1}from"path";async function a1(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 c1(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 _o(e){console.log(Rt.red(` ${e}`)),process.exit(1)}async function Zn(e){return(await n1(e,{onCancel:()=>_o("Aborted")}))[e.name]}async function Mk(e={}){console.log(),console.log(Rt.bold(" Connect email")),console.log();let t=e.configPath||i1(process.cwd(),"agentx.json");s1(t)||_o(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(r1(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&_o("No agents configured. Run: agentx agent add");let s=e.agent??await Zn({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(y=>({title:y,value:y}))});o.agents?.[s]||_o(`No agent "${s}" in ${t}`);let r=(e.address??await Zn({type:"text",name:"address",message:"Email address customers write to:",validate:y=>/^\S+@\S+\.\S+$/.test(y.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=$h(r),c=e.imapHost??a?.imapHost??await Zn({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await Zn({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await Zn({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await Zn({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&_o("Ports must be numbers.");let p=e.passwordEnv||kh(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&_o(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Rt.dim(` Gmail needs an app password, not your account password: ${yh}`)),console.log(Rt.dim(" (2-step verification must be on for that page to show.)"))),f=(await Zn({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||_o("Aborted");let g={agent:s,address:r,imapHost:c,imapPort:l,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 y=await a1(g,f);y&&(console.log(Rt.red("\u2717")),_o(y)),console.log(Rt.green("\u2713"))}e.passwordEnv||(Qn(p,f),process.env[p]=f);let w=await me(y=>{We(y,"channels.email.enabled",!0),We(y,`channels.email.accounts.${i}`,bh(g))},{configPath:e.configPath});w.success||_o(`Config save failed: ${w.error}`),console.log(),console.log(Rt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Rt.dim(` Password stored in .env as ${p}`)),console.log(Rt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let h=c1(o.agents[s]?.tier,g.allowFrom);h&&console.log(Rt.yellow(` ${h}`)),console.log(g.send==="auto"?Rt.yellow(" Replies are sent as soon as the agent writes them."):Rt.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Rt.dim(" Only mail that arrives from now on is answered.")),console.log(Rt.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as l1}from"crypto";import Ke from"chalk";import Lk from"prompts";var ec="agentx-mesh:",tc="//join/";function d1(e){return Buffer.from(e,"utf-8").toString("base64url")}function u1(e){return Buffer.from(e,"base64url").toString("utf-8")}function g1(e){return`${ec}${tc}${d1(JSON.stringify(e))}`}function m1(e){if(!e.startsWith(`${ec}${tc}`))throw new Error(`Not a mesh invite link \u2014 expected ${ec}${tc}\u2026`);let t=e.slice(ec.length+tc.length),o=JSON.parse(u1(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 p1(){return l1(32).toString("hex")}function f1(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function h1(e){return e?.node?.name||e?.node?.id||"node"}async function qk(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(Ke.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=uu("MESH_TOKEN");i||(i=p1(),Qn("MESH_TOKEN",i),console.log(Ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||f1(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Lk({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(Ke.red(" Aborted")),process.exit(1)),a=d}let l=await me(d=>{We(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ke.red(` \u2717 ${l.error}`)),process.exit(1));let u=g1({url:a,token:i,name:h1(r),version:1});console.log(),console.log(Ke.bold(" Mesh invite")),console.log(),console.log(` ${Ke.cyan(u)}`),console.log(),console.log(Ke.dim(" Run on the other node:")),console.log(Ke.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ke.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Fk(e,t={}){let o;try{o=m1(e)}catch(r){console.log(Ke.red(` \u2717 ${r.message}`)),process.exit(1)}let n=uu("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Lk({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ke.red(" Aborted (keeping existing .env)")),process.exit(1))}Qn("MESH_TOKEN",o.token);let s=await me(r=>{We(r,"mesh.enabled",!0);let i=ks(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),We(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ke.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ke.green(" \u2713 Joined mesh")),console.log(Ke.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ke.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ke.dim(" Daemon hot-reloaded.")):console.log(Ke.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(Ke.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ke.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ke.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var es=new w1().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");es.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 _k({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});es.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 Dk({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});es.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 Mk({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 Uk=es.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Uk.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 qk({url:e.url,configPath:e.config})});Uk.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 Fk(e,{configPath:t.config})});es.action(()=>{console.log(),console.log(or.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${or.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${or.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${or.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${or.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(or.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as y1}from"commander";import ce from"chalk";var ts=new y1().name("usage").description("token usage analysis and reporting");ts.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,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),u=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ce.cyan(a)}: ${l} tokens (${c.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}`))}});ts.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 c=i.now,l=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-c)/6e4)),w=d.resetsAt>c?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",h=l.has(d.window)?ce.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${p.padEnd(12)} ${[f,w,h].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`),l.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}`))}});ts.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?"))}});ts.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 c=null;if(e.baseline)try{c=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(c?{baseline:c,current:a}:a,null,2));return}let l=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)`)),c&&console.log(ce.dim(` Baseline: ${c.from} to ${c.to} (${c.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(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(g=>[g,a.channels[g],c?.channels[g]]).sort((g,w)=>(w[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,c?.total]);for(let[g,w,h]of f){let y=r(w),b=` ${g.padEnd(14)} ${String(w?.tasks||0).padStart(6)} ${u(w?.cacheRead||0).padStart(11)} ${u(w?.cacheCreate||0).padStart(11)} ${u(w?.output||0).padStart(8)} ${l(w?.cost||0).padStart(10)} ${l(y).padStart(9)}`;if(c){let v=r(h),x=y!==null&&v?`${((y-v)/v*100).toFixed(0)}%`:"-";b+=` ${l(v).padStart(9)} ${x.padStart(7)}`}console.log(b)}console.log(),c&&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()});ts.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-Y7D5W52I.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-3NLSKRKW.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();c.push(g),l(f,g)}};l(i,"");let u=c.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}/${c.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 $1}from"commander";import He from"chalk";import{readFileSync as b1}from"fs";import{resolve as k1}from"path";te();var rn=new $1().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");rn.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{qg(k1(process.cwd(),".env"))}catch{}let t=v1(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-QXYD62AT.js");o(t)}catch(t){console.log(He.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(He.dim(t.stack)),process.exit(1)}});function v1(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(He.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(He.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
570
570
|
`)),{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}}}}rn.command("list").description("list configured boards").action(()=>{try{let e=O();if(!e.boards?.length){console.log(He.dim(`
|
|
571
571
|
No boards configured.
|
|
572
572
|
`));return}console.log();for(let t of e.boards){console.log(` ${He.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(He.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(He.dim(` primary label: ${t.primaryToolLabel}`)),console.log(He.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(He.red(` ${e.message}`)),process.exit(1)}});rn.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{Qr(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(He.red(` ${o.message}`)),process.exit(1)}});rn.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{Qr(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(He.red(` ${o.message}`)),process.exit(1)}});var fu=rn.command("column").description("manage a board's columns (add / remove / edit / list)");fu.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(b1("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(He.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(` ${He.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${He.dim(r)}`)}}catch(t){console.log(He.red(` ${t.message}`)),process.exit(1)}});fu.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{Qr(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(He.red(` ${n.message}`)),process.exit(1)}});fu.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Qr(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(He.red(` ${o.message}`)),process.exit(1)}});rn.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Qr(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(He.red(` ${t.message}`)),process.exit(1)}});function Qr(e){let{summary:t,backupPath:o}=Pt(n=>e(n));console.log(He.green(`
|
|
@@ -596,19 +596,19 @@ An edit that breaks these rules is refused and the note is deferred.
|
|
|
596
596
|
|
|
597
597
|
${t}
|
|
598
598
|
`}function Hk(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(c=>c.id===i.id||i.id.length>=4&&c.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 c=oc(a.reason||"no reason given");if(a.outcome!=="patched")return{id:i.id,outcome:a.outcome,reason:c,patched:[]};let l=x1(a.edits,o,n.paths,n.agentId);if("refused"in l)return{id:i.id,outcome:"deferred",reason:oc(`patch refused: ${l.refused}. Absorb said: ${c}`),patched:[]};let u=[],d="";for(let[f,{article:g,content:w}]of l.articles){let h=!1;try{h=o.writeArticle(f,{...g.meta,lastUpdated:s,sources:[...new Set([...g.meta.sources??[],wu(i.id)])]},w,n.agentId)}catch(y){d=`${f}: ${y?.message??y}`}if(!h){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:oc(`patch not saved: could not write ${d}. Absorb said: ${c}`),patched:[]}}let p=u.map(f=>f.path);return{id:i.id,outcome:"patched",reason:oc(`${c} (edited ${p.join(", ")})`),patched:p}})}function x1(e,t,o,n){if(e.length===0)return{refused:"patched with no edits"};if(e.length>Zr.edits)return{refused:`more than ${Zr.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 c=t.readArticle(r.path);if(!c)return{refused:`${r.path} is not an existing article`};if(t.canWrite&&!t.canWrite(c.meta,n))return{refused:`no permission to write ${r.path}`};i={article:c,content:c.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>Zr.find||r.replace.length>Zr.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*Zr.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 c=[...S1(i.content,a),...C1(i.content,a)];if(c.length>0)return{refused:`the edit to ${r} drops ${c.slice(0,4).join("; ")}${c.length>4?"; \u2026":""}`}}return{articles:s}}function S1(e,t){let o=Ar(e,t),n=Ar(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 A1=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,E1=/(?<![\w@.])@[A-Za-z0-9_]{3,}/g,R1=/^\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 C1(e,t){let o=t.toLowerCase(),n=[];for(let s of e.matchAll(A1))o.includes(s[0].toLowerCase())||n.push(`email ${s[0]}`);for(let s of e.matchAll(E1))o.includes(s[0].toLowerCase())||n.push(`handle ${s[0]}`);for(let s of e.matchAll(R1)){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 oc(e){return e.length>Jc.reason?`${e.slice(0,Jc.reason-1)}\u2026`:e}import Ye from"chalk";import{resolve as T1}from"path";var O1=e=>e||T1(process.cwd(),".agentx/wiki");async function nr(e){let{FactLedger:t}=await import("./ledger-5GMBLR7W.js");return new t(O1(e))}function sr(e){return async(...t)=>{try{await e(...t)}catch(o){o?.name!=="LedgerCorruptError"&&console.error(Ye.red(` ${o?.message??o}`)),process.exitCode=1}}}function Gk(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(sr(async n=>{let{isStaleFact:s}=await import("./ledger-5GMBLR7W.js"),r=(await nr(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(Ye.dim(" no facts recorded"));return}for(let i of r){let a=i.undated?Ye.yellow(" UNCHECKED"):s(i)?Ye.yellow(" STALE"):"";console.log(` ${Ye.cyan(i.id)} ${Ye.bold(i.subject)} \xB7 ${i.attribute}: ${i.value}${a}`),console.log(Ye.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(sr(async(n,s)=>{let r=(await nr(s.dir)).get(n);if(!r){console.error(Ye.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: ${qc.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(sr(async n=>{if(n.class&&!Yg(n.class)){console.error(Ye.red(` --class must be one of ${qc.join(", ")}`)),process.exitCode=1;return}let r=(await nr(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(Ye.yellow(` not replaced: the wiki says "${r.fact.value}" (checked ${r.fact.verifiedAt.slice(0,10)}), ${i}.`)),console.log(r.questionId?Ye.dim(` Queued question ${r.questionId}: agentx wiki questions \xB7 agentx wiki answer ${r.questionId} "<true value>"`):r.questionClosed?Ye.dim(` A person already ${r.questionClosed} this same claim, so it is not asked again.`):Ye.red(" No question could be queued: the questions file is unreadable. Repair .agentx/wiki/_questions.json.")),process.exitCode=2;return}console.log(Ye.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(sr(async n=>{let{listFactProposals:s}=await import("./fact-proposals-Z7HJG7QJ.js"),r=s(await nr(n.dir),n.all?void 0:"pending");if(n.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(Ye.dim(" no fact proposals waiting"));return}for(let i of r)console.log(` ${Ye.cyan(i.id)} ${i.status==="pending"?"":Ye.dim(`[${i.status}] `)}${i.claim}`),console.log(Ye.dim(` ${i.agentId} \xB7 ${i.origin} \xB7 ${i.source} \xB7 ${i.verifiedAt.slice(0,10)}`));console.log(Ye.dim(`
|
|
599
|
-
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(sr(async(n,s)=>{let{approveFactProposal:r}=await import("./fact-proposals-Z7HJG7QJ.js"),{write:i}=r(await nr(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(Ye.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(sr(async(n,s)=>{let{rejectFactProposal:r}=await import("./fact-proposals-Z7HJG7QJ.js"),i=r(await nr(s.dir),n,s.by,s.reason);console.log(Ye.dim(` rejected: ${i.claim}`))}))}import Ze from"chalk";import{existsSync as zk,readFileSync as Yk}from"fs";import{resolve as $u}from"path";var yu=e=>e||$u(process.cwd(),".agentx/wiki");function I1(e){if(e)return e.replace(/\/+$/,"");if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL.replace(/\/+$/,"");try{let t=$u(process.cwd(),"agentx.json");if(zk(t)){let o=JSON.parse(Yk(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 bo(e){console.error(Ze.red(` ${e}`)),process.exitCode=1}function nc(e){return async(...t)=>{try{await e(...t)}catch(o){bo(o?.message??String(o))}}}function Kk(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(nc(async o=>{if(!o.from){bo("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){bo("--dir needs --to <inbox agent>");return}let{NoteStore:a,validateNote:c}=await import("./notes-WJJEJ4CJ.js"),l=c({...n,to:o.to});if("error"in l){bo(l.error);return}s={ok:!0,...new a(yu(o.dir)).add(l.note)}}else{let a=I1(o.daemon),c;try{c=await fetch(`${a}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(2e4)})}catch(l){bo(`could not reach the daemon at ${a}: ${l?.message??l}`);return}if(s=await c.json().catch(()=>({})),!c.ok){bo(s?.error||`daemon answered ${c.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?Ze.dim(` already in the inbox${i}: ${r?.id} (${r?.status})`):Ze.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(nc(async o=>{let{NoteStore:n}=await import("./notes-WJJEJ4CJ.js"),s=["waiting","open","patched","rejected","deferred","expired","all"];if(!s.includes(o.status)){bo(`--status must be one of ${s.join(", ")}`);return}let r=new n(yu(o.dir)),i=r.load();if(i.unreadable){bo(`${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(Ze.dim(` no ${o.status==="all"?"":`${o.status} `}notes`));return}for(let c of a){let l=c.status==="open"?Ze.yellow("open"):c.status==="deferred"?Ze.yellow("deferred"):Ze.dim(c.status);console.log(` ${Ze.cyan(c.id)} ${l} \xB7 from ${c.from}${c.fromNode?` on ${c.fromNode}`:""} \xB7 ${c.date}`),console.log(` ${c.change}`),console.log(Ze.dim(` source: ${c.source}`)),c.listedIn?.length&&console.log(Ze.dim(` given to: ${c.listedIn.at(-1)}${c.listedIn.length>1?` (+${c.listedIn.length-1} earlier)`:""}`)),c.handled&&console.log(Ze.dim(` ${c.handled.outcome}${c.deferrals?` (deferred ${c.deferrals}x)`:""} by ${c.handled.by} ${c.handled.at.slice(0,10)}: ${c.handled.reason}`)),c.expired&&console.log(Ze.dim(` expired ${c.expired.at.slice(0,10)} after ${c.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(nc(async(o,n)=>{let{NoteStore:s}=await import("./notes-WJJEJ4CJ.js"),r=new s(yu(n.dir)).handle(o,n.outcome,n.reason,n.by,n.run);console.log(Ze.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(nc(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){bo("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:c}=await import("./config-mutate-633Q77K3.js"),{summary:l}=c(u=>n(u,r));console.log(Ze.green(` ${l}`))}let i=$u(process.cwd(),"agentx.json");if(!zk(i)){bo(`agentx.json not found at ${i}`);return}let a=s(JSON.parse(Yk(i,"utf-8"))?.wikiNotes);if(o.json){console.log(JSON.stringify(a,null,2));return}console.log(` wiki notes: ${a.enabled?Ze.green("on"):Ze.dim("off")}`),console.log(` inbox agent: ${a.inbox||Ze.dim("not set")}`),console.log(` schedules that read it: ${a.crons.length?a.crons.join(", "):Ze.dim("none on this node")}`),console.log(` absorb that reads it: ${a.absorbAgent?`wiki absorb for ${a.absorbAgent}`:Ze.dim("none")}`),console.log(` most notes per run: ${a.maxNotesPerRun}`),console.log(` deferrals before a note expires: ${a.maxDeferrals}`)}))}import an from"chalk";import{resolve as N1}from"path";var bu=e=>e||N1(process.cwd(),".agentx/wiki");function Xk(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(bu(o.dir));console.log(an.green(` wrote ${s}`))}catch(s){console.error(an.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(bu(o.dir));if(!s){console.log(an.dim(" no ontology.yaml: the built-in defaults are in use"));return}if(r.length===0){console.log(an.green(` ${s}: no problems`));return}console.log(an.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-PG4OFRIQ.js"),i=bu(o.dir),{loadRoster:a}=await import("./roster-BZGKG2ZA.js"),{ontology:c,errors:l}=n(i),u=new r(i,()=>{}),d=new s().get(u,c,a(i,u.listAgents([]),c.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:l},null,2));return}console.log(an.bold(` ${d.entities.size} entities`));for(let f of c.pillars){let g=c.types.filter(h=>h.pillar===f.id),w=g.reduce((h,y)=>h+(p.get(y.id)??0),0);console.log(` ${f.label.padEnd(26)} ${String(w).padStart(6)} ${an.dim(g.map(h=>`${h.id} ${p.get(h.id)??0}`).join(" \xB7 "))}`)}l.length&&console.log(an.yellow(` ontology.yaml has ${l.length} problem(s): agentx wiki ontology check`))})}import st from"chalk";import{resolve as j1}from"path";var ku=e=>e||j1(process.cwd(),".agentx/wiki"),_1=()=>new Date().toISOString().slice(0,10);async function vu(e){let{WikiHub:t}=await import("./hub-PG4OFRIQ.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 Vk(e,t){let o=Number(e);return Number.isInteger(o)&&o>=1?o:(console.error(st.red(` ${t} must be a whole number, 1 or more`)),process.exitCode=1,null)}function Qk(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-LREINNTK.js"),i=Vk(o.max,"--max"),a=Vk(o.batch,"--batch");if(i===null||a===null)return;let c=Number(o.maxCost);if(!Number.isFinite(c)||c<=0){console.error(st.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let{hub:l,g:u}=await vu(ku(o.dir)),d=o.about??[],{normName:p}=await import("./graph-ZVKV3JBD.js"),f=d.filter(y=>!u.names.has(p(y))&&!u.entities.has(y));if(f.length){console.error(st.red(` no page is titled: ${f.join(", ")}`)),process.exitCode=1;return}let g=await n(l,u,r(o.model),{about:d,max:i,batch:a,maxCostUsd:c,dryRun:!!o.dryRun,force:!!o.force,rulesOnly:!!o.rulesOnly,today:_1()}),w=s(u,g,d);if(o.json){console.log(JSON.stringify({...g,about:w},null,2));return}for(let y of g.outcomes){let b=y.status==="written"?st.green("\u2713"):y.status==="dry-run"?st.cyan("~"):st.yellow("\xB7"),v=y.importance?`${y.importance}${y.proposed?` (proposed ${y.proposed})`:""}`:y.status;console.log(` ${b} ${y.date||"no date "} ${v.padEnd(8)} ${y.title} ${st.dim(`${y.by??y.status}${y.about.length?` \xB7 about ${y.about.join(", ")}`:""}${y.why?` \xB7 ${y.why}`:""}`)}`);for(let x of y.dropped.slice(0,4))console.log(st.dim(` dropped: ${x}`))}for(let y of w)console.log(st.bold(` ${y.title}`)+st.dim(` (${y.type}): ${y.before} events in its History before \xB7 after: ${y.after.major} major, ${y.after.normal} normal, ${y.after.minor} minor (folded)`));let h=g.outcomes.filter(y=>y.importance).length;g.outcomes.length===0&&console.log(st.dim(" nothing to do: every event in scope already has a level (--force redoes the ones this job set)")),console.log(st.dim(` ${h} event${h===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 $${c}${g.capped?" \xB7 stopped at the cap":""}`)),g.outcomes.some(y=>y.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"),c=n.toLowerCase();if(!a.includes(c)){console.error(st.red(` level must be one of ${a.join(", ")}`)),process.exitCode=1;return}let{hub:l,g:u}=await vu(ku(r.optsWithGlobals().dir)),d=i(l,u,o,c);d.ok?console.log(st.green(` ${d.title} is now ${c}`)+st.dim(` (${d.page})`)):(console.error(st.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 vu(ku(s.dir)),i=[...r.entities.values()].filter(a=>a.type==="event"&&a.importanceProposed&&a.importanceProposed!==a.importance).sort((a,c)=>(c.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} ${st.dim(`now ${a.importance}, proposed ${a.importanceProposed}`)}`);console.log(st.dim(i.length?` ${i.length} waiting. Decide each with: agentx wiki events set "<title>" major (or normal)`:" none waiting"))})}import Nt from"chalk";import{resolve as P1}from"path";var D1=e=>e||P1(process.cwd(),".agentx/wiki");function Zk(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-PG4OFRIQ.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:c,runRules:l,saveRulesState:u}=await import("./rules-FBOLGE2S.js"),d=D1(o.dir),p=Number(o.max);if(!Number.isInteger(p)||p<1){console.error(Nt.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(Nt.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let g=o.words?.split(",").map(x=>x.trim()).filter(Boolean);if(o.words!==void 0&&!g?.length){console.error(Nt.red(" --words needs at least one word")),process.exitCode=1;return}let w=new n(d,()=>{}),{ontology:h}=r(d);if(!h.types.some(x=>x.id==="obligation")){console.error(Nt.red(" ontology.yaml has no `obligation` type; add it back to write rule pages")),process.exitCode=1;return}let y=new s().get(w,h,i(d,w.listAgents([]),h.agent_names)),b=a(d),v=await l(w,y,qh(o.model),{only:t,words:c(g),max:p,maxCostUsd:f,dryRun:!!o.dryRun,force:!!o.force,today:new Date().toISOString().slice(0,10),save:x=>u(d,x)},b);if(o.json){console.log(JSON.stringify(v,null,2));return}for(let x of v.outcomes){let S=x.status==="written"?Nt.green("\u2713"):x.status==="dry-run"?Nt.cyan("~"):Nt.yellow("\xB7");console.log(` ${S} ${x.title} ${Nt.dim(`${x.status} \xB7 ${x.page??"no page"} \xB7 ${x.rules.length} rules \xB7 $${x.costUsd.toFixed(3)}`)}`);for(let k of x.rules){let E=[k.deadline?"":"no deadline",k.penalty?"":"no penalty"].filter(Boolean);console.log(` ${k.created?"new":"updated"}: ${k.title} ${Nt.dim(`\xB7 ${k.page}${E.length?` \xB7 ${E.join(", ")}`:""}${k.linked.length?` \xB7 linked from ${k.linked.join(", ")}`:""}`)}`),k.preview&&console.log(Nt.dim(k.preview.split(`
|
|
599
|
+
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(sr(async(n,s)=>{let{approveFactProposal:r}=await import("./fact-proposals-Z7HJG7QJ.js"),{write:i}=r(await nr(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(Ye.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(sr(async(n,s)=>{let{rejectFactProposal:r}=await import("./fact-proposals-Z7HJG7QJ.js"),i=r(await nr(s.dir),n,s.by,s.reason);console.log(Ye.dim(` rejected: ${i.claim}`))}))}import Ze from"chalk";import{existsSync as zk,readFileSync as Yk}from"fs";import{resolve as $u}from"path";var yu=e=>e||$u(process.cwd(),".agentx/wiki");function I1(e){if(e)return e.replace(/\/+$/,"");if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL.replace(/\/+$/,"");try{let t=$u(process.cwd(),"agentx.json");if(zk(t)){let o=JSON.parse(Yk(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 bo(e){console.error(Ze.red(` ${e}`)),process.exitCode=1}function nc(e){return async(...t)=>{try{await e(...t)}catch(o){bo(o?.message??String(o))}}}function Kk(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(nc(async o=>{if(!o.from){bo("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){bo("--dir needs --to <inbox agent>");return}let{NoteStore:a,validateNote:c}=await import("./notes-WJJEJ4CJ.js"),l=c({...n,to:o.to});if("error"in l){bo(l.error);return}s={ok:!0,...new a(yu(o.dir)).add(l.note)}}else{let a=I1(o.daemon),c;try{c=await fetch(`${a}/wiki/notes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(2e4)})}catch(l){bo(`could not reach the daemon at ${a}: ${l?.message??l}`);return}if(s=await c.json().catch(()=>({})),!c.ok){bo(s?.error||`daemon answered ${c.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?Ze.dim(` already in the inbox${i}: ${r?.id} (${r?.status})`):Ze.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(nc(async o=>{let{NoteStore:n}=await import("./notes-WJJEJ4CJ.js"),s=["waiting","open","patched","rejected","deferred","expired","all"];if(!s.includes(o.status)){bo(`--status must be one of ${s.join(", ")}`);return}let r=new n(yu(o.dir)),i=r.load();if(i.unreadable){bo(`${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(Ze.dim(` no ${o.status==="all"?"":`${o.status} `}notes`));return}for(let c of a){let l=c.status==="open"?Ze.yellow("open"):c.status==="deferred"?Ze.yellow("deferred"):Ze.dim(c.status);console.log(` ${Ze.cyan(c.id)} ${l} \xB7 from ${c.from}${c.fromNode?` on ${c.fromNode}`:""} \xB7 ${c.date}`),console.log(` ${c.change}`),console.log(Ze.dim(` source: ${c.source}`)),c.listedIn?.length&&console.log(Ze.dim(` given to: ${c.listedIn.at(-1)}${c.listedIn.length>1?` (+${c.listedIn.length-1} earlier)`:""}`)),c.handled&&console.log(Ze.dim(` ${c.handled.outcome}${c.deferrals?` (deferred ${c.deferrals}x)`:""} by ${c.handled.by} ${c.handled.at.slice(0,10)}: ${c.handled.reason}`)),c.expired&&console.log(Ze.dim(` expired ${c.expired.at.slice(0,10)} after ${c.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(nc(async(o,n)=>{let{NoteStore:s}=await import("./notes-WJJEJ4CJ.js"),r=new s(yu(n.dir)).handle(o,n.outcome,n.reason,n.by,n.run);console.log(Ze.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(nc(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){bo("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:c}=await import("./config-mutate-G46QCYCR.js"),{summary:l}=c(u=>n(u,r));console.log(Ze.green(` ${l}`))}let i=$u(process.cwd(),"agentx.json");if(!zk(i)){bo(`agentx.json not found at ${i}`);return}let a=s(JSON.parse(Yk(i,"utf-8"))?.wikiNotes);if(o.json){console.log(JSON.stringify(a,null,2));return}console.log(` wiki notes: ${a.enabled?Ze.green("on"):Ze.dim("off")}`),console.log(` inbox agent: ${a.inbox||Ze.dim("not set")}`),console.log(` schedules that read it: ${a.crons.length?a.crons.join(", "):Ze.dim("none on this node")}`),console.log(` absorb that reads it: ${a.absorbAgent?`wiki absorb for ${a.absorbAgent}`:Ze.dim("none")}`),console.log(` most notes per run: ${a.maxNotesPerRun}`),console.log(` deferrals before a note expires: ${a.maxDeferrals}`)}))}import an from"chalk";import{resolve as N1}from"path";var bu=e=>e||N1(process.cwd(),".agentx/wiki");function Xk(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(bu(o.dir));console.log(an.green(` wrote ${s}`))}catch(s){console.error(an.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(bu(o.dir));if(!s){console.log(an.dim(" no ontology.yaml: the built-in defaults are in use"));return}if(r.length===0){console.log(an.green(` ${s}: no problems`));return}console.log(an.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-E56MSG7W.js"),i=bu(o.dir),{loadRoster:a}=await import("./roster-BZGKG2ZA.js"),{ontology:c,errors:l}=n(i),u=new r(i,()=>{}),d=new s().get(u,c,a(i,u.listAgents([]),c.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:l},null,2));return}console.log(an.bold(` ${d.entities.size} entities`));for(let f of c.pillars){let g=c.types.filter(h=>h.pillar===f.id),w=g.reduce((h,y)=>h+(p.get(y.id)??0),0);console.log(` ${f.label.padEnd(26)} ${String(w).padStart(6)} ${an.dim(g.map(h=>`${h.id} ${p.get(h.id)??0}`).join(" \xB7 "))}`)}l.length&&console.log(an.yellow(` ontology.yaml has ${l.length} problem(s): agentx wiki ontology check`))})}import st from"chalk";import{resolve as j1}from"path";var ku=e=>e||j1(process.cwd(),".agentx/wiki"),_1=()=>new Date().toISOString().slice(0,10);async function vu(e){let{WikiHub:t}=await import("./hub-E56MSG7W.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 Vk(e,t){let o=Number(e);return Number.isInteger(o)&&o>=1?o:(console.error(st.red(` ${t} must be a whole number, 1 or more`)),process.exitCode=1,null)}function Qk(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-PK5XQCV3.js"),i=Vk(o.max,"--max"),a=Vk(o.batch,"--batch");if(i===null||a===null)return;let c=Number(o.maxCost);if(!Number.isFinite(c)||c<=0){console.error(st.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let{hub:l,g:u}=await vu(ku(o.dir)),d=o.about??[],{normName:p}=await import("./graph-ZVKV3JBD.js"),f=d.filter(y=>!u.names.has(p(y))&&!u.entities.has(y));if(f.length){console.error(st.red(` no page is titled: ${f.join(", ")}`)),process.exitCode=1;return}let g=await n(l,u,r(o.model),{about:d,max:i,batch:a,maxCostUsd:c,dryRun:!!o.dryRun,force:!!o.force,rulesOnly:!!o.rulesOnly,today:_1()}),w=s(u,g,d);if(o.json){console.log(JSON.stringify({...g,about:w},null,2));return}for(let y of g.outcomes){let b=y.status==="written"?st.green("\u2713"):y.status==="dry-run"?st.cyan("~"):st.yellow("\xB7"),v=y.importance?`${y.importance}${y.proposed?` (proposed ${y.proposed})`:""}`:y.status;console.log(` ${b} ${y.date||"no date "} ${v.padEnd(8)} ${y.title} ${st.dim(`${y.by??y.status}${y.about.length?` \xB7 about ${y.about.join(", ")}`:""}${y.why?` \xB7 ${y.why}`:""}`)}`);for(let x of y.dropped.slice(0,4))console.log(st.dim(` dropped: ${x}`))}for(let y of w)console.log(st.bold(` ${y.title}`)+st.dim(` (${y.type}): ${y.before} events in its History before \xB7 after: ${y.after.major} major, ${y.after.normal} normal, ${y.after.minor} minor (folded)`));let h=g.outcomes.filter(y=>y.importance).length;g.outcomes.length===0&&console.log(st.dim(" nothing to do: every event in scope already has a level (--force redoes the ones this job set)")),console.log(st.dim(` ${h} event${h===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 $${c}${g.capped?" \xB7 stopped at the cap":""}`)),g.outcomes.some(y=>y.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"),c=n.toLowerCase();if(!a.includes(c)){console.error(st.red(` level must be one of ${a.join(", ")}`)),process.exitCode=1;return}let{hub:l,g:u}=await vu(ku(r.optsWithGlobals().dir)),d=i(l,u,o,c);d.ok?console.log(st.green(` ${d.title} is now ${c}`)+st.dim(` (${d.page})`)):(console.error(st.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 vu(ku(s.dir)),i=[...r.entities.values()].filter(a=>a.type==="event"&&a.importanceProposed&&a.importanceProposed!==a.importance).sort((a,c)=>(c.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} ${st.dim(`now ${a.importance}, proposed ${a.importanceProposed}`)}`);console.log(st.dim(i.length?` ${i.length} waiting. Decide each with: agentx wiki events set "<title>" major (or normal)`:" none waiting"))})}import Nt from"chalk";import{resolve as P1}from"path";var D1=e=>e||P1(process.cwd(),".agentx/wiki");function Zk(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-E56MSG7W.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:c,runRules:l,saveRulesState:u}=await import("./rules-FBOLGE2S.js"),d=D1(o.dir),p=Number(o.max);if(!Number.isInteger(p)||p<1){console.error(Nt.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(Nt.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let g=o.words?.split(",").map(x=>x.trim()).filter(Boolean);if(o.words!==void 0&&!g?.length){console.error(Nt.red(" --words needs at least one word")),process.exitCode=1;return}let w=new n(d,()=>{}),{ontology:h}=r(d);if(!h.types.some(x=>x.id==="obligation")){console.error(Nt.red(" ontology.yaml has no `obligation` type; add it back to write rule pages")),process.exitCode=1;return}let y=new s().get(w,h,i(d,w.listAgents([]),h.agent_names)),b=a(d),v=await l(w,y,qh(o.model),{only:t,words:c(g),max:p,maxCostUsd:f,dryRun:!!o.dryRun,force:!!o.force,today:new Date().toISOString().slice(0,10),save:x=>u(d,x)},b);if(o.json){console.log(JSON.stringify(v,null,2));return}for(let x of v.outcomes){let S=x.status==="written"?Nt.green("\u2713"):x.status==="dry-run"?Nt.cyan("~"):Nt.yellow("\xB7");console.log(` ${S} ${x.title} ${Nt.dim(`${x.status} \xB7 ${x.page??"no page"} \xB7 ${x.rules.length} rules \xB7 $${x.costUsd.toFixed(3)}`)}`);for(let k of x.rules){let E=[k.deadline?"":"no deadline",k.penalty?"":"no penalty"].filter(Boolean);console.log(` ${k.created?"new":"updated"}: ${k.title} ${Nt.dim(`\xB7 ${k.page}${E.length?` \xB7 ${E.join(", ")}`:""}${k.linked.length?` \xB7 linked from ${k.linked.join(", ")}`:""}`)}`),k.preview&&console.log(Nt.dim(k.preview.split(`
|
|
600
600
|
`).map(C=>` | ${C}`).join(`
|
|
601
|
-
`)))}for(let k of x.dropped.slice(0,6))console.log(Nt.dim(` dropped: ${k}`))}v.outcomes.length===0&&console.log(Nt.dim(" nothing to do: no page that states rules changed since the last run (--force reads them again)")),console.log(Nt.dim(` spent $${v.costUsd.toFixed(3)} of $${f}${v.capped?" \xB7 stopped at the cap":""}`))})}import sc from"chalk";import{resolve as M1}from"path";var L1=e=>e||M1(process.cwd(),".agentx/wiki");function ev(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-
|
|
601
|
+
`)))}for(let k of x.dropped.slice(0,6))console.log(Nt.dim(` dropped: ${k}`))}v.outcomes.length===0&&console.log(Nt.dim(" nothing to do: no page that states rules changed since the last run (--force reads them again)")),console.log(Nt.dim(` spent $${v.costUsd.toFixed(3)} of $${f}${v.capped?" \xB7 stopped at the cap":""}`))})}import sc from"chalk";import{resolve as M1}from"path";var L1=e=>e||M1(process.cwd(),".agentx/wiki");function ev(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-K77I5LJP.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-QBTOYJA7.js");r=u().wiki.summaries}catch{}let i=new o(L1(t.dir),void 0,"graph"),a=t.agent||process.env.AGENTX_AGENT_ID;if(!t.all&&!a){console.log(sc.red(" Name an agent with --agent <id>, or pass --all.")),process.exitCode=1;return}let c=t.all?[...i.sharedScope("").map(u=>({id:u.id,store:u.store,skip:u.skip}))]:[{id:a,store:i.getAgentWiki(a),skip:void 0}],l=[];for(let u of c){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(sc.dim(` ${u.id}: ${p}`))});if(l.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?sc.yellow(`, ${d.failed} failed`):""}${d.removed?`, ${d.removed} removed`:""}`;console.log(` ${sc.bold(u.id)}: ${d.pages} pages, ${p}`)}}t.json&&console.log(JSON.stringify(l,null,2)),l.some(u=>u.failed>0)&&(process.exitCode=1)})}import{resolve as W,relative as tv,dirname as ov}from"path";import{exec as F1,execSync as os}from"child_process";import{promisify as U1}from"util";import{appendFileSync as W1,statSync as B1,writeFileSync as Wt,mkdirSync as eo,readFileSync as jt,readdirSync as J1,renameSync as rc,rmSync as Su,existsSync as et}from"fs";var cv=U1(F1);function Ae(e,t){return new Lc(kt(e),void 0,t||"graph")}async function lv(e){let t=[];try{let{loadDaemonConfig:n}=await import("./config-QBTOYJA7.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 dv(){try{let{loadDaemonConfig:e}=await import("./config-QBTOYJA7.js"),t=Object.keys(e().agents||{});return t.length?new Set(t):null}catch{return null}}async function nv(){try{let{loadDaemonConfig:e}=await import("./config-QBTOYJA7.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 H1(){try{let{loadDaemonConfig:e}=await import("./config-QBTOYJA7.js");return Ch(e().agents||{})}catch{return new Set}}function ns(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 sv(){let{sharedQueryEnabled:e}=await import("./query-PYJN4G32.js");return e()}async function uv(e){let{loadQuerySettings:t}=await import("./query-settings-XFOY343Z.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 kt(e){return e||W(process.cwd(),".agentx/wiki")}function Au(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var X=new q1().name("wiki").description("wiki knowledge base management");Gk(X);Kk(X);Xk(X);Fh(X);Qk(X);Zk(X);ev(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=Ae(e.dir,t),n=o.summary(),r=o.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${Au(t)}]`)),console.log(),console.log(` Total raw entries: ${r}`),console.log(` Agents: ${n.length}`);let i=W(o.getBaseDir(),Bg);if(et(i)){let c=new Date(Date.now()-6048e5).toISOString(),l=Jg(jt(i,"utf-8"),c),u=l.failed>0?m.red(`${l.failed} failed to write`):"0 failed to write";console.log(` Tasks, last 7 days: ${l.total} captured ${l.captured} \xB7 skipped ${l.skipped} \xB7 ${u}`);let d=Object.entries(l.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 c of n){let l=c.unabsorbed>0?m.yellow(`${c.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(c.agentId)}`),console.log(` Entries: ${c.totalEntries} Articles: ${c.totalArticles} ${l}`),console.log(m.dim(` Cited by an article: ${c.cited} Read, not cited: ${c.readNotCited}`)),c.articles.length>0){for(let u of c.articles.slice(0,3))console.log(m.dim(` - ${u.title} [${(u.tags||[]).slice(0,3).join(", ")}]`));c.articles.length>3&&console.log(m.dim(` ... and ${c.articles.length-3} more`))}console.log()}let a=n.reduce((c,l)=>c+l.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=Ae(e.dir,e.mode),o=e.agent?[e.agent]:t.listAgents(),n=0;console.log();for(let i of o){let c=t.getAgentWiki(i).lint();if(n+=c.length,c.length===0)console.log(` ${m.cyan(i)}: ${m.green("healthy")}`);else{console.log(` ${m.cyan(i)}: ${m.yellow(`${c.length} issues`)}`);for(let l of c){let u=l.type==="broken-link"?"x":l.type==="orphan"?"?":"!";console.log(` [${u}] ${m.dim(l.type)} ${l.article}: ${l.message}`)}}}let{factContradictions:s}=await import("./ledger-5GMBLR7W.js"),r=s(kt(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=hu(e.model)}catch(C){console.log(m.red(` ${C.message}`)),process.exitCode=1;return}let n=Ae(e.dir,t),s=await dv(),{agents:r,skipped:i}=Th(n.listAgents().filter(C=>!s||s.has(C)),{only:e.agent,off:await H1()}),a=i.length&&e.notes!==!1?(await nv())?.absorbAgent:void 0;for(let C of i)console.log(` ${m.cyan(C)}: ${m.dim(Oh(C,a))}`);let c=r.filter(C=>{let T=n.syncedFrom(C);return T&&console.log(` ${m.cyan(C)}: ${m.dim(`copied from ${T.node}, read-only here; absorb it there`)}`),!T}),l=parseInt(e.max),u=(()=>{try{let C=W(process.cwd(),".agentx/graph");return et(C)?new Fo({baseDir:C}):null}catch{return null}})(),d=new Map;if(u)try{let C=u.loadIndex();for(let[T,N]of Object.entries(C.entries))d.set(T,N.path)}catch{}let p,f=C=>{let T=C.meta?.intentPath;if(Array.isArray(T)&&T.every(D=>typeof D=="string")&&T.length>0)return T;if(!u||d.size===0)return;let N=String(C.meta?.sender??""),q=u.fingerprint({text:C.content,channel:C.source,sender:N});return d.get(q)},g=(C,T)=>{let N=new Map;for(let D of C){let G=T.find(z=>z.id===D);if(!G)continue;let B=f(G);if(!B?.length)continue;let A=B.join("/"),_=N.get(A);_?_.n++:N.set(A,{path:B,n:1})}if(N.size===0)return;let q;for(let D of N.values())(!q||D.n>q.n)&&(q=D);return q?.path},w=0,h=0,y=0,b=W(n.getBaseDir(),"_absorb-runs.jsonl"),v=typeof e.runLabel=="string"&&e.runLabel.trim()?e.runLabel.trim():void 0,x=C=>{if(!e.dryRun)try{W1(b,`${JSON.stringify(C)}
|
|
602
602
|
`)}catch{}},S=new Date().toISOString(),k=e.notes===!1?null:await nv(),E=k?new cm(n.getBaseDir()):null;for(let C of c){let T=Date.now(),N=typeof e.since=="string"?e.since.trim():"",q=typeof e.until=="string"?e.until.trim():"",D=n.getUnabsorbedEntries(C).filter(ge=>!N||(ge.date??"")>=N).filter(ge=>!q||(ge.date??"").slice(0,10)<=q).slice(0,l),G=!!(k&&E&&k.absorbAgent===C),B=`absorb/${C}/${S.replace(/[:.]/g,"-")}`,A=[];if(G&&e.dryRun?A=E.peekForRun(k.inbox,k.max,k.maxDeferrals):G&&(A=E.takeForRun(k.inbox,B,k.max,k.maxDeferrals)),D.length===0&&A.length===0){console.log(` ${m.cyan(C)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(C)}: ${D.length} entries to absorb`));for(let ge of D.slice(0,3))console.log(m.dim(` [${ge.date} via ${ge.source}] ${ge.content.slice(0,80)}...`));if(D.length>3&&console.log(m.dim(` ... and ${D.length-3} more`)),A.length>0&&console.log(m.dim(` Wiki notes: ${A.length} from the ${k.inbox} inbox${e.dryRun?"":` (run ${B})`}`)),e.dryRun)continue;let _=n.getAgentWiki(C),z=_.rebuildIndex(),fe=_.getWorldview()||n.getSharedStore().getWorldview()||"",P=D.map(ge=>`--- ENTRY ${ge.id} [${ge.date} ${ge.agentId} via ${ge.source}] ---
|
|
603
603
|
${ge.content}
|
|
604
604
|
--- END ENTRY ---`).join(`
|
|
605
605
|
|
|
606
|
-
`),Q="";if(e.facts!==!1){let{extractHints:ge,resolveFacts:gn,mergeRecords:ls,renderFactsBlock:ds,installPrompts:pi,defaultSources:us,recordsFromEntries:mn}=await import("./facts-ALJBF7IA.js");if(!p){let U=new Set;for(let Ge of n.listAgents())for(let vt of n.getAgentWiki(Ge).listArticles(Ge))vt.meta.type==="person"&&U.add(vt.meta.title);p=[...U]}let pn=ge(D.map(U=>({context:U.sourceContext,content:U.content,sender:typeof U.meta?.sender=="string"?U.meta.sender:void 0})),{known:p}),gs=mn(D);if(pn.length>0||gs.length>0){let U=us(),{records:Ge,results:vt}=pn.length>0?await gn(pn,{sources:U}):{records:[],results:[]},Re=ls([...gs,...Ge]);Q=ds(Re);let at=[...gs.length>0?[`entries:${gs.length}`]:[],...vt.filter(Ue=>Ue.records.length>0).map(Ue=>`${Ue.source}:${Ue.records.length}`)];console.log(m.dim(` Facts: ${pn.length} entities \u2192 ${Re.length} resolved${at.length?` (${at.join(" ")})`:""}`));for(let Ue of pi(vt,U))console.log(m.yellow(` ! ${Ue.source} ${Ue.kind} \u2014 would supply ${Ue.provides.join(", ")}`)),console.log(m.dim(` ${Ue.hint}`))}}let $e=z.articles.filter(ge=>ge.path&&!ge.path.includes("/_versions/")),ie=await Ph([...D,...A.map(ge=>({id:wu(ge.id),content:ge.change}))],_,C,$e);ie.length>0&&console.log(m.dim(` Existing: ${ie.map(ge=>ge.path).join(", ")}`));let j=Dh(ie),oe=Jk(A),Xe=tl(t,C,fe,z.articles,P,D.length,Q,j,oe);console.log(m.dim(` Mode: ${Au(t)}`));let no=W(_.baseDir,"_tmp");eo(no,{recursive:!0});let qe=W(no,"absorb-prompt.txt");Wt(qe,Xe),console.log(m.dim(` Compiling with Claude (${o})...`));let Fe={kind:"call",at:"",label:v,agent:C,model:o,entries:D.length,articles:0,refused:0,failed:!0,wallMs:0,promptChars:Xe.length,promptParts:{entries:P.length,catalog:Xe.length-tl(t,C,fe,[],P,D.length,Q,j,oe).length,catalogArticles:z.articles.length,covering:j.length,facts:Q.length,worldview:fe.length,notes:oe.length},...A.length?{notes:A.length}:{}},xo=Date.now();Fe.prepMs=xo-T;try{let ge,gn=!1;try{ge=os(`cat '${qe}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:qo(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(U){if(ge=U.stdout||"",!ge)throw U;gn=!0}let ls=ge;try{let U=JSON.parse(ge);Object.assign(Fe,El(U)),U.is_error===!0&&(gn=!0),ls=U.result||U.content||"",ls||(console.log(m.dim(` Claude envelope keys: ${Object.keys(U).join(", ")}`)),console.log(m.dim(` is_error: ${U.is_error}, stop_reason: ${U.stop_reason}`)))}catch{}let ds=Wk(ls);if("error"in ds){A.length>0&&console.log(m.yellow(` ${A.length} wiki note(s) stay waiting`)),console.log(m.red(` ${ds.error}`)),console.log(m.dim(` First 500 chars: ${ls.slice(0,500)}`));continue}let{articles:pi,gaps:us}=ds,mn=new Set,pn=new Set,gs=new Set(D.map(U=>U.id));for(let U of pi){let Ge=new Date().toISOString().slice(0,10),vt=Array.isArray(U.sources)?U.sources:[],Re=A.length>0?vt.filter(Lo=>gs.has(Lo)):vt;if(A.length>0&&Re.length===0){console.log(m.yellow(` ! refused ${U.path}: cites no entry from this batch; a wiki note only patches`)),Fe.refused++;continue}let at=Mh(U,$e);at!==U.path&&(console.log(m.dim(` ~ ${U.path} \u2192 ${at} (an article with this title exists)`)),U.path=at);let Ue=_.readArticle(U.path);if(Ue){let Lo=Ar(Ue.content,String(U.content??""));if(Lo.length>0){console.log(m.yellow(` ! refused ${U.path}: the rewrite drops ${Lo.length} fact(s) the article has`)),console.log(m.dim(` ${Lo.slice(0,8).join("; ")}${Lo.length>8?"; \u2026":""}`));for(let t0 of Re)mn.add(t0);Fe.refused++;continue}}let Oc=g(Re,D)??Ue?.meta.graphPath;_.writeArticle(U.path,{title:U.title,type:U.type,related:Array.isArray(U.related)?U.related:void 0,tags:U.tags||[],owner:C,access:Ue?.meta.access??"public",sharedWith:Ue?.meta.sharedWith?.length?Ue.meta.sharedWith:void 0,created:Ue?.meta.created||Ge,lastUpdated:Ge,sources:[...new Set([...Ue?.meta.sources??[],...Re])],graphPath:Oc},U.content,C);let Zx=U.type?m.magenta(`[${U.type}]`)+" ":"",e0=Array.isArray(U.related)&&U.related.length?` \u2192 ${U.related.slice(0,3).join(", ")}${U.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(Ue?"~":"+")} ${Zx}${U.path}: ${U.title}${m.dim(e0)}`);let cg=(U.tags||[]).slice(0,4).join(", ");cg&&console.log(m.dim(` tags: ${cg}`)),Oc?.length&&(console.log(m.dim(` graphPath: ${Oc.join(" \u203A ")}`)),h++),w++,Fe.articles++;for(let Lo of Re)pn.add(Lo)}if(A.length>0&&!gn){let U=A.filter(Re=>{let at=E.get(Re.id);return at&&at.status!=="open"&&at.status!=="deferred"?(console.log(m.dim(` note ${Re.id} already ${at.status} by ${at.handled?.by??"another run"}; left as it is`)),!1):at?.handled&&at.handled.at>S?(console.log(m.dim(` note ${Re.id} already deferred by ${at.handled.by} during this run; left as it is`)),!1):!0}),Ge=Hk(U,Bk(ds.notes),_,{agentId:C,paths:new Set(ie.map(Re=>Re.path))}),vt=0;for(let Re of Ge){try{E.handle(Re.id,Re.outcome,Re.reason,C,B),vt++}catch(Ue){console.log(m.yellow(` ! note ${Re.id}: could not record ${Re.outcome}: ${Ue?.message??Ue}`))}let at=Re.outcome==="patched"?m.green("~"):Re.outcome==="rejected"?m.red("x"):m.yellow("\u2026");console.log(` ${at} note ${Re.id} ${Re.outcome}: ${m.dim(Re.reason.slice(0,160))}`)}Fe.notesPatched=Ge.filter(Re=>Re.outcome==="patched").length,Fe.notesRecorded=vt}else A.length>0&&console.log(m.yellow(` ${A.length} wiki note(s) stay waiting`));if(Fe.failed=gn,Fe.heldCited=[...mn].filter(U=>pn.has(U)).length,gn)console.log(m.yellow(` Run reported an error \u2014 ${D.length} entries stay queued`));else{let U=D.map(Ge=>Ge.id).filter(Ge=>!mn.has(Ge));mn.size>0&&console.log(m.yellow(` ${D.length-U.length} entries stay queued behind refused saves`)),n.markProcessed(C,U,pi.flatMap(Ge=>Ge.sources||[]).filter(Ge=>!mn.has(Ge)))}if(us.length>0){console.log(),console.log(m.yellow(` Gaps detected (${us.length} missing pieces):`));for(let U of us)console.log(m.yellow(` ? ${U}`));try{let{QuestionStore:U}=await import("./questions-ZATLU5AW.js"),Ge=new U(kt(e.dir)).add(us.map(vt=>({kind:"article",agentId:C,path:"",subject:String(vt).slice(0,120),question:`No article yet for: ${String(vt).slice(0,160)}`})));Ge.added>0&&console.log(m.dim(` queued ${Ge.added} for follow-up (agentx wiki questions)`))}catch{}}_.rebuildIndex()}catch(ge){console.log(m.red(` Absorb failed: ${ge.message?.slice(0,200)}`)),ge.stderr&&console.log(m.dim(String(ge.stderr).slice(0,300))),ge.stdout&&console.log(m.dim("stdout: "+String(ge.stdout).slice(0,300)))}finally{Fe.at=new Date().toISOString(),Fe.wallMs=Date.now()-xo,Fe.failed&&y++,x(Fe)}}if(x({kind:"run",label:v,startedAt:S,endedAt:new Date().toISOString(),max:l,model:o,failed:y}),console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(w>0&&(console.log(m.green(` ${w} articles compiled across ${c.length} agent(s)`)),u)){let C=w>0?Math.round(h/w*100):0;console.log(m.dim(` ${h}/${w} carry graphPath (${C}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}y>0&&(console.log(m.red(` ${y} 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:c}=await import("./absorb-eval-
|
|
606
|
+
`),Q="";if(e.facts!==!1){let{extractHints:ge,resolveFacts:gn,mergeRecords:ls,renderFactsBlock:ds,installPrompts:pi,defaultSources:us,recordsFromEntries:mn}=await import("./facts-ALJBF7IA.js");if(!p){let U=new Set;for(let Ge of n.listAgents())for(let vt of n.getAgentWiki(Ge).listArticles(Ge))vt.meta.type==="person"&&U.add(vt.meta.title);p=[...U]}let pn=ge(D.map(U=>({context:U.sourceContext,content:U.content,sender:typeof U.meta?.sender=="string"?U.meta.sender:void 0})),{known:p}),gs=mn(D);if(pn.length>0||gs.length>0){let U=us(),{records:Ge,results:vt}=pn.length>0?await gn(pn,{sources:U}):{records:[],results:[]},Re=ls([...gs,...Ge]);Q=ds(Re);let at=[...gs.length>0?[`entries:${gs.length}`]:[],...vt.filter(Ue=>Ue.records.length>0).map(Ue=>`${Ue.source}:${Ue.records.length}`)];console.log(m.dim(` Facts: ${pn.length} entities \u2192 ${Re.length} resolved${at.length?` (${at.join(" ")})`:""}`));for(let Ue of pi(vt,U))console.log(m.yellow(` ! ${Ue.source} ${Ue.kind} \u2014 would supply ${Ue.provides.join(", ")}`)),console.log(m.dim(` ${Ue.hint}`))}}let $e=z.articles.filter(ge=>ge.path&&!ge.path.includes("/_versions/")),ie=await Ph([...D,...A.map(ge=>({id:wu(ge.id),content:ge.change}))],_,C,$e);ie.length>0&&console.log(m.dim(` Existing: ${ie.map(ge=>ge.path).join(", ")}`));let j=Dh(ie),oe=Jk(A),Xe=tl(t,C,fe,z.articles,P,D.length,Q,j,oe);console.log(m.dim(` Mode: ${Au(t)}`));let no=W(_.baseDir,"_tmp");eo(no,{recursive:!0});let qe=W(no,"absorb-prompt.txt");Wt(qe,Xe),console.log(m.dim(` Compiling with Claude (${o})...`));let Fe={kind:"call",at:"",label:v,agent:C,model:o,entries:D.length,articles:0,refused:0,failed:!0,wallMs:0,promptChars:Xe.length,promptParts:{entries:P.length,catalog:Xe.length-tl(t,C,fe,[],P,D.length,Q,j,oe).length,catalogArticles:z.articles.length,covering:j.length,facts:Q.length,worldview:fe.length,notes:oe.length},...A.length?{notes:A.length}:{}},xo=Date.now();Fe.prepMs=xo-T;try{let ge,gn=!1;try{ge=os(`cat '${qe}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:qo(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(U){if(ge=U.stdout||"",!ge)throw U;gn=!0}let ls=ge;try{let U=JSON.parse(ge);Object.assign(Fe,El(U)),U.is_error===!0&&(gn=!0),ls=U.result||U.content||"",ls||(console.log(m.dim(` Claude envelope keys: ${Object.keys(U).join(", ")}`)),console.log(m.dim(` is_error: ${U.is_error}, stop_reason: ${U.stop_reason}`)))}catch{}let ds=Wk(ls);if("error"in ds){A.length>0&&console.log(m.yellow(` ${A.length} wiki note(s) stay waiting`)),console.log(m.red(` ${ds.error}`)),console.log(m.dim(` First 500 chars: ${ls.slice(0,500)}`));continue}let{articles:pi,gaps:us}=ds,mn=new Set,pn=new Set,gs=new Set(D.map(U=>U.id));for(let U of pi){let Ge=new Date().toISOString().slice(0,10),vt=Array.isArray(U.sources)?U.sources:[],Re=A.length>0?vt.filter(Lo=>gs.has(Lo)):vt;if(A.length>0&&Re.length===0){console.log(m.yellow(` ! refused ${U.path}: cites no entry from this batch; a wiki note only patches`)),Fe.refused++;continue}let at=Mh(U,$e);at!==U.path&&(console.log(m.dim(` ~ ${U.path} \u2192 ${at} (an article with this title exists)`)),U.path=at);let Ue=_.readArticle(U.path);if(Ue){let Lo=Ar(Ue.content,String(U.content??""));if(Lo.length>0){console.log(m.yellow(` ! refused ${U.path}: the rewrite drops ${Lo.length} fact(s) the article has`)),console.log(m.dim(` ${Lo.slice(0,8).join("; ")}${Lo.length>8?"; \u2026":""}`));for(let t0 of Re)mn.add(t0);Fe.refused++;continue}}let Oc=g(Re,D)??Ue?.meta.graphPath;_.writeArticle(U.path,{title:U.title,type:U.type,related:Array.isArray(U.related)?U.related:void 0,tags:U.tags||[],owner:C,access:Ue?.meta.access??"public",sharedWith:Ue?.meta.sharedWith?.length?Ue.meta.sharedWith:void 0,created:Ue?.meta.created||Ge,lastUpdated:Ge,sources:[...new Set([...Ue?.meta.sources??[],...Re])],graphPath:Oc},U.content,C);let Zx=U.type?m.magenta(`[${U.type}]`)+" ":"",e0=Array.isArray(U.related)&&U.related.length?` \u2192 ${U.related.slice(0,3).join(", ")}${U.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(Ue?"~":"+")} ${Zx}${U.path}: ${U.title}${m.dim(e0)}`);let cg=(U.tags||[]).slice(0,4).join(", ");cg&&console.log(m.dim(` tags: ${cg}`)),Oc?.length&&(console.log(m.dim(` graphPath: ${Oc.join(" \u203A ")}`)),h++),w++,Fe.articles++;for(let Lo of Re)pn.add(Lo)}if(A.length>0&&!gn){let U=A.filter(Re=>{let at=E.get(Re.id);return at&&at.status!=="open"&&at.status!=="deferred"?(console.log(m.dim(` note ${Re.id} already ${at.status} by ${at.handled?.by??"another run"}; left as it is`)),!1):at?.handled&&at.handled.at>S?(console.log(m.dim(` note ${Re.id} already deferred by ${at.handled.by} during this run; left as it is`)),!1):!0}),Ge=Hk(U,Bk(ds.notes),_,{agentId:C,paths:new Set(ie.map(Re=>Re.path))}),vt=0;for(let Re of Ge){try{E.handle(Re.id,Re.outcome,Re.reason,C,B),vt++}catch(Ue){console.log(m.yellow(` ! note ${Re.id}: could not record ${Re.outcome}: ${Ue?.message??Ue}`))}let at=Re.outcome==="patched"?m.green("~"):Re.outcome==="rejected"?m.red("x"):m.yellow("\u2026");console.log(` ${at} note ${Re.id} ${Re.outcome}: ${m.dim(Re.reason.slice(0,160))}`)}Fe.notesPatched=Ge.filter(Re=>Re.outcome==="patched").length,Fe.notesRecorded=vt}else A.length>0&&console.log(m.yellow(` ${A.length} wiki note(s) stay waiting`));if(Fe.failed=gn,Fe.heldCited=[...mn].filter(U=>pn.has(U)).length,gn)console.log(m.yellow(` Run reported an error \u2014 ${D.length} entries stay queued`));else{let U=D.map(Ge=>Ge.id).filter(Ge=>!mn.has(Ge));mn.size>0&&console.log(m.yellow(` ${D.length-U.length} entries stay queued behind refused saves`)),n.markProcessed(C,U,pi.flatMap(Ge=>Ge.sources||[]).filter(Ge=>!mn.has(Ge)))}if(us.length>0){console.log(),console.log(m.yellow(` Gaps detected (${us.length} missing pieces):`));for(let U of us)console.log(m.yellow(` ? ${U}`));try{let{QuestionStore:U}=await import("./questions-ZATLU5AW.js"),Ge=new U(kt(e.dir)).add(us.map(vt=>({kind:"article",agentId:C,path:"",subject:String(vt).slice(0,120),question:`No article yet for: ${String(vt).slice(0,160)}`})));Ge.added>0&&console.log(m.dim(` queued ${Ge.added} for follow-up (agentx wiki questions)`))}catch{}}_.rebuildIndex()}catch(ge){console.log(m.red(` Absorb failed: ${ge.message?.slice(0,200)}`)),ge.stderr&&console.log(m.dim(String(ge.stderr).slice(0,300))),ge.stdout&&console.log(m.dim("stdout: "+String(ge.stdout).slice(0,300)))}finally{Fe.at=new Date().toISOString(),Fe.wallMs=Date.now()-xo,Fe.failed&&y++,x(Fe)}}if(x({kind:"run",label:v,startedAt:S,endedAt:new Date().toISOString(),max:l,model:o,failed:y}),console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(w>0&&(console.log(m.green(` ${w} articles compiled across ${c.length} agent(s)`)),u)){let C=w>0?Math.round(h/w*100):0;console.log(m.dim(` ${h}/${w} carry graphPath (${C}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}y>0&&(console.log(m.red(` ${y} 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:c}=await import("./absorb-eval-4GDAAYBL.js"),{extractJson:l}=await import("./extract-json-7775Q7KO.js"),u=Ae(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,w=new Map;for(let P of u.getSharedStore().listEntries())w.set(P.id,{id:P.id,date:P.date,content:P.content});let h=[];for(let P of d)for(let Q of u.getAgentWiki(P).listArticles(P))h.push({key:`${P}/${Q.path}`,agent:P,article:Q});let y=new Map;for(let P of h)for(let Q of P.article.meta.sources??[]){let $e=y.get(Q);$e?$e.push(P.article.content):y.set(Q,[P.article.content])}let b=P=>{if(!f)return!0;try{return B1(W(u.getAgentWiki(P.agent).baseDir,P.article.path)).mtimeMs>f.getTime()}catch{return!1}},v=h.filter(P=>!p||(P.article.meta.lastUpdated??"")>=p.slice(0,10)).filter(b),x=String(e.seed),S;if(e.sample&&et(e.sample)){let P=JSON.parse(jt(e.sample,"utf-8"));x=P.seed??x;let Q=new Map(h.map(ie=>[ie.key,ie]));S=P.keys.map(ie=>Q.get(ie)).filter(ie=>!!ie);let $e=P.keys.length-S.length;$e>0&&console.error(m.yellow(` ${$e} sampled article(s) no longer exist`))}else S=t(v.map(P=>({...P,path:P.key})),parseInt(e.n),x),e.sample&&(Wt(e.sample,`${JSON.stringify({seed:x,since:g||void 0,keys:S.map(P=>P.key)},null,2)}
|
|
607
607
|
`),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?/,""),E=P=>{let Q=u.getAgentWiki(P.agent).getVersions(P.article.path),$e=g?Q.filter(j=>j.timestamp>=g):Q.slice(0,1),ie=$e[$e.length-1];if(ie)try{return k(jt(ie.path,"utf-8"))}catch{return}},C=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:E(P)})),T=C.map(P=>o(P,w,Q=>y.get(Q)??[])),N=new Set(S.map(P=>P.key)),q=d.flatMap(P=>n(h.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})),N)),D=[];if(e.judge){let P;try{P=hu(e.judgeModel)}catch(ie){console.log(m.red(` ${ie.message}`)),process.exitCode=1;return}let Q=W(u.getBaseDir(),"_tmp");eo(Q,{recursive:!0});let $e=C.map((ie,j)=>({a:ie,i:j}));await Promise.all(Array.from({length:Math.min(3,$e.length)},async()=>{for(let ie=$e.shift();ie;ie=$e.shift()){let{a:j,i:oe}=ie,Xe=j.sources.map(qe=>w.get(qe)).filter(qe=>!!qe),no=W(Q,`absorb-eval-${process.pid}-${oe}.txt`);Wt(no,s(j,Xe));try{let{stdout:qe}=await cv(`cat '${no}' | claude -p - --output-format json --max-turns 1 --model '${P}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:qo(),encoding:"utf-8",timeout:3e5,maxBuffer:4194304}),Fe=qe;try{Fe=JSON.parse(qe).result??qe}catch{}let xo=r(l(Fe));xo?D.push({path:j.path,verdict:xo}):console.error(m.yellow(` judge reply for ${j.path} was not usable`))}catch(qe){console.error(m.yellow(` judge failed for ${j.path}: ${String(qe?.message??qe).slice(0,160)}`))}finally{Su(no,{force:!0})}}})),D.sort((ie,j)=>ie.path.localeCompare(j.path))}let G=new Set(h.flatMap(P=>P.article.meta.sources??[])),B=[];for(let P of d){let Q=W(u.getBaseDir(),"agents",P,"_absorbed.json");if(!et(Q))continue;let $e={};try{$e=JSON.parse(jt(Q,"utf-8")).entries??{}}catch{continue}for(let[ie,j]of Object.entries($e)){if(G.has(ie)||g&&String(j.at??"")<g)continue;let oe=w.get(ie);oe&&B.push(oe)}}let A=h.map(P=>P.article.content).join(`
|
|
608
|
-
`),_=c(B,A),z=i(T,q,{seed:x,since:g||void 0},D,5,{entries:B.length,lost:_}),fe=a(z);e.out&&Wt(e.out,fe),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(fe)});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=W(kt(e.dir),t);if(!et(n)){console.log(m.yellow(` no queries recorded yet (${n})`));return}let s=o(jt(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,c)=>c[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-
|
|
609
|
-
`).filter(Boolean).flatMap(c=>{try{return[JSON.parse(c)]}catch{return[]}}).filter(c=>!e.label||(c.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",c=>c.label],["calls",c=>`${c.calls}${c.failed?` (${c.failed} failed)`:""}`],["entries",c=>String(c.entries)],["articles",c=>`${c.articles}${c.refused?` (${c.refused} refused${c.heldCited?`, ${c.heldCited} held entries lost`:""})`:""}`],["wall",c=>`${(c.wallMs/6e4).toFixed(1)} min`],["call p50/p95",c=>`${Math.round(c.callMsP50/1e3)}/${Math.round(c.callMsP95/1e3)} s`],["entries/min",c=>c.entriesPerMinute.toFixed(1)],["prep",c=>`${(c.prepMs/6e4).toFixed(1)} min`],["cost",c=>`$${c.costUsd.toFixed(2)}`],["$/entry",c=>`$${c.costPerEntry.toFixed(3)}`]],i=s.map(c=>r.map(([,l])=>l(c))),a=r.map(([c],l)=>Math.max(c.length,...i.map(u=>u[l].length)));console.log(),console.log(m.bold(r.map(([c],l)=>c.padEnd(a[l])).join(" ")));for(let c of i)console.log(c.map((l,u)=>l.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=G1(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-
|
|
608
|
+
`),_=c(B,A),z=i(T,q,{seed:x,since:g||void 0},D,5,{entries:B.length,lost:_}),fe=a(z);e.out&&Wt(e.out,fe),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(fe)});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=W(kt(e.dir),t);if(!et(n)){console.log(m.yellow(` no queries recorded yet (${n})`));return}let s=o(jt(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,c)=>c[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-4GDAAYBL.js"),o=W(kt(e.dir),"_absorb-runs.jsonl");if(!et(o)){console.log(m.yellow(` no absorb runs recorded yet (${o})`));return}let n=jt(o,"utf-8").split(`
|
|
609
|
+
`).filter(Boolean).flatMap(c=>{try{return[JSON.parse(c)]}catch{return[]}}).filter(c=>!e.label||(c.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",c=>c.label],["calls",c=>`${c.calls}${c.failed?` (${c.failed} failed)`:""}`],["entries",c=>String(c.entries)],["articles",c=>`${c.articles}${c.refused?` (${c.refused} refused${c.heldCited?`, ${c.heldCited} held entries lost`:""})`:""}`],["wall",c=>`${(c.wallMs/6e4).toFixed(1)} min`],["call p50/p95",c=>`${Math.round(c.callMsP50/1e3)}/${Math.round(c.callMsP95/1e3)} s`],["entries/min",c=>c.entriesPerMinute.toFixed(1)],["prep",c=>`${(c.prepMs/6e4).toFixed(1)} min`],["cost",c=>`$${c.costUsd.toFixed(2)}`],["$/entry",c=>`$${c.costPerEntry.toFixed(3)}`]],i=s.map(c=>r.map(([,l])=>l(c))),a=r.map(([c],l)=>Math.max(c.length,...i.map(u=>u[l].length)));console.log(),console.log(m.bold(r.map(([c],l)=>c.padEnd(a[l])).join(" ")));for(let c of i)console.log(c.map((l,u)=>l.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=G1(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-5HRRFPEG.js"),{default:c}=await import("better-sqlite3"),l=W(process.cwd(),".agentx/db.sqlite");if(!et(l))console.log(m.yellow(` --reviews: no ${l}`));else{let u=new c(l,{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:c,failuresToCandidates:l}=await import("./failure-candidates-WGSFI7GR.js"),{default:u}=await import("better-sqlite3"),d=W(process.cwd(),".agentx/db.sqlite");if(!et(d))console.log(m.yellow(` --failures: no ${d}`));else{let p=new u(d,{readonly:!0});try{let f=c(p,{since:Date.now()-(t??6048e5)}),g=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${g.length} failure(s) seen in ${a}+ sessions`));let w=g[0];w&&console.log(m.dim(` most recurrent (${w.occurrences} sessions, ${w.failure.runs} runs): ${w.memory.description.slice(0,84)}`)),r=[...r,...g]}finally{p.close()}}}let i=await Zm({extraCandidates:r,wikiDir:e.dir?W(e.dir):void 0,memoryRoot:e.memoryDir?W(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 c=a.candidates[0],l=a.corroboratingAgents.length>1?m.green(` \xD7${a.corroboratingAgents.length} agents`):"";console.log(` ${m.cyan(`[${c.memory.type}]`)} ${c.memory.name}${l} ${m.dim(`(${a.corroboratingAgents.join(", ")}, conf ${a.confidence.toFixed(2)})`)}`),console.log(m.dim(` ${c.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 c=a.type?m.magenta(`[${a.type}]`)+" ":"",l=`${a.agents.length} agent(s)${a.occurrences>1?`, seen in ${a.occurrences} sessions`:""}`;console.log(` ${m.green("?")} ${c}${a.path}: ${a.title} ${m.dim(`(${l})`)}`),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 ic=X.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function ac(e){return e?W(e):W(process.cwd(),".agentx","wiki")}ic.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(ac(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(l=>l.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}]`),c=n.replaces?m.yellow("update"):m.green("new");console.log(` ${m.cyan(n.id)}${a}`),console.log(` ${c} ${n.article.path}: ${n.article.title}`),console.log(m.dim(` ${i}`))}});ic.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(ac(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(`
|
|
610
610
|
`).map(s=>` ${s}`).join(`
|
|
611
|
-
`)),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>)`))}});ic.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-
|
|
611
|
+
`)),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>)`))}});ic.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-GWDQR2DT.js"),n=o(ac(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`))});ic.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-GWDQR2DT.js"),n=o(ac(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`))});function G1(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",W(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-PYJN4G32.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:r,join:i}=await import("path"),a=Ae(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),u=parseInt(e.n),d=r(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let p=[],f=o(d).sort().reverse();for(let h of f){let y=i(d,h),b=[];try{b=o(y).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of b){if(p.length>=u)break;try{let x=JSON.parse(n(i(y,v),"utf-8")),S=x.message||x.task?.message;typeof S=="string"&&S.trim().length>10&&p.push({id:x.id||v.replace(".json",""),message:S.trim(),ts:x.at||x.timestamp||h})}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 ${c}`)),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: ${c}`,"",`_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 h=0;h<p.length;h++){let y=p[h];process.stdout.write(m.dim(` [${h+1}/${p.length}] querying... `));let v=l.findRelevant(y.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
|
|
612
612
|
`)||"_(none returned)_",x;try{let S=await t(y.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")x=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let k=S.citations.map(E=>`\`${E.title}\` [${E.type||"?"}]`).join(", ");x=`**Answer:**
|
|
613
613
|
|
|
614
614
|
${S.answer}
|
|
@@ -625,14 +625,14 @@ Q: ${j.q}
|
|
|
625
625
|
A: ${j.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(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(`
|
|
626
626
|
`),x=W(a.baseDir,"_tmp");eo(x,{recursive:!0});let S=W(x,`interview-${o().slice(0,8)}.txt`);Wt(S,v),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=os(j,{env:qo(),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Xe=JSON.parse(oe);k=String(Xe.result||Xe.content||"")}catch{k=oe}}catch(j){console.log(m.red(` synthesis failed: ${j.message?.slice(0,200)}`)),c?.close();return}k=k.trim();let E=k.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);E&&(k=E[1].trim());let C=k.indexOf("---");C>0&&(k=k.slice(C));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)),c?.close();return}let N={};for(let j of T[1].split(`
|
|
627
627
|
`)){let oe=j.match(/^(\w+):\s*(.+)$/);oe&&(N[oe[1]]=oe[2].trim().replace(/^"(.*)"$/,"$1"))}let q=T[2],D=N.title||u,G=D.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),A=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${G}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${A}`)),console.log(),console.log(k),console.log();let _=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.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=q,fe={title:D,type:N.type||d,related:N.related?N.related.replace(/^\[|\]$/g,"").split(",").map(j=>j.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:N.tags?N.tags.replace(/^\[|\]$/g,"").split(",").map(j=>j.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:N.access||"public",created:N.created||new Date().toISOString().slice(0,10),lastUpdated:N.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=W(x,`draft-${o().slice(0,8)}.md`);Wt(oe,k);try{os(`${j} '${oe}'`,{stdio:"inherit"});let no=jt(oe,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(no){let qe={};for(let Fe of no[1].split(`
|
|
628
|
-
`)){let xo=Fe.match(/^(\w+):\s*(.+)$/);xo&&(qe[xo[1]]=xo[2].trim().replace(/^"(.*)"$/,"$1"))}z=no[2],fe={...fe,title:qe.title||fe.title,type:qe.type||fe.type,access:qe.access||fe.access,related:qe.related?qe.related.replace(/^\[|\]$/g,"").split(",").map(Fe=>Fe.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):fe.related,tags:qe.tags?qe.tags.replace(/^\[|\]$/g,"").split(",").map(Fe=>Fe.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):fe.tags}}}catch(Xe){console.log(m.red(` editor failed: ${Xe.message}`));return}}if(!a.writeArticle(A,fe,z,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${A} saved.`));let Q=a.extractWikilinks(z),$e=new Map;for(let j of a.listArticles(e.agent))$e.set(j.meta.title.toLowerCase(),!0);let ie=Q.filter(j=>!$e.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-
|
|
628
|
+
`)){let xo=Fe.match(/^(\w+):\s*(.+)$/);xo&&(qe[xo[1]]=xo[2].trim().replace(/^"(.*)"$/,"$1"))}z=no[2],fe={...fe,title:qe.title||fe.title,type:qe.type||fe.type,access:qe.access||fe.access,related:qe.related?qe.related.replace(/^\[|\]$/g,"").split(",").map(Fe=>Fe.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):fe.related,tags:qe.tags?qe.tags.replace(/^\[|\]$/g,"").split(",").map(Fe=>Fe.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):fe.tags}}}catch(Xe){console.log(m.red(` editor failed: ${Xe.message}`));return}}if(!a.writeArticle(A,fe,z,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${A} saved.`));let Q=a.extractWikilinks(z),$e=new Map;for(let j of a.listArticles(e.agent))$e.set(j.meta.title.toLowerCase(),!0);let ie=Q.filter(j=>!$e.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-PYJN4G32.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Ae(e.dir);if(e.commit!==!1&&ns(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=jt(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);i=[];for(let w of g){let h=w.split(/\r?\n/).filter(v=>v.trim());if(h.length<2)continue;let y=h[0].replace(/^Q:\s*/i,"").trim(),b=h.slice(1).join(" ").trim();y&&b&&i.push({q:y,verdict:b})}}let a=i?null:t.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=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: ${l} \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<l;f++){let g,w;if(i){let B=i[f];if(!B)break;g=B.q,w=B.verdict,console.log(m.cyan(` [${f+1}] Q: `)+g)}else{if(g=await c(m.cyan(` [${f+1}] Q: `)),!g||g==="/done"||g==="/abort")break;w=""}process.stdout.write(m.dim(" querying... "));let h;try{h=await n(g,r,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(B){console.log(m.red(`failed: ${B.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),h.status!=="ok")console.log(m.yellow(` (status: ${h.status}${h.error?" \u2014 "+h.error:""})`));else{let B=h.citations.map(A=>`${A.title} [${A.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+h.answer.replace(/\n/g,`
|
|
629
629
|
`)),console.log(m.dim(" citations: "+B))}i||(w=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+w);let y={q:g,answer:h.answer,citations:h.citations,verdict:w},b=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(y);continue}let v=b[1].toLowerCase(),x=(b[2]||"").trim();if(d.push(y),v==="/ok"||v==="/skip")continue;if(!x){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let S=h.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 E=X1(k.content,v,x,k.meta.title,k.meta.type),C=W(r.baseDir,"_tmp");eo(C,{recursive:!0});let T=W(C,`quiz-patch-${o().slice(0,8)}.txt`);Wt(T,E);let N="";try{let B=`cat '${T}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,A=os(B,{env:qo(),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let z=JSON.parse(A);N=String(z.result||z.content||"")}catch{N=A}let _=N.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);_&&(N=_[1].trim()),N=N.trim()}catch(B){console.log(m.red(` patch failed: ${B.message?.slice(0,120)}`));continue}if(!N||N.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let q=k.content.split(`
|
|
630
630
|
`).length,D=N.split(`
|
|
631
631
|
`).length;if(console.log(m.dim(` diff: ${q} \u2192 ${D} lines (${D-q>=0?"+":""}${D-q})`)),!u){console.log(m.dim(" (--no-commit: patch not written)")),y.patched=S.path+" (dry)";continue}if(!r.writeArticle(S.path,{...k.meta,lastUpdated:new Date().toISOString().slice(0,10)},N,e.agent)){console.log(m.red(" write failed (permission?)"));continue}p++,y.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 w=d[g];f.push(`## ${g+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(h=>`\`${h.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}Wt(e.out,f.join(`
|
|
632
|
-
`)),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=Ae(o.dir);if(ns(n,e))return;let s;try{s=n.getAgentWiki(e)}catch(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let r=ti(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=W(s.baseDir,r),a=o.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${r} in ${a}...`));try{os(`${a} '${i}'`,{stdio:"inherit"})}catch(l){console.log(m.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(r);if(c){let l=new Set,u=s.extractWikilinks(c.content).filter(f=>l.has(f)?!1:(l.add(f),!0)),d=c.meta.related||[];(u.some(f=>!d.includes(f))||d.some(f=>!u.includes(f)))&&(s.writeArticle(r,{...c.meta,related:u.length?u:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.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(l){console.log(m.yellow(` saved, but catalog rebuild failed: ${l.message?.slice(0,100)}`))}});async function z1(){let{loadDaemonConfig:e}=await import("./config-
|
|
632
|
+
`)),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=Ae(o.dir);if(ns(n,e))return;let s;try{s=n.getAgentWiki(e)}catch(l){console.log(m.red(` can't open wiki for agent "${e}": ${l.message}`));return}let r=ti(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=W(s.baseDir,r),a=o.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${r} in ${a}...`));try{os(`${a} '${i}'`,{stdio:"inherit"})}catch(l){console.log(m.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(r);if(c){let l=new Set,u=s.extractWikilinks(c.content).filter(f=>l.has(f)?!1:(l.add(f),!0)),d=c.meta.related||[];(u.some(f=>!d.includes(f))||d.some(f=>!u.includes(f)))&&(s.writeArticle(r,{...c.meta,related:u.length?u:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.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(l){console.log(m.yellow(` saved, but catalog rebuild failed: ${l.message?.slice(0,100)}`))}});async function z1(){let{loadDaemonConfig:e}=await import("./config-QBTOYJA7.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 Y1(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=Ae(n.dir);if(ns(s,e))return;let r=ti(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 z1(),c=async(p,f,g)=>{let w=await fetch(i+f,{method:p,headers:a,...g?{body:JSON.stringify(g)}:{}}),h=await w.json().catch(()=>({}));if(!w.ok)throw new Error(h.error||`HTTP ${w.status}`);return h},l;try{l=await c("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(` ${l.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 c("GET",`/api/wiki/curate${u}`).catch(()=>null))?.messages?.find(g=>g.id===l.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)&&Y1(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=Ae(o.dir).getAgentWiki(e),s=ti(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=Ae(n.dir);if(ns(s,e))return;let r=s.getAgentWiki(e),i=ti(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,c=!1;try{c=!!a&&r.restoreVersion(i,a)}catch(l){if(!(l instanceof Hg))throw l;console.log(m.red(` ${i} was not restored: the page was busy; run again.`)),process.exitCode=1;return}if(!c){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-QBTOYJA7.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-G46QCYCR.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=Ae(n.dir);if(ns(i,e))return;let a;try{a=i.getAgentWiki(e)}catch(x){console.log(m.red(` can't open wiki for agent "${e}": ${x.message}`));return}let c=ti(a,t,e);if(!c){console.log(m.yellow(` no article matches "${t}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(m.red(` can't read ${c}.`));return}let u=K1(l.content,l.meta.title,l.meta.type,o),d=W(a.baseDir,"_tmp");eo(d,{recursive:!0});let p=W(d,`patch-${r().slice(0,8)}.txt`);Wt(p,u),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let f="";try{let x=`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=os(x,{env:qo(),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let E=JSON.parse(S);f=String(E.result||E.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(x){console.log(m.red(` patch failed: ${x.message?.slice(0,150)}`));return}if(!f||f.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let g=l.content.split(`
|
|
633
633
|
`).length,w=f.split(`
|
|
634
|
-
`).length;console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${g} \u2192 ${w} lines (${w-g>=0?"+":""}${w-g})`)),console.log(),console.log(f),console.log();let h=Lh(l.content,f);if(h.length){for(let x of h)console.log(m.yellow(` ! ${x}`));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 y=!!n.yes;if(!y){let x=s.createInterface({input:process.stdin,output:process.stdout}),S=(await x.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),y=S==="y"||S==="yes"}if(!y){console.log(m.dim(" aborted."));return}if(a.readArticle(c)?.content!==l.content){console.log(m.yellow(` ${c} changed while this patch was made (another patch or edit). Not saved; run the patch again.`)),process.exitCode=1;return}let b=[...new Set([...l.meta.related||[],...a.extractWikilinks(f)])];if(!a.writeArticle(c,{...l.meta,related:b.length?b: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 ${c} patched.`))});var rv=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-
|
|
635
|
-
agentx wiki contributions approve <id> \xB7 agentx wiki contributions reject <id>`)),console.log()});ei.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-
|
|
634
|
+
`).length;console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${g} \u2192 ${w} lines (${w-g>=0?"+":""}${w-g})`)),console.log(),console.log(f),console.log();let h=Lh(l.content,f);if(h.length){for(let x of h)console.log(m.yellow(` ! ${x}`));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 y=!!n.yes;if(!y){let x=s.createInterface({input:process.stdin,output:process.stdout}),S=(await x.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),y=S==="y"||S==="yes"}if(!y){console.log(m.dim(" aborted."));return}if(a.readArticle(c)?.content!==l.content){console.log(m.yellow(` ${c} changed while this patch was made (another patch or edit). Not saved; run the patch again.`)),process.exitCode=1;return}let b=[...new Set([...l.meta.related||[],...a.extractWikilinks(f)])];if(!a.writeArticle(c,{...l.meta,related:b.length?b: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 ${c} patched.`))});var rv=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-OOPYQSLO.js"),o=Ae(e.dir),n=kt(e.dir),s={},r={};try{let{loadDaemonConfig:d}=await import("./config-QBTOYJA7.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,c=W(process.cwd(),e.db);if(et(c)){let d=(await import("better-sqlite3")).default;a=new d(c,{readonly:!0})}else e.json||console.log(m.dim(` no trace database at ${c}; reading chat turns only`));let l=d=>async(p,f)=>{let g=W(n,"_tmp");eo(g,{recursive:!0});let w=W(g,`contribute-${process.pid}-${Date.now()}.txt`);Wt(w,p);try{let{stdout:h}=await cv(`cat '${w}' | 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:qo(),timeout:18e4,maxBuffer:4194304});try{let y=JSON.parse(h);return{text:String(y.result||y.content||""),costUsd:El(y).costUsd}}catch{return{text:h}}}finally{Su(w,{force:!0})}},u=[];try{for(let d of i){if(ns(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:l(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 w=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)}${w}${e.dryRun?m.dim(" \xB7 dry run, not queued"):""}`);for(let h of g.patches){let y=h.attribute?`${h.attribute}: ${h.previous?`${h.previous} \u2192 `:""}${h.value??""}`:h.summary??"";console.log(m.dim(` ${h.kind.padEnd(8)} ${h.page} \xB7 ${y} (${h.source}, ${h.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]])rv.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-3FGEZPF3.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 c={...rv.opts(),...n};c.maxCost&&(a.wiki.contribute.maxCostUsd=parseFloat(c.maxCost)),c.maxPatches&&(a.wiki.contribute.maxPatches=parseInt(c.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 ei=X.command("contributions").description("the daily merge of agents' wiki patches (list, merge, held, approve, reject)");ei.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-OOPYQSLO.js"),s=kt(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((c,l)=>c+l.patches.length,0)} patch(es) in ${r.length} batch(es)`));for(let c of r)console.log(m.dim(` ${c.agentId} \xB7 ${c.runAt.slice(0,16)} \xB7 ${c.patches.length} patch(es) \xB7 $${c.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(c=>c.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()});ei.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-OOPYQSLO.js"),o=t(Ae(e.dir),kt(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()});ei.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-OOPYQSLO.js"),o=t(kt(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(`
|
|
635
|
+
agentx wiki contributions approve <id> \xB7 agentx wiki contributions reject <id>`)),console.log()});ei.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-OOPYQSLO.js"),n=o(Ae(t.dir),kt(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.`))});ei.command("reject <id>").description("drop a held patch").option("--dir <path>","wiki directory").action(async(e,t)=>{let{rejectHeld:o}=await import("./contributions-OOPYQSLO.js"),n=o(kt(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 ti(e,t,o){let n=t.trim(),s=e.listArticles(o),r=n.toLowerCase(),i=s.find(l=>l.meta.title.toLowerCase()===r);if(i)return i.path;if(n.includes("/")||n.endsWith(".md")){let l=n.endsWith(".md")?n:`${n}.md`,u=s.find(d=>d.path===l||d.path===n);if(u)return u.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let u=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return u===a||u.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function K1(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(`
|
|
636
636
|
`)}function X1(e,t,o,n,s){let r={"/correct":`The operator says the article contains an error:
|
|
637
637
|
|
|
638
638
|
${o}
|
|
@@ -687,17 +687,17 @@ Output (JSON array, one entry per input article, same order):
|
|
|
687
687
|
[
|
|
688
688
|
{"path": "path/to/article.md", "type": "project"},
|
|
689
689
|
...
|
|
690
|
-
]`}X.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Ae(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||W(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=await lv(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(),Nh(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-
|
|
690
|
+
]`}X.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Ae(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||W(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=await lv(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(),Nh(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-2RFBH5N2.js"),c=Ae(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),u=parseInt(e.limit),d=parseFloat(e.min),p=[];e:for(let h of l){let y=c.getAgentWiki(h);for(let b of y.listArticles(h)){if(p.length>=u)break e;let v=y.readArticle(b.path);if(!v||e.type&&v.meta.type!==e.type)continue;let x={...t(v.meta.type),...e.fields?r(v.meta.type):{}},S=await a(s,o({path:b.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),x,{links:[{kind:"article",id:b.path}],features:{agent:h,type:v.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),E=e.fields?i(v.meta.type,S.answers):null;k.completeness>=d&&!(E&&!E.fit)||p.push({agent:h,type:v.meta.type??"?",score:k.completeness.toFixed(2),standsAlone:k.standsAlone.toFixed(2),gap:k.biggestGap,...E?{missing:E.missingCritical.join(",")||"-",cov:`${Math.round(E.coverage*100)}%`}:{},title:v.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((h,y)=>parseFloat(h.score)-parseFloat(y.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],g=f.map(h=>Math.max(h.length,...p.map(y=>String(y[h]).length))),w=h=>h.map((y,b)=>String(y).padEnd(g[b])).join(" ");console.log(),console.log(m.bold(w(f)));for(let h of p)console.log(w(f.map(y=>h[y])));if(e.fields){let h=p.filter(y=>y.missing!=="-").length;console.log(m.dim(`
|
|
691
691
|
${p.length} article(s) flagged; ${h} 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(`
|
|
692
|
-
${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-
|
|
692
|
+
${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-PYJN4G32.js"),{noteSourceFor:n}=await import("./query-settings-XFOY343Z.js"),{QUERY_RUNS_FILE:s,queryFailed:r,recordQueryRun:i,timedQuery:a}=await import("./query-runs-AENEZOM6.js"),c=await uv(t);if(!c)return;let l=Ae(t.dir),u=t.agent?[t.agent]:l.listAgents(),d=W(l.getBaseDir(),s),p=Date.now(),f=t.agent||process.env.AGENTX_AGENT_ID,g=f&&!t.ownOnly&&await sv()?f:null;for(let v of g?[]:u){let x=l.getAgentWiki(v),S=W(x.baseDir,"_index.md");try{if((await import("fs")).existsSync(S)){g=v;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 w=g,h=l.getAgentWiki(w),y=t.ownOnly||!await sv()?void 0:l.sharedScope(w),b=await a(d,w,"cli",()=>o(e,h,w,{selectorModel:t.selectorModel,synthModel:t.synthModel,maxCandidates:parseInt(t.maxCandidates),maxHops:parseInt(t.maxHops),maxArticles:parseInt(t.maxArticles),shared:y,method:c.method,summaries:c.summaries,notes:n(c,w)}));if(r(b.status)&&(process.exitCode=1),t.json){console.log(JSON.stringify(b,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${g} \xB7 status: ${b.status} \xB7 walked: ${b.walked.length}`)),console.log(),b.status!=="ok"){console.log(m.yellow(` (no answer) ${b.error||b.status}`));return}if(console.log(b.answer),console.log(),b.basis==="search"&&(console.log(m.dim(" No wiki page was used: the answer comes from a search at the source.")),console.log()),b.citations.length){console.log(m.dim(" Citations:"));for(let v of b.citations){let x=v.type?m.magenta(` [${v.type}]`):"";console.log(m.dim(` - ${v.title}${x} (${v.path})`))}console.log()}if(b.live?.length){console.log(m.dim(" Read live at the source:"));for(let v of b.live)console.log(m.dim(` - ${v.line}`));console.log()}if(t.trace&&b.trace){if(b.method==="summaries"&&console.log(m.dim(` method: summaries live reads: ${b.liveAsked??0} asked, ${b.live?.length??0} answered plan: ${b.trace.planMs??0}ms reads: ${b.trace.liveMs??0}ms`)),console.log(m.dim(` selector: ${b.trace.selectorMs}ms synthesis: ${b.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${b.candidates.map(v=>v.title).join(" | ")||"(none)"}`)),b.walked.length>b.candidates.length){let v=b.walked.filter(x=>!b.candidates.some(S=>S.path===x.path));console.log(m.dim(` followed: ${v.map(x=>`${x.title}@h${x.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)}`,c=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(C=>JSON.parse(jt(W(C),"utf-8"))),E=n(S,k);if(e.json){console.log(JSON.stringify(E,null,2));return}console.log(),console.log(m.bold(` ${r(E.before)} \u2192 ${r(E.after)}`)),console.log(m.dim(` before: ${c(E.cost.before)}`)),console.log(m.dim(` after: ${c(E.cost.after)}`)),E.changed==="unknown"?console.log(m.yellow(" ! A report records no settings, so what changed between the runs is unknown.")):(console.log(m.dim(` changed: ${E.changed.join("; ")||"nothing"}`)),E.changed.length>1&&console.log(m.yellow(" ! More than one setting changed: the difference can't be put down to one of them."))),(E.onlyBefore.length||E.onlyAfter.length)&&console.log(m.yellow(` ! The runs asked different questions. Only before: ${E.onlyBefore.join(", ")||"none"}. Only after: ${E.onlyAfter.join(", ")||"none"}.`));for(let C of E.deltas){if(C.before===C.after)continue;let T=C.after>C.before?m.green("\u25B2"):m.red("\u25BC");console.log(` ${T} ${C.id} ${r(C.before)} \u2192 ${r(C.after)} ${m.dim(C.question.slice(0,80))}`),C.gained.length&&console.log(m.green(` + ${C.gained.join(", ")}`)),C.lost.length&&console.log(m.red(` - ${C.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 l=e.agent||process.env.AGENTX_AGENT_ID;if(!l){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(jt(W(e.questions),"utf-8")),{agenticQuery:d,CATALOG_SELECTOR_MODEL:p,CATALOG_SYNTH_MODEL:f}=await import("./query-PYJN4G32.js"),{noteSourceFor:g}=await import("./query-settings-XFOY343Z.js"),{meteredModelCall:w}=await import("./model-call-HMVMUAXS.js"),h=await uv(e);if(!h)return;let y=Ae(e.dir),b=!e.ownOnly,v=[];for(let S of u){let k={calls:0,usd:0,unpriced:0},E=Date.now(),C=await d(S.question,y.getAgentWiki(l),l,{selectorModel:e.selectorModel,synthModel:e.synthModel,shared:b?y.sharedScope(l):void 0,method:h.method,summaries:h.summaries,notes:g(h,l),call:w(k)}),T=Date.now()-E,N=C.method==="summaries"&&k.unpriced===0?k.usd:void 0;v.push({q:S,answer:C.answer||C.error||"",status:C.status,citations:C.citations.map(q=>q.path),method:C.method??"catalog",ms:T,costUsd:N}),e.json||process.stderr.write(m.dim(` ${S.id} ${C.status} ${i(T)} ${a(N)}
|
|
693
693
|
`))}let x=o({questions:e.questions,agent:l,shared:b,settings:{method:h.method,linkedPages:h.summaries.linkedPages,linkedChars:h.summaries.linkedChars,live:h.summaries.live.enabled,notes:h.notes.enabled,navigatorModel:e.selectorModel??h.summaries.navigatorModel,answerModel:e.synthModel??h.summaries.answerModel,catalogSelectorModel:e.selectorModel??p,catalogSynthModel:e.synthModel??f}},v);if(e.out&&Wt(W(e.out),`${JSON.stringify(x,null,2)}
|
|
694
694
|
`),e.json){console.log(JSON.stringify(x,null,2));return}console.log(),console.log(m.bold(` ${l}: ${r(x.score)} \xB7 ${x.full}/${x.results.length} questions fully answered${b?"":" (own articles only)"}`)),console.log(m.dim(` ${c(s(x))}`));for(let S of x.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(`
|
|
695
|
-
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=Ae(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 c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.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=Ae(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=W(process.cwd(),".agentx/graph");if(!et(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Fo({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,c=0,l=0,u=0;for(let d of o){let p=t.getAgentWiki(d),f=p.listArticles(d),g=t.getSharedStore().listEntries(),w=new Map(g.map(v=>[v.id,v])),h=0,y=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;h++,c++;let x=new Map;for(let k of v.meta.sources){let E=w.get(k);if(!E)continue;let C=String(E.meta?.sender??""),T=s.fingerprint({text:E.content,channel:E.source,sender:C}),N=i.get(T);if(!N?.length)continue;let q=N.join("/"),D=x.get(q);D?D.n++:x.set(q,{path:N,n:1})}if(x.size===0)continue;y++,l++;let S;for(let k of x.values())(!S||k.n>S.n)&&(S=k);S&&(e.dryRun||(p.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,u++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${h} eligible \xB7 ${y} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*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=Ae(e.dir),o=t.getSharedStore(),n=await lv(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 dv();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 c of n){console.log(),console.log(m.bold(` Copying articles from ${c.url}...`));try{let l=await a({hub:t,peer:c,localAgents:i,dryRun:e.dryRun});console.log(m.dim(` Node: ${l.node}`));for(let u of l.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(l){console.log(m.red(` ${l.cause?.code==="ECONNREFUSED"?"Connection refused":l.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 c=a?{Authorization:`Bearer ${a}`}:{};try{let l=await fetch(`${i}/wiki/entries`,{headers:c,signal:AbortSignal.timeout(12e4)});if(!l.ok){console.log(m.red(` HTTP ${l.status}`));continue}let u=await l.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:c,signal:AbortSignal.timeout(5e3)});if(g.ok){let w=await g.json();for(let h of w.agents||[])h.totalEntries>0&&console.log(m.dim(` ${h.agentId}: ${h.totalEntries} entries, ${h.totalArticles} articles`))}}catch{}}catch(l){l.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${l.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||W(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Lc(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),p=l.getAgentEntries(o),f=l.getUnabsorbedEntries(o),g=new Set,w=0,h=new Set;for(let b of d.articles){for(let v of b.tags||[])g.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])h.add(v)}let y=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Au(c),articles:d.articles.length,entries:p.length,unabsorbed:f.length,uniqueTags:g.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:y.size,coverage:h.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(c=>c.label.padEnd(r)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(r)).join(" ")}`);let i=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of i){let u=s.map(d=>l(d).padEnd(r));console.log(` ${c.padEnd(20)} ${u.join(" ")}`)}console.log();let a=(c,l)=>{let u=Math.max(...s.map(p=>p[c])),d=s.filter(p=>p[c]===u).map(p=>p.label);u>0&&console.log(m.dim(` Best ${l}: ${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?W(process.cwd(),t.dir):W(process.cwd(),".agentx/wiki");et(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?W(process.cwd(),e):W(process.cwd(),`agentx-wiki-${n}.tar.gz`),r=W(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:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:u}=await import("fs"),d=et(s)?u(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Z1(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-74G2KLZQ.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Ae(e.dir,e.mode),u=[],d=e.agent?[e.agent]:l.listAgents(),p=parseInt(e.limit),f=0,g=[];e:for(let k of d){let E=l.getAgentWiki(k);for(let C of E.listArticles(k)){if(f>=p)break e;let T=E.readArticle(C.path);if(!T||e.type&&T.meta.type!==e.type)continue;f++;let N=await a(i,n({title:T.meta.title,type:T.meta.type,body:T.content}),t(T.meta.type),{links:[{kind:"article",id:C.path}],features:{agent:k,type:T.meta.type??"?"}});if(!N){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let q=o(T.meta.type,N.answers);for(let D of s(q,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&D.needsHuman||(e.ask&&D.needsHuman&&u.push({kind:"field",agentId:k,path:C.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 w={added:0,skipped:0};if(e.ask&&u.length>0&&(w=new c(kt(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 h=["tier","need","how","uncertain","agent","article"],y=k=>String(k).replace(/\u001b\[[0-9;]*m/g,""),b=h.map(k=>Math.max(k.length,...g.map(E=>y(E[k]).length))),v=(k,E)=>String(k)+" ".repeat(Math.max(0,b[E]-y(k).length));console.log(),console.log(m.bold(h.map((k,E)=>v(k,E)).join(" ")));for(let k of g)console.log(h.map((E,C)=>v(k[E],C)).join(" "));let x=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(` ${x} can be closed by a lookup; ${g.length-x} 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 ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:k}=await import("./article-fields-PITN4NHA.js"),E=k[e.notifyTier]??k.pillar,C=u.filter(T=>(k[T.tier??"furniture"]??9)<=E);if(C.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:T}=await import("./config-IOQKEH47.js"),N=T(),q=N?.notifications?.destination;if(!q?.channel||!q?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let D=C.slice(0,10).map(_=>`\u2022 ${_.question}`).join(`
|
|
695
|
+
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=Ae(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 c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(m.dim(` ${c.path} \u2014 ${c.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=Ae(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=W(process.cwd(),".agentx/graph");if(!et(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Fo({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,c=0,l=0,u=0;for(let d of o){let p=t.getAgentWiki(d),f=p.listArticles(d),g=t.getSharedStore().listEntries(),w=new Map(g.map(v=>[v.id,v])),h=0,y=0,b=0;for(let v of f){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;h++,c++;let x=new Map;for(let k of v.meta.sources){let E=w.get(k);if(!E)continue;let C=String(E.meta?.sender??""),T=s.fingerprint({text:E.content,channel:E.source,sender:C}),N=i.get(T);if(!N?.length)continue;let q=N.join("/"),D=x.get(q);D?D.n++:x.set(q,{path:N,n:1})}if(x.size===0)continue;y++,l++;let S;for(let k of x.values())(!S||k.n>S.n)&&(S=k);S&&(e.dryRun||(p.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),b++,u++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${h} eligible \xB7 ${y} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*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=Ae(e.dir),o=t.getSharedStore(),n=await lv(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 dv();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 c of n){console.log(),console.log(m.bold(` Copying articles from ${c.url}...`));try{let l=await a({hub:t,peer:c,localAgents:i,dryRun:e.dryRun});console.log(m.dim(` Node: ${l.node}`));for(let u of l.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(l){console.log(m.red(` ${l.cause?.code==="ECONNREFUSED"?"Connection refused":l.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 c=a?{Authorization:`Bearer ${a}`}:{};try{let l=await fetch(`${i}/wiki/entries`,{headers:c,signal:AbortSignal.timeout(12e4)});if(!l.ok){console.log(m.red(` HTTP ${l.status}`));continue}let u=await l.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:c,signal:AbortSignal.timeout(5e3)});if(g.ok){let w=await g.json();for(let h of w.agents||[])h.totalEntries>0&&console.log(m.dim(` ${h.agentId}: ${h.totalEntries} entries, ${h.totalArticles} articles`))}}catch{}}catch(l){l.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${l.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||W(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Lc(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),p=l.getAgentEntries(o),f=l.getUnabsorbedEntries(o),g=new Set,w=0,h=new Set;for(let b of d.articles){for(let v of b.tags||[])g.add(v);w+=b.tags?.length||0;for(let v of b.sources||[])h.add(v)}let y=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Au(c),articles:d.articles.length,entries:p.length,unabsorbed:f.length,uniqueTags:g.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:y.size,coverage:h.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(c=>c.label.padEnd(r)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(r)).join(" ")}`);let i=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,l]of i){let u=s.map(d=>l(d).padEnd(r));console.log(` ${c.padEnd(20)} ${u.join(" ")}`)}console.log();let a=(c,l)=>{let u=Math.max(...s.map(p=>p[c])),d=s.filter(p=>p[c]===u).map(p=>p.label);u>0&&console.log(m.dim(` Best ${l}: ${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?W(process.cwd(),t.dir):W(process.cwd(),".agentx/wiki");et(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?W(process.cwd(),e):W(process.cwd(),`agentx-wiki-${n}.tar.gz`),r=W(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:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(m.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:u}=await import("fs"),d=et(s)?u(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Z1(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-2RFBH5N2.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Ae(e.dir,e.mode),u=[],d=e.agent?[e.agent]:l.listAgents(),p=parseInt(e.limit),f=0,g=[];e:for(let k of d){let E=l.getAgentWiki(k);for(let C of E.listArticles(k)){if(f>=p)break e;let T=E.readArticle(C.path);if(!T||e.type&&T.meta.type!==e.type)continue;f++;let N=await a(i,n({title:T.meta.title,type:T.meta.type,body:T.content}),t(T.meta.type),{links:[{kind:"article",id:C.path}],features:{agent:k,type:T.meta.type??"?"}});if(!N){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let q=o(T.meta.type,N.answers);for(let D of s(q,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&D.needsHuman||(e.ask&&D.needsHuman&&u.push({kind:"field",agentId:k,path:C.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 w={added:0,skipped:0};if(e.ask&&u.length>0&&(w=new c(kt(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 h=["tier","need","how","uncertain","agent","article"],y=k=>String(k).replace(/\u001b\[[0-9;]*m/g,""),b=h.map(k=>Math.max(k.length,...g.map(E=>y(E[k]).length))),v=(k,E)=>String(k)+" ".repeat(Math.max(0,b[E]-y(k).length));console.log(),console.log(m.bold(h.map((k,E)=>v(k,E)).join(" ")));for(let k of g)console.log(h.map((E,C)=>v(k[E],C)).join(" "));let x=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(` ${x} can be closed by a lookup; ${g.length-x} 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 ${w.added} question(s) for a person (${w.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&w.added>0){let{TIER_RANK:k}=await import("./article-fields-PITN4NHA.js"),E=k[e.notifyTier]??k.pillar,C=u.filter(T=>(k[T.tier??"furniture"]??9)<=E);if(C.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:T}=await import("./config-QBTOYJA7.js"),N=T(),q=N?.notifications?.destination;if(!q?.channel||!q?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let D=C.slice(0,10).map(_=>`\u2022 ${_.question}`).join(`
|
|
696
696
|
`),G=C.length>10?`
|
|
697
697
|
\u2026and ${C.length-10} more`:"",B=`${C.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
698
698
|
${D}${G}
|
|
699
699
|
|
|
700
|
-
agentx wiki questions`,A=N?.daemon?.port??N?.port??18800;try{let _=await fetch(`http://127.0.0.1:${A}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:q.channel,chatId:q.chatId,accountId:q.accountId,text:B})});console.log(_.ok?m.cyan(` Pushed ${C.length} question(s) to ${q.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-74G2KLZQ.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:u,recordsFromEntries:d}=await import("./facts-ALJBF7IA.js"),{backfillArticle:p}=await import("./backfill-7TCF4SHG.js"),f=Ae(e.dir,e.mode),g=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),h=u(),y=c(d(f.getSharedStore().listEntries())),b=new Map(y.map(N=>[N.name.toLowerCase().trim(),N])),v=0,x=0,S=[],k=!1;e:for(let N of g){let q=f.getAgentWiki(N);for(let D of q.listArticles(N)){if(v>=w)break e;if(D.meta.type!=="person")continue;let G=q.readArticle(D.path);if(!G)continue;v++;let B=await i(s,n({title:G.meta.title,type:G.meta.type,body:G.content}),t(G.meta.type),{links:[{kind:"article",id:D.path}],features:{agent:N,op:"backfill"}});if(!B){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let _=o(G.meta.type,B.answers).missing.filter(j=>r.includes(j));if(_.length===0)continue;let{records:z,results:fe}=await a([{name:G.meta.title,type:"person"}],{sources:h}),P=b.get(G.meta.title.toLowerCase().trim());if(!k){for(let j of l(fe,h))console.log(m.yellow(` ! ${j.source} ${j.kind} \u2014 would supply ${j.provides.join(", ")}`)),console.log(m.dim(` ${j.hint}`));k=!0}let Q=c([...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:$e,edits:ie}=p(G.content,Q[0],_);if(ie.length!==0){for(let j of ie)S.push({agent:N,article:G.meta.title.slice(0,32),field:j.field,action:j.replaced?"replace":"add",got:`${j.value.split(";").length} value(s)`});e.apply&&(q.writeArticle(D.path,G.meta,$e,N)?x++: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(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let E=["agent","article","field","action","got"],C=E.map(N=>Math.max(N.length,...S.map(q=>String(q[N]).length))),T=N=>N.map((q,D)=>String(q).padEnd(C[D])).join(" ");console.log(),console.log(m.bold(T(E)));for(let N of S)console.log(T(E.map(q=>N[q])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${x} 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 ${v} 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(kt(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(kt(o.dir)),a=i.list().find(w=>(w.id===e||w.id.startsWith(e))&&w.status!=="open"&&w.kind==="contradiction");if(a&&!i.list("open").some(w=>w.id===e||w.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let w=i.resolve(e,"dismissed");console.log(w?m.dim(` dismissed: ${w.question}`):m.red(` no question matching "${e}"`))}catch(w){console.log(m.red(` ${w?.message??w}`)),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 c=i.list("open").find(w=>w.id===e||w.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:w}=await import("./ledger-5GMBLR7W.js"),h=new w(kt(o.dir));try{let y=h.get(c.factId);if(y){let b=h.write({subject:y.subject,attribute:y.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:y.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${y.id} ${y.subject} \xB7 ${y.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(y){y?.name!=="LedgerCorruptError"&&console.log(m.red(` ${y?.message??y}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}i.resolve(c.id,"answered",t),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=i.resolve(e,"answered",t)}catch(w){console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!r[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=Ae(o.dir,o.mode).getAgentWiki(l.agentId),p=d.readArticle(l.path);if(!p){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(p.content,l.field,`${t} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let g=d.writeArticle(l.path,p.meta,f.content,l.agentId);console.log(g?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.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-74G2KLZQ.js"),{labelEntries:i,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:u}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Ae(e.dir,"graph").getSharedStore(),g=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(G=>G.id)),{labeled:h,backlog:y}=i(g,w),b=a(h,G=>G.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},x=[],S=0,k=Date.now();if(e.load){let{readFileSync:G}=await import("fs");x.push(...JSON.parse(G(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${x.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${h.length} labelled (${y} in backlog) \u2014 grading ${b.length}`));for(let G of e.load?[]:b){let B=await r(t,n(G),o,{features:{source:G.source??"",absorbed:G.absorbed}});if(!B){S++;continue}let A=B.answers;x.push({entry:G,verdict:s(B.answers,v),citeWorthy:A.citeWorthy?.noul})}if(x.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:G}=await import("fs");G(e.save,JSON.stringify(x)),console.log(m.dim(` saved ${x.length} outcome(s) to ${e.save}`))}let E=c(x,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),C=l(x,"seat","seat"),T=d(C,{minN:50}),N=((Date.now()-k)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:E,calibration:T,failures:S,elapsed:N},null,2));return}let q=G=>`${(G*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${E.n} (${E.positives} kept by absorb, ${E.negatives} passed over)`),console.log(` recall ${q(E.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${q(E.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${q(E.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${E.lostPositives>0?m.yellow(`lost ${E.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)")}`),E.lostPositives>0){let G=E.droppedBy;console.log(m.dim(` dropped by: type ${G.type} \xB7 worth ${G.worth} \xB7 durability ${G.durability} (a positive can fail several)`))}let D=E.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(` ${N}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 G=parseFloat(e.minRecall),{best:B,points:A}=u(x,{minRecall:G});if(console.log(),console.log(m.bold(` threshold sweep (${A.length} policies, recall floor ${q(G)})`)),B)console.log(` best: ${B.requireTyped?`typed & type>=${B.minType}`:"type gate OFF"} worth>=${B.minWorth} durability>=${B.minDurability}`),console.log(` recall ${q(B.recall)} \xB7 filtered ${q(B.filtered)} \xB7 precision ${q(B.precision)} \xB7 lost ${B.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${q(G)} recall \u2014 not even keeping everything typed.`));let _=A.slice().sort((z,fe)=>fe.recall-z.recall)[0];_&&console.log(m.dim(` Best recall available: ${q(_.recall)} at ${_.requireTyped?`type>=${_.minType}`:"type gate OFF"} worth>=${_.minWorth} dur>=${_.minDurability}, filtering ${q(_.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=W(process.cwd(),e);et(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?W(process.cwd(),t.dir):W(process.cwd(),".agentx/wiki");et(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=W(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"),c=a("tar",i,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.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 Z1(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"}Pg();import{Command as eI}from"commander";import J from"chalk";import{resolve as cc}from"path";import{existsSync as tI}from"fs";te();var rr=new eI().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");rr.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 Fo({baseDir:cc(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(),c=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 l=0,u=0,d=0,p=0;for(let g=0;g<i.length;g++){let w=i[g],h=xi(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${g+1}/${i.length}] ${J.cyan(w.msgHash.slice(0,8))} ${J.dim(h)} ... `);let y=oI(w,a,c),b=null;try{b=await nI(n,o,y,t.dashboard?.token)}catch(S){p++,console.log(J.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){p++,console.log(J.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),x=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(J.green("APPROVE")+" "+J.dim(x)),e.dryRun)l++;else try{sI(r,w,a,c,o),r.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:o,reviewReason:x}),l++}catch(S){console.log(J.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),p++}else v==="reject"?(console.log(J.red("REJECT")+" "+J.dim(x)),e.dryRun||r.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:o,reviewReason:x}),u++):(console.log(J.yellow("SKIP")+" "+J.dim(x||v)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(J.dim(` Summary: ${f} approve ${l}, ${f} reject ${u}, ${d} skipped, ${p} errors.`)),e.dryRun&&(l>0||u>0)&&console.log(J.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});rr.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=cc(process.cwd(),t.graph.baseDir);if(!tI(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 Fo({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,c)=>c[1]-a[1]);i.length===0&&console.log(J.dim(" (none)"));for(let[a,c]of i)console.log(` ${a.padEnd(28)} ${c}`);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()});rr.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 Fo({baseDir:cc(process.cwd(),t.graph.baseDir)}),i=r.loadSchema(),a=r.loadNodes().nodes,c=new Set(a.map(E=>E.id));console.log(),console.log(J.bold(` graph pull \u2190 ${o}`));let l,u,d;try{let E=await fetch(`${o}/graph/schema`,{headers:s});if(!E.ok)throw new Error(`schema HTTP ${E.status}`);l=(await E.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 N=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!N.ok)throw new Error(`classifications HTTP ${N.status}`);d=(await N.json()).classifications||[]}catch(E){console.log(J.red(` fetch failed: ${E.message}`));return}let p=i.levels.map(E=>E.id).join(","),f=l?.levels?.map(E=>E.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(l)):console.log(J.yellow(" keeping local schema; node import may fail if levels disagree")));let w=g?i:l,h=new Map;w.levels.forEach((E,C)=>h.set(E.id,C));let y=[...u].sort((E,C)=>(h.get(E.level)??99)-(h.get(C.level)??99)),b=0,v=0,x=0;for(let E of y){if(c.has(E.id)){v++;continue}if(e.dryRun){b++,c.add(E.id);continue}try{r.addNode({...E,createdBy:E.createdBy?`${E.createdBy} (sync)`:`sync:${o}`}),c.add(E.id),b++}catch(C){x++,console.log(J.yellow(` skip node ${E.id}: ${C.message?.slice(0,100)}`))}}console.log(J.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${x} failed`));let S=0,k=0;for(let E of d)if(!(!E.msgHash||!Array.isArray(E.path))){if(r.getFingerprint(E.msgHash)){k++;continue}if(e.dryRun){S++;continue}r.setFingerprint(E.msgHash,{path:E.path,leaf:E.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 oI(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(`
|
|
700
|
+
agentx wiki questions`,A=N?.daemon?.port??N?.port??18800;try{let _=await fetch(`http://127.0.0.1:${A}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:q.channel,chatId:q.chatId,accountId:q.accountId,text:B})});console.log(_.ok?m.cyan(` Pushed ${C.length} question(s) to ${q.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-2RFBH5N2.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:u,recordsFromEntries:d}=await import("./facts-ALJBF7IA.js"),{backfillArticle:p}=await import("./backfill-7TCF4SHG.js"),f=Ae(e.dir,e.mode),g=e.agent?[e.agent]:f.listAgents(),w=parseInt(e.limit),h=u(),y=c(d(f.getSharedStore().listEntries())),b=new Map(y.map(N=>[N.name.toLowerCase().trim(),N])),v=0,x=0,S=[],k=!1;e:for(let N of g){let q=f.getAgentWiki(N);for(let D of q.listArticles(N)){if(v>=w)break e;if(D.meta.type!=="person")continue;let G=q.readArticle(D.path);if(!G)continue;v++;let B=await i(s,n({title:G.meta.title,type:G.meta.type,body:G.content}),t(G.meta.type),{links:[{kind:"article",id:D.path}],features:{agent:N,op:"backfill"}});if(!B){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let _=o(G.meta.type,B.answers).missing.filter(j=>r.includes(j));if(_.length===0)continue;let{records:z,results:fe}=await a([{name:G.meta.title,type:"person"}],{sources:h}),P=b.get(G.meta.title.toLowerCase().trim());if(!k){for(let j of l(fe,h))console.log(m.yellow(` ! ${j.source} ${j.kind} \u2014 would supply ${j.provides.join(", ")}`)),console.log(m.dim(` ${j.hint}`));k=!0}let Q=c([...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:$e,edits:ie}=p(G.content,Q[0],_);if(ie.length!==0){for(let j of ie)S.push({agent:N,article:G.meta.title.slice(0,32),field:j.field,action:j.replaced?"replace":"add",got:`${j.value.split(";").length} value(s)`});e.apply&&(q.writeArticle(D.path,G.meta,$e,N)?x++: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(` ${v} person article(s) considered \u2014 nothing to backfill`));return}let E=["agent","article","field","action","got"],C=E.map(N=>Math.max(N.length,...S.map(q=>String(q[N]).length))),T=N=>N.map((q,D)=>String(q).padEnd(C[D])).join(" ");console.log(),console.log(m.bold(T(E)));for(let N of S)console.log(T(E.map(q=>N[q])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${x} 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 ${v} 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(kt(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(kt(o.dir)),a=i.list().find(w=>(w.id===e||w.id.startsWith(e))&&w.status!=="open"&&w.kind==="contradiction");if(a&&!i.list("open").some(w=>w.id===e||w.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let w=i.resolve(e,"dismissed");console.log(w?m.dim(` dismissed: ${w.question}`):m.red(` no question matching "${e}"`))}catch(w){console.log(m.red(` ${w?.message??w}`)),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 c=i.list("open").find(w=>w.id===e||w.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:w}=await import("./ledger-5GMBLR7W.js"),h=new w(kt(o.dir));try{let y=h.get(c.factId);if(y){let b=h.write({subject:y.subject,attribute:y.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:y.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${y.id} ${y.subject} \xB7 ${y.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(y){y?.name!=="LedgerCorruptError"&&console.log(m.red(` ${y?.message??y}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}i.resolve(c.id,"answered",t),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=i.resolve(e,"answered",t)}catch(w){console.log(m.red(` ${w?.message??w}`)),console.log(m.yellow(" nothing changed.")),process.exitCode=1;return}if(!l){console.log(m.red(` no question matching "${e}"`));return}if(console.log(m.green(` answered: ${l.question}`)),l.kind!=="field"||!l.field||!l.path){console.log(m.dim(" recorded. No article to patch yet."));return}if(!r[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=Ae(o.dir,o.mode).getAgentWiki(l.agentId),p=d.readArticle(l.path);if(!p){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(p.content,l.field,`${t} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let g=d.writeArticle(l.path,p.meta,f.content,l.agentId);console.log(g?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.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-2RFBH5N2.js"),{labelEntries:i,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:u}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Ae(e.dir,"graph").getSharedStore(),g=f.listEntries(),w=new Set(f.getUnabsorbedEntries().map(G=>G.id)),{labeled:h,backlog:y}=i(g,w),b=a(h,G=>G.absorbed,parseInt(e.n)),v={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},x=[],S=0,k=Date.now();if(e.load){let{readFileSync:G}=await import("fs");x.push(...JSON.parse(G(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${x.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${h.length} labelled (${y} in backlog) \u2014 grading ${b.length}`));for(let G of e.load?[]:b){let B=await r(t,n(G),o,{features:{source:G.source??"",absorbed:G.absorbed}});if(!B){S++;continue}let A=B.answers;x.push({entry:G,verdict:s(B.answers,v),citeWorthy:A.citeWorthy?.noul})}if(x.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:G}=await import("fs");G(e.save,JSON.stringify(x)),console.log(m.dim(` saved ${x.length} outcome(s) to ${e.save}`))}let E=c(x,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),C=l(x,"seat","seat"),T=d(C,{minN:50}),N=((Date.now()-k)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:E,calibration:T,failures:S,elapsed:N},null,2));return}let q=G=>`${(G*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${E.n} (${E.positives} kept by absorb, ${E.negatives} passed over)`),console.log(` recall ${q(E.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${q(E.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${q(E.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${E.lostPositives>0?m.yellow(`lost ${E.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)")}`),E.lostPositives>0){let G=E.droppedBy;console.log(m.dim(` dropped by: type ${G.type} \xB7 worth ${G.worth} \xB7 durability ${G.durability} (a positive can fail several)`))}let D=E.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(` ${N}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 G=parseFloat(e.minRecall),{best:B,points:A}=u(x,{minRecall:G});if(console.log(),console.log(m.bold(` threshold sweep (${A.length} policies, recall floor ${q(G)})`)),B)console.log(` best: ${B.requireTyped?`typed & type>=${B.minType}`:"type gate OFF"} worth>=${B.minWorth} durability>=${B.minDurability}`),console.log(` recall ${q(B.recall)} \xB7 filtered ${q(B.filtered)} \xB7 precision ${q(B.precision)} \xB7 lost ${B.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${q(G)} recall \u2014 not even keeping everything typed.`));let _=A.slice().sort((z,fe)=>fe.recall-z.recall)[0];_&&console.log(m.dim(` Best recall available: ${q(_.recall)} at ${_.requireTyped?`type>=${_.minType}`:"type gate OFF"} worth>=${_.minWorth} dur>=${_.minDurability}, filtering ${q(_.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=W(process.cwd(),e);et(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?W(process.cwd(),t.dir):W(process.cwd(),".agentx/wiki");et(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=W(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"),c=a("tar",i,{stdio:"inherit"});c.status!==0&&(console.log(m.red(` tar exited with ${c.status}`)),process.exit(c.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 Z1(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"}Pg();import{Command as eI}from"commander";import J from"chalk";import{resolve as cc}from"path";import{existsSync as tI}from"fs";te();var rr=new eI().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");rr.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 Fo({baseDir:cc(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(),c=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 l=0,u=0,d=0,p=0;for(let g=0;g<i.length;g++){let w=i[g],h=xi(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${g+1}/${i.length}] ${J.cyan(w.msgHash.slice(0,8))} ${J.dim(h)} ... `);let y=oI(w,a,c),b=null;try{b=await nI(n,o,y,t.dashboard?.token)}catch(S){p++,console.log(J.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){p++,console.log(J.red("ERR no decision"));continue}let v=String(b.decision).toLowerCase().trim(),x=(b.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(J.green("APPROVE")+" "+J.dim(x)),e.dryRun)l++;else try{sI(r,w,a,c,o),r.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:o,reviewReason:x}),l++}catch(S){console.log(J.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),p++}else v==="reject"?(console.log(J.red("REJECT")+" "+J.dim(x)),e.dryRun||r.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:o,reviewReason:x}),u++):(console.log(J.yellow("SKIP")+" "+J.dim(x||v)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(J.dim(` Summary: ${f} approve ${l}, ${f} reject ${u}, ${d} skipped, ${p} errors.`)),e.dryRun&&(l>0||u>0)&&console.log(J.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});rr.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=cc(process.cwd(),t.graph.baseDir);if(!tI(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 Fo({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,c)=>c[1]-a[1]);i.length===0&&console.log(J.dim(" (none)"));for(let[a,c]of i)console.log(` ${a.padEnd(28)} ${c}`);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()});rr.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 Fo({baseDir:cc(process.cwd(),t.graph.baseDir)}),i=r.loadSchema(),a=r.loadNodes().nodes,c=new Set(a.map(E=>E.id));console.log(),console.log(J.bold(` graph pull \u2190 ${o}`));let l,u,d;try{let E=await fetch(`${o}/graph/schema`,{headers:s});if(!E.ok)throw new Error(`schema HTTP ${E.status}`);l=(await E.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 N=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!N.ok)throw new Error(`classifications HTTP ${N.status}`);d=(await N.json()).classifications||[]}catch(E){console.log(J.red(` fetch failed: ${E.message}`));return}let p=i.levels.map(E=>E.id).join(","),f=l?.levels?.map(E=>E.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(l)):console.log(J.yellow(" keeping local schema; node import may fail if levels disagree")));let w=g?i:l,h=new Map;w.levels.forEach((E,C)=>h.set(E.id,C));let y=[...u].sort((E,C)=>(h.get(E.level)??99)-(h.get(C.level)??99)),b=0,v=0,x=0;for(let E of y){if(c.has(E.id)){v++;continue}if(e.dryRun){b++,c.add(E.id);continue}try{r.addNode({...E,createdBy:E.createdBy?`${E.createdBy} (sync)`:`sync:${o}`}),c.add(E.id),b++}catch(C){x++,console.log(J.yellow(` skip node ${E.id}: ${C.message?.slice(0,100)}`))}}console.log(J.dim(` nodes: +${b} added \xB7 ${v} already-present \xB7 ${x} failed`));let S=0,k=0;for(let E of d)if(!(!E.msgHash||!Array.isArray(E.path))){if(r.getFingerprint(E.msgHash)){k++;continue}if(e.dryRun){S++;continue}r.setFingerprint(E.msgHash,{path:E.path,leaf:E.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 oI(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(`
|
|
701
701
|
`),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(`
|
|
702
702
|
`)}async function nI(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 c=await a.json();if(c?.error)throw new Error(String(c.error));return vi((c?.content||"").toString())}finally{clearTimeout(i)}}function sI(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function Eu(){let e=O();if(!e.graph?.baseDir)return console.log(J.red(" graph.baseDir is not configured")),null;let t=cc(process.cwd(),e.graph.baseDir);return{store:new Fo({baseDir:t}),baseDir:t}}var Ru=rr.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");Ru.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=Eu();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 c of i){let l=typeof c.confidence=="number"?c.confidence.toFixed(2):J.dim("cache");console.log(` ${J.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${J.bold(xi(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(J.dim(` ${String(c.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]"))});Ru.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=Eu();if(!n)return;let{ReviewStore:s}=await import("./review-store-PW3OBGZQ.js"),i=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.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 c=n.store.loadNodes().nodes;console.log(J.green(` ${t}: ${xi(i[0].path,c)||i[0].path.join(" \u203A ")}`)),o.path&&console.log(J.dim(` should have been: ${o.path}`))});Ru.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let t=Eu();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=c=>`${(c*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 c of i.byBin){let l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),u=c.n>=5&&l>.15?J.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.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 dI}from"commander";import ue from"chalk";import{Command as mv}from"commander";import je from"chalk";import{existsSync as rI}from"fs";import{resolve as iI}from"path";import aI from"better-sqlite3";function cI(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(je.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function lI(e){let t=iI(process.cwd(),e);return rI(t)||(console.log(je.red(` No db at ${t}`)),process.exit(1)),new aI(t,{readonly:!0})}var pv=new mv().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($r)).option("--max <n>","max clusters distilled per run",String(Oi)).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(je.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let t=lI(e.path),o=await ep(t,{since:cI(e.since),agentId:e.agent,sessions:new Wg(process.cwd()),minOccurrences:Number(e.minOccurrences)||$r,max:Number(e.max)||Oi,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(je.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(` ${je.cyan(n.key)} ${je.bold(`\xD7${n.count}`)} ${je.dim(n.status)}`),n.sampleMessage&&console.log(je.dim(` "${n.sampleMessage.slice(0,100)}"`));if(o.nearMisses.length){console.log(je.dim(`
|
|
703
703
|
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of o.nearMisses.slice(0,5))console.log(je.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of o.drafted)console.log(je.green(` \u2713 draft written: ${n.id}`)+je.dim(` (${n.count} occurrences)`));for(let n of o.skipped)console.log(je.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of o.warnings)console.log(je.yellow(` \u26A0 ${n}`));o.dryRun?console.log(je.dim(`
|
|
@@ -768,7 +768,7 @@ ${e.body||""}`)}function zI(e){return e.startsWith("test/")||/\.test\.[cm]?[jt]s
|
|
|
768
768
|
|
|
769
769
|
`))>=0;){let f=l.slice(0,p);l=l.slice(p+2),aN(f)}}}catch(i){console.error(xe.red(` disconnected: ${i.message||i}`)),process.exit(1)}});function aN(e){let t="message",o="";for(let r of e.split(`
|
|
770
770
|
`))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?xe.dim(new Date(n.at).toLocaleTimeString()):"";switch(t){case"run":{let r=xe.cyan(n.phase?.padEnd(9)??"run"),i=xe.bold(n.workflowId??""),a=xe.dim((n.runId??"").slice(0,8)),c=n.nodeId?xe.yellow(n.nodeId):"",l=n.note?xe.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${r} ${i} ${a} ${c} ${l}`);break}case"task":{let r=xe.magenta(`task.${n.phase}`.padEnd(14)),i=xe.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?xe.dim(`"${n.title}"`):"";console.log(`${s} ${r} ${i} ${xe.cyan(a)} ${c}`);break}case"signal":{let r=xe.green("signal".padEnd(9)),i=xe.bold(n.name),a=xe.dim(`(${n.scope})`),c=n.workflowId?xe.dim(n.workflowId):"";console.log(`${s} ${r} ${i} ${a} ${c}`);break}case"mesh":{let r=xe.blue("mesh".padEnd(9)),i=xe.bold(n.peer),a=n.healthy?xe.green("\u2713 healthy"):xe.red("\u2717 lost");console.log(`${s} ${r} ${i} ${a} ${xe.dim(n.delta??"")}`);break}case"channel":{let r=xe.yellow("channel".padEnd(9)),i=n.direction==="in"?xe.cyan("\u2190"):xe.magenta("\u2192"),a=xe.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?xe.dim(n.textPreview):"";console.log(`${s} ${r} ${i} ${a} ${c}`);break}case"status":{console.log(xe.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)}`)}}te();import{Command as yx}from"commander";import vo from"chalk";function cN(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 lN(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 $x(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 dN=new yx().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}=$x(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(lN(e,n)),signal:AbortSignal.timeout(1e4)}),c=await a.json().catch(()=>({}));if(!a.ok){console.error(vo.red(` Event refused (${a.status}): ${c.error||"unknown error"}`)),process.exitCode=1;return}if(n.json){console.log(JSON.stringify(c,null,2));return}console.log(vo.green(` \u2713 Emitted ${c.event?.type??e} on ${c.event?.node??"this machine"}`)+vo.dim(` (event ${c.event?.id??"?"})`))}catch(a){console.error(vo.red(` daemon unreachable at ${s}: ${a?.message||a}`)),process.exitCode=1}}),bx=new yx().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(dN).action(async e=>{let{baseUrl:t,token:o}=$x(e),n={};o&&(n.Authorization=`Bearer ${o}`);let s;try{let a=await fetch(cN(t,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(vo.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(vo.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(vo.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(r.length===0){console.log(vo.dim(" no events"));return}for(let a of r)console.log(` ${Xg(a)} ${vo.dim(a.id)}`);let i=s.next??r[r.length-1].id;console.log(vo.dim(`
|
|
771
|
-
${r.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${i}`))});import{Command as gN}from"commander";import ii from"chalk";import{spawn as mN}from"node:child_process";import{execFileSync as uN}from"node:child_process";function kx(e=()=>uN("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 vx=new gN().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(ii.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-
|
|
771
|
+
${r.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${i}`))});import{Command as gN}from"commander";import ii from"chalk";import{spawn as mN}from"node:child_process";import{execFileSync as uN}from"node:child_process";function kx(e=()=>uN("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 vx=new gN().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(ii.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-HJBH2DVH.js"),o=t({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:kx();if(n?.ok){let{fetchAgents:l}=await import("./client-HJBH2DVH.js"),u=await l(o);if(!u.length)throw new Error(`No AgentX agents returned by ${o.baseUrl}`);let d=e.agent||u[0].id;if(!u.some(y=>y.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(y=>[y.id,{name:`AgentX ${y.name||y.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(ii.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:w}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:h}=await import("./opencode-launch-ECMEY2QZ.js");await h({agentId:d,env:g,cwd:process.cwd(),pool:w,spawnImpl:mN,log:y=>console.error(ii.dim(y))});return}n&&!n.ok&&(console.error(ii.yellow(n.reason)),console.error(ii.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-UHSMBGRE.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 pN}from"commander";import pe from"chalk";import{randomUUID as Ax}from"crypto";import{createInterface as fN}from"node:readline/promises";import hN from"ora";import kc from"chalk";function xx(e){console.error(),console.error(kc.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(kc.dim(` ${e.why}`)),console.error(),console.error(` Use ${kc.cyan(e.instead)} instead.`),e.note&&console.error(kc.dim(` ${e.note}`)),console.error()}var Sx={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 Ex=new pN().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)=>{xx({what:"agentx chat",...Sx});let o=Uh({node:t.node,token:t.token,config:t.config}),n=(e??"").replace(/^@/,"").trim(),s=t.channel,r=t.chatId||`chat-cli:${Ax().slice(0,12)}`,i=[];try{i=await Zi(o)}catch(u){console.error(pe.red(` cannot reach daemon at ${o.baseUrl}: ${u?.message||u}`)),console.error(pe.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(i.length===0&&(console.error(pe.red(" no agents registered with the daemon")),process.exit(1)),n?i.find(u=>u.id===n)||(console.error(pe.red(` unknown agent: @${n}`)),console.error(pe.dim(` registered: ${i.map(u=>`@${u.id}`).join(", ")}`)),process.exit(1)):(n=i[0].id,console.log(pe.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-Z6YVST7J.js"),p=(await import("react")).default;await u(p.createElement(d,{conn:o,agentId:n,channel:s,chatId:r,agents:i})).waitUntilExit();return}yN(o.baseUrl,n,r,s);let a=fN({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(pe.dim(`
|
|
772
772
|
bye`)),process.exit(0)});;){let u;try{u=(await a.question(pe.cyan("you \u203A "))).trim()}catch{a.close();return}if(!u)continue;if(u==="/exit"||u==="/quit"){a.close();return}if(u==="/who"){console.log(pe.dim(` @${n} chatId=${r} channel=${s}`));continue}if(u==="/clear"){r=`chat-cli:${Ax().slice(0,12)}`,console.log(pe.dim(` fresh chatId=${r} (warm process dropped)`));continue}if(u==="/agents"){try{let g=await Zi(o);for(let w of g){let h=w.id===n?pe.green("\u25CF"):pe.dim("\u25CB");console.log(` ${h} @${w.id} ${pe.dim(w.tier)} ${w.model??""}`)}}catch(g){console.error(pe.red(` failed to list agents: ${g?.message||g}`))}continue}if(u.startsWith("/agent ")){let g=u.slice(7).replace(/^@/,"").trim();if(!g){console.log(pe.red(" usage: /agent <id>"));continue}try{if(!(await Zi(o)).find(h=>h.id===g)){console.log(pe.red(` unknown agent: @${g}`));continue}n=g,console.log(pe.dim(` now talking to @${n}`))}catch(w){console.error(pe.red(` failed to switch agent: ${w?.message||w}`))}continue}if(u.startsWith("/")){console.log(pe.red(` unknown command: ${u.split(/\s+/)[0]}`)),console.log(pe.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=hN({text:`@${n}\u2026`,color:"cyan"}).start(),p=Date.now(),f=wN(n);try{let g=await Wh(o,n,u,{channel:s,chatId:r,onText:h=>{d.stop(),f.text(h)},onThinking:()=>{},onTool:h=>{d.stop(),f.tool(h)}});d.stop();let w=Math.round((Date.now()-p)/100)/10;g.error?f.finishError(g.error):f.finish(w,g.usage)}catch(g){d.stop(),f.finishError(g?.message||String(g))}finally{c=!1}if(l){console.log(pe.dim(" bye"));return}}});function wN(e){let t=!1,o=!0,n=!1,s=new Set,r=()=>{t||(process.stdout.write(`${pe.green(`@${e}`)}
|
|
773
773
|
`),t=!0)};return{text(i){if(i){r(),n=!0;for(let a of i)o&&a!==`
|
|
774
774
|
`&&(process.stdout.write(" "),o=!1),process.stdout.write(a),a===`
|
|
@@ -868,7 +868,7 @@ Restart the daemon to activate.
|
|
|
868
868
|
dist/
|
|
869
869
|
*.log
|
|
870
870
|
.env
|
|
871
|
-
`}import{Command as tj}from"commander";import it from"chalk";import{writeFileSync as oj,mkdirSync as nj,existsSync as Rc,readFileSync as Ux,appendFileSync as Wx}from"fs";import{resolve as gr,dirname as Hx}from"path";import{homedir as og}from"os";var Gx=new tj().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-
|
|
871
|
+
`}import{Command as tj}from"commander";import it from"chalk";import{writeFileSync as oj,mkdirSync as nj,existsSync as Rc,readFileSync as Ux,appendFileSync as Wx}from"fs";import{resolve as gr,dirname as Hx}from"path";import{homedir as og}from"os";var Gx=new tj().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-3NLSKRKW.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=ij(o);break;case"bash":s=uj(o);break;case"fish":s=gj(o);break;default:console.error(it.red(`unsupported shell: ${n}`)),console.error(it.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?gr(String(e.output)):sj(n);nj(Hx(r),{recursive:!0}),oj(r,s),console.log(it.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),rj(n,r,!!e.yes)});function sj(e){let t=og();switch(e){case"zsh":return gr(t,".zsh","completions","_agentx");case"bash":return gr(t,".bash_completion.d","agentx.bash");case"fish":return gr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function rj(e,t,o){if(e==="zsh"){let n=gr(og(),".zshrc"),s=Hx(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Rc(n)?Ux(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(it.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Rc(n)){let u=["","# agentx completion"];c&&u.push(r),l&&u.push(i),Wx(n,u.join(`
|
|
872
872
|
`)+`
|
|
873
873
|
`),console.log(it.green("\u2713 Patched ~/.zshrc")),console.log(it.dim("Reload your shell: exec zsh"));return}console.log(it.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(it.cyan(` ${r}`)),l&&console.log(it.cyan(` ${i}`)),console.log(),console.log(it.dim("Then reload: exec zsh")),console.log(it.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=gr(og(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Rc(n)?Ux(n,"utf-8"):"").includes(t)){console.log(it.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&Rc(n)){Wx(n,`
|
|
874
874
|
# agentx completion
|
|
@@ -884,4 +884,4 @@ ${mj({...t,category:e.category})}`),u&&a.set(l.id,u)}let c=`https://github.com/$
|
|
|
884
884
|
${o.url}`)}catch(t){console.error(pr.red(` ${t.message}`)),process.exitCode=1}});mi.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",sg).action(async(e,t)=>{try{let o=await ag(t.models);if(!rg(t.model,o)){console.log(ig(t.model,o)),process.exitCode=1;return}let n=e==="-"?await hj():await fj(e,"utf8"),s=JSON.parse(n),{version:r}=await Ti(),i=Xx({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(pr.red(` ${o.message}`)),process.exitCode=1}});async function hj(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function Yz(){let e=await Ti(),t=new wj().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=xh(n);Sh(s)&&vh("cli",s)});for(let o of[xy,Dw,Pw,es,Ts,uo,Dt,nh,jb,Pb,po,ha,Io,En,zn,yo,jo,Ok,sn,aa,vx,en,y$,$$,C$,Hr,q$,J$,f$,z$,Y$,ub,fb,hb,Ut,ts,Cx,_r,Ko,Gx,mi])t.addCommand(o);for(let o of Qx)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=Qx.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,yj(o,74," "),""].join(`
|
|
885
885
|
`)}),t}var Qx=[X,rr,Do,to,Mr,Ks,tt,Po,rn,Gn,is,ar,Qo,xt,Us,Ta,Ha,Jn,Ga,za,wx,bx,Oo,ri,Lt,Bh,In,ui,sd,dn,bt,qs,rd,hc,ko,_u,Mo,_x,dr,Px,Ex];function yj(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(`
|
|
886
886
|
`)}export{Yz as buildProgram};
|
|
887
|
-
//# sourceMappingURL=program-
|
|
887
|
+
//# sourceMappingURL=program-3NLSKRKW.js.map
|