agentix-cli 0.165.0 → 0.166.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/README.md +1 -1
- package/dist/{App-4PQX4N6S.js → App-UOZT7MWS.js} +2 -2
- package/dist/{ChatApp-NHB5VPUE.js → ChatApp-N7REHHH3.js} +2 -2
- package/dist/{absorb-eval-PWLEKRFA.js → absorb-eval-MT3ZDYBM.js} +2 -2
- package/dist/{agent-USWAFKWO.js → agent-SUAQ7EBM.js} +2 -2
- package/dist/{board-dashboard-ICXWFJF7.js → board-dashboard-4C77NLY5.js} +445 -341
- package/dist/board-dashboard-4C77NLY5.js.map +1 -0
- package/dist/{chunk-JCOLQ6MO.js → chunk-33KKV3YU.js} +2 -2
- package/dist/{chunk-AM2DYH7Y.js → chunk-64POGFQZ.js} +2 -2
- package/dist/{chunk-MK3H5LQT.js → chunk-7FH2FEFA.js} +2 -2
- package/dist/{chunk-CR55SCRE.js → chunk-7O43PB6O.js} +2 -2
- package/dist/{chunk-HGQKZKXL.js → chunk-7UIK4S6T.js} +2 -2
- package/dist/{chunk-KDDCIOS7.js → chunk-A2D3PNDA.js} +2 -2
- package/dist/{chunk-6JFGNRC3.js → chunk-AE3U4GR6.js} +85 -85
- package/dist/chunk-AE3U4GR6.js.map +1 -0
- package/dist/{chunk-K7ZUE7SG.js → chunk-AFLZHY5Y.js} +2 -2
- package/dist/{chunk-3S2BNZHX.js → chunk-APPTSTL5.js} +2 -2
- package/dist/chunk-B6GVATMI.js +92 -0
- package/dist/chunk-B6GVATMI.js.map +1 -0
- package/dist/{chunk-TW2PBGYA.js → chunk-B7QHC7N4.js} +2 -2
- package/dist/chunk-BE64IJWM.js +11 -0
- package/dist/chunk-BE64IJWM.js.map +1 -0
- package/dist/{chunk-BRNAE6ET.js → chunk-BQXKTQCX.js} +2 -2
- package/dist/{chunk-AYK2MO3B.js → chunk-CTN4KYE6.js} +2 -2
- package/dist/{chunk-C65BZPUE.js → chunk-G3T73GGF.js} +2 -2
- package/dist/{chunk-EJFJBYDJ.js → chunk-IJZNM5PS.js} +2 -2
- package/dist/{chunk-UY64KKNE.js → chunk-JMZNI257.js} +2 -2
- package/dist/{chunk-QLN4W2KV.js → chunk-L7RPH3T7.js} +2 -2
- package/dist/{chunk-CLHIE4UW.js → chunk-LM3K7U6H.js} +10 -10
- package/dist/{chunk-CLHIE4UW.js.map → chunk-LM3K7U6H.js.map} +1 -1
- package/dist/{chunk-UD3WIY2B.js → chunk-LQTTLXZY.js} +3 -3
- package/dist/{chunk-DLTJCOEN.js → chunk-NHWYEIET.js} +2 -2
- package/dist/{chunk-I53O35TO.js → chunk-QGKNDGH5.js} +2 -2
- package/dist/{chunk-IMERQYQ6.js → chunk-QLJ3OMPL.js} +2 -2
- package/dist/{chunk-H4DQGVUG.js → chunk-SXKC2LH7.js} +2 -2
- package/dist/{chunk-OO7T7E4O.js → chunk-TADIDWYZ.js} +2 -2
- package/dist/{chunk-XG5FRD7G.js → chunk-UEEB3UTU.js} +9 -8
- package/dist/{chunk-XG5FRD7G.js.map → chunk-UEEB3UTU.js.map} +1 -1
- package/dist/{chunk-VL74KOR7.js → chunk-VJVXEVZ7.js} +18 -9
- package/dist/{chunk-VL74KOR7.js.map → chunk-VJVXEVZ7.js.map} +1 -1
- package/dist/{chunk-FJJBXYJ5.js → chunk-XJYGMCAV.js} +302 -302
- package/dist/chunk-XJYGMCAV.js.map +1 -0
- package/dist/{chunk-343WTR6F.js → chunk-XML72AUF.js} +2 -2
- package/dist/chunk-XQ2EFLQW.js +41 -0
- package/dist/chunk-XQ2EFLQW.js.map +1 -0
- package/dist/{chunk-EGCWS56X.js → chunk-YKHK47G5.js} +2 -2
- package/dist/{chunk-Z5JVYKVH.js → chunk-YQ25AGX6.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-3JLER5ZO.js → client-6ZHYSQU6.js} +2 -2
- package/dist/{config-HHNGJKVW.js → config-WCEFYQL4.js} +2 -2
- package/dist/config-mutate-LW366SKL.js +2 -0
- package/dist/config-mutator-NRHZ2XH3.js +2 -0
- package/dist/{contributions-6M3TIP57.js → contributions-MUCJKT73.js} +2 -2
- package/dist/{doctor-TOLXE6QQ.js → doctor-2N2MX5YP.js} +2 -2
- package/dist/{failure-candidates-HNENLQJC.js → failure-candidates-WGSFI7GR.js} +2 -2
- package/dist/{follow-up-tool-Q44GNGWF.js → follow-up-tool-W64LMQQN.js} +2 -2
- package/dist/hub-4ODFNGHL.js +2 -0
- package/dist/index.d.ts +102 -38
- package/dist/index.js +1 -1
- package/dist/{program-YJGGF5BS.js → program-6YMRDLHO.js} +24 -24
- package/dist/{promote-JLFDSQFH.js → promote-OUSVJZ64.js} +2 -2
- package/dist/{query-KNZ3EMHA.js → query-QVK5EN3P.js} +2 -2
- package/dist/{query-settings-XRNZOOWV.js → query-settings-2TNLXEL5.js} +2 -2
- package/dist/{registry-EHLXMVUV.js → registry-BYIWNEFL.js} +2 -2
- package/dist/{request-planner-T5GKPGQT.js → request-planner-7HEHLPA3.js} +2 -2
- package/dist/{review-candidates-HSKH2UGT.js → review-candidates-NJNMSOCX.js} +2 -2
- package/dist/routing-HCSXNUOY.js +2 -0
- package/dist/schedule-tool-LJYBLCLV.js +2 -0
- package/dist/scheduler-74MXJLQS.js +2 -0
- package/dist/{seat-OSYVYKBK.js → seat-CAYDECW2.js} +2 -2
- package/dist/{select-I5JLTJKJ.js → select-QUVE6RN2.js} +2 -2
- package/dist/{set-enabled-Q5EPYA33.js → set-enabled-BWJN4IVG.js} +2 -2
- package/dist/{surface-usage-W33HGXMP.js → surface-usage-Y7D5W52I.js} +2 -2
- package/dist/token-tracker-XTHSSPLB.js +2 -0
- package/dist/tool-FZ4UXMON.js +8 -0
- package/dist/tool-FZ4UXMON.js.map +1 -0
- package/dist/{tool-ZDGA6CTA.js → tool-UC7OZWIB.js} +2 -2
- package/dist/traces-O4TIZ4SM.js +2 -0
- package/dist/wiki-KNSPJT2O.js +2 -0
- package/dist/wiki-enrich-RVRTAQQF.js +2 -0
- package/dist/{workflow-pilot-25NMZYUO.js → workflow-pilot-MKG6CJ6V.js} +2 -2
- package/package.json +1 -1
- package/dist/board-dashboard-ICXWFJF7.js.map +0 -1
- package/dist/chunk-6JFGNRC3.js.map +0 -1
- package/dist/chunk-FJJBXYJ5.js.map +0 -1
- package/dist/chunk-KKOULF3I.js +0 -90
- package/dist/chunk-KKOULF3I.js.map +0 -1
- package/dist/chunk-MYEEWFXP.js +0 -41
- package/dist/chunk-MYEEWFXP.js.map +0 -1
- package/dist/chunk-XIRM45DH.js +0 -11
- package/dist/chunk-XIRM45DH.js.map +0 -1
- package/dist/config-mutate-CP2TIY2J.js +0 -2
- package/dist/config-mutator-ZSW4PTO5.js +0 -2
- package/dist/hub-H4AW5H7E.js +0 -2
- package/dist/routing-C66W2E3P.js +0 -2
- package/dist/schedule-tool-3Z45TBN6.js +0 -2
- package/dist/scheduler-TZJJGRAE.js +0 -2
- package/dist/token-tracker-B2UFOH46.js +0 -2
- package/dist/tool-SM3FPKK6.js +0 -6
- package/dist/tool-SM3FPKK6.js.map +0 -1
- package/dist/traces-G4HRLRA3.js +0 -2
- package/dist/wiki-NAE25PMF.js +0 -2
- package/dist/wiki-enrich-3XXN4XCV.js +0 -2
- /package/dist/{App-4PQX4N6S.js.map → App-UOZT7MWS.js.map} +0 -0
- /package/dist/{ChatApp-NHB5VPUE.js.map → ChatApp-N7REHHH3.js.map} +0 -0
- /package/dist/{absorb-eval-PWLEKRFA.js.map → absorb-eval-MT3ZDYBM.js.map} +0 -0
- /package/dist/{agent-USWAFKWO.js.map → agent-SUAQ7EBM.js.map} +0 -0
- /package/dist/{chunk-JCOLQ6MO.js.map → chunk-33KKV3YU.js.map} +0 -0
- /package/dist/{chunk-AM2DYH7Y.js.map → chunk-64POGFQZ.js.map} +0 -0
- /package/dist/{chunk-MK3H5LQT.js.map → chunk-7FH2FEFA.js.map} +0 -0
- /package/dist/{chunk-CR55SCRE.js.map → chunk-7O43PB6O.js.map} +0 -0
- /package/dist/{chunk-HGQKZKXL.js.map → chunk-7UIK4S6T.js.map} +0 -0
- /package/dist/{chunk-KDDCIOS7.js.map → chunk-A2D3PNDA.js.map} +0 -0
- /package/dist/{chunk-K7ZUE7SG.js.map → chunk-AFLZHY5Y.js.map} +0 -0
- /package/dist/{chunk-3S2BNZHX.js.map → chunk-APPTSTL5.js.map} +0 -0
- /package/dist/{chunk-TW2PBGYA.js.map → chunk-B7QHC7N4.js.map} +0 -0
- /package/dist/{chunk-BRNAE6ET.js.map → chunk-BQXKTQCX.js.map} +0 -0
- /package/dist/{chunk-AYK2MO3B.js.map → chunk-CTN4KYE6.js.map} +0 -0
- /package/dist/{chunk-C65BZPUE.js.map → chunk-G3T73GGF.js.map} +0 -0
- /package/dist/{chunk-EJFJBYDJ.js.map → chunk-IJZNM5PS.js.map} +0 -0
- /package/dist/{chunk-UY64KKNE.js.map → chunk-JMZNI257.js.map} +0 -0
- /package/dist/{chunk-QLN4W2KV.js.map → chunk-L7RPH3T7.js.map} +0 -0
- /package/dist/{chunk-UD3WIY2B.js.map → chunk-LQTTLXZY.js.map} +0 -0
- /package/dist/{chunk-DLTJCOEN.js.map → chunk-NHWYEIET.js.map} +0 -0
- /package/dist/{chunk-I53O35TO.js.map → chunk-QGKNDGH5.js.map} +0 -0
- /package/dist/{chunk-IMERQYQ6.js.map → chunk-QLJ3OMPL.js.map} +0 -0
- /package/dist/{chunk-H4DQGVUG.js.map → chunk-SXKC2LH7.js.map} +0 -0
- /package/dist/{chunk-OO7T7E4O.js.map → chunk-TADIDWYZ.js.map} +0 -0
- /package/dist/{chunk-343WTR6F.js.map → chunk-XML72AUF.js.map} +0 -0
- /package/dist/{chunk-EGCWS56X.js.map → chunk-YKHK47G5.js.map} +0 -0
- /package/dist/{chunk-Z5JVYKVH.js.map → chunk-YQ25AGX6.js.map} +0 -0
- /package/dist/{client-3JLER5ZO.js.map → client-6ZHYSQU6.js.map} +0 -0
- /package/dist/{config-HHNGJKVW.js.map → config-WCEFYQL4.js.map} +0 -0
- /package/dist/{config-mutate-CP2TIY2J.js.map → config-mutate-LW366SKL.js.map} +0 -0
- /package/dist/{config-mutator-ZSW4PTO5.js.map → config-mutator-NRHZ2XH3.js.map} +0 -0
- /package/dist/{contributions-6M3TIP57.js.map → contributions-MUCJKT73.js.map} +0 -0
- /package/dist/{doctor-TOLXE6QQ.js.map → doctor-2N2MX5YP.js.map} +0 -0
- /package/dist/{failure-candidates-HNENLQJC.js.map → failure-candidates-WGSFI7GR.js.map} +0 -0
- /package/dist/{follow-up-tool-Q44GNGWF.js.map → follow-up-tool-W64LMQQN.js.map} +0 -0
- /package/dist/{hub-H4AW5H7E.js.map → hub-4ODFNGHL.js.map} +0 -0
- /package/dist/{program-YJGGF5BS.js.map → program-6YMRDLHO.js.map} +0 -0
- /package/dist/{promote-JLFDSQFH.js.map → promote-OUSVJZ64.js.map} +0 -0
- /package/dist/{query-KNZ3EMHA.js.map → query-QVK5EN3P.js.map} +0 -0
- /package/dist/{query-settings-XRNZOOWV.js.map → query-settings-2TNLXEL5.js.map} +0 -0
- /package/dist/{registry-EHLXMVUV.js.map → registry-BYIWNEFL.js.map} +0 -0
- /package/dist/{request-planner-T5GKPGQT.js.map → request-planner-7HEHLPA3.js.map} +0 -0
- /package/dist/{review-candidates-HSKH2UGT.js.map → review-candidates-NJNMSOCX.js.map} +0 -0
- /package/dist/{routing-C66W2E3P.js.map → routing-HCSXNUOY.js.map} +0 -0
- /package/dist/{schedule-tool-3Z45TBN6.js.map → schedule-tool-LJYBLCLV.js.map} +0 -0
- /package/dist/{scheduler-TZJJGRAE.js.map → scheduler-74MXJLQS.js.map} +0 -0
- /package/dist/{seat-OSYVYKBK.js.map → seat-CAYDECW2.js.map} +0 -0
- /package/dist/{select-I5JLTJKJ.js.map → select-QUVE6RN2.js.map} +0 -0
- /package/dist/{set-enabled-Q5EPYA33.js.map → set-enabled-BWJN4IVG.js.map} +0 -0
- /package/dist/{surface-usage-W33HGXMP.js.map → surface-usage-Y7D5W52I.js.map} +0 -0
- /package/dist/{token-tracker-B2UFOH46.js.map → token-tracker-XTHSSPLB.js.map} +0 -0
- /package/dist/{tool-ZDGA6CTA.js.map → tool-UC7OZWIB.js.map} +0 -0
- /package/dist/{traces-G4HRLRA3.js.map → traces-O4TIZ4SM.js.map} +0 -0
- /package/dist/{wiki-NAE25PMF.js.map → wiki-KNSPJT2O.js.map} +0 -0
- /package/dist/{wiki-enrich-3XXN4XCV.js.map → wiki-enrich-RVRTAQQF.js.map} +0 -0
- /package/dist/{workflow-pilot-25NMZYUO.js.map → workflow-pilot-MKG6CJ6V.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Lp,b as Si,g as qp}from"./chunk-
|
|
1
|
+
import{a as Lp,b as Si,g as qp}from"./chunk-L7RPH3T7.js";import{a as Dp,b as Mp}from"./chunk-64POGFQZ.js";import{b as Pp}from"./chunk-QLJ3OMPL.js";import{A as fp,B as hp,C as yp,D as Oc,E as wp,J as bp,K as $p,L as Ic,M as kp,P as Ap,Q as Ep,R as Rp,T as jc,U as Cp,W as Tp,X as Op,Y as Ip,a as Km,b as Vm,f as Xm,g as Qm,i as Zm,j as ep,k as tp,l as op,m as np,n as sp,o as rp,r as Qn,s as Zn,t as no,v as cp,w as lp,x as mp,y as pp}from"./chunk-LM3K7U6H.js";import{a as vp,c as xp,d as Sp}from"./chunk-TADIDWYZ.js";import{n as Nc}from"./chunk-AFLZHY5Y.js";import{a as jp,b as Np,d as Xs,e as _p}from"./chunk-33KKV3YU.js";import"./chunk-XVTD6I34.js";import"./chunk-QAWKN2N4.js";import"./chunk-MTX4UPNB.js";import{a as Tt}from"./chunk-B7QHC7N4.js";import{a as ip,c as ap}from"./chunk-JMZNI257.js";import{d as dp,e as Tc,h as gp,i as up}from"./chunk-CTN4KYE6.js";import{a as Rc}from"./chunk-LNY6N73E.js";import"./chunk-AU3VT7BD.js";import{a as ac,b as eu}from"./chunk-RKPAVWXF.js";import{$ as Em,A as Qu,Aa as Ec,B as pc,Ba as zm,C as Zu,Ca as vi,D as em,Da as Xn,E as tm,Ea as xi,F as om,Fa as Cc,G as nm,Ga as Ym,H as pi,I as sm,J as fc,K as rm,L as im,M as am,N as fi,O as um,P as fm,Q as hm,R as ym,S as wm,T as bm,U as yc,V as $m,W as km,X as vm,Y as xm,Z as Sm,_ as Am,a as cu,aa as Rm,b as lu,ba as _m,ca as wi,da as ho,ea as jo,fa as Yn,ga as bi,h as ei,ha as $i,i as mu,ia as xc,j as Hs,ja as Pm,k as ti,ka as Dm,l as fu,la as Mm,m as yu,ma as Lm,n as Tu,na as qm,o as Ou,oa as Fm,p as ai,pa as Kn,q as gc,qa as Vn,r as Mu,ra as Um,s as Hu,sa as Ks,t as zu,ta as Wm,u as Yu,ua as it,v as Ku,va as ki,w as mi,wa as Vs,x as Vu,xa as Sc,y as Xu,ya as Bm,z as mc,za as Gm}from"./chunk-XJYGMCAV.js";import{Ca as zs,Fa as wc,Ga as hi,Ha as Cm,Jb as oo,Lb as Hm,Oa as Io,P as Bu,Pa as Tm,Qa as bc,R as gi,S as Ju,Sa as $c,Ua as Om,V as Gu,Va as Im,W as ui,Wa as Ys,_a as yi,bb as jm,cb as Nm,da as cm,db as kc,ea as lm,fa as dm,ga as hc,ia as gm,kb as vc,ub as Jm,v as hu,vb as Ac}from"./chunk-A2D3PNDA.js";import"./chunk-GTJIKXDB.js";import{a as du,c as cc,e as gu,f as uu}from"./chunk-YKHK47G5.js";import{F as si,G as Ru,H as Cu,a as rc,b as Yg,e as Kg,f as Vg,n as oi,o as ni,p as wu,q as bu,r as $u,t as ku,u as vu,w as xu,x as Su,y as Au,z as Eu}from"./chunk-BQXKTQCX.js";import"./chunk-VUEQ4SL5.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import{c as ju,e as ri,g as ii}from"./chunk-LQE73AZR.js";import{a as Nu,b as _u,c as Pu,d as Du}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-BNOGNRAM.js";import{a as Lu,b as nn,c as qu,d as ci,g as Fu,h as Uu,j as Wu,k as uc,n as li,o as sn,p as di}from"./chunk-LQS27HSV.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as mm,b as pm}from"./chunk-EKJG63EJ.js";import{a as lc,p as pu}from"./chunk-SXKC2LH7.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Ct}from"./chunk-UKUH662W.js";import{c as Iu}from"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import{b as dc}from"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import{a as to}from"./chunk-MNG2AMKZ.js";import"./chunk-X7UQY7CH.js";import{a as ic,d as Xg,e as Zr}from"./chunk-QPABR72X.js";import{a as Gs,e as tu,f as ou,h as nu,i as su,k as ru,l as iu,m as au}from"./chunk-APPTSTL5.js";import{b as zn,e as Zg}from"./chunk-PYHR4HXO.js";import{c as Qg}from"./chunk-KP7KDLZ2.js";import"./chunk-A5GYG56I.js";import{A as oc,B as jg,N as Oo,T as Gg,g as Sg,r as Ag,ra as zg}from"./chunk-AE3U4GR6.js";import{A as Wn,B as Xr,C as Qr,D as Bn,E as Ng,F as Co,H as To,Z as Bg,b as Un,ma as Jg,oa as Hg}from"./chunk-XQ2EFLQW.js";import{b as tn}from"./chunk-MEFPXHQJ.js";import"./chunk-NHWYEIET.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as Pg}from"./chunk-SZDACK6O.js";import{f as Dg,g as Mg,h as nc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as qg,f as on,k as Gn}from"./chunk-VJVXEVZ7.js";import{a as Og,k as Lg}from"./chunk-7UIK4S6T.js";import{a as fo,b as ge,c as He,d as Hn,e as Fg}from"./chunk-G3T73GGF.js";import{a as Ug,b as sc,h as Wg}from"./chunk-3UOTLMXD.js";import{i as Rg,j as Cg}from"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import{a as tc,b as Tg}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Ig}from"./chunk-X5C5W3E4.js";import{a as Jn}from"./chunk-GV7S5BAX.js";import{e as _g}from"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import{a as ec}from"./chunk-7O43PB6O.js";import"./chunk-XML72AUF.js";import{c as Eg}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-LQTTLXZY.js";import"./chunk-JTFCU5LH.js";import{g as Ro,i as Vr}from"./chunk-IJZNM5PS.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-7FH2FEFA.js";import{a as Ya,b as Qd,c as lk,d as Br,e as Zd,f as hg,g as wk,h as yg,i as bk,m as Fn,n as bg,q as $g,u as kg,y as eo,z as Js}from"./chunk-QGKNDGH5.js";import{a as po,b as qn,e as mg,f as Bs}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Kr,b as wg}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as Eo,j as vg}from"./chunk-QUFIUXMQ.js";import{n as xg}from"./chunk-AV7T3SYT.js";import"./chunk-TM2TPQKH.js";import"./chunk-BERWTVG2.js";import"./chunk-QOYAX2FT.js";import"./chunk-OSH2PEBH.js";import"./chunk-6QLRRSKU.js";import{a as Zt,b as ck}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{Fa as dg,Ga as Xa,Ia as Qa,M as ig,N as mk,Pa as fk,Qa as Za,S as Jr,Sa as gg,T as Gr,Ta as hk,W as ag,X as cg,Xa as ug,Y as Hr,Z as Va,ea as lg,fa as pk,ib as zr,j as tg,jb as Ws,k as og,kb as C,l as ng,m as sg,mb as Yr,n as rg,o as gk,tb as oe,x as Ka,y as uk}from"./chunk-B6GVATMI.js";import"./chunk-BRK6M6LA.js";import{j as Rt,r as Us}from"./chunk-UEEB3UTU.js";import{a as eg,e as dk}from"./chunk-2QNT5JDS.js";import{g as pg,k as fg,l as yk}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as $k}from"commander";var Fp=new $k().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 lu({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()});oe();import{Command as kk}from"commander";import{execFileSync as Lt}from"node:child_process";import{cpSync as Up,existsSync as Dc,mkdirSync as _c,mkdtempSync as vk,readdirSync as xk,rmSync as Wp,writeFileSync as Bp}from"node:fs";import{dirname as Jp,join as at}from"node:path";import{homedir as Ai,release as Sk,tmpdir as Ak}from"node:os";import{setTimeout as Ek}from"node:timers/promises";function Ei(){let e=wu(process.platform,process.arch,Sk());if(e)throw new Error(e)}function Ri(){let e=at(Ai(),"Library/LaunchAgents"),t=[];try{t=xk(e).filter(ku)}catch{}let o=t.flatMap(n=>{let s=at(e,n);try{return[{file:s,plist:Lt("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return vu(e,o)}function Qs(e){return`gui/${process.getuid()}/${e.label}`}async function Pc(e){try{Lt("launchctl",["bootout",Qs(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Lt("launchctl",["print",Qs(e)],{stdio:"pipe"})}catch{return}await Ek(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Gp(e){if(!Dc(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Lt("launchctl",["print",Qs(e)],{stdio:"pipe"})}catch{t=!1}t||Lt("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Lt("launchctl",["kickstart",Qs(e)],{stdio:"pipe"})}function Rk(){let e=Eu();if(e&&Dc(at(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 es=new kk("desktop").description("install and control the macOS desktop assistant");es.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=>{Ei();let t=C(),o=bu(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=Rk(),i=at(Ai(),"Applications"),{keep:a,remove:c}=Ri();if(console.log(`Desktop assistant \u2192 ${at(i,oi)}
|
|
2
2
|
Computer-use helper \u2192 ${at(i,ni)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -41,7 +41,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
41
41
|
`))});function nh(e){let t=Rt();return t||(console.log(Q.red(" The database (.agentx/db.sqlite) can't be opened here.")),process.exit(1)),e(new Rc(t))}function Hv(){let e=Rt({quiet:!0});if(!e)return[];let t=new Map;for(let o of new Rc(e).list()){if(!dc(o.deviceId))continue;let n=t.get(o.deviceId)??{deviceId:o.deviceId,deviceName:o.deviceName,createdAt:o.createdAt,subscriptions:0};n.subscriptions++,n.createdAt=Math.max(n.createdAt,o.createdAt),t.set(o.deviceId,n)}return[...t.values()]}function zv(e){let t=Math.round(ju/6e4),o=[` Pairing code: ${Q.bold.cyan(ri(e.code))}`,Q.dim(` Open the app from the phone's home screen and type this code. It works once, for ${t} minutes.`)," Or scan the QR code with the phone's camera and open the link.",` Device ${Q.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Q.yellow(" \u26A0 Anyone who scans the QR code or types the code can use the app. Clear the terminal when done.")];return e.origin.startsWith("https://")||o.push(Q.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),o}function el(){let e;try{e=JSON.parse(oh("tailscale",["status","--json"],{encoding:"utf-8",timeout:5e3}))}catch{throw new Error("Could not read this machine's Tailscale name. Is Tailscale running? Or pass --url https://<address>.")}let t=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!t)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${t}`}var Yv=new Set(["/app","/api/app","/member","/api/member"]),th="/.well-known/assetlinks.json";function Kv(){let e=new Set(["localhost","0.0.0.0","::","::1"]);try{let t=Jv().toLowerCase().replace(/\.$/,"");t&&e.add(t).add(t.replace(/\.local$/,"")).add(`${t.replace(/\.local$/,"")}.local`)}catch{}try{for(let t of Object.values(Gv()))for(let o of t??[])e.add(sh(o.address.toLowerCase().replace(/%.*$/,"")))}catch{}return e}var Vv={http:80,https:443,"https+insecure":443};function Xv(e){let t=e.match(/^(\d+)(\/[^?#]*)?$/);if(t)return{host:"localhost",port:Number(t[1]),path:t[2]??""};let o=e.match(/^(?:([a-z][a-z0-9+.-]*):\/\/)?(?:[^@/?#]*@)?(\[[^\]]*\]|[^/:?#]*)(?::(\d+))?([^?#]*)/i);if(!o)return null;let n=o[3]?Number(o[3]):Vv[(o[1]??"http").toLowerCase()];return n?{host:sh(o[2].replace(/^\[|\]$/g,"").replace(/%.*$/,"").replace(/\.$/,"").toLowerCase()),port:n,path:o[4]}:null}function sh(e){let t=e.includes(":");if(!t&&!/^[0-9a-fx.]+$/.test(e))return e;let o;try{o=new URL(`http://${t?`[${e}]`:e}/`).hostname.replace(/^\[|\]$/g,"")}catch{return e}let n=o.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);if(!n)return o;let[s,r]=[parseInt(n[1],16),parseInt(n[2],16)];return`::ffff:${s>>8}.${s&255}.${r>>8}.${r&255}`}function Qv(e,t){let o=e.replace(/^::ffff:/,"");return t.has(e)||t.has(o)||e===""||e.endsWith(".localhost")||/^127\.\d+\.\d+\.\d+$/.test(o)||o==="0.0.0.0"}function tl(e,t,o=Kv()){let n=[e,...Object.values(e?.Foreground??{})],s=[];for(let c of n){s.push({label:"",cfg:c});for(let[l,g]of Object.entries(c?.Services??{}))s.push({label:`${l} `,cfg:g})}let r=new Set(o);for(let{cfg:c}of s){for(let l of Object.keys(c?.Web??{}))r.add(l.replace(/:\d+$/,"").replace(/\.$/,"").toLowerCase());for(let l of Object.values(c?.TCP??{}))l?.TerminateTLS&&r.add(String(l.TerminateTLS).replace(/\.$/,"").toLowerCase())}let i=c=>{let l=Xv(c.trim());return l&&l.port===t&&Qv(l.host,r)?l:null},a=[];for(let{label:c,cfg:l}of s){for(let[g,d]of Object.entries(l?.Web??{}))for(let[f,p]of Object.entries(d?.Handlers??{})){if(p?.Proxy==null)continue;let u=i(String(p.Proxy));if(!u)continue;let h=f.replace(/\/+$/,"")||"/",y=h===th&&u.path===th;!Yv.has(h)&&!y&&a.push(`${c}${g}${f}`)}for(let[g,d]of Object.entries(l?.TCP??{}))d?.TCPForward==null||!i(String(d.TCPForward))||a.push(`${c}TCP port ${g}`)}return a}function ol(){try{return JSON.parse(oh("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function rr(){try{return C().dashboard.port||4202}catch{return 4202}}oe();import{Command as io}from"commander";import w from"chalk";import st from"prompts";import{readFileSync as _o,writeFileSync as is,existsSync as Ue,mkdirSync as ro,cpSync as nl,readdirSync as Zv}from"fs";import{resolve as re,join as No,dirname as ex}from"path";import{fileURLToPath as tx}from"url";function Ae(){let e=re(process.cwd(),"agentx.json");if(!Ue(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(_o(e,"utf-8"))}function mt(e){return ge(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(w.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(w.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(w.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var cn=new io().name("agent").description("manage agents \u2014 add, list, remove");cn.command("list").alias("ls").description("list configured agents").action(()=>{let e=Ae();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${w.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(w.dim(` workspace: ${o.workspace}`)),n&&console.log(w.dim(` mentions: ${n}`))}console.log()});cn.command("add").description("add a new agent interactively").action(async()=>{let e=Ae(),t=await st([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:re(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:No(t.workspace,t.id);ro(re(o,".claude/skills"),{recursive:!0});let n={name:t.name,workspace:o,tier:t.tier,model:t.model,mentions:t.mentions?.map(l=>l.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",(...l)=>{console.log(w.dim(` ${l.join(" ")}`))}),i=re(process.cwd(),"src/wiki/SKILL.md"),a=re(ex(tx(import.meta.url)),"../wiki/SKILL.md"),c=Ue(i)?i:a;Ue(c)&&(ro(re(o,".claude/skills/wiki"),{recursive:!0}),nl(c,re(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await mt(e),console.log(w.green(`
|
|
42
42
|
Agent "${t.id}" added`)),console.log(w.dim(` Workspace: ${o}`)),console.log(w.dim(` Created: ${r.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});cn.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=Ae();if(!t.agents?.[e]){console.log(w.red(` Agent "${e}" not found`));return}delete t.agents[e],await mt(t),console.log(w.green(` Agent "${e}" removed from config (workspace preserved)`))});cn.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=Ae(),n=o.agents?.[e];if(n||(console.log(w.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log(w.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):w.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":w.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||w.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(w.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(w.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(w.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(w.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=r,s.push(`maxExecutionMinutes=${r}`)}s.length===0&&(console.log(w.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await mt(o),console.log(w.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(w.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var ir=new io().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");ir.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,t)=>{let n=Ae().agents?.[e];n||(console.log(w.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(w.dim(`
|
|
43
43
|
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
44
|
-
`));return}console.log(),console.log(w.bold(` ${e}`));for(let r of s){let i=r.enabled!==!1,a=[],c=r.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?w.green(`${g}:${d}=set`):w.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(w.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(w.dim(`sessionDir:${d}`));let l=Object.entries(r.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${i?w.cyan(r.kind.padEnd(14)):w.dim(r.kind.padEnd(14))} ${w.bold(r.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${w.dim(l)}`),i||console.log(` ${w.dim("(disabled)")}`)}console.log()});ir.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=Ae();o.agents?.[e]||(console.log(w.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-HHNGJKVW.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await st({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(p=>({title:p,value:p}))})).kind||"").trim()),r||(console.log(w.red(" --kind is required")),process.exit(1));let i=String(t.label||"").trim();!i&&n&&(i=((await st({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),i||(console.log(w.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 f=await st({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"}]});f.scheme==="tokenEnv"?a=((await st({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():f.scheme==="keyring"?c="keyring":f.scheme==="sessionDir"&&(l=((await st({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${r}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(t.metadata)for(let f of String(t.metadata).split(",")){let[p,...u]=f.split("=");p&&(g[p.trim()]=u.join("=").trim())}else if(n){let f=await st({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(f.metadata)for(let p of String(f.metadata).split(",")){let[u,...h]=p.split("=");u&&(g[u.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(w.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(w.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(f=>f.kind===r&&f.label===i)&&(console.log(w.red(` Integration (${r}, ${i}) already exists on ${e}`)),process.exit(1)),o.agents[e].integrations.push({kind:r,label:i,credentials:d,metadata:g,enabled:!0}),await mt(o),console.log(w.green(` \u2713 ${e}: added ${r} integration "${i}"`)),a&&!process.env[a]&&console.log(w.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});ir.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=Ae(),n=o.agents?.[e];n||(console.log(w.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(w.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await mt(o),console.log(w.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});ir.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=Ae().agents?.[e];n||(console.log(w.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(w.yellow(" no integrations to test"));return}let i=0;console.log();for(let a of r){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){i+=1,console.log(` ${w.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${w.dim(g)}`)}else console.log(` ${w.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),i>0&&process.exit(1)});cn.addCommand(ir);var Di=new io().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Di.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Ae();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(w.bold(" Telegram:"));for(let[s,r]of Object.entries(t.accounts||{}))console.log(` ${w.cyan(s)} -> agent: ${r.agentBinding}`)}else console.log(w.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(w.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of o.routes||[]){let r=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${r} -> agent: ${s.agent}`)}}else console.log(w.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(w.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(w.dim(" GitLab: disabled"));console.log()});Di.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=Ae(),t=Object.keys(e.agents||{});if(!t.length){console.log(w.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 st({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 st([{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(w.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(w.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 mt(e),console.log(w.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await st([{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 st([{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 mt(e),ro(re(process.cwd(),s.sessionDir),{recursive:!0}),console.log(w.green(` WhatsApp enabled (${r.length} routes, default: ${s.defaultAgent})`)),console.log(w.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await st([{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 st([{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 mt(e),console.log(w.green(` GitLab enabled (${r.length} routes, webhook :${s.webhookPort})`)),console.log(w.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(w.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(w.dim(` Secret token: ${s.webhookSecret}`)),console.log(w.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(w.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var as=new io().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");as.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Ae();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?w.green("\u25CF"):w.dim("\u25CB");console.log(` ${n} ${w.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(w.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(w.dim(" No cron jobs configured")),console.log()});as.command("add").description("add a cron job").action(async()=>{let e=Ae(),t=Object.keys(e.agents||{}),o=await st([{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 mt(e),console.log(w.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});as.command("enable <id>").description("enable a cron job").action(async e=>{let t=Ae();if(!t.crons?.[e]){console.log(w.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(w.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await mt(t),console.log(w.green(` Cron "${e}" enabled`))});as.command("disable <id>").description("disable a cron job").action(async e=>{let t=Ae();if(!t.crons?.[e]){console.log(w.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await mt(t),console.log(w.green(` Cron "${e}" disabled`))});var It=new io().name("mesh").description("manage mesh peers \u2014 add, list, remove");It.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Ae();if(console.log(),!e.mesh?.enabled)console.log(w.dim(" Mesh: disabled"));else{console.log(w.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=w.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=w.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${w.cyan(t.name)} ${w.dim(t.url)} ${o}`)}}console.log()});It.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Ae(),t=await st([{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(w.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(w.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 mt(e),console.log(w.green(` Peer "${t.name}" added`)),console.log()}});It.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=Ae();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await mt(t),console.log(w.green(` Peer "${e}" removed`)))});It.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=Ae();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(w.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(w.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(w.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await mt(t),console.log(w.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(w.dim(" Restart the daemon for the new cadence to take effect."))});It.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=C().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(w.red(` Announcement refused (${r.status}): ${i.error||"unknown error"}`)),process.exit(1)),console.log(w.green(` \u2713 Announced from ${i.event?.node??"this machine"}`)+w.dim(` (event ${i.event?.id??"?"})`))}catch(r){console.log(w.red(` Could not reach the daemon at ${o}: ${r?.message||r}`)),process.exit(1)}});var rh=e=>{let t=e||"";if(!t)try{t=C().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function Mi(e,t,o={}){let n=rh(),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(w.red(` ${i.error||`HTTP ${r.status}`}`)),process.exit(1));let a=i.grant;console.log(w.green(` \u2713 ${a?.name??e}: ${a?.state}${i.stopped?`, ${i.stopped} running turn(s) stopped`:""}`))}catch(r){console.log(w.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 ln=It.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");ln.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-YGA654NI.js"),i=C(),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(w.red(` ${a.error}`)),process.exit(1));let c=(e.url||rh()).replace(/\/+$/,"");console.log(),console.log(` Grant ${w.bold(a.grant.name)} for ${w.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(w.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(` ${w.cyan(c)}`),console.log(` ${w.bold(n(a.code))}`),console.log(),console.log(` They run: ${w.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()});ln.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(w.dim(`
|
|
44
|
+
`));return}console.log(),console.log(w.bold(` ${e}`));for(let r of s){let i=r.enabled!==!1,a=[],c=r.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?w.green(`${g}:${d}=set`):w.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(w.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(w.dim(`sessionDir:${d}`));let l=Object.entries(r.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${i?w.cyan(r.kind.padEnd(14)):w.dim(r.kind.padEnd(14))} ${w.bold(r.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${w.dim(l)}`),i||console.log(` ${w.dim("(disabled)")}`)}console.log()});ir.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=Ae();o.agents?.[e]||(console.log(w.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-WCEFYQL4.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await st({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(p=>({title:p,value:p}))})).kind||"").trim()),r||(console.log(w.red(" --kind is required")),process.exit(1));let i=String(t.label||"").trim();!i&&n&&(i=((await st({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),i||(console.log(w.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 f=await st({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"}]});f.scheme==="tokenEnv"?a=((await st({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():f.scheme==="keyring"?c="keyring":f.scheme==="sessionDir"&&(l=((await st({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${r}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(t.metadata)for(let f of String(t.metadata).split(",")){let[p,...u]=f.split("=");p&&(g[p.trim()]=u.join("=").trim())}else if(n){let f=await st({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(f.metadata)for(let p of String(f.metadata).split(",")){let[u,...h]=p.split("=");u&&(g[u.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(w.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(w.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(f=>f.kind===r&&f.label===i)&&(console.log(w.red(` Integration (${r}, ${i}) already exists on ${e}`)),process.exit(1)),o.agents[e].integrations.push({kind:r,label:i,credentials:d,metadata:g,enabled:!0}),await mt(o),console.log(w.green(` \u2713 ${e}: added ${r} integration "${i}"`)),a&&!process.env[a]&&console.log(w.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});ir.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=Ae(),n=o.agents?.[e];n||(console.log(w.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(w.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await mt(o),console.log(w.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});ir.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=Ae().agents?.[e];n||(console.log(w.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(w.yellow(" no integrations to test"));return}let i=0;console.log();for(let a of r){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){i+=1,console.log(` ${w.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${w.dim(g)}`)}else console.log(` ${w.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),i>0&&process.exit(1)});cn.addCommand(ir);var Di=new io().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Di.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Ae();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(w.bold(" Telegram:"));for(let[s,r]of Object.entries(t.accounts||{}))console.log(` ${w.cyan(s)} -> agent: ${r.agentBinding}`)}else console.log(w.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(w.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of o.routes||[]){let r=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${r} -> agent: ${s.agent}`)}}else console.log(w.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(w.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(w.dim(" GitLab: disabled"));console.log()});Di.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=Ae(),t=Object.keys(e.agents||{});if(!t.length){console.log(w.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 st({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 st([{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(w.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(w.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 mt(e),console.log(w.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await st([{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 st([{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 mt(e),ro(re(process.cwd(),s.sessionDir),{recursive:!0}),console.log(w.green(` WhatsApp enabled (${r.length} routes, default: ${s.defaultAgent})`)),console.log(w.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await st([{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 st([{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 mt(e),console.log(w.green(` GitLab enabled (${r.length} routes, webhook :${s.webhookPort})`)),console.log(w.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(w.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(w.dim(` Secret token: ${s.webhookSecret}`)),console.log(w.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(w.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var as=new io().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");as.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Ae();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?w.green("\u25CF"):w.dim("\u25CB");console.log(` ${n} ${w.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(w.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(w.dim(" No cron jobs configured")),console.log()});as.command("add").description("add a cron job").action(async()=>{let e=Ae(),t=Object.keys(e.agents||{}),o=await st([{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 mt(e),console.log(w.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});as.command("enable <id>").description("enable a cron job").action(async e=>{let t=Ae();if(!t.crons?.[e]){console.log(w.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(w.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await mt(t),console.log(w.green(` Cron "${e}" enabled`))});as.command("disable <id>").description("disable a cron job").action(async e=>{let t=Ae();if(!t.crons?.[e]){console.log(w.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await mt(t),console.log(w.green(` Cron "${e}" disabled`))});var It=new io().name("mesh").description("manage mesh peers \u2014 add, list, remove");It.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Ae();if(console.log(),!e.mesh?.enabled)console.log(w.dim(" Mesh: disabled"));else{console.log(w.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=w.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=w.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${w.cyan(t.name)} ${w.dim(t.url)} ${o}`)}}console.log()});It.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Ae(),t=await st([{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(w.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(w.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 mt(e),console.log(w.green(` Peer "${t.name}" added`)),console.log()}});It.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=Ae();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await mt(t),console.log(w.green(` Peer "${e}" removed`)))});It.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=Ae();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(w.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(w.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(w.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await mt(t),console.log(w.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(w.dim(" Restart the daemon for the new cadence to take effect."))});It.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=C().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(w.red(` Announcement refused (${r.status}): ${i.error||"unknown error"}`)),process.exit(1)),console.log(w.green(` \u2713 Announced from ${i.event?.node??"this machine"}`)+w.dim(` (event ${i.event?.id??"?"})`))}catch(r){console.log(w.red(` Could not reach the daemon at ${o}: ${r?.message||r}`)),process.exit(1)}});var rh=e=>{let t=e||"";if(!t)try{t=C().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function Mi(e,t,o={}){let n=rh(),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(w.red(` ${i.error||`HTTP ${r.status}`}`)),process.exit(1));let a=i.grant;console.log(w.green(` \u2713 ${a?.name??e}: ${a?.state}${i.stopped?`, ${i.stopped} running turn(s) stopped`:""}`))}catch(r){console.log(w.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 ln=It.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");ln.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-YGA654NI.js"),i=C(),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(w.red(` ${a.error}`)),process.exit(1));let c=(e.url||rh()).replace(/\/+$/,"");console.log(),console.log(` Grant ${w.bold(a.grant.name)} for ${w.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(w.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(` ${w.cyan(c)}`),console.log(` ${w.bold(n(a.code))}`),console.log(),console.log(` They run: ${w.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()});ln.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(w.dim(`
|
|
45
45
|
No guest grants. Open one: agentx mesh guests invite --name \u2026 --guest \u2026 --agent \u2026
|
|
46
46
|
`));return}console.log();for(let n of o){let s=n.state==="active"?w.green("active"):n.state==="pending"?w.yellow(n.guestNode?"waiting for your approval":"not joined yet"):n.state==="paused"?w.yellow("paused"):w.red(`ended${n.endedReason?`: ${n.endedReason}`:""}`);console.log(` ${w.cyan(n.id)} ${w.bold(n.name)} ${n.guest} \u2192 ${n.agentId} ${n.level} ${s}`),console.log(w.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()});ln.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(w.red(` No grant "${e}". See \`agentx mesh guests\`.`)),process.exit(1)),console.log(),console.log(` ${w.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"}
|
|
47
47
|
skills: ${n.skills.join(", ")||"none"}
|
|
@@ -52,7 +52,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
|
|
|
52
52
|
Not a guest anywhere. Join with: agentx mesh join <url> --code \u2026 --name \u2026
|
|
53
53
|
`));return}console.log();for(let n of o){let s=await t(n),r=s.ok?s.grant.state==="active"?w.green("active"):w.yellow(String(s.grant.state)):s.status===403?w.yellow(s.error):w.red(s.error);console.log(` ${w.cyan(n.name)} ${w.dim(n.url)} ${n.agentId} until ${n.expiresAt.slice(0,10)} ${r}`)}console.log()});It.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(w.red(` No host "${e}". See \`agentx mesh hosts\`.`)),process.exit(1));let r=await n(s,t.join(" "));r.error&&(console.log(w.red(` ${r.error}`)),process.exit(1)),console.log(`
|
|
54
54
|
${r.content}
|
|
55
|
-
`)});It.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(w.red(` No host "${e}".`)),process.exit(1)),console.log(w.green(` \u2713 Left ${e}`))});var dn=new io().name("skill").description("manage skills \u2014 add to agent(s), list");dn.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=Ae(),n=re(e);if(!Ue(n)){console.log(w.red(` Skill not found: ${n}`));return}let s=Ue(No(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 st({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(w.yellow(` Agent "${i}" not found, skipping`));continue}let c=Qn(a.tier,a.workspace);if(!c){console.log(w.yellow(` ${i}: its runtime (${a.tier}) does not use skills, skipping`));continue}let l=re(c,s);ro(l,{recursive:!0}),Ue(No(n,"SKILL.md"))?nl(n,l,{recursive:!0}):n.endsWith(".md")&&nl(n,No(l,"SKILL.md")),console.log(w.green(` ${s} -> ${i} (${a.workspace})`))}console.log()});dn.command("list").alias("ls").description("list skills per agent").action(()=>{let e=Ae();console.log();for(let[t,o]of Object.entries(e.agents||{})){if(!Qn(o.tier,o.workspace)){console.log(` ${w.cyan(t)}: ${w.dim(`(${o.tier} does not use skills)`)}`);continue}let n=Zn(o.tier,o.workspace).map(s=>s.name);console.log(` ${w.cyan(t)}: ${n.length?n.join(", "):w.dim("(none)")}`)}console.log()});dn.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]:[re(n,"src",e,"SKILL.md"),re(n,"skills",e,"SKILL.md")],r=s.find(b=>Ue(b));if(!r){console.log(w.red(` No SKILL.md found for "${e}". Searched:`));for(let b of s)console.log(w.dim(` ${b}`));return}let i=_o(r,"utf-8"),a=o("sha256").update(i).digest("hex").slice(0,12),c=(i.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=C()}catch(b){console.log(w.red(` Can't load agentx.json: ${b.message}`));return}let g=Object.entries(l.agents||{}),d=t.agent?g.filter(([b])=>b===t.agent):g;if(d.length===0){console.log(w.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(w.bold(` Skill sync \u2014 ${e}`)),console.log(w.dim(` Source: ${r}`)),console.log(w.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(w.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let f=0,p=0,u=0,h=0;for(let[b,$]of d){let v=$.workspace;if(!v||!Ue(v)){console.log(` ${w.yellow("\u2717")} ${b.padEnd(22)} ${w.dim("(workspace missing: "+(v||"undefined")+")")}`),h++;continue}let x=Qn($.tier,v);if(!x){console.log(` ${w.dim("\xB7")} ${b.padEnd(22)} ${w.dim(`(skipped \u2014 ${$.tier} does not use skills)`)}`),h++;continue}let S=Zn($.tier,v).find(I=>I.name===e)?.dir??re(x,e),k=re(S,"SKILL.md");if(!Ue(k)){if(!t.allWorkspaces){console.log(` ${w.dim("\xB7")} ${b.padEnd(22)} ${w.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}t.dryRun||(ro(S,{recursive:!0}),is(k,i)),console.log(` ${w.green("+")} ${b.padEnd(22)} ${w.dim("\u2192 seeded v"+c)}`),f++;continue}let A=_o(k,"utf-8");if(o("sha256").update(A).digest("hex").slice(0,12)===a){console.log(` ${w.dim("=")} ${b.padEnd(22)} ${w.dim("up to date (v"+c+")")}`),u++;continue}let O=(A.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||is(k,i),console.log(` ${w.yellow("\u21BB")} ${b.padEnd(22)} ${w.dim(`v${O} \u2192 v${c}`)}`),p++}console.log();let y=t.dryRun?"would":"did";console.log(w.dim(` Summary: ${y} seed ${f}, ${y} update ${p}, ${u} already current, ${h} skipped.`)),t.dryRun&&(f>0||p>0)&&console.log(w.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});dn.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 p=Ae().agents?.[e.workspace];p||(console.log(w.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),r.push(re(p.workspace))}else if(e.allWorkspaces){let f=Ae();for(let p of Object.values(f.agents||{}))p?.workspace&&r.push(re(p.workspace))}else r.push(re(e.cwd));let i=re(e.referencesCwd||e.cwd),c=(await Promise.all(r.map(f=>t(f)))).flat(),[l,g]=await Promise.all([n(i),s(i)]),d=o({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(f=>({name:f.name,verdict:f.verdict,reasons:f.reasons,path:f.skill?.path})),null,2));else{let f={PASS:0,REVIEW:0,FAILING:0};for(let p of d)f[p.verdict]++;console.log();for(let p of d){let u=p.verdict==="PASS"?w.green("PASS "):p.verdict==="REVIEW"?w.yellow("REVIEW "):w.red("FAILING");console.log(` ${u} ${w.bold(p.name)}${p.skill?.path?w.dim(` (${p.skill.path})`):""}`);for(let h of p.reasons)console.log(` ${w.dim("\xB7")} ${h}`)}console.log(),console.log(` ${w.green(`${f.PASS} PASS`)} ${w.yellow(`${f.REVIEW} REVIEW`)} ${w.red(`${f.FAILING} FAILING`)}`),console.log()}process.exit(d.some(f=>f.verdict==="FAILING")?1:0)});dn.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=Ae(),n=Object.entries(o.agents||{}),[s,r]=t.agent?n.find(([g])=>g===t.agent)??[]:n[0]??[];r||(console.log(w.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:i}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-
|
|
55
|
+
`)});It.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(w.red(` No host "${e}".`)),process.exit(1)),console.log(w.green(` \u2713 Left ${e}`))});var dn=new io().name("skill").description("manage skills \u2014 add to agent(s), list");dn.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=Ae(),n=re(e);if(!Ue(n)){console.log(w.red(` Skill not found: ${n}`));return}let s=Ue(No(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 st({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(w.yellow(` Agent "${i}" not found, skipping`));continue}let c=Qn(a.tier,a.workspace);if(!c){console.log(w.yellow(` ${i}: its runtime (${a.tier}) does not use skills, skipping`));continue}let l=re(c,s);ro(l,{recursive:!0}),Ue(No(n,"SKILL.md"))?nl(n,l,{recursive:!0}):n.endsWith(".md")&&nl(n,No(l,"SKILL.md")),console.log(w.green(` ${s} -> ${i} (${a.workspace})`))}console.log()});dn.command("list").alias("ls").description("list skills per agent").action(()=>{let e=Ae();console.log();for(let[t,o]of Object.entries(e.agents||{})){if(!Qn(o.tier,o.workspace)){console.log(` ${w.cyan(t)}: ${w.dim(`(${o.tier} does not use skills)`)}`);continue}let n=Zn(o.tier,o.workspace).map(s=>s.name);console.log(` ${w.cyan(t)}: ${n.length?n.join(", "):w.dim("(none)")}`)}console.log()});dn.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]:[re(n,"src",e,"SKILL.md"),re(n,"skills",e,"SKILL.md")],r=s.find(b=>Ue(b));if(!r){console.log(w.red(` No SKILL.md found for "${e}". Searched:`));for(let b of s)console.log(w.dim(` ${b}`));return}let i=_o(r,"utf-8"),a=o("sha256").update(i).digest("hex").slice(0,12),c=(i.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=C()}catch(b){console.log(w.red(` Can't load agentx.json: ${b.message}`));return}let g=Object.entries(l.agents||{}),d=t.agent?g.filter(([b])=>b===t.agent):g;if(d.length===0){console.log(w.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(w.bold(` Skill sync \u2014 ${e}`)),console.log(w.dim(` Source: ${r}`)),console.log(w.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(w.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let f=0,p=0,u=0,h=0;for(let[b,$]of d){let v=$.workspace;if(!v||!Ue(v)){console.log(` ${w.yellow("\u2717")} ${b.padEnd(22)} ${w.dim("(workspace missing: "+(v||"undefined")+")")}`),h++;continue}let x=Qn($.tier,v);if(!x){console.log(` ${w.dim("\xB7")} ${b.padEnd(22)} ${w.dim(`(skipped \u2014 ${$.tier} does not use skills)`)}`),h++;continue}let S=Zn($.tier,v).find(I=>I.name===e)?.dir??re(x,e),k=re(S,"SKILL.md");if(!Ue(k)){if(!t.allWorkspaces){console.log(` ${w.dim("\xB7")} ${b.padEnd(22)} ${w.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}t.dryRun||(ro(S,{recursive:!0}),is(k,i)),console.log(` ${w.green("+")} ${b.padEnd(22)} ${w.dim("\u2192 seeded v"+c)}`),f++;continue}let A=_o(k,"utf-8");if(o("sha256").update(A).digest("hex").slice(0,12)===a){console.log(` ${w.dim("=")} ${b.padEnd(22)} ${w.dim("up to date (v"+c+")")}`),u++;continue}let O=(A.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||is(k,i),console.log(` ${w.yellow("\u21BB")} ${b.padEnd(22)} ${w.dim(`v${O} \u2192 v${c}`)}`),p++}console.log();let y=t.dryRun?"would":"did";console.log(w.dim(` Summary: ${y} seed ${f}, ${y} update ${p}, ${u} already current, ${h} skipped.`)),t.dryRun&&(f>0||p>0)&&console.log(w.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});dn.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 p=Ae().agents?.[e.workspace];p||(console.log(w.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),r.push(re(p.workspace))}else if(e.allWorkspaces){let f=Ae();for(let p of Object.values(f.agents||{}))p?.workspace&&r.push(re(p.workspace))}else r.push(re(e.cwd));let i=re(e.referencesCwd||e.cwd),c=(await Promise.all(r.map(f=>t(f)))).flat(),[l,g]=await Promise.all([n(i),s(i)]),d=o({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(f=>({name:f.name,verdict:f.verdict,reasons:f.reasons,path:f.skill?.path})),null,2));else{let f={PASS:0,REVIEW:0,FAILING:0};for(let p of d)f[p.verdict]++;console.log();for(let p of d){let u=p.verdict==="PASS"?w.green("PASS "):p.verdict==="REVIEW"?w.yellow("REVIEW "):w.red("FAILING");console.log(` ${u} ${w.bold(p.name)}${p.skill?.path?w.dim(` (${p.skill.path})`):""}`);for(let h of p.reasons)console.log(` ${w.dim("\xB7")} ${h}`)}console.log(),console.log(` ${w.green(`${f.PASS} PASS`)} ${w.yellow(`${f.REVIEW} REVIEW`)} ${w.red(`${f.FAILING} FAILING`)}`),console.log()}process.exit(d.some(f=>f.verdict==="FAILING")?1:0)});dn.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=Ae(),n=Object.entries(o.agents||{}),[s,r]=t.agent?n.find(([g])=>g===t.agent)??[]:n[0]??[];r||(console.log(w.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:i}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-QUVE6RN2.js"),c=await i(r.workspace);if(c.length===0){console.log(w.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(` ${w.green("\u2192")} ${w.bold(l.skill.frontmatter.name)} ${w.dim(`\xB7 ${l.reason}`)}`),console.log(` ${w.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${w.yellow("\xB7")} no skill for this ${w.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(w.dim(`
|
|
56
56
|
shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(w.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(w.dim(`
|
|
57
57
|
(lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var ar=new io().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");ar.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(w.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let o=re(t.cwd),n=re(o,"references/example"),s=re(o,"references/recipes/example.yaml");Ue(n)||(console.log(w.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let r=re(o,".agentx/references",e),i=re(o,".agentx/references/recipes");ro(r,{recursive:!0}),ro(i,{recursive:!0});let a=Zv(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let f=No(r,d);if(Ue(f)&&!t.force){console.log(w.dim(` skip ${f} (exists; --force to overwrite)`)),l++;continue}let u=_o(No(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);is(f,u),console.log(w.green(` + ${f}`)),c++}let g=No(i,`${e}.yaml`);if(Ue(g)&&!t.force)console.log(w.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(Ue(s)){let d=_o(s,"utf-8").replaceAll("example.",`${e}.`);is(g,d),console.log(w.green(` + ${g}`)),c++}console.log(),console.log(w.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(w.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(w.dim(" 2. agentx skill audit # verify references resolve")),console.log(w.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});ar.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(w.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=re(t.cwd),i=t.from?String(t.from).split(",").map(h=>h.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(w.yellow(` No skills matched filter [${i.join(", ")}] under ${r}`)),console.log(w.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(w.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([h,y])=>[h,y.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=re(t.referencesCwd||t.cwd),f=re(d,".agentx/references",e);if(!t.write){console.log(),console.log(w.dim(` Dry-run \u2014 would write to ${f}/`));for(let[h,y]of Object.entries(g))console.log(w.cyan(`
|
|
58
58
|
--- ${h} ---`)),console.log(y.split(`
|
|
@@ -61,7 +61,7 @@ ${r.content}
|
|
|
61
61
|
`).length>30&&console.log(w.dim(` \u2026 (${y.split(`
|
|
62
62
|
`).length-30} more lines truncated in preview)`));console.log(),console.log(w.dim(` Re-run with --write to commit these to ${f}/`)),console.log();return}ro(f,{recursive:!0});let p=0,u=0;for(let[h,y]of Object.entries(g)){let b=No(f,h);if(Ue(b)&&!t.force){console.log(w.dim(` skip ${b} (exists; --force to overwrite)`)),u++;continue}is(b,y),console.log(w.green(` + ${b}`)),p++}console.log(),console.log(w.dim(` ${p} written, ${u} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(w.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});ar.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(re(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(w.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(` ${w.cyan(s.id)} ${w.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),r&&console.log(w.dim(` ${r}`))}console.log(),console.log(w.dim(` ${n.length} reference(s) loaded.`)),console.log()});var rl=new io().name("hook").description("manage hooks \u2014 add to agent workspace");rl.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=Ae().agents?.[e];if(!o){console.log(w.red(` Agent "${e}" not found`));return}let n=re(o.workspace,".claude/settings.json"),s=Ue(n)?JSON.parse(_o(n,"utf-8")):{},r=await st([{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),ro(re(o.workspace,".claude"),{recursive:!0}),is(n,JSON.stringify(s,null,2)),console.log(w.green(` Hook added to ${e}: ${r.event} -> ${r.type}`)),console.log()});var il=new io().name("migrate").description("import configuration from OpenClaw or other tools");il.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,re(process.env.HOME||"",".openclaw/openclaw.json"),re(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let p of o)if(p&&Ue(p)){n=p;break}if(!n){console.log(w.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(w.dim(` Reading: ${n}`));let s=JSON.parse(_o(n,"utf-8")),r=Ue(re(process.cwd(),"agentx.json"))?Ae():{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 p of a)p.match?.channel==="telegram"&&(c[p.match.accountId]=p.agentId);i.find(p=>p.id==="main"||p.default)&&(c.default="main");let l=0;for(let p of i){if(p.workspace?.startsWith("/data"))continue;let u=p.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),h=p.groupChat?.mentionPatterns||[];if(h.some(y=>y===u)||h.push(u),r.agents[u]={name:p.name,workspace:p.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:h,maxConcurrent:p.id==="main"?2:1,systemPrompt:`You are ${p.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!t.dryRun){ro(re(p.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-HAV4CQV7.js");y(u,r.agents[u])}}console.log(` ${w.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[p,u]of Object.entries(g)){if(!u.botToken)continue;let y=c[p]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.channels.telegram.accounts[p]={token:u.botToken,agentBinding:y},r.channels.telegram.enabled=!0,d++}console.log(` ${w.green(d)} Telegram accounts imported`);let f=re(n,"../cron/jobs.json");if(Ue(f)){let p=JSON.parse(_o(f,"utf-8")),u=0;for(let h of p.jobs||[]){let y=h.name||h.id,b=h.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.crons[y]={enabled:h.enabled||!1,schedule:h.schedule?.expr||"0 9 * * *",timezone:h.schedule?.tz||"UTC",agent:b,prompt:h.payload?.message||"",timeout:h.payload?.timeoutSeconds||600,onError:["log"]},u++}console.log(` ${w.green(u)} cron jobs imported`)}t.dryRun?(console.log(w.yellow(`
|
|
63
63
|
Dry run \u2014 nothing written`)),console.log(JSON.stringify(r,null,2))):(await mt(r),console.log(w.green(`
|
|
64
|
-
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Po=new io().name("config").description("validate and inspect configuration");Po.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=C(e.config);console.log(w.green(" \u2713 Config valid")),console.log(w.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(w.dim(` Bind: ${t.node.bind}`)),console.log(w.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(w.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(w.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(w.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(w.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Yr(t);if(n.length){console.log(),console.log(w.yellow(" Warnings:"));for(let s of n)console.log(w.yellow(` \u26A0 ${s}`))}else console.log(w.green(" \u2713 All workspaces valid"));console.log();for(let[s,r]of Object.entries(t.agents)){let i=r.workspace,a=Ue(re(i,".claude")),c=Ue(re(i,"CLAUDE.md")),l=Ue(re(i,".claude/settings.json")),g=Zn(r.tier,i).length,d=[a?w.green("\u2713"):w.red("\u2717"),".claude",c?w.green("\u2713"):w.yellow("\u25CB"),"CLAUDE.md",l?w.green("\u2713"):w.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${w.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(w.red(` \u2717 ${t.message}`))}console.log()});Po.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=C(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(w.red(t.message))}});function ox(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 sl(e){return e===void 0?w.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Po.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-
|
|
64
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Po=new io().name("config").description("validate and inspect configuration");Po.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=C(e.config);console.log(w.green(" \u2713 Config valid")),console.log(w.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(w.dim(` Bind: ${t.node.bind}`)),console.log(w.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(w.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(w.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(w.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(w.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Yr(t);if(n.length){console.log(),console.log(w.yellow(" Warnings:"));for(let s of n)console.log(w.yellow(` \u26A0 ${s}`))}else console.log(w.green(" \u2713 All workspaces valid"));console.log();for(let[s,r]of Object.entries(t.agents)){let i=r.workspace,a=Ue(re(i,".claude")),c=Ue(re(i,"CLAUDE.md")),l=Ue(re(i,".claude/settings.json")),g=Zn(r.tier,i).length,d=[a?w.green("\u2713"):w.red("\u2717"),".claude",c?w.green("\u2713"):w.yellow("\u25CB"),"CLAUDE.md",l?w.green("\u2713"):w.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${w.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(w.red(` \u2717 ${t.message}`))}console.log()});Po.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=C(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(w.red(t.message))}});function ox(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 sl(e){return e===void 0?w.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Po.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-NRHZ2XH3.js"),{expandEnvVars:i}=await import("./config-WCEFYQL4.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(w.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(o(a,"utf-8")),l=t.raw?c:i(c),g=r(l,e);t.json?console.log(JSON.stringify(g)):console.log(sl(g))});Po.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-NRHZ2XH3.js"),i=ox(t,!!o.string),a=await n(l=>{s(l,e,i)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(w.red(` \u2717 ${a.error}`)),process.exit(1));let c=r(a.after,e);o.dryRun?console.log(w.yellow(` (dry-run) ${w.cyan(e)} would become: ${sl(c)}`)):(console.log(w.green(` \u2713 ${w.cyan(e)} = ${sl(c)}`)),a.reloaded?console.log(w.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(w.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Po.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-NRHZ2XH3.js"),r=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(r.success||(console.log(w.red(` \u2717 ${r.error}`)),process.exit(1)),n(r.after,e)!==void 0){console.log(w.dim(` (no-op) ${w.cyan(e)} was not set`));return}t.dryRun?console.log(w.yellow(` (dry-run) ${w.cyan(e)} would be removed`)):(console.log(w.green(` \u2713 ${w.cyan(e)} removed`)),r.reloaded&&console.log(w.dim(" Daemon hot-reloaded.")))});Po.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=C(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(w.bold(" Governance flags")),console.log(),n&&(console.log(w.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?w.green:s==="shadow"?w.cyan:s==="off"?w.dim:w.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":w.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?w.green("active"):i?w.yellow("env=true but business.enabled=false \u2192 inactive"):w.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(w.dim(` business.enabled ${t?w.green("true"):w.dim("false")}`)),console.log(w.dim(` business.projects[] ${o}`)),console.log(),console.log(w.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(w.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});Us();import{Command as nx}from"commander";import Do from"chalk";import{resolve as Mo}from"path";import{existsSync as sx}from"fs";var wo=new nx().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function gn(e){let t=Mo(e,".agentx/db.sqlite");sx(t)||(console.log(Do.red(` No SQLite at ${t}`)),console.log(Do.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=Rt({path:t});return o||(console.log(Do.red(` Could not open ${t}`)),console.log(Do.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function un(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Do.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])))}wo.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=gn(Mo(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=`
|
|
65
65
|
SELECT agent_id, channel, status, duration_ms,
|
|
66
66
|
input_tokens, output_tokens,
|
|
67
67
|
substr(message_preview, 1, 60) AS message,
|
|
@@ -489,7 +489,7 @@ return aid ?? null`}function US(e,t){if(e.kind==="path"){let s=e.pts,r=s[Math.fl
|
|
|
489
489
|
Resume plan${n.plan?` (${n.plan.author==="agent"?"written by the agent":`written by AgentX: ${n.plan.note}`})`:""}:`)),console.log(n.plan?n.plan.text.split(`
|
|
490
490
|
`).map(s=>` ${s}`).join(`
|
|
491
491
|
`):" not written yet")});wr(vn.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 yr(t,"POST","/api/signals/resume",{id:e,reason:t.reason,node:t.peer});console.log(je.green(` resumed ${o.agentId} task ${o.id}`)),o.delivery&&console.log(je.dim(` its answer goes to ${o.delivery}`))});wr(vn.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 yr(t,"POST","/api/signals/drop",{id:e,node:t.peer});console.log(je.green(` dropped ${o.agentId} task ${o.id}`))});oe();import{Command as FA}from"commander";import pt from"chalk";var ua=new FA().name("review-gate").description("independent pre-merge review of agent PRs against their linked issue");function UA(e){let t=e.node||"",o=e.token||"";if(!t||!o)try{let s=C(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 Qy(e,t,o,n){let{baseUrl:s,headers:r}=UA(e),i;try{i=await fetch(`${s}${o}`,{method:t,headers:r,...n?{body:JSON.stringify(n)}:{}})}catch(a){console.log(pt.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(!i.ok){let a=await i.json().catch(()=>({}));console.log(pt.red(` HTTP ${i.status}${a.error?` \u2014 ${a.error}`:""}`)),process.exit(1)}return i}var Zy=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)"),ew=e=>e==="success"?pt.green(e):e==="failure"?pt.red(e):pt.yellow(e);Zy(ua.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 Qy(e,"GET",`/api/review-gate/reviews?${t}`)).json(),n=o.summary;console.log(pt.bold(` Last ${o.days} days: ${n.reviews} reviews on ${n.prs} PRs`)+pt.dim(` \u2014 ${n.byState.success} passed, ${n.byState.failure} failed, ${n.byState.error} errors`)),console.log(pt.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.pr} ${s.sha.slice(0,7)} ${ew(s.state)} ${pt.dim(s.reason)}${s.replay?pt.dim(" (replay)"):""}`)});Zy(ua.command("replay <repo> <prs...>").description("review past PRs at their head commit without posting anything; counts how many get flagged")).action(async(e,t,o)=>{let s=(await Qy(o,"POST","/api/review-gate/replay",{repo:e,prs:t.map(Number)})).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(`
|
|
492
|
-
`))>=0;){let g=i.slice(0,l).trim();if(i=i.slice(l+1),!g)continue;let d=JSON.parse(g);d.done?console.log(pt.bold(` flagged ${d.flagged} of ${d.of}`)):d.error?console.log(` #${d.pr} ${pt.yellow("error")} ${pt.dim(d.error)}`):console.log(` #${d.pr} ${ew(d.state)}${d.flagged?pt.red(" flagged"):""} ${pt.dim(d.reason)}`)}if(a)break}});import{Command as WA}from"commander";import dt from"chalk";import{existsSync as Wl,rmSync as BA}from"fs";import{resolve as Bl}from"path";var ys=new WA().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");ys.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(dt.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),r=await Dg(e,t,{verbose:n}),i=Date.now()-s;console.log(dt.green(` \u2713 indexed ${r.docs} doc(s) for ${dt.bold(e)} in ${i}ms`)),console.log(dt.dim(` \u2192 ${r.path}`))});ys.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=Bl(e.cwd,".agentx","rag");if(!Wl(t)){console.log(dt.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>Wl(Bl(t,s,"index.json")));if(n.length===0){console.log(dt.dim(" (no indexes)"));return}for(let s of n.sort()){let r=nc(s);console.log(` ${dt.bold(s)} ${r.docs} doc(s) ${dt.dim(r.path)}`)}});ys.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=Mg(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let r=nc(e);r.exists?console.log(dt.dim(` (no hits in ${r.docs} indexed docs)`)):console.log(dt.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let r of s)console.log(` ${dt.bold(r.title)} ${dt.dim(`(${r.score.toFixed(2)})`)}`),console.log(` ${dt.dim(r.path)}`),console.log(` ${dt.dim(r.snippet.slice(0,200))}`)});ys.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=Bl(process.cwd(),".agentx","rag",e);if(!Wl(t)){console.log(dt.dim(` no index for ${e} \u2014 nothing to clear`));return}BA(t,{recursive:!0,force:!0}),console.log(dt.green(` \u2713 cleared index for ${e}`))});oe();import{Command as JA}from"commander";import ue from"chalk";import ws from"prompts";var xn=new JA().name("backlog").description("manage the local backlog used by business workSource=backlog");function br(e){let t=C(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new Jm(n)}}function GA(e){return e?ue.cyan(`${e.type}:${e.project}#${e.iid}`):ue.dim("manual")}function HA(e){return{todo:ue.gray("todo"),doing:ue.yellow("doing"),blocked:ue.red("blocked"),done:ue.green("done")}[e]}xn.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}=br(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(ue.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?ue.magenta(`@${n.assignee}`):ue.dim("unassigned");console.log(` ${HA(n.status).padEnd(7)} ${GA(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(ue.dim(` ${n.source.url}`))}console.log(),console.log(ue.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});xn.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=br(o.config);n.store.findById(e)||(console.error(ue.red(` item ${e} not found`)),process.exit(1));let r=n.store.update(e,{assignee:t,status:"doing"});if(console.log(ue.green(` claimed: ${r.title} -> ${t}`)),r.source){let i=dm([t],r.source,n.config),a=await hc(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(ue.dim(" sync:"),...c));console.log(a.ok?ue.dim(` synced -> ${a.url??r.source.type}`):ue.yellow(` sync failed: ${a.error}`))}});xn.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=br(t.config);o.store.findById(e)||(console.error(ue.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(ue.green(` done: ${s.title}`)),s.source){let r=await hc(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...i)=>console.log(ue.dim(" sync:"),...i));console.log(r.ok?ue.dim(` synced -> ${r.url??s.source.type}`):ue.yellow(` sync failed: ${r.error}`))}});xn.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}=br(t.config);o.remove(e)||(console.error(ue.red(` item ${e} not found`)),process.exit(1)),console.log(ue.green(` removed ${e}`))});xn.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=br(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(ue.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await ws({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!o&&(console.error(ue.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(ue.red(" channels.github.token not configured")),process.exit(1));let r=e.project;if(!r){let y=s==="gitlab"?YA(t.config):KA(t.config);y.length?(r=(await ws({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map($=>({title:$,value:$})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,r==="__CUSTOM__"&&(r=(await ws({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):r=(await ws({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!r)return;let a=((await ws({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(ue.dim(` fetching open issues from ${s}:${r}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await VA(t.config,r,a):await XA(t.config,r,a);if(!c.length){console.log(ue.yellow(" no open issues matched"));return}console.log(ue.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=r,g=new Set(t.store.list().map(y=>y.id)),d=c.map(y=>{let b=Ac({type:s,project:l,iid:y.iid,url:y.url}),$=g.has(b),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${$?ue.dim(" (already imported)"):""}`,value:y,disabled:$}}),p=(await ws({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!p.length){console.log(ue.dim(" nothing selected"));return}let u=p.map(y=>{let b={type:s,host:s==="gitlab"?zA(t.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Ac(b),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:b,importedAt:new Date().toISOString()}}),h=t.store.addMany(u);console.log(ue.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let y of h)console.log(ue.dim(` ${y.id} \u2014 ${y.title}`))});function zA(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function YA(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 KA(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 VA(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 XA(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(tw)}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(tw):[]}function tw(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 QA}from"commander";import K from"chalk";import{existsSync as ZA,readFileSync as eE}from"fs";import{resolve as tE}from"path";import oE from"prompts";oe();function ow(e){let t=e||tE(process.cwd(),"agentx.json");return ZA(t)||(console.log(K.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(eE(t,"utf-8"))}async function nE(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(K.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:r,accountId:i}=await oE([{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(K.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var bo=new QA().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');bo.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("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${Gs})`,Gs).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){bo.help();return}t.agent||(console.log(K.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(K.red(' --do "<prompt>" is required')),process.exit(1));let o=ac(e);o||(console.log(K.red(` Couldn't parse: "${e}"`)),console.log(K.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(K.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(K.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=ow(t.config),s=Ws(n);n.agents?.[t.agent]||(console.log(K.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(K.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let r=await nE(t.notify,s),i=t.id||eu(o.matched,t.agent),a=ou({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:r,deliverResult:t.deliver,onError:tu(t.onError),enabled:!t.disabled}),c=a.onError,l=await ge(d=>He(d,`crons.${i}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(K.red(` \u2717 ${l.error}`)),process.exit(1));let g=t.dryRun?"would add":"Added";console.log(K.green(` \u2713 ${g} cron ${K.cyan(i)}`)),console.log(K.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(K.dim(` Agent: ${t.agent}`)),r&&console.log(K.dim(` Notify: ${r.channel} ${r.chatId}${a.deliverResult===!1?" (failures only)":" (results and failures)"}`)),c.length&&console.log(K.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(K.dim(" Daemon hot-reloaded."))});bo.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=ow(e.config).crons||{},n=Object.entries(o),s=new Set;try{let{loadDaemonConfig:r}=await import("./config-HHNGJKVW.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(K.dim(" No scheduled jobs"));return}console.log();for(let[r,i]of n){let a=i.approval?K.yellow("\u25D0"):i.enabled?K.green("\u25CF"):K.dim("\u25CB"),c=i.schedule;try{c=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${a} ${K.cyan(r.padEnd(32))} ${K.dim(i.schedule.padEnd(14))} ${K.dim("\u2192")} ${i.agent}`),console.log(K.dim(` ${c} (${i.timezone||"UTC"})`)),i.notify&&console.log(K.dim(` notify: ${i.notify.channel} ${i.notify.chatId}${i.deliverResult===!1?" (failures only)":" (results and failures)"}`)),i.createdBy&&console.log(K.dim(` created by agent: ${i.createdBy}`)),s.has(r)&&console.log(K.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",g=su(nu(i.schedule,l),l);console.log(K.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${g}`)),console.log(K.dim(` agentx schedule approve ${r} | agentx schedule reject ${r}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])bo.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await au(o,t);n.success||(console.log(K.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(K.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(K.dim(" Daemon hot-reloaded."))});bo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await ge(o=>{if(!Hn(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);Fg(o,`crons.${e}`)});t.success||(console.log(K.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(K.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(K.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",ru,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",iu,"reject an agent's pending create/delete request (drops the request)"]])bo.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(K.red(` \u2717 ${r.message}`)),process.exit(1)),console.log(K.green(` \u2713 ${r.message}`)),r.result?.reloaded&&console.log(K.dim(" Daemon hot-reloaded."))});bo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=ac(t);o||(console.log(K.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(K.green(` "${t}"`)),console.log(K.dim(` \u2192 ${o.cron}`)),console.log(K.dim(` \u2192 ${o.human}`))});import{Command as SE}from"commander";import me from"chalk";import{cpSync as AE,existsSync as vs,mkdirSync as ww,readFileSync as Yl,writeFileSync as EE}from"fs";import{dirname as zl,resolve as Sn}from"path";import{fileURLToPath as RE}from"url";oe();dk();import{z as ee}from"zod";import{existsSync as nw,lstatSync as Jl,mkdirSync as sE,readdirSync as rE,readFileSync as iE,writeFileSync as aE}from"fs";import{dirname as cE,join as sw,relative as rw,resolve as $r,sep as kr}from"path";var Go="agentx-team/1",iw=/^[a-z0-9][a-z0-9-]*$/,bs=ee.string().regex(iw,"use lowercase letters, numbers and hyphens"),lE=["claude-code","codex-cli","opencode","sdk","orchestrator"],aw=256*1024,dE=ee.record(ee.string(),ee.string().max(aw)).refine(e=>"SKILL.md"in e,{message:"a skill needs a SKILL.md"}).refine(e=>Object.keys(e).every(hE),{message:"skill file paths must stay inside the skill folder"}),gE=ee.object({name:ee.string().min(1),tier:ee.enum(lE).optional(),model:ee.string().optional(),systemPrompt:ee.string().default(""),mentions:ee.array(ee.string()).default([]),intents:ee.array(ee.string()).default([]),maxConcurrent:ee.number().int().min(1).optional(),maxExecutionMinutes:ee.number().int().min(1).max(240).optional(),skills:ee.record(bs,dE).default({})}).strict(),uE=ee.object({agent:bs,schedule:ee.string().refine(ug,{message:"not a 5-field cron expression"}),timezone:ee.string().optional(),prompt:ee.string().trim().min(1),timeout:ee.number().int().min(1).optional(),enabled:ee.boolean().default(!0),maxOutputTokens:ee.number().int().min(50).max(8e3).optional(),taskType:ee.string().trim().min(1).max(64).optional(),autonomy:eg.optional(),onError:ee.array(ee.enum(["log","notify","disable"])).optional(),deliver:ee.boolean().default(!0)}).strict(),mE=["telegram","whatsapp","gitlab","github"],pE=ee.object({kind:ee.enum(mE),agent:bs,why:ee.string().optional()}).strict(),fE=ee.object({format:ee.literal(Go),name:bs,title:ee.string().min(1),result:ee.string().min(1),description:ee.string().optional(),agents:ee.record(bs,gE).refine(e=>Object.keys(e).length>0,{message:"a team needs at least one agent"}),schedules:ee.record(bs,uE).default({}),channels:ee.array(pE).default([])}).strict().superRefine((e,t)=>{for(let[o,n]of Object.entries(e.schedules))e.agents[n.agent]||t.addIssue({code:ee.ZodIssueCode.custom,path:["schedules",o,"agent"],message:`"${n.agent}" is not an agent of this team`});e.channels.forEach((o,n)=>{e.agents[o.agent]||t.addIssue({code:ee.ZodIssueCode.custom,path:["channels",n,"agent"],message:`"${o.agent}" is not an agent of this team`})})});function hE(e){return!e||e.startsWith("/")||e.includes("\\")||/^[a-zA-Z]:/.test(e)?!1:e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function ks(e){let t=fE.safeParse(e);if(!t.success){let n=t.error.issues.map(s=>` ${s.path.join(".")||"<root>"}: ${s.message}`).join(`
|
|
492
|
+
`))>=0;){let g=i.slice(0,l).trim();if(i=i.slice(l+1),!g)continue;let d=JSON.parse(g);d.done?console.log(pt.bold(` flagged ${d.flagged} of ${d.of}`)):d.error?console.log(` #${d.pr} ${pt.yellow("error")} ${pt.dim(d.error)}`):console.log(` #${d.pr} ${ew(d.state)}${d.flagged?pt.red(" flagged"):""} ${pt.dim(d.reason)}`)}if(a)break}});import{Command as WA}from"commander";import dt from"chalk";import{existsSync as Wl,rmSync as BA}from"fs";import{resolve as Bl}from"path";var ys=new WA().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");ys.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(dt.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),r=await Dg(e,t,{verbose:n}),i=Date.now()-s;console.log(dt.green(` \u2713 indexed ${r.docs} doc(s) for ${dt.bold(e)} in ${i}ms`)),console.log(dt.dim(` \u2192 ${r.path}`))});ys.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=Bl(e.cwd,".agentx","rag");if(!Wl(t)){console.log(dt.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>Wl(Bl(t,s,"index.json")));if(n.length===0){console.log(dt.dim(" (no indexes)"));return}for(let s of n.sort()){let r=nc(s);console.log(` ${dt.bold(s)} ${r.docs} doc(s) ${dt.dim(r.path)}`)}});ys.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=Mg(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let r=nc(e);r.exists?console.log(dt.dim(` (no hits in ${r.docs} indexed docs)`)):console.log(dt.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let r of s)console.log(` ${dt.bold(r.title)} ${dt.dim(`(${r.score.toFixed(2)})`)}`),console.log(` ${dt.dim(r.path)}`),console.log(` ${dt.dim(r.snippet.slice(0,200))}`)});ys.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=Bl(process.cwd(),".agentx","rag",e);if(!Wl(t)){console.log(dt.dim(` no index for ${e} \u2014 nothing to clear`));return}BA(t,{recursive:!0,force:!0}),console.log(dt.green(` \u2713 cleared index for ${e}`))});oe();import{Command as JA}from"commander";import ue from"chalk";import ws from"prompts";var xn=new JA().name("backlog").description("manage the local backlog used by business workSource=backlog");function br(e){let t=C(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new Jm(n)}}function GA(e){return e?ue.cyan(`${e.type}:${e.project}#${e.iid}`):ue.dim("manual")}function HA(e){return{todo:ue.gray("todo"),doing:ue.yellow("doing"),blocked:ue.red("blocked"),done:ue.green("done")}[e]}xn.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}=br(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(ue.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?ue.magenta(`@${n.assignee}`):ue.dim("unassigned");console.log(` ${HA(n.status).padEnd(7)} ${GA(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(ue.dim(` ${n.source.url}`))}console.log(),console.log(ue.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});xn.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=br(o.config);n.store.findById(e)||(console.error(ue.red(` item ${e} not found`)),process.exit(1));let r=n.store.update(e,{assignee:t,status:"doing"});if(console.log(ue.green(` claimed: ${r.title} -> ${t}`)),r.source){let i=dm([t],r.source,n.config),a=await hc(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(ue.dim(" sync:"),...c));console.log(a.ok?ue.dim(` synced -> ${a.url??r.source.type}`):ue.yellow(` sync failed: ${a.error}`))}});xn.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=br(t.config);o.store.findById(e)||(console.error(ue.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(ue.green(` done: ${s.title}`)),s.source){let r=await hc(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...i)=>console.log(ue.dim(" sync:"),...i));console.log(r.ok?ue.dim(` synced -> ${r.url??s.source.type}`):ue.yellow(` sync failed: ${r.error}`))}});xn.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}=br(t.config);o.remove(e)||(console.error(ue.red(` item ${e} not found`)),process.exit(1)),console.log(ue.green(` removed ${e}`))});xn.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=br(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(ue.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await ws({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!o&&(console.error(ue.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(ue.red(" channels.github.token not configured")),process.exit(1));let r=e.project;if(!r){let y=s==="gitlab"?YA(t.config):KA(t.config);y.length?(r=(await ws({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map($=>({title:$,value:$})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,r==="__CUSTOM__"&&(r=(await ws({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):r=(await ws({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!r)return;let a=((await ws({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(ue.dim(` fetching open issues from ${s}:${r}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await VA(t.config,r,a):await XA(t.config,r,a);if(!c.length){console.log(ue.yellow(" no open issues matched"));return}console.log(ue.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=r,g=new Set(t.store.list().map(y=>y.id)),d=c.map(y=>{let b=Ac({type:s,project:l,iid:y.iid,url:y.url}),$=g.has(b),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${$?ue.dim(" (already imported)"):""}`,value:y,disabled:$}}),p=(await ws({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!p.length){console.log(ue.dim(" nothing selected"));return}let u=p.map(y=>{let b={type:s,host:s==="gitlab"?zA(t.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Ac(b),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:b,importedAt:new Date().toISOString()}}),h=t.store.addMany(u);console.log(ue.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let y of h)console.log(ue.dim(` ${y.id} \u2014 ${y.title}`))});function zA(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function YA(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 KA(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 VA(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 XA(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(tw)}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(tw):[]}function tw(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 QA}from"commander";import K from"chalk";import{existsSync as ZA,readFileSync as eE}from"fs";import{resolve as tE}from"path";import oE from"prompts";oe();function ow(e){let t=e||tE(process.cwd(),"agentx.json");return ZA(t)||(console.log(K.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(eE(t,"utf-8"))}async function nE(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(K.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:r,accountId:i}=await oE([{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(K.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var bo=new QA().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');bo.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("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${Gs})`,Gs).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){bo.help();return}t.agent||(console.log(K.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(K.red(' --do "<prompt>" is required')),process.exit(1));let o=ac(e);o||(console.log(K.red(` Couldn't parse: "${e}"`)),console.log(K.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(K.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(K.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=ow(t.config),s=Ws(n);n.agents?.[t.agent]||(console.log(K.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(K.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let r=await nE(t.notify,s),i=t.id||eu(o.matched,t.agent),a=ou({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:r,deliverResult:t.deliver,onError:tu(t.onError),enabled:!t.disabled}),c=a.onError,l=await ge(d=>He(d,`crons.${i}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(K.red(` \u2717 ${l.error}`)),process.exit(1));let g=t.dryRun?"would add":"Added";console.log(K.green(` \u2713 ${g} cron ${K.cyan(i)}`)),console.log(K.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(K.dim(` Agent: ${t.agent}`)),r&&console.log(K.dim(` Notify: ${r.channel} ${r.chatId}${a.deliverResult===!1?" (failures only)":" (results and failures)"}`)),c.length&&console.log(K.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(K.dim(" Daemon hot-reloaded."))});bo.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=ow(e.config).crons||{},n=Object.entries(o),s=new Set;try{let{loadDaemonConfig:r}=await import("./config-WCEFYQL4.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(K.dim(" No scheduled jobs"));return}console.log();for(let[r,i]of n){let a=i.approval?K.yellow("\u25D0"):i.enabled?K.green("\u25CF"):K.dim("\u25CB"),c=i.schedule;try{c=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${a} ${K.cyan(r.padEnd(32))} ${K.dim(i.schedule.padEnd(14))} ${K.dim("\u2192")} ${i.agent}`),console.log(K.dim(` ${c} (${i.timezone||"UTC"})`)),i.notify&&console.log(K.dim(` notify: ${i.notify.channel} ${i.notify.chatId}${i.deliverResult===!1?" (failures only)":" (results and failures)"}`)),i.createdBy&&console.log(K.dim(` created by agent: ${i.createdBy}`)),s.has(r)&&console.log(K.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",g=su(nu(i.schedule,l),l);console.log(K.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${g}`)),console.log(K.dim(` agentx schedule approve ${r} | agentx schedule reject ${r}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])bo.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await au(o,t);n.success||(console.log(K.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(K.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(K.dim(" Daemon hot-reloaded."))});bo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await ge(o=>{if(!Hn(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);Fg(o,`crons.${e}`)});t.success||(console.log(K.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(K.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(K.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",ru,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",iu,"reject an agent's pending create/delete request (drops the request)"]])bo.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(K.red(` \u2717 ${r.message}`)),process.exit(1)),console.log(K.green(` \u2713 ${r.message}`)),r.result?.reloaded&&console.log(K.dim(" Daemon hot-reloaded."))});bo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=ac(t);o||(console.log(K.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(K.green(` "${t}"`)),console.log(K.dim(` \u2192 ${o.cron}`)),console.log(K.dim(` \u2192 ${o.human}`))});import{Command as SE}from"commander";import me from"chalk";import{cpSync as AE,existsSync as vs,mkdirSync as ww,readFileSync as Yl,writeFileSync as EE}from"fs";import{dirname as zl,resolve as Sn}from"path";import{fileURLToPath as RE}from"url";oe();dk();import{z as ee}from"zod";import{existsSync as nw,lstatSync as Jl,mkdirSync as sE,readdirSync as rE,readFileSync as iE,writeFileSync as aE}from"fs";import{dirname as cE,join as sw,relative as rw,resolve as $r,sep as kr}from"path";var Go="agentx-team/1",iw=/^[a-z0-9][a-z0-9-]*$/,bs=ee.string().regex(iw,"use lowercase letters, numbers and hyphens"),lE=["claude-code","codex-cli","opencode","sdk","orchestrator"],aw=256*1024,dE=ee.record(ee.string(),ee.string().max(aw)).refine(e=>"SKILL.md"in e,{message:"a skill needs a SKILL.md"}).refine(e=>Object.keys(e).every(hE),{message:"skill file paths must stay inside the skill folder"}),gE=ee.object({name:ee.string().min(1),tier:ee.enum(lE).optional(),model:ee.string().optional(),systemPrompt:ee.string().default(""),mentions:ee.array(ee.string()).default([]),intents:ee.array(ee.string()).default([]),maxConcurrent:ee.number().int().min(1).optional(),maxExecutionMinutes:ee.number().int().min(1).max(240).optional(),skills:ee.record(bs,dE).default({})}).strict(),uE=ee.object({agent:bs,schedule:ee.string().refine(ug,{message:"not a 5-field cron expression"}),timezone:ee.string().optional(),prompt:ee.string().trim().min(1),timeout:ee.number().int().min(1).optional(),enabled:ee.boolean().default(!0),maxOutputTokens:ee.number().int().min(50).max(8e3).optional(),taskType:ee.string().trim().min(1).max(64).optional(),autonomy:eg.optional(),onError:ee.array(ee.enum(["log","notify","disable"])).optional(),deliver:ee.boolean().default(!0)}).strict(),mE=["telegram","whatsapp","gitlab","github"],pE=ee.object({kind:ee.enum(mE),agent:bs,why:ee.string().optional()}).strict(),fE=ee.object({format:ee.literal(Go),name:bs,title:ee.string().min(1),result:ee.string().min(1),description:ee.string().optional(),agents:ee.record(bs,gE).refine(e=>Object.keys(e).length>0,{message:"a team needs at least one agent"}),schedules:ee.record(bs,uE).default({}),channels:ee.array(pE).default([])}).strict().superRefine((e,t)=>{for(let[o,n]of Object.entries(e.schedules))e.agents[n.agent]||t.addIssue({code:ee.ZodIssueCode.custom,path:["schedules",o,"agent"],message:`"${n.agent}" is not an agent of this team`});e.channels.forEach((o,n)=>{e.agents[o.agent]||t.addIssue({code:ee.ZodIssueCode.custom,path:["channels",n,"agent"],message:`"${o.agent}" is not an agent of this team`})})});function hE(e){return!e||e.startsWith("/")||e.includes("\\")||/^[a-zA-Z]:/.test(e)?!1:e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function ks(e){let t=fE.safeParse(e);if(!t.success){let n=t.error.issues.map(s=>` ${s.path.join(".")||"<root>"}: ${s.message}`).join(`
|
|
493
493
|
`);throw new Error(`Not a valid team package:
|
|
494
494
|
${n}`)}let o=ma(t.data);if(o.length)throw new Error(`The team package contains what looks like a secret:
|
|
495
495
|
${o.map(n=>` ${n}`).join(`
|
|
@@ -525,7 +525,7 @@ Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choos
|
|
|
525
525
|
Plan ${_.dim(`[${r.state}] by ${r.createdBy}, ${Rn(r.createdAt)}`)}`),qw(s.steps(e)),console.log(`
|
|
526
526
|
Log`);for(let i of s.events(e))console.log(_.dim(` ${Rn(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});Ho.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(_.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=xr();if(!s)return;let r=ya();if(!r){process.exitCode=1;return}let i=Number(t),a=sm(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(_.red(` ${a}`)),process.exitCode=1;return}console.log(_.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+_.dim(" (the daemon goes on within a minute)")),qw(r.steps(e))});function Fw(e,t,o,n){let s=Ho.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=xr();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(_.red(` ${n}`)),process.exitCode=1;return}let l=a.get(r);if(!l||l.state==="candidate"){console.error(_.red(` no request "${r}"`)),process.exitCode=1;return}if(!a.close(r,e==="done"?"done":"dropped",c,Date.now())){console.error(_.red(` ${r} is already closed (${ed[l.state]??l.state})`)),process.exitCode=1;return}console.log(_.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}Fw("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>");Fw("drop","drop a request you no longer want","--reason <text>","");Ho.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("--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 (${Jr.join(", ")}); "none" to turn them all off`).option("--check-every <minutes>","how often each open loop's check runs").action(async e=>{let t={};try{let l=(u,h)=>{if(h===void 0)return;let y=Number(h);if(!(y>0))throw new Error(`${u} must be a positive number`);return y},g=(u,h)=>u===void 0?void 0:u===h?[]:u.split(",").map(y=>y.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=g(e.from,"none"),t.channels=g(e.channels,"all"),t.staleAfterHours=l("--stale-hours",e.staleHours),t.retentionDays=l("--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 u=l("--catch-cap",e.catchCap);if(u!==void 0&&!Number.isInteger(u))throw new Error("--catch-cap must be a whole number");t.catchPromises={...e.catch!==void 0?{enabled:e.catch==="on"}:{},...u!==void 0?{dailyCap:u}:{}}}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"}let d={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");d.enabled=e.plans==="on"}if(d.stallMinutes=l("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let u=Number(e.maxNudges);if(!Number.isInteger(u)||u<0)throw new Error("--max-nudges must be a whole number, 0 or more");d.maxNudges=u}if(d.approveKinds=g(e.approveKinds,"none"),d.disabledAgents=g(e.plansOffFor,"none"),d.requireForWork=g(e.planFor,"none"),e.planOver!==void 0){let u=Number(e.planOver);if(!(u>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");d.requireOverMinutes=u}Object.values(d).some(u=>u!==void 0)&&(t.plans=d);let f={},p=g(e.checks,"none");if(p){let u=p.filter(h=>!Jr.includes(h));if(u.length)throw new Error(`unknown check ${u.join(", ")}: use ${Jr.join(", ")}`);f.enabled=p}f.checkEveryMinutes=l("--check-every",e.checkEvery),Object.values(f).some(u=>u!==void 0)&&(t.checkers=f)}catch(l){console.error(_.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(t).some(l=>l!==void 0)){let l=await Ju(t);if(!l.success){console.error(_.red(` ${l.error}`)),process.exitCode=1;return}console.log(_.green(" \u2713 saved")+(l.reloaded?_.dim(" (daemon reloaded)"):""))}let o=gi();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"}`);let s=o.plans??pi;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??pi.requireOverMinutes,i=s.requireForWork??pi.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.checkers??Gr;console.log(` Loop checks ${a.enabled.length?a.enabled.join(", "):"off"}, every ${a.checkEveryMinutes} minute(s)`);let c=Object.keys(a.repos);console.log(` Repos for git-ancestor ${c.length?c.join(", "):"none (requests.checkers.repos in agentx.json)"}`)});import{Command as VE}from"commander";import Ss from"chalk";oe();var Uw=new VE("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Ic.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(Ss.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await ge(r=>{n=kp(r,e,t==="on")});s.success||(console.error(Ss.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(Ss.green(`\u2713 ${n}`)),s.reloaded&&console.log(Ss.dim(" daemon hot-reloaded"))}let o=C().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Ic)console.log(` ${n.padEnd(8)} ${o.includes(n)?Ss.green("on"):Ss.dim("off")}`)});import{Command as bR}from"commander";import As from"chalk";import he from"chalk";import Ar from"prompts";import{readFileSync as XE,writeFileSync as QE,existsSync as ZE}from"fs";import{resolve as Ww}from"path";var eR=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function tR(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function od(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Bw(e=".env"){let t=Ww(e);if(!ZE(t))return[];let o=XE(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(eR);r?n.push({kind:"kv",key:r[1],value:tR(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function oR(e){return e.map(t=>t.kind==="kv"?`${t.key}=${od(t.value)}`:t.raw).join(`
|
|
527
527
|
`)+`
|
|
528
|
-
`}function Sr(e,t,o=".env"){let n=Ww(o),s=Bw(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${od(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${od(t)}`})),QE(n,oR(s))}function nd(e,t=".env"){return Bw(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Jw="https://t.me/BotFather";async function nR(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 sR(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 Gw(e={}){console.log(),console.log(he.bold(" Connect Telegram")),console.log(),console.log(he.dim(` 1. Open ${Jw}`)),console.log(he.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(he.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Ar({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&yo(Jw);let{token:o}=await Ar({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(he.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await nR(o.trim());n||(console.log(he.red("\u2717 invalid or revoked")),process.exit(1)),console.log(he.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(he.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(he.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Ar({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),g||(console.log(he.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await Ar({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(he.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Sr(p,o.trim()),process.env[p]=o.trim();let u=await ge(x=>{He(x,"channels.telegram.enabled",!0),He(x,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let S=Hn(x,`agents.${g}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),He(x,`agents.${g}.mentions`,S))},{configPath:e.configPath});if(u.success||(console.log(he.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(he.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(he.dim(` Token stored in .env as ${p}`)),console.log(he.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(he.dim(" Daemon hot-reloaded.")):console.log(he.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Ar({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(he.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(he.dim(" Waiting up to 90s..."));let y=await sR(o.trim(),9e4);if(!y){console.log(he.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(he.dim(" agentx config set notifications.destination.channel telegram")),console.log(he.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(he.dim(` agentx config set notifications.destination.accountId ${f}`));return}let b={channel:"telegram",chatId:String(y.chatId),accountId:f},$=[],v=await ge(x=>{He(x,"notifications.destination",b),$=pa(x,b)},{configPath:e.configPath});if(!v.success){console.log(he.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(he.green(" \u2713 Default --notify target set")),console.log(he.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(he.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(he.dim(` Schedules that now report here: ${$.join(", ")}`)),v.reloaded&&console.log(he.dim(" Daemon hot-reloaded."))}import Oe from"chalk";import sd from"prompts";import{existsSync as id,mkdirSync as rR,readdirSync as iR,readFileSync as Hw}from"fs";import{resolve as rd}from"path";var aR=".agentx/whatsapp-sessions";function cR(){let e=rd(process.cwd(),".agentx/daemon.pid");if(!id(e))return!1;try{let t=parseInt(Hw(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function lR(e){if(!id(e))return!1;try{return iR(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function dR(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Oe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Oe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;rR(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(g=>{let f=setTimeout(()=>{t(Oe.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(Oe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:u}=await import("qrcode-terminal");u.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Oe.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Oe.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function zw(e={}){if(console.log(),console.log(Oe.bold(" Connect WhatsApp")),console.log(),cR()){console.log(Oe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Oe.dim(" agentx daemon stop")),console.log();let{cont:l}=await sd({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Oe.red(" Aborted")),process.exit(1))}let t=e.configPath||rd(process.cwd(),"agentx.json");id(t)||(console.log(Oe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Hw(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||aR,s=rd(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Oe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await sd({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(Oe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(lR(s)&&a){let{keep:l}=await sd({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(Oe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await dR(s,g=>console.log(g))||(console.log(Oe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ge(l=>{He(l,"channels.whatsapp.enabled",!0),He(l,"channels.whatsapp.sessionDir",n),He(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Oe.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Oe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Oe.dim(` Session: ${n}`)),console.log(Oe.dim(" Start the daemon to begin receiving:")),console.log(Oe.dim(" agentx daemon start")),console.log(Oe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Oe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Oe.dim(" Add routes later with:")),console.log(Oe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import{randomBytes as gR}from"crypto";import Je from"chalk";import Yw from"prompts";var wa="agentx-mesh:",ba="//join/";function uR(e){return Buffer.from(e,"utf-8").toString("base64url")}function mR(e){return Buffer.from(e,"base64url").toString("utf-8")}function pR(e){return`${wa}${ba}${uR(JSON.stringify(e))}`}function fR(e){if(!e.startsWith(`${wa}${ba}`))throw new Error(`Not a mesh invite link \u2014 expected ${wa}${ba}\u2026`);let t=e.slice(wa.length+ba.length),o=JSON.parse(mR(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 hR(){return gR(32).toString("hex")}function yR(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function wR(e){return e?.node?.name||e?.node?.id||"node"}async function Kw(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(Je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=nd("MESH_TOKEN");i||(i=hR(),Sr("MESH_TOKEN",i),console.log(Je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||yR(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Yw({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:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(Je.red(" Aborted")),process.exit(1)),a=d}let l=await ge(d=>{He(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Je.red(` \u2717 ${l.error}`)),process.exit(1));let g=pR({url:a,token:i,name:wR(r),version:1});console.log(),console.log(Je.bold(" Mesh invite")),console.log(),console.log(` ${Je.cyan(g)}`),console.log(),console.log(Je.dim(" Run on the other node:")),console.log(Je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Vw(e,t={}){let o;try{o=fR(e)}catch(r){console.log(Je.red(` \u2717 ${r.message}`)),process.exit(1)}let n=nd("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Yw({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Je.red(" Aborted (keeping existing .env)")),process.exit(1))}Sr("MESH_TOKEN",o.token);let s=await ge(r=>{He(r,"mesh.enabled",!0);let i=Hn(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),He(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Je.green(" \u2713 Joined mesh")),console.log(Je.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Je.dim(" Daemon hot-reloaded.")):console.log(Je.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(Je.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Je.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Je.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 bR().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 Gw({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 zw({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Xw=Es.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Xw.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 Kw({url:e.url,configPath:e.config})});Xw.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 Vw(e,{configPath:t.config})});Es.action(()=>{console.log(),console.log(As.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${As.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${As.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${As.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${As.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(As.dim(" GitLab connect is the next slice.")),console.log()});oe();import{Command as $R}from"commander";import ne from"chalk";var Cn=new $R().name("usage").description("token usage analysis and reporting");Cn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=C(),[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(ne.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ne.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${ne.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: ${ne.red(String(s.totalErrors))}`),console.log(),console.log(ne.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),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ne.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ne.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ne.red(" Daemon not running. Start with: agentx daemon start")):console.log(ne.red(` ${e.message}`))}});Cn.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=C(),[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(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:ne.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(ne.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(ne.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 f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",u=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?u<60?`resets in ${u} min`:u<48*60?`resets in ${Math.round(u/60)} h`:`resets in ${Math.round(u/1440)} days`:"",y=l.has(d.window)?ne.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,y].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(ne.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(ne.red(" Daemon not running. Start with: agentx daemon start")):console.log(ne.red(` ${t.message}`))}});Cn.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(ne.red(` Script not found: ${s}`)),console.log(ne.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ne.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ne.red(" Analysis failed. Is Python 3 installed?"))}});Cn.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-B2UFOH46.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=u=>/^\d{4}-\d{2}-\d{2}$/.test(u)&&!Number.isNaN(Date.parse(u));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(ne.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(u){console.log(ne.red(` Cannot read baseline ${e.baseline}: ${u.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=u=>u===null?"-":`$${u.toFixed(u<10?3:2)}`,g=u=>`${(u/1e6).toFixed(1)}M`;console.log(),console.log(ne.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(ne.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(ne.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(u=>[u,a.channels[u],c?.channels[u]]).sort((u,h)=>(h[1]?.cost||0)-(u[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[u,h,y]of p){let b=r(h),$=` ${u.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${g(h?.cacheRead||0).padStart(11)} ${g(h?.cacheCreate||0).padStart(11)} ${g(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l(b).padStart(9)}`;if(c){let v=r(y),x=b!==null&&v?`${((b-v)/v*100).toFixed(0)}%`:"-";$+=` ${l(v).padStart(9)} ${x.padStart(7)}`}console.log($)}console.log(),c&&console.log(ne.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(ne.dim(` Saved ${e.save}`)),console.log()});Cn.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-W33HGXMP.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-YJGGF5BS.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let u=f?`${f} ${p.name()}`:p.name();c.push(u),l(p,u)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(ne.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ne.dim("\xB7")} ${d}`);console.log(),console.log(ne.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ne.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(ne.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ne.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ne.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(ne.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=ne.dim(`${r.days}d`);console.log(` ${ne.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(ne.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as kR}from"commander";import qe from"chalk";import{readFileSync as vR}from"fs";import{resolve as xR}from"path";oe();var zo=new kR().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");zo.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{vg(xR(process.cwd(),".env"))}catch{}let t=SR(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-ICXWFJF7.js");o(t)}catch(t){console.log(qe.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(qe.dim(t.stack)),process.exit(1)}});function SR(e,t){try{let o=C();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(qe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(qe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
528
|
+
`}function Sr(e,t,o=".env"){let n=Ww(o),s=Bw(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${od(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${od(t)}`})),QE(n,oR(s))}function nd(e,t=".env"){return Bw(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Jw="https://t.me/BotFather";async function nR(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 sR(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 Gw(e={}){console.log(),console.log(he.bold(" Connect Telegram")),console.log(),console.log(he.dim(` 1. Open ${Jw}`)),console.log(he.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(he.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Ar({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&yo(Jw);let{token:o}=await Ar({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(he.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await nR(o.trim());n||(console.log(he.red("\u2717 invalid or revoked")),process.exit(1)),console.log(he.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(he.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(he.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Ar({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),g||(console.log(he.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await Ar({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(he.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Sr(p,o.trim()),process.env[p]=o.trim();let u=await ge(x=>{He(x,"channels.telegram.enabled",!0),He(x,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let S=Hn(x,`agents.${g}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),He(x,`agents.${g}.mentions`,S))},{configPath:e.configPath});if(u.success||(console.log(he.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(he.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(he.dim(` Token stored in .env as ${p}`)),console.log(he.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(he.dim(" Daemon hot-reloaded.")):console.log(he.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Ar({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(he.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(he.dim(" Waiting up to 90s..."));let y=await sR(o.trim(),9e4);if(!y){console.log(he.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(he.dim(" agentx config set notifications.destination.channel telegram")),console.log(he.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(he.dim(` agentx config set notifications.destination.accountId ${f}`));return}let b={channel:"telegram",chatId:String(y.chatId),accountId:f},$=[],v=await ge(x=>{He(x,"notifications.destination",b),$=pa(x,b)},{configPath:e.configPath});if(!v.success){console.log(he.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(he.green(" \u2713 Default --notify target set")),console.log(he.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(he.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(he.dim(` Schedules that now report here: ${$.join(", ")}`)),v.reloaded&&console.log(he.dim(" Daemon hot-reloaded."))}import Oe from"chalk";import sd from"prompts";import{existsSync as id,mkdirSync as rR,readdirSync as iR,readFileSync as Hw}from"fs";import{resolve as rd}from"path";var aR=".agentx/whatsapp-sessions";function cR(){let e=rd(process.cwd(),".agentx/daemon.pid");if(!id(e))return!1;try{let t=parseInt(Hw(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function lR(e){if(!id(e))return!1;try{return iR(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function dR(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Oe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Oe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;rR(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(g=>{let f=setTimeout(()=>{t(Oe.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(Oe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:u}=await import("qrcode-terminal");u.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Oe.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Oe.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function zw(e={}){if(console.log(),console.log(Oe.bold(" Connect WhatsApp")),console.log(),cR()){console.log(Oe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Oe.dim(" agentx daemon stop")),console.log();let{cont:l}=await sd({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Oe.red(" Aborted")),process.exit(1))}let t=e.configPath||rd(process.cwd(),"agentx.json");id(t)||(console.log(Oe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Hw(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||aR,s=rd(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Oe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await sd({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(Oe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(lR(s)&&a){let{keep:l}=await sd({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(Oe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await dR(s,g=>console.log(g))||(console.log(Oe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ge(l=>{He(l,"channels.whatsapp.enabled",!0),He(l,"channels.whatsapp.sessionDir",n),He(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Oe.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Oe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Oe.dim(` Session: ${n}`)),console.log(Oe.dim(" Start the daemon to begin receiving:")),console.log(Oe.dim(" agentx daemon start")),console.log(Oe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Oe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Oe.dim(" Add routes later with:")),console.log(Oe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import{randomBytes as gR}from"crypto";import Je from"chalk";import Yw from"prompts";var wa="agentx-mesh:",ba="//join/";function uR(e){return Buffer.from(e,"utf-8").toString("base64url")}function mR(e){return Buffer.from(e,"base64url").toString("utf-8")}function pR(e){return`${wa}${ba}${uR(JSON.stringify(e))}`}function fR(e){if(!e.startsWith(`${wa}${ba}`))throw new Error(`Not a mesh invite link \u2014 expected ${wa}${ba}\u2026`);let t=e.slice(wa.length+ba.length),o=JSON.parse(mR(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 hR(){return gR(32).toString("hex")}function yR(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function wR(e){return e?.node?.name||e?.node?.id||"node"}async function Kw(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(Je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=nd("MESH_TOKEN");i||(i=hR(),Sr("MESH_TOKEN",i),console.log(Je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||yR(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Yw({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:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(Je.red(" Aborted")),process.exit(1)),a=d}let l=await ge(d=>{He(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Je.red(` \u2717 ${l.error}`)),process.exit(1));let g=pR({url:a,token:i,name:wR(r),version:1});console.log(),console.log(Je.bold(" Mesh invite")),console.log(),console.log(` ${Je.cyan(g)}`),console.log(),console.log(Je.dim(" Run on the other node:")),console.log(Je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Vw(e,t={}){let o;try{o=fR(e)}catch(r){console.log(Je.red(` \u2717 ${r.message}`)),process.exit(1)}let n=nd("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Yw({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Je.red(" Aborted (keeping existing .env)")),process.exit(1))}Sr("MESH_TOKEN",o.token);let s=await ge(r=>{He(r,"mesh.enabled",!0);let i=Hn(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),He(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Je.green(" \u2713 Joined mesh")),console.log(Je.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Je.dim(" Daemon hot-reloaded.")):console.log(Je.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(Je.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Je.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Je.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 bR().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 Gw({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 zw({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Xw=Es.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Xw.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 Kw({url:e.url,configPath:e.config})});Xw.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 Vw(e,{configPath:t.config})});Es.action(()=>{console.log(),console.log(As.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${As.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${As.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${As.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${As.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(As.dim(" GitLab connect is the next slice.")),console.log()});oe();import{Command as $R}from"commander";import ne from"chalk";var Cn=new $R().name("usage").description("token usage analysis and reporting");Cn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=C(),[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(ne.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ne.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${ne.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: ${ne.red(String(s.totalErrors))}`),console.log(),console.log(ne.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),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ne.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ne.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ne.red(" Daemon not running. Start with: agentx daemon start")):console.log(ne.red(` ${e.message}`))}});Cn.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=C(),[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(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:ne.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(ne.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(ne.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 f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",u=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?u<60?`resets in ${u} min`:u<48*60?`resets in ${Math.round(u/60)} h`:`resets in ${Math.round(u/1440)} days`:"",y=l.has(d.window)?ne.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,y].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(ne.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(ne.red(" Daemon not running. Start with: agentx daemon start")):console.log(ne.red(` ${t.message}`))}});Cn.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(ne.red(` Script not found: ${s}`)),console.log(ne.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ne.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ne.red(" Analysis failed. Is Python 3 installed?"))}});Cn.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=u=>/^\d{4}-\d{2}-\d{2}$/.test(u)&&!Number.isNaN(Date.parse(u));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(ne.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(u){console.log(ne.red(` Cannot read baseline ${e.baseline}: ${u.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=u=>u===null?"-":`$${u.toFixed(u<10?3:2)}`,g=u=>`${(u/1e6).toFixed(1)}M`;console.log(),console.log(ne.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(ne.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(ne.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(u=>[u,a.channels[u],c?.channels[u]]).sort((u,h)=>(h[1]?.cost||0)-(u[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[u,h,y]of p){let b=r(h),$=` ${u.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${g(h?.cacheRead||0).padStart(11)} ${g(h?.cacheCreate||0).padStart(11)} ${g(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l(b).padStart(9)}`;if(c){let v=r(y),x=b!==null&&v?`${((b-v)/v*100).toFixed(0)}%`:"-";$+=` ${l(v).padStart(9)} ${x.padStart(7)}`}console.log($)}console.log(),c&&console.log(ne.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(ne.dim(` Saved ${e.save}`)),console.log()});Cn.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-6YMRDLHO.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let u=f?`${f} ${p.name()}`:p.name();c.push(u),l(p,u)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(ne.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ne.dim("\xB7")} ${d}`);console.log(),console.log(ne.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ne.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(ne.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ne.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ne.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(ne.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=ne.dim(`${r.days}d`);console.log(` ${ne.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(ne.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as kR}from"commander";import qe from"chalk";import{readFileSync as vR}from"fs";import{resolve as xR}from"path";oe();var zo=new kR().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");zo.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{vg(xR(process.cwd(),".env"))}catch{}let t=SR(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-4C77NLY5.js");o(t)}catch(t){console.log(qe.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(qe.dim(t.stack)),process.exit(1)}});function SR(e,t){try{let o=C();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(qe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(qe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
529
529
|
`)),{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}}}}zo.command("list").description("list configured boards").action(()=>{try{let e=C();if(!e.boards?.length){console.log(qe.dim(`
|
|
530
530
|
No boards configured.
|
|
531
531
|
`));return}console.log();for(let t of e.boards){console.log(` ${qe.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(qe.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(qe.dim(` primary label: ${t.primaryToolLabel}`)),console.log(qe.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(qe.red(` ${e.message}`)),process.exit(1)}});zo.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{Er(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(qe.red(` ${o.message}`)),process.exit(1)}});zo.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{Er(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(qe.red(` ${o.message}`)),process.exit(1)}});var ad=zo.command("column").description("manage a board's columns (add / remove / edit / list)");ad.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(vR("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(qe.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(` ${qe.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${qe.dim(r)}`)}}catch(t){console.log(qe.red(` ${t.message}`)),process.exit(1)}});ad.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{Er(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(qe.red(` ${n.message}`)),process.exit(1)}});ad.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Er(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(qe.red(` ${o.message}`)),process.exit(1)}});zo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Er(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(qe.red(` ${t.message}`)),process.exit(1)}});function Er(e){let{summary:t,backupPath:o}=Tt(n=>e(n));console.log(qe.green(`
|
|
@@ -555,19 +555,19 @@ An edit that breaks these rules is refused and the note is deferred.
|
|
|
555
555
|
|
|
556
556
|
${t}
|
|
557
557
|
`}function tb(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=$a(a.reason||"no reason given");if(a.outcome!=="patched")return{id:i.id,outcome:a.outcome,reason:c,patched:[]};let l=AR(a.edits,o,n.paths,n.agentId);if("refused"in l)return{id:i.id,outcome:"deferred",reason:$a(`patch refused: ${l.refused}. Absorb said: ${c}`),patched:[]};let g=[],d="";for(let[p,{article:u,content:h}]of l.articles){let y=!1;try{y=o.writeArticle(p,{...u.meta,lastUpdated:s,sources:[...new Set([...u.meta.sources??[],ld(i.id)])]},h,n.agentId)}catch(b){d=`${p}: ${b?.message??b}`}if(!y){d||=p;break}g.push({path:p,article:u})}if(d){for(let p of g)try{o.writeArticle(p.path,p.article.meta,p.article.content,n.agentId)}catch{}return{id:i.id,outcome:"deferred",reason:$a(`patch not saved: could not write ${d}. Absorb said: ${c}`),patched:[]}}let f=g.map(p=>p.path);return{id:i.id,outcome:"patched",reason:$a(`${c} (edited ${f.join(", ")})`),patched:f}})}function AR(e,t,o,n){if(e.length===0)return{refused:"patched with no edits"};if(e.length>Rr.edits)return{refused:`more than ${Rr.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>Rr.find||r.replace.length>Rr.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*Rr.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=[...ER(i.content,a),...OR(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 ER(e,t){let o=Xs(e,t),n=Xs(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 RR=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,CR=/(?<![\w@.])@[A-Za-z0-9_]{3,}/g,TR=/^\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 OR(e,t){let o=t.toLowerCase(),n=[];for(let s of e.matchAll(RR))o.includes(s[0].toLowerCase())||n.push(`email ${s[0]}`);for(let s of e.matchAll(CR))o.includes(s[0].toLowerCase())||n.push(`handle ${s[0]}`);for(let s of e.matchAll(TR)){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 $a(e){return e.length>sc.reason?`${e.slice(0,sc.reason-1)}\u2026`:e}import We from"chalk";import{resolve as IR}from"path";var jR=e=>e||IR(process.cwd(),".agentx/wiki");async function Rs(e){let{FactLedger:t}=await import("./ledger-P62U3FHT.js");return new t(jR(e))}function Cs(e){return async(...t)=>{try{await e(...t)}catch(o){o?.name!=="LedgerCorruptError"&&console.error(We.red(` ${o?.message??o}`)),process.exitCode=1}}}function ob(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(Cs(async n=>{let{isStaleFact:s}=await import("./ledger-P62U3FHT.js"),r=(await Rs(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(We.dim(" no facts recorded"));return}for(let i of r){let a=i.undated?We.yellow(" UNCHECKED"):s(i)?We.yellow(" STALE"):"";console.log(` ${We.cyan(i.id)} ${We.bold(i.subject)} \xB7 ${i.attribute}: ${i.value}${a}`),console.log(We.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(Cs(async(n,s)=>{let r=(await Rs(s.dir)).get(n);if(!r){console.error(We.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: ${tc.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(Cs(async n=>{if(n.class&&!Tg(n.class)){console.error(We.red(` --class must be one of ${tc.join(", ")}`)),process.exitCode=1;return}let r=(await Rs(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(We.yellow(` not replaced: the wiki says "${r.fact.value}" (checked ${r.fact.verifiedAt.slice(0,10)}), ${i}.`)),console.log(r.questionId?We.dim(` Queued question ${r.questionId}: agentx wiki questions \xB7 agentx wiki answer ${r.questionId} "<true value>"`):r.questionClosed?We.dim(` A person already ${r.questionClosed} this same claim, so it is not asked again.`):We.red(" No question could be queued: the questions file is unreadable. Repair .agentx/wiki/_questions.json.")),process.exitCode=2;return}console.log(We.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(Cs(async n=>{let{listFactProposals:s}=await import("./fact-proposals-X2O4W7VN.js"),r=s(await Rs(n.dir),n.all?void 0:"pending");if(n.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(We.dim(" no fact proposals waiting"));return}for(let i of r)console.log(` ${We.cyan(i.id)} ${i.status==="pending"?"":We.dim(`[${i.status}] `)}${i.claim}`),console.log(We.dim(` ${i.agentId} \xB7 ${i.origin} \xB7 ${i.source} \xB7 ${i.verifiedAt.slice(0,10)}`));console.log(We.dim(`
|
|
558
|
-
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(Cs(async(n,s)=>{let{approveFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),{write:i}=r(await Rs(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(We.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(Cs(async(n,s)=>{let{rejectFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),i=r(await Rs(s.dir),n,s.by,s.reason);console.log(We.dim(` rejected: ${i.claim}`))}))}import Ke from"chalk";import{existsSync as nb,readFileSync as sb}from"fs";import{resolve as gd}from"path";var dd=e=>e||gd(process.cwd(),".agentx/wiki");function NR(e){if(e)return e.replace(/\/+$/,"");if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL.replace(/\/+$/,"");try{let t=gd(process.cwd(),"agentx.json");if(nb(t)){let o=JSON.parse(sb(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 go(e){console.error(Ke.red(` ${e}`)),process.exitCode=1}function ka(e){return async(...t)=>{try{await e(...t)}catch(o){go(o?.message??String(o))}}}function rb(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(ka(async o=>{if(!o.from){go("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){go("--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){go(l.error);return}s={ok:!0,...new a(dd(o.dir)).add(l.note)}}else{let a=NR(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){go(`could not reach the daemon at ${a}: ${l?.message??l}`);return}if(s=await c.json().catch(()=>({})),!c.ok){go(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?Ke.dim(` already in the inbox${i}: ${r?.id} (${r?.status})`):Ke.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(ka(async o=>{let{NoteStore:n}=await import("./notes-WJJEJ4CJ.js"),s=["waiting","open","patched","rejected","deferred","expired","all"];if(!s.includes(o.status)){go(`--status must be one of ${s.join(", ")}`);return}let r=new n(dd(o.dir)),i=r.load();if(i.unreadable){go(`${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(Ke.dim(` no ${o.status==="all"?"":`${o.status} `}notes`));return}for(let c of a){let l=c.status==="open"?Ke.yellow("open"):c.status==="deferred"?Ke.yellow("deferred"):Ke.dim(c.status);console.log(` ${Ke.cyan(c.id)} ${l} \xB7 from ${c.from}${c.fromNode?` on ${c.fromNode}`:""} \xB7 ${c.date}`),console.log(` ${c.change}`),console.log(Ke.dim(` source: ${c.source}`)),c.listedIn?.length&&console.log(Ke.dim(` given to: ${c.listedIn.at(-1)}${c.listedIn.length>1?` (+${c.listedIn.length-1} earlier)`:""}`)),c.handled&&console.log(Ke.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(Ke.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(ka(async(o,n)=>{let{NoteStore:s}=await import("./notes-WJJEJ4CJ.js"),r=new s(dd(n.dir)).handle(o,n.outcome,n.reason,n.by,n.run);console.log(Ke.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(ka(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){go("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-CP2TIY2J.js"),{summary:l}=c(g=>n(g,r));console.log(Ke.green(` ${l}`))}let i=gd(process.cwd(),"agentx.json");if(!nb(i)){go(`agentx.json not found at ${i}`);return}let a=s(JSON.parse(sb(i,"utf-8"))?.wikiNotes);if(o.json){console.log(JSON.stringify(a,null,2));return}console.log(` wiki notes: ${a.enabled?Ke.green("on"):Ke.dim("off")}`),console.log(` inbox agent: ${a.inbox||Ke.dim("not set")}`),console.log(` schedules that read it: ${a.crons.length?a.crons.join(", "):Ke.dim("none on this node")}`),console.log(` absorb that reads it: ${a.absorbAgent?`wiki absorb for ${a.absorbAgent}`:Ke.dim("none")}`),console.log(` most notes per run: ${a.maxNotesPerRun}`),console.log(` deferrals before a note expires: ${a.maxDeferrals}`)}))}import Yo from"chalk";import{resolve as _R}from"path";var ud=e=>e||_R(process.cwd(),".agentx/wiki");function ib(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-LQ2I2PQI.js");try{let s=n(ud(o.dir));console.log(Yo.green(` wrote ${s}`))}catch(s){console.error(Yo.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-LQ2I2PQI.js"),{file:s,errors:r}=n(ud(o.dir));if(!s){console.log(Yo.dim(" no ontology.yaml: the built-in defaults are in use"));return}if(r.length===0){console.log(Yo.green(` ${s}: no problems`));return}console.log(Yo.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-LQ2I2PQI.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{WikiHub:r}=await import("./hub-H4AW5H7E.js"),i=ud(o.dir),{loadRoster:a}=await import("./roster-BZGKG2ZA.js"),{ontology:c,errors:l}=n(i),g=new r(i,()=>{}),d=new s().get(g,c,a(i,g.listAgents([]),c.agent_names)),f=new Map;for(let p of d.entities.values())f.set(p.type,(f.get(p.type)??0)+1);if(o.json){console.log(JSON.stringify({entities:d.entities.size,types:Object.fromEntries(f),errors:l},null,2));return}console.log(Yo.bold(` ${d.entities.size} entities`));for(let p of c.pillars){let u=c.types.filter(y=>y.pillar===p.id),h=u.reduce((y,b)=>y+(f.get(b.id)??0),0);console.log(` ${p.label.padEnd(26)} ${String(h).padStart(6)} ${Yo.dim(u.map(y=>`${y.id} ${f.get(y.id)??0}`).join(" \xB7 "))}`)}l.length&&console.log(Yo.yellow(` ontology.yaml has ${l.length} problem(s): agentx wiki ontology check`))})}import Qe from"chalk";import{resolve as PR}from"path";var md=e=>e||PR(process.cwd(),".agentx/wiki"),DR=()=>new Date().toISOString().slice(0,10);async function pd(e){let{WikiHub:t}=await import("./hub-H4AW5H7E.js"),{GraphCache:o}=await import("./graph-ZVKV3JBD.js"),{loadOntology:n}=await import("./load-LQ2I2PQI.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 ab(e,t){let o=Number(e);return Number.isInteger(o)&&o>=1?o:(console.error(Qe.red(` ${t} must be a whole number, 1 or more`)),process.exitCode=1,null)}function cb(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-NBOMTB23.js"),{claudeCall:r}=await import("./wiki-enrich-3XXN4XCV.js"),i=ab(o.max,"--max"),a=ab(o.batch,"--batch");if(i===null||a===null)return;let c=Number(o.maxCost);if(!Number.isFinite(c)||c<=0){console.error(Qe.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let{hub:l,g}=await pd(md(o.dir)),d=o.about??[],{normName:f}=await import("./graph-ZVKV3JBD.js"),p=d.filter(b=>!g.names.has(f(b))&&!g.entities.has(b));if(p.length){console.error(Qe.red(` no page is titled: ${p.join(", ")}`)),process.exitCode=1;return}let u=await n(l,g,r(o.model),{about:d,max:i,batch:a,maxCostUsd:c,dryRun:!!o.dryRun,force:!!o.force,rulesOnly:!!o.rulesOnly,today:DR()}),h=s(g,u,d);if(o.json){console.log(JSON.stringify({...u,about:h},null,2));return}for(let b of u.outcomes){let $=b.status==="written"?Qe.green("\u2713"):b.status==="dry-run"?Qe.cyan("~"):Qe.yellow("\xB7"),v=b.importance?`${b.importance}${b.proposed?` (proposed ${b.proposed})`:""}`:b.status;console.log(` ${$} ${b.date||"no date "} ${v.padEnd(8)} ${b.title} ${Qe.dim(`${b.by??b.status}${b.about.length?` \xB7 about ${b.about.join(", ")}`:""}${b.why?` \xB7 ${b.why}`:""}`)}`);for(let x of b.dropped.slice(0,4))console.log(Qe.dim(` dropped: ${x}`))}for(let b of h)console.log(Qe.bold(` ${b.title}`)+Qe.dim(` (${b.type}): ${b.before} events in its History before \xB7 after: ${b.after.major} major, ${b.after.normal} normal, ${b.after.minor} minor (folded)`));let y=u.outcomes.filter(b=>b.importance).length;u.outcomes.length===0&&console.log(Qe.dim(" nothing to do: every event in scope already has a level (--force redoes the ones this job set)")),console.log(Qe.dim(` ${y} event${y===1?"":"s"} ${o.dryRun?"would get":"got"} a level \xB7 ${u.left} left \xB7 ${u.calls} model call${u.calls===1?"":"s"} \xB7 spent $${u.costUsd.toFixed(3)} of $${c}${u.capped?" \xB7 stopped at the cap":""}`)),u.outcomes.some(b=>b.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-NBOMTB23.js"),{IMPORTANCE_LEVELS:a}=await import("./types-YZX46RES.js"),c=n.toLowerCase();if(!a.includes(c)){console.error(Qe.red(` level must be one of ${a.join(", ")}`)),process.exitCode=1;return}let{hub:l,g}=await pd(md(r.optsWithGlobals().dir)),d=i(l,g,o,c);d.ok?console.log(Qe.green(` ${d.title} is now ${c}`)+Qe.dim(` (${d.page})`)):(console.error(Qe.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 pd(md(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} ${Qe.dim(`now ${a.importance}, proposed ${a.importanceProposed}`)}`);console.log(Qe.dim(i.length?` ${i.length} waiting. Decide each with: agentx wiki events set "<title>" major (or normal)`:" none waiting"))})}import Et from"chalk";import{resolve as MR}from"path";var LR=e=>e||MR(process.cwd(),".agentx/wiki");function lb(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-H4AW5H7E.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{loadOntology:r}=await import("./load-LQ2I2PQI.js"),{loadRoster:i}=await import("./roster-BZGKG2ZA.js"),{loadRulesState:a,ruleWordsPattern:c,runRules:l,saveRulesState:g}=await import("./rules-5ZZQZLQA.js"),d=LR(o.dir),f=Number(o.max);if(!Number.isInteger(f)||f<1){console.error(Et.red(" --max must be a whole number of pages, 1 or more")),process.exitCode=1;return}let p=Number(o.maxCost);if(!Number.isFinite(p)||p<=0){console.error(Et.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let u=o.words?.split(",").map(x=>x.trim()).filter(Boolean);if(o.words!==void 0&&!u?.length){console.error(Et.red(" --words needs at least one word")),process.exitCode=1;return}let h=new n(d,()=>{}),{ontology:y}=r(d);if(!y.types.some(x=>x.id==="obligation")){console.error(Et.red(" ontology.yaml has no `obligation` type; add it back to write rule pages")),process.exitCode=1;return}let b=new s().get(h,y,i(d,h.listAgents([]),y.agent_names)),$=a(d),v=await l(h,b,Dp(o.model),{only:t,words:c(u),max:f,maxCostUsd:p,dryRun:!!o.dryRun,force:!!o.force,today:new Date().toISOString().slice(0,10),save:x=>g(d,x)},$);if(o.json){console.log(JSON.stringify(v,null,2));return}for(let x of v.outcomes){let S=x.status==="written"?Et.green("\u2713"):x.status==="dry-run"?Et.cyan("~"):Et.yellow("\xB7");console.log(` ${S} ${x.title} ${Et.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 A=[k.deadline?"":"no deadline",k.penalty?"":"no penalty"].filter(Boolean);console.log(` ${k.created?"new":"updated"}: ${k.title} ${Et.dim(`\xB7 ${k.page}${A.length?` \xB7 ${A.join(", ")}`:""}${k.linked.length?` \xB7 linked from ${k.linked.join(", ")}`:""}`)}`),k.preview&&console.log(Et.dim(k.preview.split(`
|
|
558
|
+
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(Cs(async(n,s)=>{let{approveFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),{write:i}=r(await Rs(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(We.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(Cs(async(n,s)=>{let{rejectFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),i=r(await Rs(s.dir),n,s.by,s.reason);console.log(We.dim(` rejected: ${i.claim}`))}))}import Ke from"chalk";import{existsSync as nb,readFileSync as sb}from"fs";import{resolve as gd}from"path";var dd=e=>e||gd(process.cwd(),".agentx/wiki");function NR(e){if(e)return e.replace(/\/+$/,"");if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL.replace(/\/+$/,"");try{let t=gd(process.cwd(),"agentx.json");if(nb(t)){let o=JSON.parse(sb(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 go(e){console.error(Ke.red(` ${e}`)),process.exitCode=1}function ka(e){return async(...t)=>{try{await e(...t)}catch(o){go(o?.message??String(o))}}}function rb(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(ka(async o=>{if(!o.from){go("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){go("--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){go(l.error);return}s={ok:!0,...new a(dd(o.dir)).add(l.note)}}else{let a=NR(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){go(`could not reach the daemon at ${a}: ${l?.message??l}`);return}if(s=await c.json().catch(()=>({})),!c.ok){go(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?Ke.dim(` already in the inbox${i}: ${r?.id} (${r?.status})`):Ke.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(ka(async o=>{let{NoteStore:n}=await import("./notes-WJJEJ4CJ.js"),s=["waiting","open","patched","rejected","deferred","expired","all"];if(!s.includes(o.status)){go(`--status must be one of ${s.join(", ")}`);return}let r=new n(dd(o.dir)),i=r.load();if(i.unreadable){go(`${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(Ke.dim(` no ${o.status==="all"?"":`${o.status} `}notes`));return}for(let c of a){let l=c.status==="open"?Ke.yellow("open"):c.status==="deferred"?Ke.yellow("deferred"):Ke.dim(c.status);console.log(` ${Ke.cyan(c.id)} ${l} \xB7 from ${c.from}${c.fromNode?` on ${c.fromNode}`:""} \xB7 ${c.date}`),console.log(` ${c.change}`),console.log(Ke.dim(` source: ${c.source}`)),c.listedIn?.length&&console.log(Ke.dim(` given to: ${c.listedIn.at(-1)}${c.listedIn.length>1?` (+${c.listedIn.length-1} earlier)`:""}`)),c.handled&&console.log(Ke.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(Ke.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(ka(async(o,n)=>{let{NoteStore:s}=await import("./notes-WJJEJ4CJ.js"),r=new s(dd(n.dir)).handle(o,n.outcome,n.reason,n.by,n.run);console.log(Ke.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(ka(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){go("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-LW366SKL.js"),{summary:l}=c(g=>n(g,r));console.log(Ke.green(` ${l}`))}let i=gd(process.cwd(),"agentx.json");if(!nb(i)){go(`agentx.json not found at ${i}`);return}let a=s(JSON.parse(sb(i,"utf-8"))?.wikiNotes);if(o.json){console.log(JSON.stringify(a,null,2));return}console.log(` wiki notes: ${a.enabled?Ke.green("on"):Ke.dim("off")}`),console.log(` inbox agent: ${a.inbox||Ke.dim("not set")}`),console.log(` schedules that read it: ${a.crons.length?a.crons.join(", "):Ke.dim("none on this node")}`),console.log(` absorb that reads it: ${a.absorbAgent?`wiki absorb for ${a.absorbAgent}`:Ke.dim("none")}`),console.log(` most notes per run: ${a.maxNotesPerRun}`),console.log(` deferrals before a note expires: ${a.maxDeferrals}`)}))}import Yo from"chalk";import{resolve as _R}from"path";var ud=e=>e||_R(process.cwd(),".agentx/wiki");function ib(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-LQ2I2PQI.js");try{let s=n(ud(o.dir));console.log(Yo.green(` wrote ${s}`))}catch(s){console.error(Yo.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-LQ2I2PQI.js"),{file:s,errors:r}=n(ud(o.dir));if(!s){console.log(Yo.dim(" no ontology.yaml: the built-in defaults are in use"));return}if(r.length===0){console.log(Yo.green(` ${s}: no problems`));return}console.log(Yo.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-LQ2I2PQI.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{WikiHub:r}=await import("./hub-4ODFNGHL.js"),i=ud(o.dir),{loadRoster:a}=await import("./roster-BZGKG2ZA.js"),{ontology:c,errors:l}=n(i),g=new r(i,()=>{}),d=new s().get(g,c,a(i,g.listAgents([]),c.agent_names)),f=new Map;for(let p of d.entities.values())f.set(p.type,(f.get(p.type)??0)+1);if(o.json){console.log(JSON.stringify({entities:d.entities.size,types:Object.fromEntries(f),errors:l},null,2));return}console.log(Yo.bold(` ${d.entities.size} entities`));for(let p of c.pillars){let u=c.types.filter(y=>y.pillar===p.id),h=u.reduce((y,b)=>y+(f.get(b.id)??0),0);console.log(` ${p.label.padEnd(26)} ${String(h).padStart(6)} ${Yo.dim(u.map(y=>`${y.id} ${f.get(y.id)??0}`).join(" \xB7 "))}`)}l.length&&console.log(Yo.yellow(` ontology.yaml has ${l.length} problem(s): agentx wiki ontology check`))})}import Qe from"chalk";import{resolve as PR}from"path";var md=e=>e||PR(process.cwd(),".agentx/wiki"),DR=()=>new Date().toISOString().slice(0,10);async function pd(e){let{WikiHub:t}=await import("./hub-4ODFNGHL.js"),{GraphCache:o}=await import("./graph-ZVKV3JBD.js"),{loadOntology:n}=await import("./load-LQ2I2PQI.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 ab(e,t){let o=Number(e);return Number.isInteger(o)&&o>=1?o:(console.error(Qe.red(` ${t} must be a whole number, 1 or more`)),process.exitCode=1,null)}function cb(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-NBOMTB23.js"),{claudeCall:r}=await import("./wiki-enrich-RVRTAQQF.js"),i=ab(o.max,"--max"),a=ab(o.batch,"--batch");if(i===null||a===null)return;let c=Number(o.maxCost);if(!Number.isFinite(c)||c<=0){console.error(Qe.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let{hub:l,g}=await pd(md(o.dir)),d=o.about??[],{normName:f}=await import("./graph-ZVKV3JBD.js"),p=d.filter(b=>!g.names.has(f(b))&&!g.entities.has(b));if(p.length){console.error(Qe.red(` no page is titled: ${p.join(", ")}`)),process.exitCode=1;return}let u=await n(l,g,r(o.model),{about:d,max:i,batch:a,maxCostUsd:c,dryRun:!!o.dryRun,force:!!o.force,rulesOnly:!!o.rulesOnly,today:DR()}),h=s(g,u,d);if(o.json){console.log(JSON.stringify({...u,about:h},null,2));return}for(let b of u.outcomes){let $=b.status==="written"?Qe.green("\u2713"):b.status==="dry-run"?Qe.cyan("~"):Qe.yellow("\xB7"),v=b.importance?`${b.importance}${b.proposed?` (proposed ${b.proposed})`:""}`:b.status;console.log(` ${$} ${b.date||"no date "} ${v.padEnd(8)} ${b.title} ${Qe.dim(`${b.by??b.status}${b.about.length?` \xB7 about ${b.about.join(", ")}`:""}${b.why?` \xB7 ${b.why}`:""}`)}`);for(let x of b.dropped.slice(0,4))console.log(Qe.dim(` dropped: ${x}`))}for(let b of h)console.log(Qe.bold(` ${b.title}`)+Qe.dim(` (${b.type}): ${b.before} events in its History before \xB7 after: ${b.after.major} major, ${b.after.normal} normal, ${b.after.minor} minor (folded)`));let y=u.outcomes.filter(b=>b.importance).length;u.outcomes.length===0&&console.log(Qe.dim(" nothing to do: every event in scope already has a level (--force redoes the ones this job set)")),console.log(Qe.dim(` ${y} event${y===1?"":"s"} ${o.dryRun?"would get":"got"} a level \xB7 ${u.left} left \xB7 ${u.calls} model call${u.calls===1?"":"s"} \xB7 spent $${u.costUsd.toFixed(3)} of $${c}${u.capped?" \xB7 stopped at the cap":""}`)),u.outcomes.some(b=>b.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-NBOMTB23.js"),{IMPORTANCE_LEVELS:a}=await import("./types-YZX46RES.js"),c=n.toLowerCase();if(!a.includes(c)){console.error(Qe.red(` level must be one of ${a.join(", ")}`)),process.exitCode=1;return}let{hub:l,g}=await pd(md(r.optsWithGlobals().dir)),d=i(l,g,o,c);d.ok?console.log(Qe.green(` ${d.title} is now ${c}`)+Qe.dim(` (${d.page})`)):(console.error(Qe.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 pd(md(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} ${Qe.dim(`now ${a.importance}, proposed ${a.importanceProposed}`)}`);console.log(Qe.dim(i.length?` ${i.length} waiting. Decide each with: agentx wiki events set "<title>" major (or normal)`:" none waiting"))})}import Et from"chalk";import{resolve as MR}from"path";var LR=e=>e||MR(process.cwd(),".agentx/wiki");function lb(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-4ODFNGHL.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{loadOntology:r}=await import("./load-LQ2I2PQI.js"),{loadRoster:i}=await import("./roster-BZGKG2ZA.js"),{loadRulesState:a,ruleWordsPattern:c,runRules:l,saveRulesState:g}=await import("./rules-5ZZQZLQA.js"),d=LR(o.dir),f=Number(o.max);if(!Number.isInteger(f)||f<1){console.error(Et.red(" --max must be a whole number of pages, 1 or more")),process.exitCode=1;return}let p=Number(o.maxCost);if(!Number.isFinite(p)||p<=0){console.error(Et.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let u=o.words?.split(",").map(x=>x.trim()).filter(Boolean);if(o.words!==void 0&&!u?.length){console.error(Et.red(" --words needs at least one word")),process.exitCode=1;return}let h=new n(d,()=>{}),{ontology:y}=r(d);if(!y.types.some(x=>x.id==="obligation")){console.error(Et.red(" ontology.yaml has no `obligation` type; add it back to write rule pages")),process.exitCode=1;return}let b=new s().get(h,y,i(d,h.listAgents([]),y.agent_names)),$=a(d),v=await l(h,b,Dp(o.model),{only:t,words:c(u),max:f,maxCostUsd:p,dryRun:!!o.dryRun,force:!!o.force,today:new Date().toISOString().slice(0,10),save:x=>g(d,x)},$);if(o.json){console.log(JSON.stringify(v,null,2));return}for(let x of v.outcomes){let S=x.status==="written"?Et.green("\u2713"):x.status==="dry-run"?Et.cyan("~"):Et.yellow("\xB7");console.log(` ${S} ${x.title} ${Et.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 A=[k.deadline?"":"no deadline",k.penalty?"":"no penalty"].filter(Boolean);console.log(` ${k.created?"new":"updated"}: ${k.title} ${Et.dim(`\xB7 ${k.page}${A.length?` \xB7 ${A.join(", ")}`:""}${k.linked.length?` \xB7 linked from ${k.linked.join(", ")}`:""}`)}`),k.preview&&console.log(Et.dim(k.preview.split(`
|
|
559
559
|
`).map(R=>` | ${R}`).join(`
|
|
560
|
-
`)))}for(let k of x.dropped.slice(0,6))console.log(Et.dim(` dropped: ${k}`))}v.outcomes.length===0&&console.log(Et.dim(" nothing to do: no page that states rules changed since the last run (--force reads them again)")),console.log(Et.dim(` spent $${v.costUsd.toFixed(3)} of $${p}${v.capped?" \xB7 stopped at the cap":""}`))})}import va from"chalk";import{resolve as qR}from"path";var FR=e=>e||qR(process.cwd(),".agentx/wiki");function db(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-
|
|
560
|
+
`)))}for(let k of x.dropped.slice(0,6))console.log(Et.dim(` dropped: ${k}`))}v.outcomes.length===0&&console.log(Et.dim(" nothing to do: no page that states rules changed since the last run (--force reads them again)")),console.log(Et.dim(` spent $${v.costUsd.toFixed(3)} of $${p}${v.capped?" \xB7 stopped at the cap":""}`))})}import va from"chalk";import{resolve as qR}from"path";var FR=e=>e||qR(process.cwd(),".agentx/wiki");function db(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-KNSPJT2O.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:g}=await import("./config-WCEFYQL4.js");r=g().wiki.summaries}catch{}let i=new o(FR(t.dir),void 0,"graph"),a=t.agent||process.env.AGENTX_AGENT_ID;if(!t.all&&!a){console.log(va.red(" Name an agent with --agent <id>, or pass --all.")),process.exitCode=1;return}let c=t.all?[...i.sharedScope("").map(g=>({id:g.id,store:g.store,skip:g.skip}))]:[{id:a,store:i.getAgentWiki(a),skip:void 0}],l=[];for(let g of c){let d=await n(g.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:g.skip,log:t.json?void 0:f=>console.log(va.dim(` ${g.id}: ${f}`))});if(l.push({agent:g.id,...d}),!t.json&&(d.pages>0||d.removed>0)){let f=t.dryRun?`${d.due} due`:`${d.written} written${d.failed?va.yellow(`, ${d.failed} failed`):""}${d.removed?`, ${d.removed} removed`:""}`;console.log(` ${va.bold(g.id)}: ${d.pages} pages, ${f}`)}}t.json&&console.log(JSON.stringify(l,null,2)),l.some(g=>g.failed>0)&&(process.exitCode=1)})}import{resolve as F,relative as gb,dirname as ub}from"path";import{exec as WR,execSync as Tn}from"child_process";import{promisify as BR}from"util";import{appendFileSync as JR,statSync as GR,writeFileSync as Pt,mkdirSync as Kt,readFileSync as Dt,readdirSync as HR,renameSync as xa,rmSync as hd,existsSync as Ze}from"fs";var wb=BR(WR);function $e(e,t){return new ec(ft(e),void 0,t||"graph")}async function bb(e){let t=[];try{let{loadDaemonConfig:n}=await import("./config-WCEFYQL4.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 $b(){try{let{loadDaemonConfig:e}=await import("./config-WCEFYQL4.js"),t=Object.keys(e().agents||{});return t.length?new Set(t):null}catch{return null}}async function mb(){try{let{loadDaemonConfig:e}=await import("./config-WCEFYQL4.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 zR(){try{let{loadDaemonConfig:e}=await import("./config-WCEFYQL4.js");return Ap(e().agents||{})}catch{return new Set}}function On(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 pb(){let{sharedQueryEnabled:e}=await import("./query-QVK5EN3P.js");return e()}async function kb(e){let{loadQuerySettings:t}=await import("./query-settings-2TNLXEL5.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 ft(e){return e||F(process.cwd(),".agentx/wiki")}function yd(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var H=new UR().name("wiki").description("wiki knowledge base management");ob(H);rb(H);ib(H);Mp(H);cb(H);lb(H);db(H);H.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let t=e.mode,o=$e(e.dir,t),n=o.summary(),r=o.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${yd(t)}]`)),console.log(),console.log(` Total raw entries: ${r}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?m.yellow(`${a.unabsorbed} unabsorbed`):m.green("up to date");if(console.log(` ${m.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),console.log(m.dim(` Cited by an article: ${a.cited} Read, not cited: ${a.readNotCited}`)),a.articles.length>0){for(let l of a.articles.slice(0,3))console.log(m.dim(` - ${l.title} [${(l.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(m.dim(` ... and ${a.articles.length-3} more`))}console.log()}let i=n.reduce((a,c)=>a+c.unabsorbed,0);i>0&&(console.log(m.dim(` ${i} raw entries wait for absorb \u2014 run 'agentx wiki absorb'.`)),console.log())});H.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(async e=>{let t=$e(e.dir,e.mode),o=e.agent?[e.agent]:t.listAgents(),n=0;console.log();for(let i of o){let 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 g=l.type==="broken-link"?"x":l.type==="orphan"?"?":"!";console.log(` [${g}] ${m.dim(l.type)} ${l.article}: ${l.message}`)}}}let{factContradictions:s}=await import("./ledger-P62U3FHT.js"),r=s(ft(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()});H.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=cd(e.model)}catch(R){console.log(m.red(` ${R.message}`)),process.exitCode=1;return}let n=$e(e.dir,t),s=await $b(),{agents:r,skipped:i}=Ep(n.listAgents().filter(R=>!s||s.has(R)),{only:e.agent,off:await zR()}),a=i.length&&e.notes!==!1?(await mb())?.absorbAgent:void 0;for(let R of i)console.log(` ${m.cyan(R)}: ${m.dim(Rp(R,a))}`);let c=r.filter(R=>{let O=n.syncedFrom(R);return O&&console.log(` ${m.cyan(R)}: ${m.dim(`copied from ${O.node}, read-only here; absorb it there`)}`),!O}),l=parseInt(e.max),g=(()=>{try{let R=F(process.cwd(),".agentx/graph");return Ze(R)?new Ro({baseDir:R}):null}catch{return null}})(),d=new Map;if(g)try{let R=g.loadIndex();for(let[O,I]of Object.entries(R.entries))d.set(O,I.path)}catch{}let f,p=R=>{let O=R.meta?.intentPath;if(Array.isArray(O)&&O.every(P=>typeof P=="string")&&O.length>0)return O;if(!g||d.size===0)return;let I=String(R.meta?.sender??""),D=g.fingerprint({text:R.content,channel:R.source,sender:I});return d.get(D)},u=(R,O)=>{let I=new Map;for(let P of R){let J=O.find(Ce=>Ce.id===P);if(!J)continue;let W=p(J);if(!W?.length)continue;let V=W.join("/"),X=I.get(V);X?X.n++:I.set(V,{path:W,n:1})}if(I.size===0)return;let D;for(let P of I.values())(!D||P.n>D.n)&&(D=P);return D?.path},h=0,y=0,b=0,$=F(n.getBaseDir(),"_absorb-runs.jsonl"),v=typeof e.runLabel=="string"&&e.runLabel.trim()?e.runLabel.trim():void 0,x=R=>{if(!e.dryRun)try{JR($,`${JSON.stringify(R)}
|
|
561
561
|
`)}catch{}},S=new Date().toISOString(),k=e.notes===!1?null:await mb(),A=k?new Wg(n.getBaseDir()):null;for(let R of c){let O=Date.now(),I=typeof e.since=="string"?e.since.trim():"",D=typeof e.until=="string"?e.until.trim():"",P=n.getUnabsorbedEntries(R).filter(ce=>!I||(ce.date??"")>=I).filter(ce=>!D||(ce.date??"").slice(0,10)<=D).slice(0,l),J=!!(k&&A&&k.absorbAgent===R),W=`absorb/${R}/${S.replace(/[:.]/g,"-")}`,V=[];if(J&&e.dryRun?V=A.peekForRun(k.inbox,k.max,k.maxDeferrals):J&&(V=A.takeForRun(k.inbox,W,k.max,k.maxDeferrals)),P.length===0&&V.length===0){console.log(` ${m.cyan(R)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(R)}: ${P.length} entries to absorb`));for(let ce of P.slice(0,3))console.log(m.dim(` [${ce.date} via ${ce.source}] ${ce.content.slice(0,80)}...`));if(P.length>3&&console.log(m.dim(` ... and ${P.length-3} more`)),V.length>0&&console.log(m.dim(` Wiki notes: ${V.length} from the ${k.inbox} inbox${e.dryRun?"":` (run ${W})`}`)),e.dryRun)continue;let X=n.getAgentWiki(R),Ce=X.rebuildIndex(),Ge=X.getWorldview()||n.getSharedStore().getWorldview()||"",M=P.map(ce=>`--- ENTRY ${ce.id} [${ce.date} ${ce.agentId} via ${ce.source}] ---
|
|
562
562
|
${ce.content}
|
|
563
563
|
--- END ENTRY ---`).join(`
|
|
564
564
|
|
|
565
|
-
`),ae="";if(e.facts!==!1){let{extractHints:ce,resolveFacts:Qo,mergeRecords:Pn,renderFactsBlock:Dn,installPrompts:Wr,defaultSources:Mn,recordsFromEntries:Zo}=await import("./facts-ROUMKS7I.js");if(!f){let q=new Set;for(let Fe of n.listAgents())for(let ht of n.getAgentWiki(Fe).listArticles(Fe))ht.meta.type==="person"&&q.add(ht.meta.title);f=[...q]}let en=ce(P.map(q=>({context:q.sourceContext,content:q.content,sender:typeof q.meta?.sender=="string"?q.meta.sender:void 0})),{known:f}),Ln=Zo(P);if(en.length>0||Ln.length>0){let q=Mn(),{records:Fe,results:ht}=en.length>0?await Qo(en,{sources:q}):{records:[],results:[]},ve=Pn([...Ln,...Fe]);ae=Dn(ve);let nt=[...Ln.length>0?[`entries:${Ln.length}`]:[],...ht.filter(Pe=>Pe.records.length>0).map(Pe=>`${Pe.source}:${Pe.records.length}`)];console.log(m.dim(` Facts: ${en.length} entities \u2192 ${ve.length} resolved${nt.length?` (${nt.join(" ")})`:""}`));for(let Pe of Wr(ht,q))console.log(m.yellow(` ! ${Pe.source} ${Pe.kind} \u2014 would supply ${Pe.provides.join(", ")}`)),console.log(m.dim(` ${Pe.hint}`))}}let Ie=Ce.articles.filter(ce=>ce.path&&!ce.path.includes("/_versions/")),de=await jp([...P,...V.map(ce=>({id:ld(ce.id),content:ce.change}))],X,R,Ie);de.length>0&&console.log(m.dim(` Existing: ${de.map(ce=>ce.path).join(", ")}`));let j=Np(de),we=eb(V),ot=lc(t,R,Ge,Ce.articles,M,P.length,ae,j,we);console.log(m.dim(` Mode: ${yd(t)}`));let Qt=F(X.baseDir,"_tmp");Kt(Qt,{recursive:!0});let Ne=F(Qt,"absorb-prompt.txt");Pt(Ne,ot),console.log(m.dim(` Compiling with Claude (${o})...`));let _e={kind:"call",at:"",label:v,agent:R,model:o,entries:P.length,articles:0,refused:0,failed:!0,wallMs:0,promptChars:ot.length,promptParts:{entries:M.length,catalog:ot.length-lc(t,R,Ge,[],M,P.length,ae,j,we).length,catalogArticles:Ce.articles.length,covering:j.length,facts:ae.length,worldview:Ge.length,notes:we.length},...V.length?{notes:V.length}:{}},mo=Date.now();_e.prepMs=mo-O;try{let ce,Qo=!1;try{ce=Tn(`cat '${Ne}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Eo(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(q){if(ce=q.stdout||"",!ce)throw q;Qo=!0}let Pn=ce;try{let q=JSON.parse(ce);Object.assign(_e,Nc(q)),q.is_error===!0&&(Qo=!0),Pn=q.result||q.content||"",Pn||(console.log(m.dim(` Claude envelope keys: ${Object.keys(q).join(", ")}`)),console.log(m.dim(` is_error: ${q.is_error}, stop_reason: ${q.stop_reason}`)))}catch{}let Dn=Qw(Pn);if("error"in Dn){V.length>0&&console.log(m.yellow(` ${V.length} wiki note(s) stay waiting`)),console.log(m.red(` ${Dn.error}`)),console.log(m.dim(` First 500 chars: ${Pn.slice(0,500)}`));continue}let{articles:Wr,gaps:Mn}=Dn,Zo=new Set,en=new Set,Ln=new Set(P.map(q=>q.id));for(let q of Wr){let Fe=new Date().toISOString().slice(0,10),ht=Array.isArray(q.sources)?q.sources:[],ve=V.length>0?ht.filter(Ao=>Ln.has(Ao)):ht;if(V.length>0&&ve.length===0){console.log(m.yellow(` ! refused ${q.path}: cites no entry from this batch; a wiki note only patches`)),_e.refused++;continue}let nt=_p(q,Ie);nt!==q.path&&(console.log(m.dim(` ~ ${q.path} \u2192 ${nt} (an article with this title exists)`)),q.path=nt);let Pe=X.readArticle(q.path);if(Pe){let Ao=Xs(Pe.content,String(q.content??""));if(Ao.length>0){console.log(m.yellow(` ! refused ${q.path}: the rewrite drops ${Ao.length} fact(s) the article has`)),console.log(m.dim(` ${Ao.slice(0,8).join("; ")}${Ao.length>8?"; \u2026":""}`));for(let ak of ve)Zo.add(ak);_e.refused++;continue}}let za=u(ve,P)??Pe?.meta.graphPath;X.writeArticle(q.path,{title:q.title,type:q.type,related:Array.isArray(q.related)?q.related:void 0,tags:q.tags||[],owner:R,access:Pe?.meta.access??"public",sharedWith:Pe?.meta.sharedWith?.length?Pe.meta.sharedWith:void 0,created:Pe?.meta.created||Fe,lastUpdated:Fe,sources:[...new Set([...Pe?.meta.sources??[],...ve])],graphPath:za},q.content,R);let rk=q.type?m.magenta(`[${q.type}]`)+" ":"",ik=Array.isArray(q.related)&&q.related.length?` \u2192 ${q.related.slice(0,3).join(", ")}${q.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(Pe?"~":"+")} ${rk}${q.path}: ${q.title}${m.dim(ik)}`);let Xd=(q.tags||[]).slice(0,4).join(", ");Xd&&console.log(m.dim(` tags: ${Xd}`)),za?.length&&(console.log(m.dim(` graphPath: ${za.join(" \u203A ")}`)),y++),h++,_e.articles++;for(let Ao of ve)en.add(Ao)}if(V.length>0&&!Qo){let q=V.filter(ve=>{let nt=A.get(ve.id);return nt&&nt.status!=="open"&&nt.status!=="deferred"?(console.log(m.dim(` note ${ve.id} already ${nt.status} by ${nt.handled?.by??"another run"}; left as it is`)),!1):nt?.handled&&nt.handled.at>S?(console.log(m.dim(` note ${ve.id} already deferred by ${nt.handled.by} during this run; left as it is`)),!1):!0}),Fe=tb(q,Zw(Dn.notes),X,{agentId:R,paths:new Set(de.map(ve=>ve.path))}),ht=0;for(let ve of Fe){try{A.handle(ve.id,ve.outcome,ve.reason,R,W),ht++}catch(Pe){console.log(m.yellow(` ! note ${ve.id}: could not record ${ve.outcome}: ${Pe?.message??Pe}`))}let nt=ve.outcome==="patched"?m.green("~"):ve.outcome==="rejected"?m.red("x"):m.yellow("\u2026");console.log(` ${nt} note ${ve.id} ${ve.outcome}: ${m.dim(ve.reason.slice(0,160))}`)}_e.notesPatched=Fe.filter(ve=>ve.outcome==="patched").length,_e.notesRecorded=ht}else V.length>0&&console.log(m.yellow(` ${V.length} wiki note(s) stay waiting`));if(_e.failed=Qo,_e.heldCited=[...Zo].filter(q=>en.has(q)).length,Qo)console.log(m.yellow(` Run reported an error \u2014 ${P.length} entries stay queued`));else{let q=P.map(Fe=>Fe.id).filter(Fe=>!Zo.has(Fe));Zo.size>0&&console.log(m.yellow(` ${P.length-q.length} entries stay queued behind refused saves`)),n.markProcessed(R,q,Wr.flatMap(Fe=>Fe.sources||[]).filter(Fe=>!Zo.has(Fe)))}if(Mn.length>0){console.log(),console.log(m.yellow(` Gaps detected (${Mn.length} missing pieces):`));for(let q of Mn)console.log(m.yellow(` ? ${q}`));try{let{QuestionStore:q}=await import("./questions-ZATLU5AW.js"),Fe=new q(ft(e.dir)).add(Mn.map(ht=>({kind:"article",agentId:R,path:"",subject:String(ht).slice(0,120),question:`No article yet for: ${String(ht).slice(0,160)}`})));Fe.added>0&&console.log(m.dim(` queued ${Fe.added} for follow-up (agentx wiki questions)`))}catch{}}X.rebuildIndex()}catch(ce){console.log(m.red(` Absorb failed: ${ce.message?.slice(0,200)}`)),ce.stderr&&console.log(m.dim(String(ce.stderr).slice(0,300))),ce.stdout&&console.log(m.dim("stdout: "+String(ce.stdout).slice(0,300)))}finally{_e.at=new Date().toISOString(),_e.wallMs=Date.now()-mo,_e.failed&&b++,x(_e)}}if(x({kind:"run",label:v,startedAt:S,endedAt:new Date().toISOString(),max:l,model:o,failed:b}),console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(h>0&&(console.log(m.green(` ${h} articles compiled across ${c.length} agent(s)`)),g)){let R=h>0?Math.round(y/h*100):0;console.log(m.dim(` ${y}/${h} carry graphPath (${R}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}b>0&&(console.log(m.red(` ${b} absorb call(s) failed; their entries stay queued`)),process.exitCode=1),console.log()});H.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-
|
|
565
|
+
`),ae="";if(e.facts!==!1){let{extractHints:ce,resolveFacts:Qo,mergeRecords:Pn,renderFactsBlock:Dn,installPrompts:Wr,defaultSources:Mn,recordsFromEntries:Zo}=await import("./facts-ROUMKS7I.js");if(!f){let q=new Set;for(let Fe of n.listAgents())for(let ht of n.getAgentWiki(Fe).listArticles(Fe))ht.meta.type==="person"&&q.add(ht.meta.title);f=[...q]}let en=ce(P.map(q=>({context:q.sourceContext,content:q.content,sender:typeof q.meta?.sender=="string"?q.meta.sender:void 0})),{known:f}),Ln=Zo(P);if(en.length>0||Ln.length>0){let q=Mn(),{records:Fe,results:ht}=en.length>0?await Qo(en,{sources:q}):{records:[],results:[]},ve=Pn([...Ln,...Fe]);ae=Dn(ve);let nt=[...Ln.length>0?[`entries:${Ln.length}`]:[],...ht.filter(Pe=>Pe.records.length>0).map(Pe=>`${Pe.source}:${Pe.records.length}`)];console.log(m.dim(` Facts: ${en.length} entities \u2192 ${ve.length} resolved${nt.length?` (${nt.join(" ")})`:""}`));for(let Pe of Wr(ht,q))console.log(m.yellow(` ! ${Pe.source} ${Pe.kind} \u2014 would supply ${Pe.provides.join(", ")}`)),console.log(m.dim(` ${Pe.hint}`))}}let Ie=Ce.articles.filter(ce=>ce.path&&!ce.path.includes("/_versions/")),de=await jp([...P,...V.map(ce=>({id:ld(ce.id),content:ce.change}))],X,R,Ie);de.length>0&&console.log(m.dim(` Existing: ${de.map(ce=>ce.path).join(", ")}`));let j=Np(de),we=eb(V),ot=lc(t,R,Ge,Ce.articles,M,P.length,ae,j,we);console.log(m.dim(` Mode: ${yd(t)}`));let Qt=F(X.baseDir,"_tmp");Kt(Qt,{recursive:!0});let Ne=F(Qt,"absorb-prompt.txt");Pt(Ne,ot),console.log(m.dim(` Compiling with Claude (${o})...`));let _e={kind:"call",at:"",label:v,agent:R,model:o,entries:P.length,articles:0,refused:0,failed:!0,wallMs:0,promptChars:ot.length,promptParts:{entries:M.length,catalog:ot.length-lc(t,R,Ge,[],M,P.length,ae,j,we).length,catalogArticles:Ce.articles.length,covering:j.length,facts:ae.length,worldview:Ge.length,notes:we.length},...V.length?{notes:V.length}:{}},mo=Date.now();_e.prepMs=mo-O;try{let ce,Qo=!1;try{ce=Tn(`cat '${Ne}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Eo(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(q){if(ce=q.stdout||"",!ce)throw q;Qo=!0}let Pn=ce;try{let q=JSON.parse(ce);Object.assign(_e,Nc(q)),q.is_error===!0&&(Qo=!0),Pn=q.result||q.content||"",Pn||(console.log(m.dim(` Claude envelope keys: ${Object.keys(q).join(", ")}`)),console.log(m.dim(` is_error: ${q.is_error}, stop_reason: ${q.stop_reason}`)))}catch{}let Dn=Qw(Pn);if("error"in Dn){V.length>0&&console.log(m.yellow(` ${V.length} wiki note(s) stay waiting`)),console.log(m.red(` ${Dn.error}`)),console.log(m.dim(` First 500 chars: ${Pn.slice(0,500)}`));continue}let{articles:Wr,gaps:Mn}=Dn,Zo=new Set,en=new Set,Ln=new Set(P.map(q=>q.id));for(let q of Wr){let Fe=new Date().toISOString().slice(0,10),ht=Array.isArray(q.sources)?q.sources:[],ve=V.length>0?ht.filter(Ao=>Ln.has(Ao)):ht;if(V.length>0&&ve.length===0){console.log(m.yellow(` ! refused ${q.path}: cites no entry from this batch; a wiki note only patches`)),_e.refused++;continue}let nt=_p(q,Ie);nt!==q.path&&(console.log(m.dim(` ~ ${q.path} \u2192 ${nt} (an article with this title exists)`)),q.path=nt);let Pe=X.readArticle(q.path);if(Pe){let Ao=Xs(Pe.content,String(q.content??""));if(Ao.length>0){console.log(m.yellow(` ! refused ${q.path}: the rewrite drops ${Ao.length} fact(s) the article has`)),console.log(m.dim(` ${Ao.slice(0,8).join("; ")}${Ao.length>8?"; \u2026":""}`));for(let ak of ve)Zo.add(ak);_e.refused++;continue}}let za=u(ve,P)??Pe?.meta.graphPath;X.writeArticle(q.path,{title:q.title,type:q.type,related:Array.isArray(q.related)?q.related:void 0,tags:q.tags||[],owner:R,access:Pe?.meta.access??"public",sharedWith:Pe?.meta.sharedWith?.length?Pe.meta.sharedWith:void 0,created:Pe?.meta.created||Fe,lastUpdated:Fe,sources:[...new Set([...Pe?.meta.sources??[],...ve])],graphPath:za},q.content,R);let rk=q.type?m.magenta(`[${q.type}]`)+" ":"",ik=Array.isArray(q.related)&&q.related.length?` \u2192 ${q.related.slice(0,3).join(", ")}${q.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(Pe?"~":"+")} ${rk}${q.path}: ${q.title}${m.dim(ik)}`);let Xd=(q.tags||[]).slice(0,4).join(", ");Xd&&console.log(m.dim(` tags: ${Xd}`)),za?.length&&(console.log(m.dim(` graphPath: ${za.join(" \u203A ")}`)),y++),h++,_e.articles++;for(let Ao of ve)en.add(Ao)}if(V.length>0&&!Qo){let q=V.filter(ve=>{let nt=A.get(ve.id);return nt&&nt.status!=="open"&&nt.status!=="deferred"?(console.log(m.dim(` note ${ve.id} already ${nt.status} by ${nt.handled?.by??"another run"}; left as it is`)),!1):nt?.handled&&nt.handled.at>S?(console.log(m.dim(` note ${ve.id} already deferred by ${nt.handled.by} during this run; left as it is`)),!1):!0}),Fe=tb(q,Zw(Dn.notes),X,{agentId:R,paths:new Set(de.map(ve=>ve.path))}),ht=0;for(let ve of Fe){try{A.handle(ve.id,ve.outcome,ve.reason,R,W),ht++}catch(Pe){console.log(m.yellow(` ! note ${ve.id}: could not record ${ve.outcome}: ${Pe?.message??Pe}`))}let nt=ve.outcome==="patched"?m.green("~"):ve.outcome==="rejected"?m.red("x"):m.yellow("\u2026");console.log(` ${nt} note ${ve.id} ${ve.outcome}: ${m.dim(ve.reason.slice(0,160))}`)}_e.notesPatched=Fe.filter(ve=>ve.outcome==="patched").length,_e.notesRecorded=ht}else V.length>0&&console.log(m.yellow(` ${V.length} wiki note(s) stay waiting`));if(_e.failed=Qo,_e.heldCited=[...Zo].filter(q=>en.has(q)).length,Qo)console.log(m.yellow(` Run reported an error \u2014 ${P.length} entries stay queued`));else{let q=P.map(Fe=>Fe.id).filter(Fe=>!Zo.has(Fe));Zo.size>0&&console.log(m.yellow(` ${P.length-q.length} entries stay queued behind refused saves`)),n.markProcessed(R,q,Wr.flatMap(Fe=>Fe.sources||[]).filter(Fe=>!Zo.has(Fe)))}if(Mn.length>0){console.log(),console.log(m.yellow(` Gaps detected (${Mn.length} missing pieces):`));for(let q of Mn)console.log(m.yellow(` ? ${q}`));try{let{QuestionStore:q}=await import("./questions-ZATLU5AW.js"),Fe=new q(ft(e.dir)).add(Mn.map(ht=>({kind:"article",agentId:R,path:"",subject:String(ht).slice(0,120),question:`No article yet for: ${String(ht).slice(0,160)}`})));Fe.added>0&&console.log(m.dim(` queued ${Fe.added} for follow-up (agentx wiki questions)`))}catch{}}X.rebuildIndex()}catch(ce){console.log(m.red(` Absorb failed: ${ce.message?.slice(0,200)}`)),ce.stderr&&console.log(m.dim(String(ce.stderr).slice(0,300))),ce.stdout&&console.log(m.dim("stdout: "+String(ce.stdout).slice(0,300)))}finally{_e.at=new Date().toISOString(),_e.wallMs=Date.now()-mo,_e.failed&&b++,x(_e)}}if(x({kind:"run",label:v,startedAt:S,endedAt:new Date().toISOString(),max:l,model:o,failed:b}),console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(h>0&&(console.log(m.green(` ${h} articles compiled across ${c.length} agent(s)`)),g)){let R=h>0?Math.round(y/h*100):0;console.log(m.dim(` ${y}/${h} carry graphPath (${R}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}b>0&&(console.log(m.red(` ${b} absorb call(s) failed; their entries stay queued`)),process.exitCode=1),console.log()});H.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-MT3ZDYBM.js"),{extractJson:l}=await import("./extract-json-7775Q7KO.js"),g=$e(e.dir,e.mode),d=e.agent?[e.agent]:g.listAgents(),f=typeof e.since=="string"?e.since.trim():"",p=typeof e.changedAfter=="string"&&e.changedAfter.trim()?new Date(e.changedAfter.trim()):null;if(p&&Number.isNaN(p.getTime())){console.log(m.red(` not a time: ${e.changedAfter}`)),process.exitCode=1;return}let u=p?p.toISOString().slice(0,19):f,h=new Map;for(let M of g.getSharedStore().listEntries())h.set(M.id,{id:M.id,date:M.date,content:M.content});let y=[];for(let M of d)for(let ae of g.getAgentWiki(M).listArticles(M))y.push({key:`${M}/${ae.path}`,agent:M,article:ae});let b=new Map;for(let M of y)for(let ae of M.article.meta.sources??[]){let Ie=b.get(ae);Ie?Ie.push(M.article.content):b.set(ae,[M.article.content])}let $=M=>{if(!p)return!0;try{return GR(F(g.getAgentWiki(M.agent).baseDir,M.article.path)).mtimeMs>p.getTime()}catch{return!1}},v=y.filter(M=>!f||(M.article.meta.lastUpdated??"")>=f.slice(0,10)).filter($),x=String(e.seed),S;if(e.sample&&Ze(e.sample)){let M=JSON.parse(Dt(e.sample,"utf-8"));x=M.seed??x;let ae=new Map(y.map(de=>[de.key,de]));S=M.keys.map(de=>ae.get(de)).filter(de=>!!de);let Ie=M.keys.length-S.length;Ie>0&&console.error(m.yellow(` ${Ie} sampled article(s) no longer exist`))}else S=t(v.map(M=>({...M,path:M.key})),parseInt(e.n),x),e.sample&&(Pt(e.sample,`${JSON.stringify({seed:x,since:u||void 0,keys:S.map(M=>M.key)},null,2)}
|
|
566
566
|
`),console.error(m.dim(` sample saved to ${e.sample}`)));if(S.length===0){console.log(m.yellow(` no articles${u?` changed since ${u}`:""} to score`));return}let k=M=>M.replace(/^---\n[\s\S]*?\n---\n?/,""),A=M=>{let ae=g.getAgentWiki(M.agent).getVersions(M.article.path),Ie=u?ae.filter(j=>j.timestamp>=u):ae.slice(0,1),de=Ie[Ie.length-1];if(de)try{return k(Dt(de.path,"utf-8"))}catch{return}},R=S.map(M=>({path:M.key,title:M.article.meta.title,type:M.article.meta.type,content:M.article.content,sources:M.article.meta.sources??[],lastUpdated:M.article.meta.lastUpdated,previous:A(M)})),O=R.map(M=>o(M,h,ae=>b.get(ae)??[])),I=new Set(S.map(M=>M.key)),D=d.flatMap(M=>n(y.filter(ae=>ae.agent===M).map(ae=>({path:ae.key,title:ae.article.meta.title,type:ae.article.meta.type,sources:ae.article.meta.sources})),I)),P=[];if(e.judge){let M;try{M=cd(e.judgeModel)}catch(de){console.log(m.red(` ${de.message}`)),process.exitCode=1;return}let ae=F(g.getBaseDir(),"_tmp");Kt(ae,{recursive:!0});let Ie=R.map((de,j)=>({a:de,i:j}));await Promise.all(Array.from({length:Math.min(3,Ie.length)},async()=>{for(let de=Ie.shift();de;de=Ie.shift()){let{a:j,i:we}=de,ot=j.sources.map(Ne=>h.get(Ne)).filter(Ne=>!!Ne),Qt=F(ae,`absorb-eval-${process.pid}-${we}.txt`);Pt(Qt,s(j,ot));try{let{stdout:Ne}=await wb(`cat '${Qt}' | claude -p - --output-format json --max-turns 1 --model '${M}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Eo(),encoding:"utf-8",timeout:3e5,maxBuffer:4194304}),_e=Ne;try{_e=JSON.parse(Ne).result??Ne}catch{}let mo=r(l(_e));mo?P.push({path:j.path,verdict:mo}):console.error(m.yellow(` judge reply for ${j.path} was not usable`))}catch(Ne){console.error(m.yellow(` judge failed for ${j.path}: ${String(Ne?.message??Ne).slice(0,160)}`))}finally{hd(Qt,{force:!0})}}})),P.sort((de,j)=>de.path.localeCompare(j.path))}let J=new Set(y.flatMap(M=>M.article.meta.sources??[])),W=[];for(let M of d){let ae=F(g.getBaseDir(),"agents",M,"_absorbed.json");if(!Ze(ae))continue;let Ie={};try{Ie=JSON.parse(Dt(ae,"utf-8")).entries??{}}catch{continue}for(let[de,j]of Object.entries(Ie)){if(J.has(de)||u&&String(j.at??"")<u)continue;let we=h.get(de);we&&W.push(we)}}let V=y.map(M=>M.article.content).join(`
|
|
567
|
-
`),X=c(W,V),Ce=i(O,D,{seed:x,since:u||void 0},P,5,{entries:W.length,lost:X}),Ge=a(Ce);e.out&&Pt(e.out,Ge),e.json?console.log(JSON.stringify({card:Ce,checks:O},null,2)):e.out?console.log(m.green(` scorecard written to ${e.out}`)):console.log(Ge)});H.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-VXS572PQ.js"),n=F(ft(e.dir),t);if(!Ze(n)){console.log(m.yellow(` no queries recorded yet (${n})`));return}let s=o(Dt(n,"utf-8"),typeof e.since=="string"?e.since.trim():void 0);if(e.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(m.bold(` ${s.total} queries \xB7 ${s.failed} failed \xB7 p50 ${(s.wallMsP50/1e3).toFixed(1)} s \xB7 p95 ${(s.wallMsP95/1e3).toFixed(1)} s`));for(let[r,i]of Object.entries(s.byStatus).sort((a,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()});H.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-
|
|
568
|
-
`).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(g=>g[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,g)=>l.padEnd(a[g])).join(" "));console.log()});H.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=YR(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-
|
|
567
|
+
`),X=c(W,V),Ce=i(O,D,{seed:x,since:u||void 0},P,5,{entries:W.length,lost:X}),Ge=a(Ce);e.out&&Pt(e.out,Ge),e.json?console.log(JSON.stringify({card:Ce,checks:O},null,2)):e.out?console.log(m.green(` scorecard written to ${e.out}`)):console.log(Ge)});H.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-VXS572PQ.js"),n=F(ft(e.dir),t);if(!Ze(n)){console.log(m.yellow(` no queries recorded yet (${n})`));return}let s=o(Dt(n,"utf-8"),typeof e.since=="string"?e.since.trim():void 0);if(e.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(m.bold(` ${s.total} queries \xB7 ${s.failed} failed \xB7 p50 ${(s.wallMsP50/1e3).toFixed(1)} s \xB7 p95 ${(s.wallMsP95/1e3).toFixed(1)} s`));for(let[r,i]of Object.entries(s.byStatus).sort((a,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()});H.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-MT3ZDYBM.js"),o=F(ft(e.dir),"_absorb-runs.jsonl");if(!Ze(o)){console.log(m.yellow(` no absorb runs recorded yet (${o})`));return}let n=Dt(o,"utf-8").split(`
|
|
568
|
+
`).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(g=>g[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,g)=>l.padEnd(a[g])).join(" "));console.log()});H.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=YR(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-NJNMSOCX.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!Ze(l))console.log(m.yellow(` --reviews: no ${l}`));else{let g=new c(l,{readonly:!0});try{let d=g.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(u=>u.trim()).filter(Boolean)});let f=r.filter(u=>(u.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${r.length} candidate finding(s), ${f} seen in more than one session`));let p=r[0];p&&(p.occurrences??1)>1&&console.log(m.dim(` most recurrent (${p.occurrences} sessions): ${p.memory.description.slice(0,84)}`))}finally{g.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:g}=await import("better-sqlite3"),d=F(process.cwd(),".agentx/db.sqlite");if(!Ze(d))console.log(m.yellow(` --failures: no ${d}`));else{let f=new g(d,{readonly:!0});try{let p=c(f,{since:Date.now()-(t??6048e5)}),u=l(p,{minSessions:a});console.log(m.dim(` ${p.length} failed run(s) in window \u2192 ${u.length} failure(s) seen in ${a}+ sessions`));let h=u[0];h&&console.log(m.dim(` most recurrent (${h.occurrences} sessions, ${h.failure.runs} runs): ${h.memory.description.slice(0,84)}`)),r=[...r,...u]}finally{f.close()}}}let i=await pu({extraCandidates:r,wikiDir:e.dir?F(e.dir):void 0,memoryRoot:e.memoryDir?F(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 Sa=H.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Aa(e){return e?F(e):F(process.cwd(),".agentx","wiki")}Sa.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(Aa(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}`))}});Sa.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(Aa(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(`
|
|
569
569
|
`).map(s=>` ${s}`).join(`
|
|
570
|
-
`)),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>)`))}});Sa.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-
|
|
570
|
+
`)),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>)`))}});Sa.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-OUSVJZ64.js"),n=o(Aa(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`))});Sa.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-OUSVJZ64.js"),n=o(Aa(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 YR(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)}H.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",F(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-QVK5EN3P.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:r,join:i}=await import("path"),a=$e(e.dir),c=e.agent;if(!c){console.log(m.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),g=parseInt(e.n),d=r(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let f=[],p=o(d).sort().reverse();for(let y of p){let b=i(d,y),$=[];try{$=o(b).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of $){if(f.length>=g)break;try{let x=JSON.parse(n(i(b,v),"utf-8")),S=x.message||x.task?.message;typeof S=="string"&&S.trim().length>10&&f.push({id:x.id||v.replace(".json",""),message:S.trim(),ts:x.at||x.timestamp||y})}catch{}}if(f.length>=g)break}if(f.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${f.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 u=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${f.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let y=0;y<f.length;y++){let b=f[y];process.stdout.write(m.dim(` [${y+1}/${f.length}] querying... `));let v=l.findRelevant(b.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
|
|
571
571
|
`)||"_(none returned)_",x;try{let S=await t(b.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(A=>`\`${A.title}\` [${A.type||"?"}]`).join(", ");x=`**Answer:**
|
|
572
572
|
|
|
573
573
|
${S.answer}
|
|
@@ -584,14 +584,14 @@ Q: ${j.q}
|
|
|
584
584
|
A: ${j.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",$||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${d}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
|
|
585
585
|
`),x=F(a.baseDir,"_tmp");Kt(x,{recursive:!0});let S=F(x,`interview-${o().slice(0,8)}.txt`);Pt(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"`,we=Tn(j,{env:Eo(),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let ot=JSON.parse(we);k=String(ot.result||ot.content||"")}catch{k=we}}catch(j){console.log(m.red(` synthesis failed: ${j.message?.slice(0,200)}`)),c?.close();return}k=k.trim();let A=k.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);A&&(k=A[1].trim());let R=k.indexOf("---");R>0&&(k=k.slice(R));let O=k.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!O){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(k.slice(0,600)),c?.close();return}let I={};for(let j of O[1].split(`
|
|
586
586
|
`)){let we=j.match(/^(\w+):\s*(.+)$/);we&&(I[we[1]]=we[2].trim().replace(/^"(.*)"$/,"$1"))}let D=O[2],P=I.title||g,J=P.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),V=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${J}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${V}`)),console.log(),console.log(k),console.log();let X=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),X==="scrap"||X==="/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 Ce=D,Ge={title:P,type:I.type||d,related:I.related?I.related.replace(/^\[|\]$/g,"").split(",").map(j=>j.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:I.tags?I.tags.replace(/^\[|\]$/g,"").split(",").map(j=>j.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:I.access||"public",created:I.created||new Date().toISOString().slice(0,10),lastUpdated:I.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(X==="edit"){let j=process.env.EDITOR||"vi",we=F(x,`draft-${o().slice(0,8)}.md`);Pt(we,k);try{Tn(`${j} '${we}'`,{stdio:"inherit"});let Qt=Dt(we,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Qt){let Ne={};for(let _e of Qt[1].split(`
|
|
587
|
-
`)){let mo=_e.match(/^(\w+):\s*(.+)$/);mo&&(Ne[mo[1]]=mo[2].trim().replace(/^"(.*)"$/,"$1"))}Ce=Qt[2],Ge={...Ge,title:Ne.title||Ge.title,type:Ne.type||Ge.type,access:Ne.access||Ge.access,related:Ne.related?Ne.related.replace(/^\[|\]$/g,"").split(",").map(_e=>_e.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Ge.related,tags:Ne.tags?Ne.tags.replace(/^\[|\]$/g,"").split(",").map(_e=>_e.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Ge.tags}}}catch(ot){console.log(m.red(` editor failed: ${ot.message}`));return}}if(!a.writeArticle(V,Ge,Ce,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${V} saved.`));let ae=a.extractWikilinks(Ce),Ie=new Map;for(let j of a.listArticles(e.agent))Ie.set(j.meta.title.toLowerCase(),!0);let de=ae.filter(j=>!Ie.has(j.toLowerCase()));if(de.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let j of de.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.`))}});H.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-
|
|
587
|
+
`)){let mo=_e.match(/^(\w+):\s*(.+)$/);mo&&(Ne[mo[1]]=mo[2].trim().replace(/^"(.*)"$/,"$1"))}Ce=Qt[2],Ge={...Ge,title:Ne.title||Ge.title,type:Ne.type||Ge.type,access:Ne.access||Ge.access,related:Ne.related?Ne.related.replace(/^\[|\]$/g,"").split(",").map(_e=>_e.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Ge.related,tags:Ne.tags?Ne.tags.replace(/^\[|\]$/g,"").split(",").map(_e=>_e.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Ge.tags}}}catch(ot){console.log(m.red(` editor failed: ${ot.message}`));return}}if(!a.writeArticle(V,Ge,Ce,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${V} saved.`));let ae=a.extractWikilinks(Ce),Ie=new Map;for(let j of a.listArticles(e.agent))Ie.set(j.meta.title.toLowerCase(),!0);let de=ae.filter(j=>!Ie.has(j.toLowerCase()));if(de.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let j of de.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.`))}});H.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-QVK5EN3P.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=$e(e.dir);if(e.commit!==!1&&On(s,e.agent))return;let r;try{r=s.getAgentWiki(e.agent)}catch(p){console.log(m.red(` can't open wiki for agent "${e.agent}": ${p.message}`));return}let i=null;if(e.script){let u=Dt(e.script,"utf-8").split(/\n\s*\n/).map(h=>h.trim()).filter(Boolean);i=[];for(let h of u){let y=h.split(/\r?\n/).filter(v=>v.trim());if(y.length<2)continue;let b=y[0].replace(/^Q:\s*/i,"").trim(),$=y.slice(1).join(" ").trim();b&&$&&i.push({q:b,verdict:$})}}let a=i?null:t.createInterface({input:process.stdin,output:process.stdout}),c=async p=>a?(await a.question(p)).trim():"",l=Math.min(parseInt(e.rounds)||20,i?.length??999),g=e.commit!==!1;console.log(),console.log(m.bold(" Wiki Quiz")),console.log(m.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${g?"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=[],f=0;for(let p=0;p<l;p++){let u,h;if(i){let W=i[p];if(!W)break;u=W.q,h=W.verdict,console.log(m.cyan(` [${p+1}] Q: `)+u)}else{if(u=await c(m.cyan(` [${p+1}] Q: `)),!u||u==="/done"||u==="/abort")break;h=""}process.stdout.write(m.dim(" querying... "));let y;try{y=await n(u,r,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(W){console.log(m.red(`failed: ${W.message?.slice(0,120)}`));continue}if(console.log(m.dim("done")),y.status!=="ok")console.log(m.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let W=y.citations.map(V=>`${V.title} [${V.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+y.answer.replace(/\n/g,`
|
|
588
588
|
`)),console.log(m.dim(" citations: "+W))}i||(h=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+h);let b={q:u,answer:y.answer,citations:y.citations,verdict:h},$=h.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!$){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(b);continue}let v=$[1].toLowerCase(),x=($[2]||"").trim();if(d.push(b),v==="/ok"||v==="/skip")continue;if(!x){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let S=y.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let k=r.readArticle(S.path);if(!k){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let A=QR(k.content,v,x,k.meta.title,k.meta.type),R=F(r.baseDir,"_tmp");Kt(R,{recursive:!0});let O=F(R,`quiz-patch-${o().slice(0,8)}.txt`);Pt(O,A);let I="";try{let W=`cat '${O}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,V=Tn(W,{env:Eo(),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ce=JSON.parse(V);I=String(Ce.result||Ce.content||"")}catch{I=V}let X=I.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);X&&(I=X[1].trim()),I=I.trim()}catch(W){console.log(m.red(` patch failed: ${W.message?.slice(0,120)}`));continue}if(!I||I.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let D=k.content.split(`
|
|
589
589
|
`).length,P=I.split(`
|
|
590
590
|
`).length;if(console.log(m.dim(` diff: ${D} \u2192 ${P} lines (${P-D>=0?"+":""}${P-D})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),b.patched=S.path+" (dry)";continue}if(!r.writeArticle(S.path,{...k.meta,lastUpdated:new Date().toISOString().slice(0,10)},I,e.agent)){console.log(m.red(" write failed (permission?)"));continue}f++,b.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),f>0&&g&&r.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${f} patches applied.`)),e.out){let p=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${f} patches_`,""];for(let u=0;u<d.length;u++){let h=d[u];p.push(`## ${u+1}. Q: ${h.q}`,"",`**A:** ${h.answer}`,"",`**Citations:** ${h.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${h.verdict}\``+(h.patched?` \u2192 patched \`${h.patched}\``:""),"")}Pt(e.out,p.join(`
|
|
591
|
-
`)),console.log(m.dim(` Transcript written to ${e.out}`))}});H.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,t,o)=>{let n=$e(o.dir);if(On(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=Tr(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=F(s.baseDir,r),a=o.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${r} in ${a}...`));try{Tn(`${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,g=s.extractWikilinks(c.content).filter(p=>l.has(p)?!1:(l.add(p),!0)),d=c.meta.related||[];(g.some(p=>!d.includes(p))||d.some(p=>!g.includes(p)))&&(s.writeArticle(r,{...c.meta,related:g.length?g:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${g.length} wikilink${g.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 KR(){let{loadDaemonConfig:e}=await import("./config-
|
|
591
|
+
`)),console.log(m.dim(` Transcript written to ${e.out}`))}});H.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,t,o)=>{let n=$e(o.dir);if(On(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=Tr(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=F(s.baseDir,r),a=o.editor||process.env.EDITOR||"vi";console.log(m.dim(` opening ${r} in ${a}...`));try{Tn(`${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,g=s.extractWikilinks(c.content).filter(p=>l.has(p)?!1:(l.add(p),!0)),d=c.meta.related||[];(g.some(p=>!d.includes(p))||d.some(p=>!g.includes(p)))&&(s.writeArticle(r,{...c.meta,related:g.length?g:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(m.dim(` (synced frontmatter.related from body: ${g.length} wikilink${g.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 KR(){let{loadDaemonConfig:e}=await import("./config-WCEFYQL4.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 VR(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}`))}H.command("curate <agent> <titleOrPath> <instruction>").description("ask the page curator agent to research and edit one page (needs the daemon)").option("--dir <path>","wiki directory").option("--timeout <minutes>","stop waiting after this long","30").action(async(e,t,o,n)=>{let s=$e(n.dir);if(On(s,e))return;let r=Tr(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 KR(),c=async(f,p,u)=>{let h=await fetch(i+p,{method:f,headers:a,...u?{body:JSON.stringify(u)}:{}}),y=await h.json().catch(()=>({}));if(!h.ok)throw new Error(y.error||`HTTP ${h.status}`);return y},l;try{l=await c("POST","/api/wiki/curate",{agent:e,path:r,message:o})}catch(f){console.log(m.red(` ${f.message?.includes("fetch failed")?`the daemon at ${i} is not running`:f.message}`)),process.exitCode=1;return}console.log(m.dim(` ${l.curator} is working on ${r}\u2026`));let g=`?agent=${encodeURIComponent(e)}&path=${encodeURIComponent(r)}`,d=Date.now()+Number(n.timeout||30)*6e4;for(;Date.now()<d;){await new Promise(u=>setTimeout(u,2e3));let p=(await c("GET",`/api/wiki/curate${g}`).catch(()=>null))?.messages?.find(u=>u.id===l.id);if(!(!p||p.status==="pending")){console.log(p.status==="error"?m.red(` ${p.text}`):` ${p.text}`),p.edit&&(p.edit.added||p.edit.removed)&&VR(p.edit),p.status==="error"&&(process.exitCode=1);return}}console.log(m.yellow(" still working; the result will show in the chat on the page."))});H.command("versions <agent> <titleOrPath>").description("list the saved earlier versions of one page, newest first").option("--dir <path>","wiki directory").action((e,t,o)=>{let n=$e(o.dir).getAgentWiki(e),s=Tr(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}`)});H.command("restore <agent> <titleOrPath> [version]").description("put a page back to an earlier version (default: the newest); the current text is kept as a version").option("--dir <path>","wiki directory").action((e,t,o,n)=>{let s=$e(n.dir);if(On(s,e))return;let r=s.getAgentWiki(e),i=Tr(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 Eg))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}.`))});H.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-WCEFYQL4.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-LW366SKL.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"}`)});H.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").option("--allow-fact-loss","save even when the patch shrinks the article or drops a phone number, email, role, link or number it had").action(async(e,t,o,n)=>{let s=await import("node:readline/promises"),{randomUUID:r}=await import("node:crypto"),i=$e(n.dir);if(On(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=Tr(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 g=XR(l.content,l.meta.title,l.meta.type,o),d=F(a.baseDir,"_tmp");Kt(d,{recursive:!0});let f=F(d,`patch-${r().slice(0,8)}.txt`);Pt(f,g),console.log(),console.log(m.dim(` Target: ${l.meta.title} (${c})`)),console.log(m.dim(` Patching with ${n.patchModel}...`));let p="";try{let x=`cat '${f}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,S=Tn(x,{env:Eo(),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let A=JSON.parse(S);p=String(A.result||A.content||"")}catch{p=S}let k=p.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(p=k[1].trim()),p=p.trim()}catch(x){console.log(m.red(` patch failed: ${x.message?.slice(0,150)}`));return}if(!p||p.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let u=l.content.split(`
|
|
592
592
|
`).length,h=p.split(`
|
|
593
|
-
`).length;console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${u} \u2192 ${h} lines (${h-u>=0?"+":""}${h-u})`)),console.log(),console.log(p),console.log();let y=Pp(l.content,p);if(y.length){for(let x of y)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 b=!!n.yes;if(!b){let x=s.createInterface({input:process.stdin,output:process.stdout}),S=(await x.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),b=S==="y"||S==="yes"}if(!b){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 $=[...new Set([...l.meta.related||[],...a.extractWikilinks(p)])];if(!a.writeArticle(c,{...l.meta,related:$.length?$:void 0,lastUpdated:new Date().toISOString().slice(0,10)},p,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${c} patched.`))});var fb=H.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-
|
|
594
|
-
agentx wiki contributions approve <id> \xB7 agentx wiki contributions reject <id>`)),console.log()});Cr.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-
|
|
593
|
+
`).length;console.log(),console.log(m.bold(" === Patched preview ===")),console.log(m.dim(` diff: ${u} \u2192 ${h} lines (${h-u>=0?"+":""}${h-u})`)),console.log(),console.log(p),console.log();let y=Pp(l.content,p);if(y.length){for(let x of y)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 b=!!n.yes;if(!b){let x=s.createInterface({input:process.stdin,output:process.stdout}),S=(await x.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();x.close(),b=S==="y"||S==="yes"}if(!b){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 $=[...new Set([...l.meta.related||[],...a.extractWikilinks(p)])];if(!a.writeArticle(c,{...l.meta,related:$.length?$:void 0,lastUpdated:new Date().toISOString().slice(0,10)},p,e)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${c} patched.`))});var fb=H.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-MUCJKT73.js"),o=$e(e.dir),n=ft(e.dir),s={},r={};try{let{loadDaemonConfig:d}=await import("./config-WCEFYQL4.js"),f=d();s=Object.fromEntries(Object.entries(f.agents||{}).map(([p,u])=>[p,u.wiki?.contribute])),r=f.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=F(process.cwd(),e.db);if(Ze(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(f,p)=>{let u=F(n,"_tmp");Kt(u,{recursive:!0});let h=F(u,`contribute-${process.pid}-${Date.now()}.txt`);Pt(h,f);try{let{stdout:y}=await wb(`cat '${h}' | claude -p - --output-format json --max-turns 1 --max-budget-usd ${p.toFixed(2)} --model ${d} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Eo(),timeout:18e4,maxBuffer:4194304});try{let b=JSON.parse(y);return{text:String(b.result||b.content||""),costUsd:Nc(b).costUsd}}catch{return{text:y}}}finally{hd(h,{force:!0})}},g=[];try{for(let d of i){if(On(o,d))continue;let f=s[d],p=e.model||f?.model||r.model||process.env.AGENTX_WIKI_CONTRIBUTE_MODEL||"sonnet";try{let u=await t(o,n,d,{model:p,call:l(p),db:a,since:e.since,dryRun:!!e.dryRun,maxPatches:e.maxPatches?parseInt(e.maxPatches):f?.maxPatches,maxCostUsd:e.maxCost?parseFloat(e.maxCost):f?.maxCostUsd??r.maxCostUsd,maxItems:parseInt(e.maxItems)});if(g.push(u),e.json)continue;let h=u.stoppedBy?m.yellow(` \xB7 stopped at ${u.stoppedBy}`):"";console.log(` ${m.cyan(d)}: ${u.patches.length} patch(es) from ${u.workIds.length} item(s) of work \xB7 $${u.costUsd.toFixed(4)}${h}${e.dryRun?m.dim(" \xB7 dry run, not queued"):""}`);for(let y of u.patches){let b=y.attribute?`${y.attribute}: ${y.previous?`${y.previous} \u2192 `:""}${y.value??""}`:y.summary??"";console.log(m.dim(` ${y.kind.padEnd(8)} ${y.page} \xB7 ${b} (${y.source}, ${y.checkedAt.slice(0,10)})`))}}catch(u){console.log(m.red(` ${d}: ${u.message?.slice(0,200)}`)),process.exitCode=1}}}finally{a?.close()}e.json?console.log(JSON.stringify(g,null,2)):!e.dryRun&&g.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]])fb.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-NRHZ2XH3.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={...fb.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 Cr=H.command("contributions").description("the daily merge of agents' wiki patches (list, merge, held, approve, reject)");Cr.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-MUCJKT73.js"),s=ft(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()});Cr.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-MUCJKT73.js"),o=t($e(e.dir),ft(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()});Cr.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-MUCJKT73.js"),o=t(ft(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(`
|
|
594
|
+
agentx wiki contributions approve <id> \xB7 agentx wiki contributions reject <id>`)),console.log()});Cr.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-MUCJKT73.js"),n=o($e(t.dir),ft(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.`))});Cr.command("reject <id>").description("drop a held patch").option("--dir <path>","wiki directory").action(async(e,t)=>{let{rejectHeld:o}=await import("./contributions-MUCJKT73.js"),n=o(ft(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 Tr(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`,g=s.find(d=>d.path===l||d.path===n);if(g)return g.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let g=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return g===a||g.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function XR(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(`
|
|
595
595
|
`)}function QR(e,t,o,n,s){let r={"/correct":`The operator says the article contains an error:
|
|
596
596
|
|
|
597
597
|
${o}
|
|
@@ -646,17 +646,17 @@ Output (JSON array, one entry per input article, same order):
|
|
|
646
646
|
[
|
|
647
647
|
{"path": "path/to/article.md", "type": "project"},
|
|
648
648
|
...
|
|
649
|
-
]`}H.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=$e(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});H.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||F(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=await bb(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(),Tp(t,o,e.agent,n,e.mode)});H.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-
|
|
649
|
+
]`}H.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=$e(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(m.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${m.dim(s.date)} ${m.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(m.dim(` ... showing last 20 of ${n.length}`)),console.log()});H.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||F(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=await bb(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(),Tp(t,o,e.agent,n,e.mode)});H.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-CAYDECW2.js"),c=$e(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),f=[];e:for(let y of l){let b=c.getAgentWiki(y);for(let $ of b.listArticles(y)){if(f.length>=g)break e;let v=b.readArticle($.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:$.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),x,{links:[{kind:"article",id:$.path}],features:{agent:y,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),A=e.fields?i(v.meta.type,S.answers):null;k.completeness>=d&&!(A&&!A.fit)||f.push({agent:y,type:v.meta.type??"?",score:k.completeness.toFixed(2),standsAlone:k.standsAlone.toFixed(2),gap:k.biggestGap,...A?{missing:A.missingCritical.join(",")||"-",cov:`${Math.round(A.coverage*100)}%`}:{},title:v.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(f,null,2));return}if(f.length===0){console.log(m.green(" no articles below the threshold"));return}f.sort((y,b)=>parseFloat(y.score)-parseFloat(b.score));let p=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],u=p.map(y=>Math.max(y.length,...f.map(b=>String(b[y]).length))),h=y=>y.map((b,$)=>String(b).padEnd(u[$])).join(" ");console.log(),console.log(m.bold(h(p)));for(let y of f)console.log(h(p.map(b=>y[b])));if(e.fields){let y=f.filter(b=>b.missing!=="-").length;console.log(m.dim(`
|
|
650
650
|
${f.length} article(s) flagged; ${y} missing a required field.`)),console.log(m.dim(" 'missing' is the actionable column \u2014 a named field beats a score."))}else console.log(m.dim(`
|
|
651
|
-
${f.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."))});H.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-
|
|
651
|
+
${f.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."))});H.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-QVK5EN3P.js"),{noteSourceFor:n}=await import("./query-settings-2TNLXEL5.js"),{QUERY_RUNS_FILE:s,queryFailed:r,recordQueryRun:i,timedQuery:a}=await import("./query-runs-VXS572PQ.js"),c=await kb(t);if(!c)return;let l=$e(t.dir),g=t.agent?[t.agent]:l.listAgents(),d=F(l.getBaseDir(),s),f=Date.now(),p=t.agent||process.env.AGENTX_AGENT_ID,u=p&&!t.ownOnly&&await pb()?p:null;for(let v of u?[]:g){let x=l.getAgentWiki(v),S=F(x.baseDir,"_index.md");try{if((await import("fs")).existsSync(S)){u=v;break}}catch{}}if(!u){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first.")),i(d,{at:new Date().toISOString(),agent:p||"",status:"no-catalog",source:"cli",wallMs:Date.now()-f}),process.exitCode=1;return}let h=u,y=l.getAgentWiki(h),b=t.ownOnly||!await pb()?void 0:l.sharedScope(h),$=await a(d,h,"cli",()=>o(e,y,h,{selectorModel:t.selectorModel,synthModel:t.synthModel,maxCandidates:parseInt(t.maxCandidates),maxHops:parseInt(t.maxHops),maxArticles:parseInt(t.maxArticles),shared:b,method:c.method,summaries:c.summaries,notes:n(c,h)}));if(r($.status)&&(process.exitCode=1),t.json){console.log(JSON.stringify($,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${u} \xB7 status: ${$.status} \xB7 walked: ${$.walked.length}`)),console.log(),$.status!=="ok"){console.log(m.yellow(` (no answer) ${$.error||$.status}`));return}if(console.log($.answer),console.log(),$.basis==="search"&&(console.log(m.dim(" No wiki page was used: the answer comes from a search at the source.")),console.log()),$.citations.length){console.log(m.dim(" Citations:"));for(let v of $.citations){let x=v.type?m.magenta(` [${v.type}]`):"";console.log(m.dim(` - ${v.title}${x} (${v.path})`))}console.log()}if($.live?.length){console.log(m.dim(" Read live at the source:"));for(let v of $.live)console.log(m.dim(` - ${v.line}`));console.log()}if(t.trace&&$.trace){if($.method==="summaries"&&console.log(m.dim(` method: summaries live reads: ${$.liveAsked??0} asked, ${$.live?.length??0} answered plan: ${$.trace.planMs??0}ms reads: ${$.trace.liveMs??0}ms`)),console.log(m.dim(` selector: ${$.trace.selectorMs}ms synthesis: ${$.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${$.candidates.map(v=>v.title).join(" | ")||"(none)"}`)),$.walked.length>$.candidates.length){let v=$.walked.filter(x=>!$.candidates.some(S=>S.path===x.path));console.log(m.dim(` followed: ${v.map(x=>`${x.title}@h${x.hop}`).join(" | ")}`))}console.log()}});H.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(R=>JSON.parse(Dt(F(R),"utf-8"))),A=n(S,k);if(e.json){console.log(JSON.stringify(A,null,2));return}console.log(),console.log(m.bold(` ${r(A.before)} \u2192 ${r(A.after)}`)),console.log(m.dim(` before: ${c(A.cost.before)}`)),console.log(m.dim(` after: ${c(A.cost.after)}`)),A.changed==="unknown"?console.log(m.yellow(" ! A report records no settings, so what changed between the runs is unknown.")):(console.log(m.dim(` changed: ${A.changed.join("; ")||"nothing"}`)),A.changed.length>1&&console.log(m.yellow(" ! More than one setting changed: the difference can't be put down to one of them."))),(A.onlyBefore.length||A.onlyAfter.length)&&console.log(m.yellow(` ! The runs asked different questions. Only before: ${A.onlyBefore.join(", ")||"none"}. Only after: ${A.onlyAfter.join(", ")||"none"}.`));for(let R of A.deltas){if(R.before===R.after)continue;let O=R.after>R.before?m.green("\u25B2"):m.red("\u25BC");console.log(` ${O} ${R.id} ${r(R.before)} \u2192 ${r(R.after)} ${m.dim(R.question.slice(0,80))}`),R.gained.length&&console.log(m.green(` + ${R.gained.join(", ")}`)),R.lost.length&&console.log(m.red(` - ${R.lost.join(", ")}`))}console.log();return}if(!e.questions){console.log(m.red(" --questions <file> is required (or --compare before.json after.json).")),process.exitCode=1;return}let 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 g=t(Dt(F(e.questions),"utf-8")),{agenticQuery:d,CATALOG_SELECTOR_MODEL:f,CATALOG_SYNTH_MODEL:p}=await import("./query-QVK5EN3P.js"),{noteSourceFor:u}=await import("./query-settings-2TNLXEL5.js"),{meteredModelCall:h}=await import("./model-call-HMVMUAXS.js"),y=await kb(e);if(!y)return;let b=$e(e.dir),$=!e.ownOnly,v=[];for(let S of g){let k={calls:0,usd:0,unpriced:0},A=Date.now(),R=await d(S.question,b.getAgentWiki(l),l,{selectorModel:e.selectorModel,synthModel:e.synthModel,shared:$?b.sharedScope(l):void 0,method:y.method,summaries:y.summaries,notes:u(y,l),call:h(k)}),O=Date.now()-A,I=R.method==="summaries"&&k.unpriced===0?k.usd:void 0;v.push({q:S,answer:R.answer||R.error||"",status:R.status,citations:R.citations.map(D=>D.path),method:R.method??"catalog",ms:O,costUsd:I}),e.json||process.stderr.write(m.dim(` ${S.id} ${R.status} ${i(O)} ${a(I)}
|
|
652
652
|
`))}let x=o({questions:e.questions,agent:l,shared:$,settings:{method:y.method,linkedPages:y.summaries.linkedPages,linkedChars:y.summaries.linkedChars,live:y.summaries.live.enabled,notes:y.notes.enabled,navigatorModel:e.selectorModel??y.summaries.navigatorModel,answerModel:e.synthModel??y.summaries.answerModel,catalogSelectorModel:e.selectorModel??f,catalogSynthModel:e.synthModel??p}},v);if(e.out&&Pt(F(e.out),`${JSON.stringify(x,null,2)}
|
|
653
653
|
`),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${$?"":" (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(`
|
|
654
|
-
report saved to ${e.out}`)),console.log()});H.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,t)=>{let o=$e(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let r of n){let a=await o.getAgentWiki(r).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(r)}:`));for(let 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()});H.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let t=$e(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Ze(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Ro({baseDir:n}),r=s.loadIndex(),i=new Map;for(let[d,f]of Object.entries(r.entries))i.set(d,f.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,g=0;for(let d of o){let f=t.getAgentWiki(d),p=f.listArticles(d),u=t.getSharedStore().listEntries(),h=new Map(u.map(v=>[v.id,v])),y=0,b=0,$=0;for(let v of p){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let x=new Map;for(let k of v.meta.sources){let A=h.get(k);if(!A)continue;let R=String(A.meta?.sender??""),O=s.fingerprint({text:A.content,channel:A.source,sender:R}),I=i.get(O);if(!I?.length)continue;let D=I.join("/"),P=x.get(D);P?P.n++:x.set(D,{path:I,n:1})}if(x.size===0)continue;b++,l++;let S;for(let k of x.values())(!S||k.n>S.n)&&(S=k);S&&(e.dryRun||(f.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),$++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(p.length)} articles \xB7 ${y} eligible \xB7 ${b} matched \xB7 ${m.green($)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});H.command("sync").description("pull raw entries from mesh peers into local wiki, or with --articles copy their agents' articles (read-only)").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--articles","copy the articles of agents this node does not run, instead of raw entries").option("--dry-run","show what would be synced without writing").action(async e=>{let t=$e(e.dir),o=t.getSharedStore(),n=await bb(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 $b();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 g of l.agents){if(g.skipped==="local"){console.log(m.dim(` ${g.agentId}: runs here, not copied`));continue}if(g.skipped){console.log(m.yellow(` ${g.agentId}: skipped (${g.skipped})`));continue}let d=[`${g.copied} ${e.dryRun?"to copy":"copied"}`,`${g.unchanged} unchanged`];g.removed&&d.push(`${g.removed} removed (gone on the peer)`),g.rejected&&d.push(`${g.rejected} refused`),console.log(` ${m.cyan(g.agentId)}: ${d.join(", ")}${g.error?m.red(` \u2014 stopped: ${g.error}`):""}`),g.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 g=await l.json(),d=g.entries||[],f=g.nodeId||"unknown";console.log(m.dim(` Node: ${f} \u2014 ${d.length} entries`));let p=0;for(let u of d)s.has(u.id)||(e.dryRun||(o.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${f}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),p++);p>0?console.log(m.green(` ${p} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),r+=p;try{let u=await fetch(`${i}/wiki/agents`,{headers:c,signal:AbortSignal.timeout(5e3)});if(u.ok){let h=await u.json();for(let y of h.agents||[])y.totalEntries>0&&console.log(m.dim(` ${y.agentId}: ${y.totalEntries} entries, ${y.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()});H.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||F(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new ec(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),f=l.getAgentEntries(o),p=l.getUnabsorbedEntries(o),u=new Set,h=0,y=new Set;for(let $ of d.articles){for(let v of $.tags||[])u.add(v);h+=$.tags?.length||0;for(let v of $.sources||[])y.add(v)}let b=new Set(d.articles.map($=>$.path.includes("/")?$.path.split("/")[0]:"/"));return{mode:c,label:yd(c),articles:d.articles.length,entries:f.length,unabsorbed:p.length,uniqueTags:u.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:b.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${o}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let r=22;console.log(` ${"".padEnd(20)} ${s.map(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 g=s.map(d=>l(d).padEnd(r));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(f=>f[c])),d=s.filter(f=>f[c]===g).map(f=>f.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});H.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?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ze(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),r=F(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:g}=await import("fs"),d=Ze(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${tC(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});H.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-OSYVYKBK.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=$e(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),f=parseInt(e.limit),p=0,u=[];e:for(let k of d){let A=l.getAgentWiki(k);for(let R of A.listArticles(k)){if(p>=f)break e;let O=A.readArticle(R.path);if(!O||e.type&&O.meta.type!==e.type)continue;p++;let I=await a(i,n({title:O.meta.title,type:O.meta.type,body:O.content}),t(O.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:k,type:O.meta.type??"?"}});if(!I){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=o(O.meta.type,I.answers);for(let P of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&P.needsHuman||(e.ask&&P.needsHuman&&g.push({kind:"field",agentId:k,path:R.path,subject:O.meta.title,field:P.field,tier:P.tier,question:`${O.meta.title} (${O.meta.type??"?"}) \u2014 ${P.label}?`}),u.push({tier:P.tier,need:P.field,how:P.needsHuman?m.yellow("ask"):P.sources.join("/"),uncertain:P.uncertain?"?":"",agent:k,article:O.meta.title.slice(0,40)}))}}let h={added:0,skipped:0};if(e.ask&&g.length>0&&(h=new c(ft(e.dir)).add(g)),e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(` ${p} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],b=k=>String(k).replace(/\u001b\[[0-9;]*m/g,""),$=y.map(k=>Math.max(k.length,...u.map(A=>b(A[k]).length))),v=(k,A)=>String(k)+" ".repeat(Math.max(0,$[A]-b(k).length));console.log(),console.log(m.bold(y.map((k,A)=>v(k,A)).join(" ")));for(let k of u)console.log(y.map((A,R)=>v(k[A],R)).join(" "));let x=u.filter(k=>k.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${u.length} gap(s) across ${p} article(s).`)),console.log(m.dim(` ${x} can be closed by a lookup; ${u.length-x} need a person.`));let S=u[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${r[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:k}=await import("./article-fields-PITN4NHA.js"),A=k[e.notifyTier]??k.pillar,R=g.filter(O=>(k[O.tier??"furniture"]??9)<=A);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:O}=await import("./config-HHNGJKVW.js"),I=O(),D=I?.notifications?.destination;if(!D?.channel||!D?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let P=R.slice(0,10).map(X=>`\u2022 ${X.question}`).join(`
|
|
654
|
+
report saved to ${e.out}`)),console.log()});H.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action(async(e,t)=>{let o=$e(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let r of n){let a=await o.getAgentWiki(r).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(r)}:`));for(let 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()});H.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let t=$e(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=F(process.cwd(),".agentx/graph");if(!Ze(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Ro({baseDir:n}),r=s.loadIndex(),i=new Map;for(let[d,f]of Object.entries(r.entries))i.set(d,f.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,g=0;for(let d of o){let f=t.getAgentWiki(d),p=f.listArticles(d),u=t.getSharedStore().listEntries(),h=new Map(u.map(v=>[v.id,v])),y=0,b=0,$=0;for(let v of p){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;y++,c++;let x=new Map;for(let k of v.meta.sources){let A=h.get(k);if(!A)continue;let R=String(A.meta?.sender??""),O=s.fingerprint({text:A.content,channel:A.source,sender:R}),I=i.get(O);if(!I?.length)continue;let D=I.join("/"),P=x.get(D);P?P.n++:x.set(D,{path:I,n:1})}if(x.size===0)continue;b++,l++;let S;for(let k of x.values())(!S||k.n>S.n)&&(S=k);S&&(e.dryRun||(f.writeArticle(v.path,{...v.meta,graphPath:S.path},v.content,d),$++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(p.length)} articles \xB7 ${y} eligible \xB7 ${b} matched \xB7 ${m.green($)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});H.command("sync").description("pull raw entries from mesh peers into local wiki, or with --articles copy their agents' articles (read-only)").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--articles","copy the articles of agents this node does not run, instead of raw entries").option("--dry-run","show what would be synced without writing").action(async e=>{let t=$e(e.dir),o=t.getSharedStore(),n=await bb(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 $b();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 g of l.agents){if(g.skipped==="local"){console.log(m.dim(` ${g.agentId}: runs here, not copied`));continue}if(g.skipped){console.log(m.yellow(` ${g.agentId}: skipped (${g.skipped})`));continue}let d=[`${g.copied} ${e.dryRun?"to copy":"copied"}`,`${g.unchanged} unchanged`];g.removed&&d.push(`${g.removed} removed (gone on the peer)`),g.rejected&&d.push(`${g.rejected} refused`),console.log(` ${m.cyan(g.agentId)}: ${d.join(", ")}${g.error?m.red(` \u2014 stopped: ${g.error}`):""}`),g.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 g=await l.json(),d=g.entries||[],f=g.nodeId||"unknown";console.log(m.dim(` Node: ${f} \u2014 ${d.length} entries`));let p=0;for(let u of d)s.has(u.id)||(e.dryRun||(o.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${f}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),p++);p>0?console.log(m.green(` ${p} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),r+=p;try{let u=await fetch(`${i}/wiki/agents`,{headers:c,signal:AbortSignal.timeout(5e3)});if(u.ok){let h=await u.json();for(let y of h.agents||[])y.totalEntries>0&&console.log(m.dim(` ${y.agentId}: ${y.totalEntries} entries, ${y.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()});H.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||F(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new ec(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),f=l.getAgentEntries(o),p=l.getUnabsorbedEntries(o),u=new Set,h=0,y=new Set;for(let $ of d.articles){for(let v of $.tags||[])u.add(v);h+=$.tags?.length||0;for(let v of $.sources||[])y.add(v)}let b=new Set(d.articles.map($=>$.path.includes("/")?$.path.split("/")[0]:"/"));return{mode:c,label:yd(c),articles:d.articles.length,entries:f.length,unabsorbed:p.length,uniqueTags:u.size,avgTags:d.articles.length>0?(h/d.articles.length).toFixed(1):"0",dirs:b.size,coverage:y.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${o}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let r=22;console.log(` ${"".padEnd(20)} ${s.map(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 g=s.map(d=>l(d).padEnd(r));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(f=>f[c])),d=s.filter(f=>f[c]===g).map(f=>f.label);g>0&&console.log(m.dim(` Best ${l}: ${d.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});H.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?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ze(o)||(console.log(m.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?F(process.cwd(),e):F(process.cwd(),`agentx-wiki-${n}.tar.gz`),r=F(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:g}=await import("fs"),d=Ze(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${tC(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});H.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-CAYDECW2.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=$e(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),f=parseInt(e.limit),p=0,u=[];e:for(let k of d){let A=l.getAgentWiki(k);for(let R of A.listArticles(k)){if(p>=f)break e;let O=A.readArticle(R.path);if(!O||e.type&&O.meta.type!==e.type)continue;p++;let I=await a(i,n({title:O.meta.title,type:O.meta.type,body:O.content}),t(O.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:k,type:O.meta.type??"?"}});if(!I){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let D=o(O.meta.type,I.answers);for(let P of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&P.needsHuman||(e.ask&&P.needsHuman&&g.push({kind:"field",agentId:k,path:R.path,subject:O.meta.title,field:P.field,tier:P.tier,question:`${O.meta.title} (${O.meta.type??"?"}) \u2014 ${P.label}?`}),u.push({tier:P.tier,need:P.field,how:P.needsHuman?m.yellow("ask"):P.sources.join("/"),uncertain:P.uncertain?"?":"",agent:k,article:O.meta.title.slice(0,40)}))}}let h={added:0,skipped:0};if(e.ask&&g.length>0&&(h=new c(ft(e.dir)).add(g)),e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(` ${p} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let y=["tier","need","how","uncertain","agent","article"],b=k=>String(k).replace(/\u001b\[[0-9;]*m/g,""),$=y.map(k=>Math.max(k.length,...u.map(A=>b(A[k]).length))),v=(k,A)=>String(k)+" ".repeat(Math.max(0,$[A]-b(k).length));console.log(),console.log(m.bold(y.map((k,A)=>v(k,A)).join(" ")));for(let k of u)console.log(y.map((A,R)=>v(k[A],R)).join(" "));let x=u.filter(k=>k.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${u.length} gap(s) across ${p} article(s).`)),console.log(m.dim(` ${x} can be closed by a lookup; ${u.length-x} need a person.`));let S=u[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${r[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${h.added} question(s) for a person (${h.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&h.added>0){let{TIER_RANK:k}=await import("./article-fields-PITN4NHA.js"),A=k[e.notifyTier]??k.pillar,R=g.filter(O=>(k[O.tier??"furniture"]??9)<=A);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:O}=await import("./config-WCEFYQL4.js"),I=O(),D=I?.notifications?.destination;if(!D?.channel||!D?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let P=R.slice(0,10).map(X=>`\u2022 ${X.question}`).join(`
|
|
655
655
|
`),J=R.length>10?`
|
|
656
656
|
\u2026and ${R.length-10} more`:"",W=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
|
|
657
657
|
${P}${J}
|
|
658
658
|
|
|
659
|
-
agentx wiki questions`,V=I?.daemon?.port??I?.port??18800;try{let X=await fetch(`http://127.0.0.1:${V}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:W})});console.log(X.ok?m.cyan(` Pushed ${R.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${X.status}) \u2014 questions are still queued.`))}catch(X){console.log(m.yellow(` Push failed (${String(X?.message??X).slice(0,80)}) \u2014 questions are still queued.`))}}}}});H.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-OSYVYKBK.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ROUMKS7I.js"),{backfillArticle:f}=await import("./backfill-7TCF4SHG.js"),p=$e(e.dir,e.mode),u=e.agent?[e.agent]:p.listAgents(),h=parseInt(e.limit),y=g(),b=c(d(p.getSharedStore().listEntries())),$=new Map(b.map(I=>[I.name.toLowerCase().trim(),I])),v=0,x=0,S=[],k=!1;e:for(let I of u){let D=p.getAgentWiki(I);for(let P of D.listArticles(I)){if(v>=h)break e;if(P.meta.type!=="person")continue;let J=D.readArticle(P.path);if(!J)continue;v++;let W=await i(s,n({title:J.meta.title,type:J.meta.type,body:J.content}),t(J.meta.type),{links:[{kind:"article",id:P.path}],features:{agent:I,op:"backfill"}});if(!W){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let X=o(J.meta.type,W.answers).missing.filter(j=>r.includes(j));if(X.length===0)continue;let{records:Ce,results:Ge}=await a([{name:J.meta.title,type:"person"}],{sources:y}),M=$.get(J.meta.title.toLowerCase().trim());if(!k){for(let j of l(Ge,y))console.log(m.yellow(` ! ${j.source} ${j.kind} \u2014 would supply ${j.provides.join(", ")}`)),console.log(m.dim(` ${j.hint}`));k=!0}let ae=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([j,we])=>[j,we.value]))}]:[],...Ce]);if(ae.length===0)continue;let{content:Ie,edits:de}=f(J.content,ae[0],X);if(de.length!==0){for(let j of de)S.push({agent:I,article:J.meta.title.slice(0,32),field:j.field,action:j.replaced?"replace":"add",got:`${j.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(P.path,J.meta,Ie,I)?x++:console.log(m.red(` could not write ${P.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 A=["agent","article","field","action","got"],R=A.map(I=>Math.max(I.length,...S.map(D=>String(D[I]).length))),O=I=>I.map((D,P)=>String(D).padEnd(R[P])).join(" ");console.log(),console.log(m.bold(O(A)));for(let I of S)console.log(O(A.map(D=>I[D])));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.")))});H.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(ft(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`))});H.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(ft(o.dir)),a=i.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!i.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let h=i.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let c=i.list("open").find(h=>h.id===e||h.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:h}=await import("./ledger-P62U3FHT.js"),y=new h(ft(o.dir));try{let b=y.get(c.factId);if(b){let $=y.write({subject:b.subject,attribute:b.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:b.volatility},{confirmedBy:"operator"});console.log(m.green(` ${$.status}: ${b.id} ${b.subject} \xB7 ${b.attribute}: ${$.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(b){b?.name!=="LedgerCorruptError"&&console.log(m.red(` ${b?.message??b}`)),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(h){console.log(m.red(` ${h?.message??h}`)),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=$e(o.dir,o.mode).getAgentWiki(l.agentId),f=d.readArticle(l.path);if(!f){console.log(m.yellow(` article gone: ${l.path}`));return}let p=s(f.content,l.field,`${t} (answered by operator)`);if(!p){console.log(m.dim(" already present \u2014 nothing to write."));return}let u=d.writeArticle(l.path,f.meta,p.content,l.agentId);console.log(u?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});H.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-OSYVYKBK.js"),{labelEntries:i,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),p=$e(e.dir,"graph").getSharedStore(),u=p.listEntries(),h=new Set(p.getUnabsorbedEntries().map(J=>J.id)),{labeled:y,backlog:b}=i(u,h),$=a(y,J=>J.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:J}=await import("fs");x.push(...JSON.parse(J(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${x.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${b} in backlog) \u2014 grading ${$.length}`));for(let J of e.load?[]:$){let W=await r(t,n(J),o,{features:{source:J.source??"",absorbed:J.absorbed}});if(!W){S++;continue}let V=W.answers;x.push({entry:J,verdict:s(W.answers,v),citeWorthy:V.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:J}=await import("fs");J(e.save,JSON.stringify(x)),console.log(m.dim(` saved ${x.length} outcome(s) to ${e.save}`))}let A=c(x,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(x,"seat","seat"),O=d(R,{minN:50}),I=((Date.now()-k)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:A,calibration:O,failures:S,elapsed:I},null,2));return}let D=J=>`${(J*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${A.n} (${A.positives} kept by absorb, ${A.negatives} passed over)`),console.log(` recall ${D(A.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D(A.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D(A.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${A.lostPositives>0?m.yellow(`lost ${A.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in O)||!O.insufficient)&&console.log(` ECE ${O.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),A.lostPositives>0){let J=A.droppedBy;console.log(m.dim(` dropped by: type ${J.type} \xB7 worth ${J.worth} \xB7 durability ${J.durability} (a positive can fail several)`))}let P=A.positiveMeans;if(console.log(m.dim(` positives avg: worth ${P.worth.toFixed(2)} \xB7 durability ${P.durability.toFixed(2)} \xB7 typeConf ${P.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${I}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let J=parseFloat(e.minRecall),{best:W,points:V}=g(x,{minRecall:J});if(console.log(),console.log(m.bold(` threshold sweep (${V.length} policies, recall floor ${D(J)})`)),W)console.log(` best: ${W.requireTyped?`typed & type>=${W.minType}`:"type gate OFF"} worth>=${W.minWorth} durability>=${W.minDurability}`),console.log(` recall ${D(W.recall)} \xB7 filtered ${D(W.filtered)} \xB7 precision ${D(W.precision)} \xB7 lost ${W.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${D(J)} recall \u2014 not even keeping everything typed.`));let X=V.slice().sort((Ce,Ge)=>Ge.recall-Ce.recall)[0];X&&console.log(m.dim(` Best recall available: ${D(X.recall)} at ${X.requireTyped?`type>=${X.minType}`:"type gate OFF"} worth>=${X.minWorth} dur>=${X.minDurability}, filtering ${D(X.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});H.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=F(process.cwd(),e);Ze(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ze(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=F(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 tC(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"}wg();import{Command as oC}from"commander";import U from"chalk";import{resolve as Ea}from"path";import{existsSync as nC}from"fs";oe();var Ts=new oC().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Ts.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=C();if(!t.graph?.enabled){console.log(U.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(U.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(U.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 Ro({baseDir:Ea(process.cwd(),t.graph.baseDir)}),i=r.listPendingClassifications(s);if(i.length===0){console.log(U.dim(" no pending classifications \u2014 nothing to review"));return}let a=r.loadSchema(),c=r.loadNodes().nodes;console.log(),console.log(U.bold(` Graph review \u2014 ${i.length} pending`)),console.log(U.dim(` Reviewer: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,f=0;for(let u=0;u<i.length;u++){let h=i[u],y=Vr(h.path,c)||h.path.join(" \u203A ");process.stdout.write(` [${u+1}/${i.length}] ${U.cyan(h.msgHash.slice(0,8))} ${U.dim(y)} ... `);let b=sC(h,a,c),$=null;try{$=await rC(n,o,b,t.dashboard?.token)}catch(S){f++,console.log(U.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!$||!$.decision){f++,console.log(U.red("ERR no decision"));continue}let v=String($.decision).toLowerCase().trim(),x=($.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(U.green("APPROVE")+" "+U.dim(x)),e.dryRun)l++;else try{iC(r,h,a,c,o),r.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:o,reviewReason:x}),l++}catch(S){console.log(U.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),f++}else v==="reject"?(console.log(U.red("REJECT")+" "+U.dim(x)),e.dryRun||r.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:o,reviewReason:x}),g++):(console.log(U.yellow("SKIP")+" "+U.dim(x||v)),d++)}console.log();let p=e.dryRun?"would":"did";console.log(U.dim(` Summary: ${p} approve ${l}, ${p} reject ${g}, ${d} skipped, ${f} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(U.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Ts.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=C();if(!t.graph){console.log(U.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=Ea(process.cwd(),t.graph.baseDir);if(!nC(o)){console.log(U.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new Ro({baseDir:o,log:()=>{}}),r=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(U.dim(" "),...a)});console.log(),console.log(U.bold(" Pattern hits:"));let i=Object.entries(r.patternHits).sort((a,c)=>c[1]-a[1]);i.length===0&&console.log(U.dim(" (none)"));for(let[a,c]of i)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(U.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(U.green(` Done. Backups: ${r.backups.length} file(s).`)),console.log()});Ts.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=C();if(!t.graph?.enabled){console.log(U.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 Ro({baseDir:Ea(process.cwd(),t.graph.baseDir)}),i=r.loadSchema(),a=r.loadNodes().nodes,c=new Set(a.map(A=>A.id));console.log(),console.log(U.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let A=await fetch(`${o}/graph/schema`,{headers:s});if(!A.ok)throw new Error(`schema HTTP ${A.status}`);l=(await A.json()).schema;let O=await fetch(`${o}/graph/nodes`,{headers:s});if(!O.ok)throw new Error(`nodes HTTP ${O.status}`);g=(await O.json()).nodes||[];let I=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!I.ok)throw new Error(`classifications HTTP ${I.status}`);d=(await I.json()).classifications||[]}catch(A){console.log(U.red(` fetch failed: ${A.message}`));return}let f=i.levels.map(A=>A.id).join(","),p=l?.levels?.map(A=>A.id).join(","),u=f===p;u?console.log(U.dim(` schema matches (${i.levels.length} levels)`)):(console.log(U.yellow(" \u26A0 schema levels differ:")),console.log(U.dim(` local: ${f}`)),console.log(U.dim(` peer: ${p}`)),a.length===0&&!e.dryRun?(console.log(U.dim(" local is empty \u2014 adopting peer schema")),r.saveSchema(l)):console.log(U.yellow(" keeping local schema; node import may fail if levels disagree")));let h=u?i:l,y=new Map;h.levels.forEach((A,R)=>y.set(A.id,R));let b=[...g].sort((A,R)=>(y.get(A.level)??99)-(y.get(R.level)??99)),$=0,v=0,x=0;for(let A of b){if(c.has(A.id)){v++;continue}if(e.dryRun){$++,c.add(A.id);continue}try{r.addNode({...A,createdBy:A.createdBy?`${A.createdBy} (sync)`:`sync:${o}`}),c.add(A.id),$++}catch(R){x++,console.log(U.yellow(` skip node ${A.id}: ${R.message?.slice(0,100)}`))}}console.log(U.dim(` nodes: +${$} added \xB7 ${v} already-present \xB7 ${x} failed`));let S=0,k=0;for(let A of d)if(!(!A.msgHash||!Array.isArray(A.path))){if(r.getFingerprint(A.msgHash)){k++;continue}if(e.dryRun){S++;continue}r.setFingerprint(A.msgHash,{path:A.path,leaf:A.leaf||{}}),S++}console.log(U.dim(` fingerprints: +${S} cached \xB7 ${k} already-present`)),console.log(),e.dryRun?console.log(U.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(U.green(` \u2713 pulled from ${o}`)),console.log()});function sC(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(`
|
|
659
|
+
agentx wiki questions`,V=I?.daemon?.port??I?.port??18800;try{let X=await fetch(`http://127.0.0.1:${V}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:D.channel,chatId:D.chatId,accountId:D.accountId,text:W})});console.log(X.ok?m.cyan(` Pushed ${R.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${X.status}) \u2014 questions are still queued.`))}catch(X){console.log(m.yellow(` Push failed (${String(X?.message??X).slice(0,80)}) \u2014 questions are still queued.`))}}}}});H.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-CAYDECW2.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ROUMKS7I.js"),{backfillArticle:f}=await import("./backfill-7TCF4SHG.js"),p=$e(e.dir,e.mode),u=e.agent?[e.agent]:p.listAgents(),h=parseInt(e.limit),y=g(),b=c(d(p.getSharedStore().listEntries())),$=new Map(b.map(I=>[I.name.toLowerCase().trim(),I])),v=0,x=0,S=[],k=!1;e:for(let I of u){let D=p.getAgentWiki(I);for(let P of D.listArticles(I)){if(v>=h)break e;if(P.meta.type!=="person")continue;let J=D.readArticle(P.path);if(!J)continue;v++;let W=await i(s,n({title:J.meta.title,type:J.meta.type,body:J.content}),t(J.meta.type),{links:[{kind:"article",id:P.path}],features:{agent:I,op:"backfill"}});if(!W){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let X=o(J.meta.type,W.answers).missing.filter(j=>r.includes(j));if(X.length===0)continue;let{records:Ce,results:Ge}=await a([{name:J.meta.title,type:"person"}],{sources:y}),M=$.get(J.meta.title.toLowerCase().trim());if(!k){for(let j of l(Ge,y))console.log(m.yellow(` ! ${j.source} ${j.kind} \u2014 would supply ${j.provides.join(", ")}`)),console.log(m.dim(` ${j.hint}`));k=!0}let ae=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([j,we])=>[j,we.value]))}]:[],...Ce]);if(ae.length===0)continue;let{content:Ie,edits:de}=f(J.content,ae[0],X);if(de.length!==0){for(let j of de)S.push({agent:I,article:J.meta.title.slice(0,32),field:j.field,action:j.replaced?"replace":"add",got:`${j.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(P.path,J.meta,Ie,I)?x++:console.log(m.red(` could not write ${P.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 A=["agent","article","field","action","got"],R=A.map(I=>Math.max(I.length,...S.map(D=>String(D[I]).length))),O=I=>I.map((D,P)=>String(D).padEnd(R[P])).join(" ");console.log(),console.log(m.bold(O(A)));for(let I of S)console.log(O(A.map(D=>I[D])));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.")))});H.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(ft(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`))});H.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(ft(o.dir)),a=i.list().find(h=>(h.id===e||h.id.startsWith(e))&&h.status!=="open"&&h.kind==="contradiction");if(a&&!i.list("open").some(h=>h.id===e||h.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(o.dismiss){try{let h=i.resolve(e,"dismissed");console.log(h?m.dim(` dismissed: ${h.question}`):m.red(` no question matching "${e}"`))}catch(h){console.log(m.red(` ${h?.message??h}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!t){console.log(m.red(" give a value, or pass --dismiss"));return}let c=i.list("open").find(h=>h.id===e||h.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:h}=await import("./ledger-P62U3FHT.js"),y=new h(ft(o.dir));try{let b=y.get(c.factId);if(b){let $=y.write({subject:b.subject,attribute:b.attribute,value:t,source:"owner said",verifiedBy:"operator",volatility:b.volatility},{confirmedBy:"operator"});console.log(m.green(` ${$.status}: ${b.id} ${b.subject} \xB7 ${b.attribute}: ${$.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(b){b?.name!=="LedgerCorruptError"&&console.log(m.red(` ${b?.message??b}`)),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(h){console.log(m.red(` ${h?.message??h}`)),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=$e(o.dir,o.mode).getAgentWiki(l.agentId),f=d.readArticle(l.path);if(!f){console.log(m.yellow(` article gone: ${l.path}`));return}let p=s(f.content,l.field,`${t} (answered by operator)`);if(!p){console.log(m.dim(" already present \u2014 nothing to write."));return}let u=d.writeArticle(l.path,f.meta,p.content,l.agentId);console.log(u?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});H.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-CAYDECW2.js"),{labelEntries:i,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),p=$e(e.dir,"graph").getSharedStore(),u=p.listEntries(),h=new Set(p.getUnabsorbedEntries().map(J=>J.id)),{labeled:y,backlog:b}=i(u,h),$=a(y,J=>J.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:J}=await import("fs");x.push(...JSON.parse(J(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${x.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${y.length} labelled (${b} in backlog) \u2014 grading ${$.length}`));for(let J of e.load?[]:$){let W=await r(t,n(J),o,{features:{source:J.source??"",absorbed:J.absorbed}});if(!W){S++;continue}let V=W.answers;x.push({entry:J,verdict:s(W.answers,v),citeWorthy:V.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:J}=await import("fs");J(e.save,JSON.stringify(x)),console.log(m.dim(` saved ${x.length} outcome(s) to ${e.save}`))}let A=c(x,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(x,"seat","seat"),O=d(R,{minN:50}),I=((Date.now()-k)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:A,calibration:O,failures:S,elapsed:I},null,2));return}let D=J=>`${(J*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${A.n} (${A.positives} kept by absorb, ${A.negatives} passed over)`),console.log(` recall ${D(A.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${D(A.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${D(A.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${A.lostPositives>0?m.yellow(`lost ${A.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in O)||!O.insufficient)&&console.log(` ECE ${O.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),A.lostPositives>0){let J=A.droppedBy;console.log(m.dim(` dropped by: type ${J.type} \xB7 worth ${J.worth} \xB7 durability ${J.durability} (a positive can fail several)`))}let P=A.positiveMeans;if(console.log(m.dim(` positives avg: worth ${P.worth.toFixed(2)} \xB7 durability ${P.durability.toFixed(2)} \xB7 typeConf ${P.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${I}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let J=parseFloat(e.minRecall),{best:W,points:V}=g(x,{minRecall:J});if(console.log(),console.log(m.bold(` threshold sweep (${V.length} policies, recall floor ${D(J)})`)),W)console.log(` best: ${W.requireTyped?`typed & type>=${W.minType}`:"type gate OFF"} worth>=${W.minWorth} durability>=${W.minDurability}`),console.log(` recall ${D(W.recall)} \xB7 filtered ${D(W.filtered)} \xB7 precision ${D(W.precision)} \xB7 lost ${W.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${D(J)} recall \u2014 not even keeping everything typed.`));let X=V.slice().sort((Ce,Ge)=>Ge.recall-Ce.recall)[0];X&&console.log(m.dim(` Best recall available: ${D(X.recall)} at ${X.requireTyped?`type>=${X.minType}`:"type gate OFF"} worth>=${X.minWorth} dur>=${X.minDurability}, filtering ${D(X.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});H.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=F(process.cwd(),e);Ze(o)||(console.log(m.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?F(process.cwd(),t.dir):F(process.cwd(),".agentx/wiki");Ze(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=F(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 tC(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"}wg();import{Command as oC}from"commander";import U from"chalk";import{resolve as Ea}from"path";import{existsSync as nC}from"fs";oe();var Ts=new oC().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Ts.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=C();if(!t.graph?.enabled){console.log(U.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(U.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(U.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 Ro({baseDir:Ea(process.cwd(),t.graph.baseDir)}),i=r.listPendingClassifications(s);if(i.length===0){console.log(U.dim(" no pending classifications \u2014 nothing to review"));return}let a=r.loadSchema(),c=r.loadNodes().nodes;console.log(),console.log(U.bold(` Graph review \u2014 ${i.length} pending`)),console.log(U.dim(` Reviewer: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,f=0;for(let u=0;u<i.length;u++){let h=i[u],y=Vr(h.path,c)||h.path.join(" \u203A ");process.stdout.write(` [${u+1}/${i.length}] ${U.cyan(h.msgHash.slice(0,8))} ${U.dim(y)} ... `);let b=sC(h,a,c),$=null;try{$=await rC(n,o,b,t.dashboard?.token)}catch(S){f++,console.log(U.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!$||!$.decision){f++,console.log(U.red("ERR no decision"));continue}let v=String($.decision).toLowerCase().trim(),x=($.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(U.green("APPROVE")+" "+U.dim(x)),e.dryRun)l++;else try{iC(r,h,a,c,o),r.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:o,reviewReason:x}),l++}catch(S){console.log(U.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),f++}else v==="reject"?(console.log(U.red("REJECT")+" "+U.dim(x)),e.dryRun||r.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:o,reviewReason:x}),g++):(console.log(U.yellow("SKIP")+" "+U.dim(x||v)),d++)}console.log();let p=e.dryRun?"would":"did";console.log(U.dim(` Summary: ${p} approve ${l}, ${p} reject ${g}, ${d} skipped, ${f} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(U.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Ts.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=C();if(!t.graph){console.log(U.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=Ea(process.cwd(),t.graph.baseDir);if(!nC(o)){console.log(U.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new Ro({baseDir:o,log:()=>{}}),r=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(U.dim(" "),...a)});console.log(),console.log(U.bold(" Pattern hits:"));let i=Object.entries(r.patternHits).sort((a,c)=>c[1]-a[1]);i.length===0&&console.log(U.dim(" (none)"));for(let[a,c]of i)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(U.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(U.green(` Done. Backups: ${r.backups.length} file(s).`)),console.log()});Ts.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=C();if(!t.graph?.enabled){console.log(U.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 Ro({baseDir:Ea(process.cwd(),t.graph.baseDir)}),i=r.loadSchema(),a=r.loadNodes().nodes,c=new Set(a.map(A=>A.id));console.log(),console.log(U.bold(` graph pull \u2190 ${o}`));let l,g,d;try{let A=await fetch(`${o}/graph/schema`,{headers:s});if(!A.ok)throw new Error(`schema HTTP ${A.status}`);l=(await A.json()).schema;let O=await fetch(`${o}/graph/nodes`,{headers:s});if(!O.ok)throw new Error(`nodes HTTP ${O.status}`);g=(await O.json()).nodes||[];let I=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!I.ok)throw new Error(`classifications HTTP ${I.status}`);d=(await I.json()).classifications||[]}catch(A){console.log(U.red(` fetch failed: ${A.message}`));return}let f=i.levels.map(A=>A.id).join(","),p=l?.levels?.map(A=>A.id).join(","),u=f===p;u?console.log(U.dim(` schema matches (${i.levels.length} levels)`)):(console.log(U.yellow(" \u26A0 schema levels differ:")),console.log(U.dim(` local: ${f}`)),console.log(U.dim(` peer: ${p}`)),a.length===0&&!e.dryRun?(console.log(U.dim(" local is empty \u2014 adopting peer schema")),r.saveSchema(l)):console.log(U.yellow(" keeping local schema; node import may fail if levels disagree")));let h=u?i:l,y=new Map;h.levels.forEach((A,R)=>y.set(A.id,R));let b=[...g].sort((A,R)=>(y.get(A.level)??99)-(y.get(R.level)??99)),$=0,v=0,x=0;for(let A of b){if(c.has(A.id)){v++;continue}if(e.dryRun){$++,c.add(A.id);continue}try{r.addNode({...A,createdBy:A.createdBy?`${A.createdBy} (sync)`:`sync:${o}`}),c.add(A.id),$++}catch(R){x++,console.log(U.yellow(` skip node ${A.id}: ${R.message?.slice(0,100)}`))}}console.log(U.dim(` nodes: +${$} added \xB7 ${v} already-present \xB7 ${x} failed`));let S=0,k=0;for(let A of d)if(!(!A.msgHash||!Array.isArray(A.path))){if(r.getFingerprint(A.msgHash)){k++;continue}if(e.dryRun){S++;continue}r.setFingerprint(A.msgHash,{path:A.path,leaf:A.leaf||{}}),S++}console.log(U.dim(` fingerprints: +${S} cached \xB7 ${k} already-present`)),console.log(),e.dryRun?console.log(U.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(U.green(` \u2713 pulled from ${o}`)),console.log()});function sC(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(`
|
|
660
660
|
`),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(`
|
|
661
661
|
`)}async function rC(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 Kr((c?.content||"").toString())}finally{clearTimeout(i)}}function iC(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function wd(){let e=C();if(!e.graph?.baseDir)return console.log(U.red(" graph.baseDir is not configured")),null;let t=Ea(process.cwd(),e.graph.baseDir);return{store:new Ro({baseDir:t}),baseDir:t}}var bd=Ts.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");bd.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=wd();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(U.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):U.dim("cache");console.log(` ${U.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${U.bold(Vr(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(U.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(U.dim(` ${i.length} to check (${e.strategy}).`)),console.log(U.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});bd.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(U.red(" verdict must be correct | wrong | unsure"));return}let n=wd();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(U.red(` no classification matching "${e}"`));return}if(i.length>1){console.log(U.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(U.green(` ${t}: ${Vr(i[0].path,c)||i[0].path.join(" \u203A ")}`)),o.path&&console.log(U.dim(` should have been: ${o.path}`))});bd.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let t=wd();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} ${U.dim("reviewed rows that carry a confidence")}`),i.byBin.length>0){console.log(),console.log(U.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),g=c.n>=5&&l>.15?U.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),i.calibratable<100?console.log(U.dim(` ${100-i.calibratable} more labelled rows before a calibration report means anything.`)):console.log(U.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as uC}from"commander";import ie from"chalk";import{Command as xb}from"commander";import Ee from"chalk";import{existsSync as aC}from"fs";import{resolve as cC}from"path";import lC from"better-sqlite3";function dC(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(Ee.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function gC(e){let t=cC(process.cwd(),e);return aC(t)||(console.log(Ee.red(` No db at ${t}`)),process.exit(1)),new lC(t,{readonly:!0})}var Sb=new xb().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(Hs)).option("--max <n>","max clusters distilled per run",String(ti)).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(Ee.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let t=gC(e.path),o=await fu(t,{since:dC(e.since),agentId:e.agent,sessions:new Ag(process.cwd()),minOccurrences:Number(e.minOccurrences)||Hs,max:Number(e.max)||ti,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(Ee.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(` ${Ee.cyan(n.key)} ${Ee.bold(`\xD7${n.count}`)} ${Ee.dim(n.status)}`),n.sampleMessage&&console.log(Ee.dim(` "${n.sampleMessage.slice(0,100)}"`));if(o.nearMisses.length){console.log(Ee.dim(`
|
|
662
662
|
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of o.nearMisses.slice(0,5))console.log(Ee.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of o.drafted)console.log(Ee.green(` \u2713 draft written: ${n.id}`)+Ee.dim(` (${n.count} occurrences)`));for(let n of o.skipped)console.log(Ee.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of o.warnings)console.log(Ee.yellow(` \u26A0 ${n}`));o.dryRun?console.log(Ee.dim(`
|
|
@@ -672,7 +672,7 @@ agentx wiki questions`,V=I?.daemon?.port??I?.port??18800;try{let X=await fetch(`
|
|
|
672
672
|
${n.join(`
|
|
673
673
|
`)}`)}oe();var Ve=new fC().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");function Cb(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}Ve.command("list").description("list all workflows with their trigger + state count").action(()=>{let t=new Co().list();if(!t.length){console.log(E.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let o of t){let s=o.nodes.find(a=>a.type.startsWith("trigger."))?.config??{},r=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / "),i=o.state==="active"?E.green("dispatch: active"):E.yellow(`dispatch: ${o.state}`);console.log(` ${E.cyan(o.id)} ${E.bold(o.title)} ${E.dim(`v${o.version} \xB7`)} ${i} ${E.dim(`\xB7 review: ${o.status}`)}`),console.log(` ${E.dim("trigger:")} ${s.source??"?"}${r?` ${E.dim(r)}`:""}`),console.log(` ${E.dim("nodes: ")} ${o.nodes.length} (${o.nodes.map(a=>a.type).join(", ")})`)}console.log(),console.log(E.dim(` ${t.length} workflow${t.length===1?"":"s"}.`))});Ve.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,t)=>{let n=new Co().get(e);n||(console.log(E.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=t.format.toLowerCase();s==="yaml"||s==="yml"?console.log(Ng(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(E.red(` unknown format "${t.format}" \u2014 use json or yaml`)),process.exit(1))});Ve.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let r=In(process.cwd(),e);Ca(r)||(console.log(E.red(` file not found: ${r}`)),process.exit(1));try{let i=Ir(r,"utf-8"),c=/\.(ya?ml)$/i.test(e)?Bn(i,{filePath:e}):JSON.parse(i),l=Wn.safeParse(c);if(!l.success){console.log(E.red(` \u2717 ${r}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let g=Xr(l.data);if(g.length){console.log(E.yellow(` ! ${r} (lint)`));for(let d of g)console.log(` ${d}`);process.exit(1)}console.log(E.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(i){let a=i instanceof Qr?i.message:`parse error: ${i?.message??i}`;console.log(E.red(` ${a}`)),process.exit(1)}return}let o=new Co().validateAll(),n=0,s=0;for(let r of o)if(r.isValid)console.log(E.green(` \u2713 ${r.workflow.id}`)),n++;else{let i=r.workflow?.id||r.id;console.log(E.red(` \u2717 ${i}`));for(let a of r.issues)console.log(` ${a}`);s++}console.log(),console.log(E.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Ve.command("init <id>").description("scaffold a new workflow YAML from a template (linear by default)").option("--template <name>",`which template to use (${Or.map(e=>e.name).join(" | ")})`,"linear").option("--agent <id>","fill the agent placeholder with this agent id","default").option("--reviewer <id>","fill the reviewer placeholder for human-in-the-loop templates","alice").option("--title <text>","workflow title","").option("--json","scaffold as .json instead of .yaml",!1).option("--force","overwrite an existing workflow with the same id",!1).action((e,t)=>{let o=String(t.template||"linear");Or.some(a=>a.name===o)||(console.log(E.red(` unknown template "${t.template}"`)),console.log(E.dim(` available: ${Or.map(a=>a.name).join(", ")}`)),process.exit(1)),/^[a-z0-9][a-z0-9_-]*$/.test(e)||(console.log(E.red(` workflow id must be lower-kebab (got "${e}")`)),process.exit(1));let n=new Co;!t.force&&n.get(e)&&(console.log(E.red(` workflow "${e}" already exists. Use --force to overwrite or pick a new id.`)),process.exit(1));let s=Rb(o);s=s.replace(/__ID__/g,e).replace(/__TITLE__/g,t.title?String(t.title):`${o} workflow ${e}`).replace(/__AGENT__/g,String(t.agent)).replace(/__REVIEWER__/g,String(t.reviewer));try{let a=Bn(s,{filePath:`${e}.yaml`}),c=Wn.safeParse(a);if(!c.success){console.log(E.red(` template "${o}" failed schema validation after substitution:`));for(let l of c.error.issues)console.log(` ${l.path.join(".")||"<root>"}: ${l.message}`);process.exit(1)}}catch(a){console.log(E.red(` template parse failed: ${a?.message??a}`)),process.exit(1)}let r=t.json?"json":"yaml",i=In(process.cwd(),".agentx/workflows",`${e}.${r}`);if(t.json){let a=Bn(s,{filePath:`${e}.yaml`}),c=Wn.parse(a);Ra(i,JSON.stringify(c,null,2)+`
|
|
674
674
|
`)}else Ra(i,s);console.log(),console.log(E.green(` \u2713 scaffolded ${i}`)),console.log(E.dim(` template: ${o}`)),console.log(),console.log(E.dim(" Next:")),console.log(E.dim(` 1. edit ${i}`)),console.log(E.dim(` 2. agentx workflow validate ${i}`)),console.log(E.dim(` 3. agentx workflow run ${e} --watch`)),console.log()});Ve.command("templates").description("list the available workflow templates for `init`").action(()=>{console.log();for(let e of Or)console.log(` ${E.cyan(e.name.padEnd(20))} ${E.bold(e.title)}`),console.log(` ${" ".repeat(20)} ${E.dim(e.description)}`);console.log(),console.log(E.dim(" Use: agentx workflow init <id> --template <name>")),console.log()});Ve.command("add <file>").description("import a YAML/JSON workflow file into .agentx/workflows and hot-reload").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--no-reload","skip the POST /reload after writing").action(async(e,t)=>{let o=In(process.cwd(),e);Ca(o)||(console.log(E.red(` file not found: ${o}`)),process.exit(1));let n=Ir(o,"utf-8"),s=/\.(ya?ml)$/i.test(e),r;try{r=s?Bn(n,{filePath:e}):JSON.parse(n)}catch(f){let p=f instanceof Qr?f.message:`parse error: ${f?.message??f}`;console.log(E.red(` ${p}`)),process.exit(1)}let i=Wn.safeParse(r);if(!i.success){console.log(E.red(" \u2717 schema:"));for(let f of i.error.issues)console.log(` ${f.path.join(".")||"<root>"}: ${f.message}`);process.exit(1)}let a=Xr(i.data);if(a.length){console.log(E.red(" \u2717 lint:"));for(let f of a)console.log(` ${f}`);process.exit(1)}let c=new Co,l=s?hC(e).match(/\.yml$/i)?"yml":"yaml":"json",g=In(c.baseDir,`${i.data.id}.${l}`);if(Ra(g,s?n:JSON.stringify(i.data,null,2)+`
|
|
675
|
-
`),console.log(E.green(` \u2713 ${i.data.id} \u2192 ${g}`)),t.reload===!1){console.log(E.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let d=`${String(t.daemon).replace(/\/$/,"")}/reload`;try{let f=await fetch(d,{method:"POST"});f.ok?console.log(E.dim(" \u2713 daemon reloaded")):console.log(E.dim(` daemon /reload returned ${f.status} \u2014 restart manually if needed`))}catch{console.log(E.dim(` daemon not reachable at ${t.daemon} \u2014 start it or restart to pick up the new workflow`))}});Ve.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local",n=new To({nodeId:o}).list({workflowId:e,limit:Number(t.limit)});if(!n.length){console.log(E.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let r=s.history.at(-1),i=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?E.cyan:s.status==="failed"?E.red:E.green;console.log(` ${E.dim(s.id.slice(0,8))} ${E.bold(s.workflowId)} ${a(i)} ${E.dim(s.status)}`),console.log(` ${E.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${E.dim("home: ")} ${s.homeNode}`),console.log(` ${E.dim("updated: ")} ${s.updatedAt}`),r&&console.log(` ${E.dim("last: ")} ${r.nodeId} (${r.status})`)}console.log(),console.log(E.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Ve.command("pilot-report <live> <pilot>").description("compare a live workflow with a pilot that ran beside it: cost per run, hand-backs, failures (#928)").option("--since <when>","only runs started after this: an ISO date, or a duration like 7d").option("--db <path>","trace database",".agentx/db.sqlite").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').option("--pairs","list each pair with its run and trace ids",!1).option("--json","print the report as JSON",!1).action(async(e,t,o)=>{let{comparePilot:n,FALLBACK_PRICING_MODEL:s}=await import("./workflow-pilot-
|
|
675
|
+
`),console.log(E.green(` \u2713 ${i.data.id} \u2192 ${g}`)),t.reload===!1){console.log(E.dim(" --no-reload: skipped daemon hot-reload; restart manually if running."));return}let d=`${String(t.daemon).replace(/\/$/,"")}/reload`;try{let f=await fetch(d,{method:"POST"});f.ok?console.log(E.dim(" \u2713 daemon reloaded")):console.log(E.dim(` daemon /reload returned ${f.status} \u2014 restart manually if needed`))}catch{console.log(E.dim(` daemon not reachable at ${t.daemon} \u2014 start it or restart to pick up the new workflow`))}});Ve.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local",n=new To({nodeId:o}).list({workflowId:e,limit:Number(t.limit)});if(!n.length){console.log(E.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let r=s.history.at(-1),i=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?E.cyan:s.status==="failed"?E.red:E.green;console.log(` ${E.dim(s.id.slice(0,8))} ${E.bold(s.workflowId)} ${a(i)} ${E.dim(s.status)}`),console.log(` ${E.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${E.dim("home: ")} ${s.homeNode}`),console.log(` ${E.dim("updated: ")} ${s.updatedAt}`),r&&console.log(` ${E.dim("last: ")} ${r.nodeId} (${r.status})`)}console.log(),console.log(E.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Ve.command("pilot-report <live> <pilot>").description("compare a live workflow with a pilot that ran beside it: cost per run, hand-backs, failures (#928)").option("--since <when>","only runs started after this: an ISO date, or a duration like 7d").option("--db <path>","trace database",".agentx/db.sqlite").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').option("--pairs","list each pair with its run and trace ids",!1).option("--json","print the report as JSON",!1).action(async(e,t,o)=>{let{comparePilot:n,FALLBACK_PRICING_MODEL:s}=await import("./workflow-pilot-MKG6CJ6V.js"),{listTracesForRuns:r}=await import("./traces-O4TIZ4SM.js"),{loadPricingWithOverrides:i}=await import("./token-tracker-XTHSSPLB.js"),a=o.since?Cb(o.since)!==null?Date.now()-Cb(o.since):Date.parse(o.since):void 0;o.since&&!Number.isFinite(a)&&(console.log(E.red(` --since: "${o.since}" is not a date or a duration`)),process.exit(1));let c=new To({nodeId:o.node||process.env.WF_NODE_ID||"local"}),l=a!==void 0?new Date(a).toISOString():"",g=[...c.list({workflowId:e,since:a}),...c.list({workflowId:t,since:a})].filter(v=>v.createdAt>=l),d=In(process.cwd(),o.db);Ca(d)||(console.log(E.red(` No trace database at ${d}`)),process.exit(1));let f=new yC(d,{readonly:!0}),p;try{p=r(f,g.map(v=>v.id))}finally{f.close()}let u=n({liveWorkflow:e,pilotWorkflow:t,runs:g,traces:p,pricing:i(),agentModels:bC()});if(o.json){console.log(JSON.stringify(u,null,2));return}let h=v=>v===null?E.dim("n/a"):`$${v.toFixed(4)}`,y=v=>`${(v*100).toFixed(1)}%`,b=(v,x)=>console.log(` ${v.padEnd(22)} ${String(x.runs).padStart(5)} ${String(x.failed).padStart(6)} ${h(x.costPerRunUsd).padStart(9)} ${h(x.medianCostUsd).padStart(9)} ${h(x.totalCostUsd)}`);console.log(),console.log(E.bold(` Pilot: ${t} beside ${e}`)),console.log(E.dim(` ${"".padEnd(22)} ${"runs".padStart(5)} ${"failed".padStart(6)} ${"mean".padStart(9)} ${"median".padStart(9)} total`)),b(`${e} (all)`.slice(0,22),u.live),b("live, paired runs",u.paired.live),b("pilot path, paired",u.paired.pilotPath),console.log(),console.log(` Handed back to the full agent: ${u.paired.handedBack} of ${u.paired.runs} (${y(u.paired.handBackShare)})`),console.log(` Saving on the paired runs: ${u.paired.saving===null?E.dim("n/a"):y(u.paired.saving)}`),(u.unpairedLive||u.orphanPilot)&&console.log(E.dim(` Not compared: ${u.unpairedLive} live run(s) without a pilot run, ${u.orphanPilot} pilot run(s) without a live run`)),u.pilotInProgress&&console.log(E.dim(` Not compared yet: ${u.pilotInProgress} pilot run(s) still in progress`));let $=u.fallbackPriced;if(($.live||$.pilot)&&(console.log(E.yellow(` No price known for ${$.live+$.pilot} of ${$.calls} model call(s) (live ${$.live}, pilot ${$.pilot}): priced at ${s} rates.${$.noModel?` ${$.noModel} had no model on record: set the agent's model in agentx.json.`:""}`)),$.unpricedModels.length&&console.log(E.yellow(` Models with no price: ${$.unpricedModels.join(", ")}`))),o.pairs){console.log();for(let v of u.pairs)v.pilot&&(console.log(` ${E.dim(v.live.startedAt)} live ${v.live.runId.slice(0,8)} ${h(v.live.costUsd)} pilot ${v.pilot.runId.slice(0,8)} ${h(v.pilot.costUsd)}${v.handedBack?E.yellow(` handed back: ${v.handedBack}`):""}`),console.log(E.dim(` traces: live ${v.live.traceIds.join(" ")||"-"} | pilot ${v.pilot.traceIds.join(" ")||"-"}`)))}console.log()});Ve.command("run <id-or-file>").description("manually trigger a workflow by id, or load + register + run a YAML/JSON file").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--watch","tail per-step traces while the run executes",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--follow","follow it to the end: reminders, nudges and one summary for you when it ends",!1).option("--title <text>","with --follow: what this run is for, in a few words").option("--tag <kind:name...>","with --follow: what it concerns, e.g. client:acme employee:sam (repeatable)").action(async(e,t)=>{let o={};if(t.input)try{o=JSON.parse(t.input)}catch{console.log(E.red(" --input must be valid JSON")),process.exit(1)}let n=e,s=In(process.cwd(),e);if((e.includes("/")||/\.(ya?ml|json)$/i.test(e))&&Ca(s)){let c=Ir(s,"utf-8"),l=/\.(ya?ml)$/i.test(e),g;try{g=l?Bn(c,{filePath:e}):JSON.parse(c)}catch($){let v=$ instanceof Qr?$.message:`parse error: ${$?.message??$}`;console.log(E.red(` ${v}`)),process.exit(1)}let d=Wn.safeParse(g);if(!d.success){console.log(E.red(" \u2717 schema:"));for(let $ of d.error.issues)console.log(` ${$.path.join(".")||"<root>"}: ${$.message}`);process.exit(1)}let f=Xr(d.data);if(f.length){console.log(E.red(" \u2717 lint:"));for(let $ of f)console.log(` ${$}`);process.exit(1)}let p=new Co,u=d.data.id.startsWith("_adhoc-")?d.data.id:`_adhoc-${d.data.id}-${Date.now().toString(36)}`,h=l?"yaml":"json",y=In(p.baseDir,`${u}.${h}`),b=l?c.replace(new RegExp(`^id:\\s*${d.data.id}\\b`,"m"),`id: ${u}`):JSON.stringify({...d.data,id:u},null,2)+`
|
|
676
676
|
`;Ra(y,b),n=u,console.log(E.dim(` ad-hoc registered as "${u}" \u2192 ${y}`));try{await fetch(`${String(t.daemon).replace(/\/$/,"")}/reload`,{method:"POST"})}catch{}}let i=`${String(t.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(n)}/run`,a;try{let c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:o,force:!!t.force,...t.follow?{follow:{title:t.title,tags:t.tag??[]}}:{}})});if(!c.ok){let g=await c.text();console.log(E.red(` run failed (${c.status}): ${g.slice(0,300)}`)),c.status===409&&g.includes('"hint"')&&console.log(E.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let l=await c.json();a=l.runId,console.log(E.green(` \u2713 run started: ${a||"(unknown id)"}${l.force?E.dim(` (forced, source=${l.source})`):""}${l.followUp?E.dim(" (followed)"):""}`)),l.awaitingApproval&&console.log(E.yellow(" It waits for your approval (Approvals inbox) before the first step."))}catch(c){console.log(E.red(` request to daemon failed: ${c.message}`)),process.exit(1)}t.watch&&a&&await wC({daemonUrl:String(t.daemon).replace(/\/$/,""),runId:a})});async function wC(e){let t=new Set,o=new Map,n=Date.now(),s=15*60*1e3;for(;Date.now()-n<s;){let r=[];try{let i=await fetch(`${e.daemonUrl}/traces?workflowRunId=${encodeURIComponent(e.runId)}&limit=200`);i.ok&&(r=(await i.json()).traces||[])}catch{}for(let i of r){if(!i.taskId||t.has(i.taskId)||(t.add(i.taskId),o.set(i.taskId,i),e.quiet))continue;let a=i.status||"running",c=a==="ok"?E.green:a==="error"?E.red:E.cyan,l=i.totalTokens!=null?E.dim(`${i.totalTokens}t`):"",g=i.durationMs!=null?E.dim(`${i.durationMs}ms`):"";console.log(` ${c(a.padEnd(5))} ${E.bold(i.nodeId||i.label||"(node)")} ${l} ${g}`),i.error&&console.log(` ${E.red(String(i.error).slice(0,200))}`)}try{let i=await fetch(`${e.daemonUrl}/api/workflows/runs/${encodeURIComponent(e.runId)}`);if(i.ok){let c=(await i.json()).run;if(c&&c.status&&c.status!=="running")return e.quiet||(console.log(),console.log(` ${E.dim("run finished:")} ${c.status}`),console.log(E.dim(` full traces: ${e.daemonUrl}/traces?workflowRunId=${e.runId}`))),Array.from(o.values())}}catch{}await new Promise(i=>setTimeout(i,500))}return e.quiet||console.log(E.yellow(" watch timed out after 15min. Run is still active \u2014 check /traces")),Array.from(o.values())}Ve.command("trace <id>").description("pretty-print a task's execution trace (taskId or runId)").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output",!1).action(async(e,t)=>{let o=String(t.daemon).replace(/\/$/,"");try{let r=await fetch(`${o}/traces/${encodeURIComponent(e)}`);if(r.ok){let i=await r.json();if(t.json){console.log(JSON.stringify(i,null,2));return}Tb(i);return}}catch{}let n;try{let r=await fetch(`${o}/traces?workflowRunId=${encodeURIComponent(e)}&limit=200`);r.ok||(console.log(E.red(` /traces returned ${r.status}`)),process.exit(1)),n=await r.json()}catch(r){console.log(E.red(` daemon request failed: ${r.message}`)),process.exit(1)}let s=n.traces||[];if(s.length===0){console.log(E.yellow(` no traces for "${e}"`)),console.log(E.dim(" (sqlite must be opened \u2014 check 'agentx doctor' if the daemon logged 'sqlite: not opened')"));return}if(t.json){console.log(JSON.stringify(s,null,2));return}console.log(),console.log(E.bold(` ${s.length} step${s.length===1?"":"s"} for run ${e}:`)),console.log();for(let r of s)Tb(r)});function Tb(e){let t=e.status||"ok",o=t==="ok"?E.green:t==="error"?E.red:E.cyan,n=e.totalTokens!=null?`${e.totalTokens}t`:"\u2014",s=e.durationMs!=null?`${e.durationMs}ms`:"\u2014",r=e.model||"\u2014";console.log(` ${o(t.padEnd(5))} ${E.bold(String(e.nodeId||e.label||"(node)"))}`),console.log(` ${E.dim("taskId:")} ${e.taskId||"\u2014"}`),console.log(` ${E.dim("model:")} ${r}`),console.log(` ${E.dim("tokens:")} ${n} ${E.dim("duration:")} ${s}`),e.error&&console.log(` ${E.dim("error:")} ${E.red(String(e.error).slice(0,300))}`),console.log()}Ve.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new To({nodeId:o}).setStatus(e,"paused")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 paused ${e}`))});Ve.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local",n=new To({nodeId:o}),s=n.get(e);s?.status==="paused"&&s.pausedAt?.kind==="agentStop"&&(console.log(E.yellow(` ${e} was paused by a stop signal at step ${s.pausedAt.nodeId}. Resume it with: agentx signal resume ${s.pausedAt.taskId??"<taskId>"}`)),process.exit(1)),n.setStatus(e,"running")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 resumed ${e}`))});Ve.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,t)=>{try{let r=await fetch(`${String(t.daemon).replace(/\/$/,"")}/workflow-runs/${encodeURIComponent(e)}/cancel`,{method:"POST",signal:AbortSignal.timeout(5e3)});if(r.ok){console.log(E.green(` \u2713 canceled ${e}`));return}r.status===404&&(console.log(E.yellow(` no running run ${e}`)),process.exit(1))}catch{}let o=t.node||process.env.WF_NODE_ID||"local";new To({nodeId:o}).setStatus(e,"canceled")||(console.log(E.yellow(` no such run: ${e}`)),process.exit(1)),console.log(E.green(` \u2713 canceled ${e}`))});Ve.command("progress").description("follow-up runs still going, grouped by who or what they concern").option("--tag <kind:name>","only this tag, e.g. client:acme").option("--json","machine-readable output",!1).action(e=>{let t=new To({nodeId:process.env.WF_NODE_ID||"local"}).list({limit:500}),o=new Map(new Co().list().map(s=>[s.id,s.title])),n=Bg(t,s=>o.get(s)).filter(s=>!e.tag||s.tag===e.tag.toLowerCase());if(e.json){console.log(JSON.stringify(n,null,2));return}if(!n.length){console.log(E.dim(` nothing is being followed${e.tag?` for ${e.tag}`:""}`));return}console.log();for(let s of n){console.log(` ${E.bold(s.tag)} ${E.dim(`(${s.rows.length})`)}`);for(let r of s.rows){let i=r.blocked?E.red("\u26A0 "):"";console.log(` ${i}${E.cyan(r.title)} ${E.dim(r.runId.slice(0,8))}`),console.log(` ${E.dim("step")} ${r.step} ${E.dim("waiting on")} ${r.blocked?E.red(r.waitingOn):r.waitingOn}`),console.log(` ${E.dim(`since ${r.since.slice(0,16).replace("T"," ")} UTC${r.startedBy?` \xB7 started by ${r.startedBy}`:""}`)}`)}}console.log(),console.log(E.dim(" Details: agentx workflow trace <runId> \xB7 Stop one: agentx workflow cancel <runId>"))});function bC(){let e={};try{e=Ws(JSON.parse(Ir(fo(),"utf-8")))}catch{e={}}let t={};for(let[o,n]of Object.entries(e?.agents??{}))typeof n?.model=="string"&&n.model&&(t[o]=n.model);return t}function $C(){let e=fo(),t={};try{t=Ws(JSON.parse(Ir(e,"utf-8")))}catch{t={}}let o=t?.workflows?.followUp??{};return{enabled:o.enabled??!0,agents:o.agents??{},stallMinutes:o.stallMinutes??30,maxNudges:o.maxNudges??2,approval:o.approval??"step",engine:t?.workflows?.enabled===!0}}Ve.command("follow-up").description("show or change how follow-up workflows run: reminders, approvals, which agents may start them").option("--enabled <on|off>","agents may start follow-up workflows").option("--stall-minutes <n>","minutes without progress before an agent step gets a reminder").option("--max-nudges <n>","reminders before the step counts as blocked and you are told").option("--approval <start|step>","approve messages to people all at once when a run starts, or each before it is sent").option("--agent <id>","with --agent-enabled: the agent to turn it on or off for").option("--agent-enabled <on|off>","turn follow-up workflows on or off for --agent").action(async e=>{let t=(r,i)=>{if(i!==void 0){if(i!=="on"&&i!=="off")throw new Error(`${r} takes on or off`);return i==="on"}},o={};try{if(o.enabled=t("--enabled",e.enabled),e.stallMinutes!==void 0){let i=Number(e.stallMinutes);if(!(i>0))throw new Error("--stall-minutes must be a positive number");o.stallMinutes=i}if(e.maxNudges!==void 0){let i=Number(e.maxNudges);if(!Number.isInteger(i)||i<0||i>20)throw new Error("--max-nudges must be a whole number from 0 to 20");o.maxNudges=i}if(e.approval!==void 0){if(e.approval!=="start"&&e.approval!=="step")throw new Error("--approval takes start or step");o.approval=e.approval}let r=t("--agent-enabled",e.agentEnabled);if(r===void 0!=(e.agent===void 0))throw new Error("--agent and --agent-enabled go together");e.agent&&r!==void 0&&(o.agent=[e.agent,r])}catch(r){console.error(E.red(` ${r.message}`)),process.exitCode=1;return}if(o=Object.fromEntries(Object.entries(o).filter(([,r])=>r!==void 0)),Object.keys(o).length){let r=await ge(i=>{let a=i.workflows??={},c=a.followUp??={};for(let l of["enabled","stallMinutes","maxNudges","approval"])o[l]!==void 0&&(c[l]=o[l]);o.agent&&((c.agents??={})[o.agent[0]]=o.agent[1])});if(!r.success){console.error(E.red(` ${r.error}`)),process.exitCode=1;return}console.log(E.green(" \u2713 saved")+(r.reloaded?E.dim(" (daemon reloaded)"):""))}let n=$C(),s=Object.entries(n.agents).filter(([,r])=>!r).map(([r])=>r);n.engine||console.log(E.yellow(" The workflow engine is off: set workflows.enabled to true first.")),console.log(` Follow-up workflows ${n.enabled?"on":"off"}${s.length?E.dim(` (off for ${s.join(", ")})`):""}`),console.log(` Reminder after ${n.stallMinutes} minute(s) without progress`),console.log(` Reminders before block ${n.maxNudges}`),console.log(` Messages to people ${n.approval==="start"?"approved all at once when a run starts":"approved one by one, before each is sent"}`)});Ve.command("required").description("show or change whether every task runs through a workflow (workflows.required)").option("--enabled <on|off>","every task of every agent runs inside a workflow run").option("--exempt-questions <on|off>","a plain question that changed nothing leaves no run (default on)").option("--retention-days <n>","remove task runs that ended more than n days ago (default 30, 0 keeps them all)").option("--agent <id>","with --agent-required: the agent to set it for").option("--agent-required <on|off|default>","on or off for --agent whatever --enabled says; default follows --enabled again").action(async e=>{let t=(i,a)=>{if(a!==void 0){if(a!=="on"&&a!=="off")throw new Error(`${i} takes on or off`);return a==="on"}},o={};try{if(o.enabled=t("--enabled",e.enabled),o.exemptQuestions=t("--exempt-questions",e.exemptQuestions),e.retentionDays!==void 0){if(!/^\d+$/.test(e.retentionDays)||Number(e.retentionDays)>3650)throw new Error("--retention-days takes a whole number from 0 to 3650");o.retentionDays=Number(e.retentionDays)}if(e.agentRequired===void 0!=(e.agent===void 0))throw new Error("--agent and --agent-required go together");if(e.agent&&e.agentRequired!==void 0){if(!["on","off","default"].includes(e.agentRequired))throw new Error("--agent-required takes on, off or default");o.agent={id:e.agent,value:e.agentRequired==="default"?null:e.agentRequired==="on"}}}catch(i){console.error(E.red(` ${i.message}`)),process.exitCode=1;return}if(o.enabled!==void 0||o.exemptQuestions!==void 0||o.retentionDays!==void 0||o.agent){let i=await Ip(o);if(!i.success){console.error(E.red(` ${i.error}`)),process.exitCode=1;return}console.log(E.green(" \u2713 saved")+(i.reloaded?E.dim(" (daemon reloaded)"):""))}let n=Op(),s=Object.entries(n.agents).filter(([,i])=>i).map(([i])=>i),r=Object.entries(n.agents).filter(([,i])=>!i).map(([i])=>i);n.engine||console.log(E.yellow(" The workflow engine is off: nothing is required until workflows.enabled is true.")),console.log(` Every task in a workflow ${n.enabled?"on":"off"}${s.length?E.dim(` (on for ${s.join(", ")})`):""}${r.length?E.dim(` (off for ${r.join(", ")})`):""}`),console.log(` Plain questions ${n.exemptQuestions?"exempt: no run when nothing was changed":"run through a workflow too"}`),console.log(` Task runs kept ${n.retentionDays?`${n.retentionDays} day${n.retentionDays===1?"":"s"} after they end`:"forever"}`)});Ve.command("records").description("one line per workflow run: steps taken, how long each took, where it failed (JSON lines, for analysis)").option("--workflow <id>","only runs of this workflow (task = runs that wrapped a task)").option("--agent <id>","only runs of this agent").option("--days <n>","only runs started in the last n days").option("--limit <n>","at most this many runs, newest first","500").action(e=>{let t=Math.max(1,Math.min(1e4,Number(e.limit)||500)),o=e.days!==void 0?Date.now()-Math.max(0,Number(e.days)||0)*864e5:0,n=new To({nodeId:process.env.WF_NODE_ID||"local"}).list({workflowId:e.workflow,tasks:e.workflow?void 0:"include",since:o||void 0,limit:e.agent?void 0:t}),s=0;for(let r of n){if(o&&Date.parse(r.createdAt)<o)continue;let i=Jg(r);if(!(e.agent&&i.agentId!==e.agent)&&(console.log(JSON.stringify(i)),++s>=t))break}});import{Command as Ob}from"commander";import xe from"chalk";import jn from"prompts";import{readFileSync as kC,existsSync as vC}from"fs";import{resolve as xC}from"path";var jr=["gitlab","github","sentry","stripe","vercel","odoo","hubspot","discord","slack","custom"],$d=new Set(["gitlab","github","sentry","stripe","vercel","odoo","hubspot"]),Ib={gitlab:"GitLab \u2192 Settings \u2192 Webhooks (tick Push/Issue/Pipeline events)",github:"GitHub \u2192 Repo Settings \u2192 Webhooks",sentry:"Sentry \u2192 Project Settings \u2192 Alerts \u2192 Webhooks",stripe:"Stripe Dashboard \u2192 Developers \u2192 Webhooks",vercel:"Vercel \u2192 Project Settings \u2192 Webhooks",odoo:"Odoo \u2192 Settings \u2192 Technical \u2192 Automation \u2192 Webhooks (or your installed `webhook` module)",hubspot:"HubSpot \u2192 Settings \u2192 Integrations \u2192 Private Apps \u2192 Webhooks subscription",discord:"Discord channel \u2192 Integrations \u2192 Webhooks (inbound-only, no on:* events)",slack:"Slack Outgoing Webhooks / Events API (inbound-only, no on:* events)",custom:"Any service that POSTs JSON \u2014 Linear, Calendly, Notion, etc. (inbound-only)"};function jb(){let e=xC(process.cwd(),"agentx.json");if(!vC(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(kC(e,"utf-8"))}function SC(e){return e.enabled?e.source!=="custom"&&!e.secretEnv?xe.yellow("\u26A0 no signing secret"):xe.green("\u2713 active"):xe.dim("disabled")}function AC(e,t){let o=t?`${t.replace(/\/+$/,"")}/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`:`/webhook/${encodeURIComponent(e.agentId)}/${encodeURIComponent(e.source)}`,n=$d.has(e.source)?xe.dim(" \xB7 emits on:"+e.source+"-* hook events"):"";console.log(` ${xe.cyan(e.id)} ${SC(e)}`),console.log(` ${xe.dim(e.source)} \u2192 ${xe.bold(e.agentId)}${n}`),console.log(` POST ${xe.dim(o)}`),e.secretEnv&&console.log(` secret: ${xe.dim("$"+e.secretEnv)}`),e.description&&console.log(` ${xe.dim(e.description)}`);let s=e.triggers&&typeof e.triggers=="object"?e.triggers:{},r=Object.keys(s);if(r.length){console.log(` ${xe.dim("triggers:")}`);for(let i of r)console.log(` ${i} \u2192 ${s[i]}`)}e.defaultWorkflow&&console.log(` ${xe.dim("default workflow:")} ${e.defaultWorkflow}`),console.log()}var vo=new Ob().name("webhook").description("manage webhook entries (gitlab, github, sentry, stripe, vercel, custom)");vo.command("list").alias("ls").description("list webhook entries").option("--json","emit JSON").action(e=>{let t=jb(),o=Array.isArray(t.webhooks)?t.webhooks:[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(xe.dim(`
|
|
677
677
|
No webhooks registered. Add one with: agentx webhook add
|
|
678
678
|
`));return}console.log();for(let n of o)AC(n)});vo.command("add [id]").description("register a new webhook entry").option("--source <source>",`one of: ${jr.join(", ")}`).option("--agent <agentId>","agent that receives the webhook").option("--secret-env <name>","env var holding the signing secret (recommended)").option("--description <text>","free-text description").option("--node <peer>","forward to a mesh peer (skips local agent check; validates against mesh.peers)").option("--no-prompt","fail instead of prompting for missing values").action(async(e,t)=>{let o=jb(),n=Object.keys(o.agents||{}),s=(o.mesh?.peers||[]).map(p=>p.name).filter(Boolean),r=String(t.node||"").trim();if(!n.length&&!r)throw new Error("No local agents configured. Add one with: agentx agent add \u2014 or use --node <peer> to forward to a mesh peer.");let i=(e||"").trim(),a=String(t.source||"").trim(),c=String(t.agent||"").trim(),l=String(t.secretEnv||"").trim(),g=String(t.description||"").trim(),d=t.prompt!==!1;if(!i&&d&&(i=((await jn({type:"text",name:"id",message:"Webhook id (lowercase, e.g. globex-gitlab)",validate:u=>/^[a-z0-9][a-z0-9_-]*$/.test(u)||"Use lowercase letters, digits, -, _"})).id||"").trim()),!i)throw new Error("Webhook id is required.");if(!/^[a-z0-9][a-z0-9_-]*$/.test(i))throw new Error("Webhook id must be lowercase (letters, digits, -, _).");if(!a&&d&&(a=(await jn({type:"select",name:"source",message:"Source",choices:jr.map(u=>({title:`${u}${$d.has(u)?" \u2713 wired":""}`,value:u,description:Ib[u]}))})).source),!jr.includes(a))throw new Error(`Source must be one of: ${jr.join(", ")}`);if(!c&&d&&(r?c=((await jn({type:"text",name:"agentId",message:`Agent on remote peer "${r}"`})).agentId||"").trim():c=(await jn({type:"select",name:"agentId",message:"Agent",choices:n.map(u=>({title:u,value:u}))})).agentId),!c)throw new Error("Agent is required.");if(r){if(!s.includes(r))throw new Error(`Mesh peer "${r}" not found in mesh.peers. Add the peer first or omit --node.`)}else if(!o.agents?.[c])throw new Error(`Unknown agent "${c}". Add it locally, or use --node <peer> to forward to a mesh peer.`);!l&&d&&a!=="custom"&&(l=((await jn({type:"text",name:"secretEnv",message:`Signing secret env-var (recommended for ${a})`,initial:`${a.toUpperCase()}_WEBHOOK_SECRET`})).secretEnv||"").trim()),!g&&d&&(g=((await jn({type:"text",name:"description",message:"Description (optional)"})).description||"").trim());let f=await ge(p=>{if(p.webhooks=Array.isArray(p.webhooks)?p.webhooks:[],p.webhooks.find(h=>h.id===i))throw new Error(`Webhook "${i}" already exists.`);let u={id:i,source:a,agentId:c,enabled:!0};l&&(u.secretEnv=l),g&&(u.description=g),r&&(u.node=r),p.webhooks.push(u)});if(!f.success)throw new Error(f.error);console.log(xe.green(`\u2713 added webhook "${i}" (${a} \u2192 ${c}${r?` @ ${r}`:""})`)),f.reloaded&&console.log(xe.dim(" daemon hot-reloaded")),!l&&a!=="custom"&&console.log(xe.yellow(" \u26A0 no signing secret set \u2014 payloads will be accepted unsigned. Add one with --secret-env"))});vo.command("remove <id>").alias("rm").description("delete a webhook entry").option("--yes","skip confirmation").action(async(e,t)=>{if(!t.yes&&!(await jn({type:"confirm",name:"ok",message:`Delete webhook "${e}"?`,initial:!1})).ok)return;let o=await ge(n=>{let s=(n.webhooks||[]).length;if(n.webhooks=(n.webhooks||[]).filter(r=>r.id!==e),n.webhooks.length===s)throw new Error(`Webhook "${e}" not found.`)});if(!o.success)throw new Error(o.error);console.log(xe.green(`\u2713 removed webhook "${e}"`))});function Nb(e){return async t=>{let o=await ge(n=>{let s=(n.webhooks||[]).find(r=>r.id===t);if(!s)throw new Error(`Webhook "${t}" not found.`);s.enabled=e});if(!o.success)throw new Error(o.error);console.log(xe.green(`\u2713 ${e?"enabled":"disabled"} webhook "${t}"`))}}vo.command("enable <id>").description("enable a webhook entry").action(Nb(!0));vo.command("disable <id>").description("disable a webhook entry").action(Nb(!1));var Ta=new Ob().name("triggers").description("manage event-type \u2192 workflow mappings on a webhook");Ta.command("set <id> <eventType> <workflowId>").description("map an event-type to a workflow id").action(async(e,t,o)=>{let n=await ge(s=>{let r=(s.webhooks||[]).find(i=>i.id===e);if(!r)throw new Error(`Webhook "${e}" not found.`);r.triggers=r.triggers&&typeof r.triggers=="object"?r.triggers:{},r.triggers[t]=o});if(!n.success)throw new Error(n.error);console.log(xe.green(`\u2713 ${e}: ${t} \u2192 ${o}`))});Ta.command("remove <id> <eventType>").alias("rm").description("remove an event-type \u2192 workflow mapping").action(async(e,t)=>{let o=await ge(n=>{let s=(n.webhooks||[]).find(r=>r.id===e);if(!s)throw new Error(`Webhook "${e}" not found.`);s.triggers&&typeof s.triggers=="object"&&delete s.triggers[t]});if(!o.success)throw new Error(o.error);console.log(xe.green(`\u2713 removed trigger ${t} from "${e}"`))});Ta.command("default <id> <workflowId>").description("set the default workflow when no event-type matches (use '-' to clear)").action(async(e,t)=>{let o=t==="-"||t==="",n=await ge(s=>{let r=(s.webhooks||[]).find(i=>i.id===e);if(!r)throw new Error(`Webhook "${e}" not found.`);o?delete r.defaultWorkflow:r.defaultWorkflow=t});if(!n.success)throw new Error(n.error);console.log(xe.green(`\u2713 ${e}: defaultWorkflow ${o?"cleared":`\u2192 ${t}`}`))});vo.addCommand(Ta);vo.command("sources").description("list known webhook source types").option("--json","emit JSON").action(e=>{let t=jr.map(o=>({source:o,wired:$d.has(o),hint:Ib[o]}));if(e.json){console.log(JSON.stringify(t,null,2));return}console.log();for(let o of t){let n=o.wired?xe.green("\u2713 wired"):xe.dim("inbound-only");console.log(` ${xe.cyan(o.source.padEnd(8))} ${n} ${xe.dim(o.hint)}`)}console.log(),console.log(xe.dim(" Wired sources emit on:<source>-* hook events that workflows can subscribe to via trigger.hook.")),console.log(xe.dim(" Use 'custom' for any service not in the list (Odoo, HubSpot, Linear, Calendly, etc.).")),console.log()});import{Command as EC}from"commander";import Se from"chalk";oe();function Is(e){let{summary:t,backupPath:o}=Tt(n=>e(n));console.log(Se.green(`
|
|
@@ -727,7 +727,7 @@ ${e.body||""}`)}function HC(e){return e.startsWith("test/")||/\.test\.[cm]?[jt]s
|
|
|
727
727
|
|
|
728
728
|
`))>=0;){let p=l.slice(0,f);l=l.slice(f+2),iT(p)}}}catch(i){console.error(ye.red(` disconnected: ${i.message||i}`)),process.exit(1)}});function iT(e){let t="message",o="";for(let r of e.split(`
|
|
729
729
|
`))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?ye.dim(new Date(n.at).toLocaleTimeString()):"";switch(t){case"run":{let r=ye.cyan(n.phase?.padEnd(9)??"run"),i=ye.bold(n.workflowId??""),a=ye.dim((n.runId??"").slice(0,8)),c=n.nodeId?ye.yellow(n.nodeId):"",l=n.note?ye.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${r} ${i} ${a} ${c} ${l}`);break}case"task":{let r=ye.magenta(`task.${n.phase}`.padEnd(14)),i=ye.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ye.dim(`"${n.title}"`):"";console.log(`${s} ${r} ${i} ${ye.cyan(a)} ${c}`);break}case"signal":{let r=ye.green("signal".padEnd(9)),i=ye.bold(n.name),a=ye.dim(`(${n.scope})`),c=n.workflowId?ye.dim(n.workflowId):"";console.log(`${s} ${r} ${i} ${a} ${c}`);break}case"mesh":{let r=ye.blue("mesh".padEnd(9)),i=ye.bold(n.peer),a=n.healthy?ye.green("\u2713 healthy"):ye.red("\u2717 lost");console.log(`${s} ${r} ${i} ${a} ${ye.dim(n.delta??"")}`);break}case"channel":{let r=ye.yellow("channel".padEnd(9)),i=n.direction==="in"?ye.cyan("\u2190"):ye.magenta("\u2192"),a=ye.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ye.dim(n.textPreview):"";console.log(`${s} ${r} ${i} ${a} ${c}`);break}case"status":{console.log(ye.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)}`)}}oe();import{Command as aT}from"commander";import Ps from"chalk";function cT(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}`}var R$=new aT().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)").action(async e=>{let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let a=C(e.config);t||(t=a.dashboard?.daemonUrl||""),o||(o=a.dashboard?.token||"")}catch{}t||(t="http://localhost:18800");let n={};o&&(n.Authorization=`Bearer ${o}`);let s;try{let a=await fetch(cT(t,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(Ps.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(Ps.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(Ps.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(r.length===0){console.log(Ps.dim(" no events"));return}for(let a of r)console.log(` ${Ig(a)} ${Ps.dim(a.id)}`);let i=s.next??r[r.length-1].id;console.log(Ps.dim(`
|
|
730
|
-
${r.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${i}`))});import{Command as dT}from"commander";import _r from"chalk";import{spawn as gT}from"node:child_process";import{execFileSync as lT}from"node:child_process";function C$(e=()=>lT("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 T$=new dT().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(_r.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-
|
|
730
|
+
${r.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${i}`))});import{Command as dT}from"commander";import _r from"chalk";import{spawn as gT}from"node:child_process";import{execFileSync as lT}from"node:child_process";function C$(e=()=>lT("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 T$=new dT().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(_r.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-6ZHYSQU6.js"),o=t({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:C$();if(n?.ok){let{fetchAgents:l}=await import("./client-6ZHYSQU6.js"),g=await l(o);if(!g.length)throw new Error(`No AgentX agents returned by ${o.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(b=>b.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let f={};try{f=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let p=Object.fromEntries(g.map(b=>[b.id,{name:`AgentX ${b.name||b.id}`}])),u={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...f,model:`agentx/${d}`,providers:{...f.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${o.baseUrl}/v1`},models:p}}})};console.error(_r.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:h}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:y}=await import("./opencode-launch-ECMEY2QZ.js");await y({agentId:d,env:u,cwd:process.cwd(),pool:h,spawnImpl:gT,log:b=>console.error(_r.dim(b))});return}n&&!n.ok&&(console.error(_r.yellow(n.reason)),console.error(_r.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-UOZT7MWS.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 uT}from"commander";import le from"chalk";import{randomUUID as j$}from"crypto";import{createInterface as mT}from"node:readline/promises";import pT from"ora";import La from"chalk";function O$(e){console.error(),console.error(La.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(La.dim(` ${e.why}`)),console.error(),console.error(` Use ${La.cyan(e.instead)} instead.`),e.note&&console.error(La.dim(` ${e.note}`)),console.error()}var I$={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 N$=new uT().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)=>{O$({what:"agentx chat",...I$});let o=Lp({node:t.node,token:t.token,config:t.config}),n=(e??"").replace(/^@/,"").trim(),s=t.channel,r=t.chatId||`chat-cli:${j$().slice(0,12)}`,i=[];try{i=await Si(o)}catch(g){console.error(le.red(` cannot reach daemon at ${o.baseUrl}: ${g?.message||g}`)),console.error(le.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(i.length===0&&(console.error(le.red(" no agents registered with the daemon")),process.exit(1)),n?i.find(g=>g.id===n)||(console.error(le.red(` unknown agent: @${n}`)),console.error(le.dim(` registered: ${i.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=i[0].id,console.log(le.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:d}=await import("./ChatApp-N7REHHH3.js"),f=(await import("react")).default;await g(f.createElement(d,{conn:o,agentId:n,channel:s,chatId:r,agents:i})).waitUntilExit();return}hT(o.baseUrl,n,r,s);let a=mT({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(le.dim(`
|
|
731
731
|
bye`)),process.exit(0)});;){let g;try{g=(await a.question(le.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(le.dim(` @${n} chatId=${r} channel=${s}`));continue}if(g==="/clear"){r=`chat-cli:${j$().slice(0,12)}`,console.log(le.dim(` fresh chatId=${r} (warm process dropped)`));continue}if(g==="/agents"){try{let u=await Si(o);for(let h of u){let y=h.id===n?le.green("\u25CF"):le.dim("\u25CB");console.log(` ${y} @${h.id} ${le.dim(h.tier)} ${h.model??""}`)}}catch(u){console.error(le.red(` failed to list agents: ${u?.message||u}`))}continue}if(g.startsWith("/agent ")){let u=g.slice(7).replace(/^@/,"").trim();if(!u){console.log(le.red(" usage: /agent <id>"));continue}try{if(!(await Si(o)).find(y=>y.id===u)){console.log(le.red(` unknown agent: @${u}`));continue}n=u,console.log(le.dim(` now talking to @${n}`))}catch(h){console.error(le.red(` failed to switch agent: ${h?.message||h}`))}continue}if(g.startsWith("/")){console.log(le.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(le.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=pT({text:`@${n}\u2026`,color:"cyan"}).start(),f=Date.now(),p=fT(n);try{let u=await qp(o,n,g,{channel:s,chatId:r,onText:y=>{d.stop(),p.text(y)},onThinking:()=>{},onTool:y=>{d.stop(),p.tool(y)}});d.stop();let h=Math.round((Date.now()-f)/100)/10;u.error?p.finishError(u.error):p.finish(h,u.usage)}catch(u){d.stop(),p.finishError(u?.message||String(u))}finally{c=!1}if(l){console.log(le.dim(" bye"));return}}});function fT(e){let t=!1,o=!0,n=!1,s=new Set,r=()=>{t||(process.stdout.write(`${le.green(`@${e}`)}
|
|
732
732
|
`),t=!0)};return{text(i){if(i){r(),n=!0;for(let a of i)o&&a!==`
|
|
733
733
|
`&&(process.stdout.write(" "),o=!1),process.stdout.write(a),a===`
|
|
@@ -824,7 +824,7 @@ Restart the daemon to activate.
|
|
|
824
824
|
dist/
|
|
825
825
|
*.log
|
|
826
826
|
.env
|
|
827
|
-
`}import{Command as VT}from"commander";import tt from"chalk";import{writeFileSync as XT,mkdirSync as QT,existsSync as Ja,readFileSync as z$,appendFileSync as Y$}from"fs";import{resolve as Ls,dirname as X$}from"path";import{homedir as Gd}from"os";var Q$=new VT().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-
|
|
827
|
+
`}import{Command as VT}from"commander";import tt from"chalk";import{writeFileSync as XT,mkdirSync as QT,existsSync as Ja,readFileSync as z$,appendFileSync as Y$}from"fs";import{resolve as Ls,dirname as X$}from"path";import{homedir as Gd}from"os";var Q$=new VT().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-6YMRDLHO.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=tO(o);break;case"bash":s=iO(o);break;case"fish":s=aO(o);break;default:console.error(tt.red(`unsupported shell: ${n}`)),console.error(tt.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?Ls(String(e.output)):ZT(n);QT(X$(r),{recursive:!0}),XT(r,s),console.log(tt.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),eO(n,r,!!e.yes)});function ZT(e){let t=Gd();switch(e){case"zsh":return Ls(t,".zsh","completions","_agentx");case"bash":return Ls(t,".bash_completion.d","agentx.bash");case"fish":return Ls(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function eO(e,t,o){if(e==="zsh"){let n=Ls(Gd(),".zshrc"),s=X$(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Ja(n)?z$(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(tt.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Ja(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),Y$(n,g.join(`
|
|
828
828
|
`)+`
|
|
829
829
|
`),console.log(tt.green("\u2713 Patched ~/.zshrc")),console.log(tt.dim("Reload your shell: exec zsh"));return}console.log(tt.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(tt.cyan(` ${r}`)),l&&console.log(tt.cyan(` ${i}`)),console.log(),console.log(tt.dim("Then reload: exec zsh")),console.log(tt.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Ls(Gd(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Ja(n)?z$(n,"utf-8"):"").includes(t)){console.log(tt.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&Ja(n)){Y$(n,`
|
|
830
830
|
# agentx completion
|
|
@@ -840,4 +840,4 @@ ${cO({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
|
|
|
840
840
|
${o.url}`)}catch(t){console.error(Fs.red(` ${t.message}`)),process.exitCode=1}});Ur.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",zd).action(async(e,t)=>{try{let o=await Vd(t.models);if(!Yd(t.model,o)){console.log(Kd(t.model,o)),process.exitCode=1;return}let n=e==="-"?await gO():await dO(e,"utf8"),s=JSON.parse(n),{version:r}=await ei(),i=ok({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(Fs.red(` ${o.message}`)),process.exitCode=1}});async function gO(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function _J(){let e=await ei(),t=new uO().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=xp(n);Sp(s)&&vp("cli",s)});for(let o of[Zf,jf,If,Es,es,so,Ot,ap,cn,Di,bo,An,ko,Ho,Uw,Jo,ji,T$,Fo,Fh,Uh,Vh,fr,ay,uy,Mh,fy,hy,Ny,My,Ly,_t,Cn,P$,sr,Po,Q$,Ur])t.addCommand(o);for(let o of sk)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=sk.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,mO(o,74," "),""].join(`
|
|
841
841
|
`)}),t}var sk=[H,Ts,xo,Vt,ar,ys,Ve,vo,zo,xn,js,Ns,Lo,yt,ls,Ki,ga,vn,ua,E$,R$,wo,Nr,It,Fp,dn,qr,rl,Vo,kt,as,il,Na,uo,So,U$,W$,N$];function mO(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(`
|
|
842
842
|
`)}export{_J as buildProgram};
|
|
843
|
-
//# sourceMappingURL=program-
|
|
843
|
+
//# sourceMappingURL=program-6YMRDLHO.js.map
|