agentix-cli 0.183.0 → 0.185.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.
Files changed (154) hide show
  1. package/apps/mac-helper/Sources/AgentXHelper/Presence.swift +9 -0
  2. package/apps/mac-helper/Sources/AgentXHelper/PresenceTag.swift +25 -9
  3. package/dist/{App-777XBP22.js → App-WIHCYMHM.js} +2 -2
  4. package/dist/{ChatApp-ZYMF5HSR.js → ChatApp-V3UASKNG.js} +2 -2
  5. package/dist/{absorb-eval-HYGBAPXS.js → absorb-eval-EAGXITJH.js} +2 -2
  6. package/dist/{adapter-VV626IYN.js → adapter-7IDPCEJ7.js} +2 -2
  7. package/dist/{agent-BS5VSO5T.js → agent-H75SWYT6.js} +2 -2
  8. package/dist/{board-dashboard-3CMB3NPI.js → board-dashboard-TCZ3RAQR.js} +2004 -443
  9. package/dist/board-dashboard-TCZ3RAQR.js.map +1 -0
  10. package/dist/{chunk-PIVIOIEC.js → chunk-2GIYVYIM.js} +2 -2
  11. package/dist/{chunk-OTITQCEQ.js → chunk-2HZXLYWQ.js} +269 -264
  12. package/dist/chunk-2HZXLYWQ.js.map +1 -0
  13. package/dist/{chunk-RQOMUGUM.js → chunk-2LTZUZJU.js} +3 -3
  14. package/dist/{chunk-ZOCRNNNG.js → chunk-2V6ZGE74.js} +2 -2
  15. package/dist/{chunk-DOCAWXV5.js → chunk-4HYIERJ4.js} +2 -2
  16. package/dist/{chunk-QSJA6S66.js → chunk-56F5UTTA.js} +2 -2
  17. package/dist/{chunk-RG6MO7G5.js → chunk-7EMPPP3E.js} +2 -2
  18. package/dist/{chunk-3ENH7HAS.js → chunk-A4PW7EIK.js} +2 -2
  19. package/dist/chunk-AHWWJ7AF.js +2 -0
  20. package/dist/chunk-AHWWJ7AF.js.map +1 -0
  21. package/dist/{chunk-OIECBQ45.js → chunk-BITVUKT7.js} +2 -2
  22. package/dist/chunk-BLWVMGSJ.js +12 -0
  23. package/dist/chunk-BLWVMGSJ.js.map +1 -0
  24. package/dist/{chunk-M7V7NCX6.js → chunk-BZJF7DJR.js} +2 -2
  25. package/dist/chunk-BZJF7DJR.js.map +1 -0
  26. package/dist/{chunk-KLWCVTBM.js → chunk-DSIPKP2D.js} +2 -2
  27. package/dist/{chunk-TD2D4TGI.js → chunk-FJMTCU4S.js} +2 -2
  28. package/dist/{chunk-R2QFKEX5.js → chunk-GSQ2RCOZ.js} +2 -2
  29. package/dist/{chunk-UMHN33JQ.js → chunk-JJ7FHH53.js} +2 -2
  30. package/dist/{chunk-6D4RGQCU.js → chunk-LR4QUAJT.js} +2 -2
  31. package/dist/{chunk-MLNA54RW.js → chunk-LZVQ4N2Z.js} +72 -72
  32. package/dist/chunk-LZVQ4N2Z.js.map +1 -0
  33. package/dist/{chunk-GXOKZSCS.js → chunk-NBWSZ53L.js} +2 -2
  34. package/dist/{chunk-ZSS3GL5A.js → chunk-NHW4IY6N.js} +2 -2
  35. package/dist/{chunk-6MY7VXQV.js → chunk-NS2HSAHF.js} +2 -2
  36. package/dist/{chunk-VDUMYEJH.js → chunk-OJ53ATNN.js} +2 -2
  37. package/dist/{chunk-XPE2WKPF.js → chunk-P7K5ZQVT.js} +2 -2
  38. package/dist/{chunk-YH7NALJ4.js → chunk-PN42ECV3.js} +2 -2
  39. package/dist/{chunk-JJ2WRGKI.js → chunk-R2KSORSK.js} +2 -2
  40. package/dist/{chunk-6KWHQAXS.js → chunk-RTIGD4NG.js} +2 -2
  41. package/dist/{chunk-YZCQDZCA.js → chunk-UASRZKZQ.js} +6 -6
  42. package/dist/{chunk-UNZVDS3P.js → chunk-V4IOGISL.js} +2 -2
  43. package/dist/{chunk-SBJHIBWX.js → chunk-V6QFBL6F.js} +3 -3
  44. package/dist/{chunk-XBQISUBE.js → chunk-YTS54UZ5.js} +2 -2
  45. package/dist/{chunk-DYNXOYFN.js → chunk-Z5DHUJIL.js} +2 -2
  46. package/dist/cli.js +1 -1
  47. package/dist/{client-CMQZO22V.js → client-57TCFIV5.js} +2 -2
  48. package/dist/{compaction-26OHHULF.js → compaction-R7VWQB6X.js} +2 -2
  49. package/dist/{config-BMYFEAO5.js → config-RHCIE7VE.js} +2 -2
  50. package/dist/{config-mutate-N6W52YXB.js → config-mutate-HCYXR2WP.js} +2 -2
  51. package/dist/config-mutator-JQ2R4J5Z.js +2 -0
  52. package/dist/{contributions-KRES5F2V.js → contributions-R4HXLJXU.js} +2 -2
  53. package/dist/doctor-DKW3EP3O.js +2 -0
  54. package/dist/{follow-up-tool-M57XXTPX.js → follow-up-tool-MC4TBGLP.js} +2 -2
  55. package/dist/grants-COGXFWO3.js +2 -0
  56. package/dist/hub-HXVIO4U5.js +2 -0
  57. package/dist/index.d.ts +62 -8
  58. package/dist/index.js +1 -1
  59. package/dist/{program-BHDAV67G.js → program-2DFU4DCC.js} +24 -24
  60. package/dist/program-2DFU4DCC.js.map +1 -0
  61. package/dist/{promote-LXKF6A24.js → promote-D24WO52J.js} +2 -2
  62. package/dist/{query-W7OBMMVM.js → query-J5NRZZUQ.js} +2 -2
  63. package/dist/{query-settings-PTA2SA63.js → query-settings-NT6ACLQY.js} +2 -2
  64. package/dist/{registry-OHUOHAD2.js → registry-SBIZVSQV.js} +2 -2
  65. package/dist/{request-planner-T44RMVNO.js → request-planner-2CVL22EB.js} +2 -2
  66. package/dist/{review-candidates-LKFIKTY6.js → review-candidates-MMNDJOTD.js} +2 -2
  67. package/dist/{routing-7HEUMP4R.js → routing-KRST324W.js} +2 -2
  68. package/dist/schedule-tool-KOFUKVX5.js +2 -0
  69. package/dist/{scheduler-I3UNKBBJ.js → scheduler-GCCE4FQP.js} +2 -2
  70. package/dist/{seat-DAMUB3CU.js → seat-E6F56TUM.js} +2 -2
  71. package/dist/{select-PMNHXNKI.js → select-D2VUSUCJ.js} +2 -2
  72. package/dist/{set-enabled-36JN5ZRJ.js → set-enabled-GBI7JREU.js} +2 -2
  73. package/dist/{sprint-tool-Z4RRPK6I.js → sprint-tool-HZ24VIC2.js} +2 -2
  74. package/dist/{tool-SK3AAQYW.js → tool-7BEFI5SJ.js} +2 -2
  75. package/dist/{tool-KTL4TLZP.js → tool-OXZ4TQBG.js} +2 -2
  76. package/dist/{tool-B6I22BG2.js → tool-QLQEYQYM.js} +2 -2
  77. package/dist/wiki-RFDU6SVD.js +2 -0
  78. package/dist/wiki-enrich-LDI67VQU.js +2 -0
  79. package/package.json +1 -1
  80. package/dist/board-dashboard-3CMB3NPI.js.map +0 -1
  81. package/dist/chunk-CTNZVRPA.js +0 -6
  82. package/dist/chunk-CTNZVRPA.js.map +0 -1
  83. package/dist/chunk-M7V7NCX6.js.map +0 -1
  84. package/dist/chunk-MLNA54RW.js.map +0 -1
  85. package/dist/chunk-OTITQCEQ.js.map +0 -1
  86. package/dist/chunk-QOYAX2FT.js +0 -2
  87. package/dist/chunk-QOYAX2FT.js.map +0 -1
  88. package/dist/config-mutator-S5SGBNOG.js +0 -2
  89. package/dist/doctor-2KACCIZU.js +0 -2
  90. package/dist/grants-FY2TIT7I.js +0 -2
  91. package/dist/hub-FVAPTKTF.js +0 -2
  92. package/dist/program-BHDAV67G.js.map +0 -1
  93. package/dist/schedule-tool-W6KPENHW.js +0 -2
  94. package/dist/wiki-H2CBE4SM.js +0 -2
  95. package/dist/wiki-enrich-GTUSSLCD.js +0 -2
  96. /package/dist/{App-777XBP22.js.map → App-WIHCYMHM.js.map} +0 -0
  97. /package/dist/{ChatApp-ZYMF5HSR.js.map → ChatApp-V3UASKNG.js.map} +0 -0
  98. /package/dist/{absorb-eval-HYGBAPXS.js.map → absorb-eval-EAGXITJH.js.map} +0 -0
  99. /package/dist/{adapter-VV626IYN.js.map → adapter-7IDPCEJ7.js.map} +0 -0
  100. /package/dist/{agent-BS5VSO5T.js.map → agent-H75SWYT6.js.map} +0 -0
  101. /package/dist/{chunk-PIVIOIEC.js.map → chunk-2GIYVYIM.js.map} +0 -0
  102. /package/dist/{chunk-RQOMUGUM.js.map → chunk-2LTZUZJU.js.map} +0 -0
  103. /package/dist/{chunk-ZOCRNNNG.js.map → chunk-2V6ZGE74.js.map} +0 -0
  104. /package/dist/{chunk-DOCAWXV5.js.map → chunk-4HYIERJ4.js.map} +0 -0
  105. /package/dist/{chunk-QSJA6S66.js.map → chunk-56F5UTTA.js.map} +0 -0
  106. /package/dist/{chunk-RG6MO7G5.js.map → chunk-7EMPPP3E.js.map} +0 -0
  107. /package/dist/{chunk-3ENH7HAS.js.map → chunk-A4PW7EIK.js.map} +0 -0
  108. /package/dist/{chunk-OIECBQ45.js.map → chunk-BITVUKT7.js.map} +0 -0
  109. /package/dist/{chunk-KLWCVTBM.js.map → chunk-DSIPKP2D.js.map} +0 -0
  110. /package/dist/{chunk-TD2D4TGI.js.map → chunk-FJMTCU4S.js.map} +0 -0
  111. /package/dist/{chunk-R2QFKEX5.js.map → chunk-GSQ2RCOZ.js.map} +0 -0
  112. /package/dist/{chunk-UMHN33JQ.js.map → chunk-JJ7FHH53.js.map} +0 -0
  113. /package/dist/{chunk-6D4RGQCU.js.map → chunk-LR4QUAJT.js.map} +0 -0
  114. /package/dist/{chunk-GXOKZSCS.js.map → chunk-NBWSZ53L.js.map} +0 -0
  115. /package/dist/{chunk-ZSS3GL5A.js.map → chunk-NHW4IY6N.js.map} +0 -0
  116. /package/dist/{chunk-6MY7VXQV.js.map → chunk-NS2HSAHF.js.map} +0 -0
  117. /package/dist/{chunk-VDUMYEJH.js.map → chunk-OJ53ATNN.js.map} +0 -0
  118. /package/dist/{chunk-XPE2WKPF.js.map → chunk-P7K5ZQVT.js.map} +0 -0
  119. /package/dist/{chunk-YH7NALJ4.js.map → chunk-PN42ECV3.js.map} +0 -0
  120. /package/dist/{chunk-JJ2WRGKI.js.map → chunk-R2KSORSK.js.map} +0 -0
  121. /package/dist/{chunk-6KWHQAXS.js.map → chunk-RTIGD4NG.js.map} +0 -0
  122. /package/dist/{chunk-YZCQDZCA.js.map → chunk-UASRZKZQ.js.map} +0 -0
  123. /package/dist/{chunk-UNZVDS3P.js.map → chunk-V4IOGISL.js.map} +0 -0
  124. /package/dist/{chunk-SBJHIBWX.js.map → chunk-V6QFBL6F.js.map} +0 -0
  125. /package/dist/{chunk-XBQISUBE.js.map → chunk-YTS54UZ5.js.map} +0 -0
  126. /package/dist/{chunk-DYNXOYFN.js.map → chunk-Z5DHUJIL.js.map} +0 -0
  127. /package/dist/{client-CMQZO22V.js.map → client-57TCFIV5.js.map} +0 -0
  128. /package/dist/{compaction-26OHHULF.js.map → compaction-R7VWQB6X.js.map} +0 -0
  129. /package/dist/{config-BMYFEAO5.js.map → config-RHCIE7VE.js.map} +0 -0
  130. /package/dist/{config-mutate-N6W52YXB.js.map → config-mutate-HCYXR2WP.js.map} +0 -0
  131. /package/dist/{config-mutator-S5SGBNOG.js.map → config-mutator-JQ2R4J5Z.js.map} +0 -0
  132. /package/dist/{contributions-KRES5F2V.js.map → contributions-R4HXLJXU.js.map} +0 -0
  133. /package/dist/{doctor-2KACCIZU.js.map → doctor-DKW3EP3O.js.map} +0 -0
  134. /package/dist/{follow-up-tool-M57XXTPX.js.map → follow-up-tool-MC4TBGLP.js.map} +0 -0
  135. /package/dist/{grants-FY2TIT7I.js.map → grants-COGXFWO3.js.map} +0 -0
  136. /package/dist/{hub-FVAPTKTF.js.map → hub-HXVIO4U5.js.map} +0 -0
  137. /package/dist/{promote-LXKF6A24.js.map → promote-D24WO52J.js.map} +0 -0
  138. /package/dist/{query-W7OBMMVM.js.map → query-J5NRZZUQ.js.map} +0 -0
  139. /package/dist/{query-settings-PTA2SA63.js.map → query-settings-NT6ACLQY.js.map} +0 -0
  140. /package/dist/{registry-OHUOHAD2.js.map → registry-SBIZVSQV.js.map} +0 -0
  141. /package/dist/{request-planner-T44RMVNO.js.map → request-planner-2CVL22EB.js.map} +0 -0
  142. /package/dist/{review-candidates-LKFIKTY6.js.map → review-candidates-MMNDJOTD.js.map} +0 -0
  143. /package/dist/{routing-7HEUMP4R.js.map → routing-KRST324W.js.map} +0 -0
  144. /package/dist/{schedule-tool-W6KPENHW.js.map → schedule-tool-KOFUKVX5.js.map} +0 -0
  145. /package/dist/{scheduler-I3UNKBBJ.js.map → scheduler-GCCE4FQP.js.map} +0 -0
  146. /package/dist/{seat-DAMUB3CU.js.map → seat-E6F56TUM.js.map} +0 -0
  147. /package/dist/{select-PMNHXNKI.js.map → select-D2VUSUCJ.js.map} +0 -0
  148. /package/dist/{set-enabled-36JN5ZRJ.js.map → set-enabled-GBI7JREU.js.map} +0 -0
  149. /package/dist/{sprint-tool-Z4RRPK6I.js.map → sprint-tool-HZ24VIC2.js.map} +0 -0
  150. /package/dist/{tool-SK3AAQYW.js.map → tool-7BEFI5SJ.js.map} +0 -0
  151. /package/dist/{tool-KTL4TLZP.js.map → tool-OXZ4TQBG.js.map} +0 -0
  152. /package/dist/{tool-B6I22BG2.js.map → tool-QLQEYQYM.js.map} +0 -0
  153. /package/dist/{wiki-H2CBE4SM.js.map → wiki-RFDU6SVD.js.map} +0 -0
  154. /package/dist/{wiki-enrich-GTUSSLCD.js.map → wiki-enrich-LDI67VQU.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as ch,b as zi,g as lh}from"./chunk-R2QFKEX5.js";import{b as rh}from"./chunk-RG6MO7G5.js";import{$ as Bf,A as xf,B as Sf,C as Af,E as co,G as Tf,H as Cf,I as jf,J as Pf,L as _f,M as Df,N as Mf,O as ul,P as Lf,U as qf,V as Ff,W as ml,X as Uf,_ as Wf,aa as Jf,ba as Hf,ca as Kf,da as Xf,ea as Vf,ga as pl,ha as Qf,ja as Zf,ka as eh,l as ff,la as th,m as hf,q as wf,r as yf,t as bf,v as ks,w as vs,x as $f,y as kf,z as vf}from"./chunk-XPE2WKPF.js";import{n as fl}from"./chunk-XBQISUBE.js";import{a as oh,b as nh,d as yr,e as sh}from"./chunk-VDUMYEJH.js";import{a as ih,b as ah}from"./chunk-YH7NALJ4.js";import"./chunk-EFGAPAYZ.js";import{d as Of,e as gl,h as If,i as Nf}from"./chunk-CTN4KYE6.js";import{a as Gf,c as zf,d as Yf}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as jt}from"./chunk-3ENH7HAS.js";import{a as Ef,c as Rf}from"./chunk-DYNXOYFN.js";import{a as ll}from"./chunk-LNY6N73E.js";import{a as km,b as Bc}from"./chunk-CZMVJP7O.js";import{a as Lc,b as om}from"./chunk-RKPAVWXF.js";import{$ as Wp,A as pp,Aa as il,B as Xc,Ba as lf,C as fp,Ca as gf,D as hp,Da as cl,E as wp,Ea as mf,F as yp,Fa as Hi,G as bp,Ga as $s,H as $p,Ha as Gi,I as Mi,Ia as dl,J as kp,Ja as pf,K as Vc,L as vp,M as xp,N as Sp,O as Ap,P as Ep,Q as Li,R as Ip,S as Pp,T as _p,U as Dp,V as Mp,W as Lp,X as Zc,Y as qp,Z as Fp,_ as Up,a as vm,aa as Bp,b as xm,ba as Jp,ca as Hp,da as Gp,ea as Zp,fa as Ui,ga as Eo,h as xi,ha as Wo,i as Rm,ia as ws,j as mr,ja as Wi,k as Si,ka as Bi,l as Cm,la as rl,m as Im,ma as ef,n as Bm,na as tf,o as Jm,oa as of,p as Oi,pa as nf,q as zc,qa as sf,r as Vm,ra as rf,s as cp,sa as ys,t as lp,ta as bs,u as dp,ua as af,v as gp,va as hr,w as Di,wa as cf,x as up,xa as lt,y as mp,ya as Ji,z as Kc,za as wr}from"./chunk-OTITQCEQ.js";import{$a as Yp,Gb as df,Hb as al,Oa as pr,Q as np,Ra as el,S as Pi,Sa as qi,T as sp,Ta as zp,Vb as ao,W as rp,X as _i,Xb as uf,_a as Uo,ab as tl,cb as ol,ea as Rp,eb as Kp,fa as Tp,fb as Xp,ga as Cp,gb as fr,ha as Qc,ka as Op,kb as Fi,nb as Vp,ob as Qp,pb as nl,v as Om,wb as sl}from"./chunk-MLNA54RW.js";import"./chunk-GTJIKXDB.js";import{a as Sm,c as Jc,e as Am,f as Em}from"./chunk-GXOKZSCS.js";import"./chunk-ZVP6GB4G.js";import{F as Ri,G as Um,H as Wm,L as ip,M as ap,a as Dc,b as Xu,e as Vu,f as Qu,n as Ai,o as Ei,p as Nm,q as jm,r as Pm,t as _m,u as Dm,w as Mm,x as Lm,y as qm,z as Fm}from"./chunk-KLWCVTBM.js";import"./chunk-IMLAPB7G.js";import"./chunk-VZLIBDLH.js";import{a as Np,b as jp}from"./chunk-EKJG63EJ.js";import"./chunk-ZSS3GL5A.js";import{c as Hm}from"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import{b as Gc}from"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import{c as Gm,e as Ti,g as Ci}from"./chunk-LQE73AZR.js";import{a as zm,b as Ym,c as Km,d as Xm}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-UMHN33JQ.js";import{a as Qm,b as hn,c as Zm,d as Ii,g as ep,h as tp,j as op,k as Yc,n as Ni,o as Ao,p as ji}from"./chunk-CTNZVRPA.js";import"./chunk-PPUN7YHA.js";import"./chunk-A5GYG56I.js";import{a as Hc,p as Tm}from"./chunk-ZOCRNNNG.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Nt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import{a as io}from"./chunk-MNG2AMKZ.js";import{a as dm,b as gm,c as um,d as mm,e as Fc,f as pm,g as Uc,h as Wc,l as fm,m as hm}from"./chunk-RX5O5637.js";import{f as wm,i as ym,l as bm,m as $m}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{a as Mc,d as Zu,e as vi}from"./chunk-QPABR72X.js";import{a as ur,e as nm,f as sm,g as qc,i as rm,j as im,l as am,m as cm,n as lm}from"./chunk-UNZVDS3P.js";import{b as hs,e as tm}from"./chunk-AJ5HMDRW.js";import{c as em}from"./chunk-KP7KDLZ2.js";import{B as Ic,C as Ou,O as Fo,U as Hu,X as zu,Y as Yu,g as vu,r as xu,ya as Ku}from"./chunk-YZCQDZCA.js";import{I as gs,J as $i,K as ki,L as us,M as Nu,N as Lo,P as qo,b as ds,fa as Bu,r as xo,s as Nc,t as Iu,u as jc,ua as Ju,w as So,wa as Gu,x as bi}from"./chunk-PIVIOIEC.js";import{b as pn}from"./chunk-MEFPXHQJ.js";import"./chunk-RQOMUGUM.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as Pu}from"./chunk-SZDACK6O.js";import{f as _u,g as Du,h as Pc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as Lu,f as fn,k as ps}from"./chunk-VJVXEVZ7.js";import{a as Tu,k as Mu,n as Wu}from"./chunk-6KWHQAXS.js";import{a as Tt,b as de,c as qe,d as fs,e as qu}from"./chunk-6MY7VXQV.js";import{a as Fu,b as _c,h as Uu}from"./chunk-3UOTLMXD.js";import{i as Au,j as Eu}from"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import{a as Oc,b as Ru}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Cu}from"./chunk-X5C5W3E4.js";import{a as ms}from"./chunk-GV7S5BAX.js";import{e as ju}from"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import{a as Cc}from"./chunk-TD2D4TGI.js";import"./chunk-OIECBQ45.js";import{c as Su}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-SBJHIBWX.js";import"./chunk-JTFCU5LH.js";import{g as Mo,i as yi}from"./chunk-QSJA6S66.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-JJ2WRGKI.js";import{a as xc,b as zg,c as mx,d as li,e as Yg,f as pu,g as vx,h as fu,i as xx,m as ls,n as wu,q as yu,u as bu,y as ro,z as gr}from"./chunk-6D4RGQCU.js";import{a as vo,b as cs,e as gu,f as dr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as wi,b as hu}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as Do,j as $u}from"./chunk-QUFIUXMQ.js";import{n as ku}from"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-QOYAX2FT.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as so,b as ux}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as mi,$a as Tc,F as Ac,G as wx,Gb as oe,Qa as au,Ra as cr,Ta as Rc,U as nu,V as yx,_ as ui,_a as cu,bb as lu,c as di,ca as su,cb as $x,d as Kg,da as ru,e as mn,ea as pi,f as Sc,fa as Ec,h as Xg,hb as du,i as gi,j as px,oa as iu,pa as bx,r as Qg,s as Zg,t as eu,u as tu,v as ou,vb as fi,w as hx,wb as lr,xb as T,zb as hi}from"./chunk-M7V7NCX6.js";import"./chunk-VJ5HC63R.js";import{j as $t,r as as}from"./chunk-UEEB3UTU.js";import{a as Vg,e as fx}from"./chunk-VQRY4IDI.js";import{g as uu,k as mu,l as kx}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Sx}from"commander";var dh=new Sx().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 xm({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 Ax}from"commander";import{execFileSync as Bt}from"node:child_process";import{cpSync as gh,existsSync as yl,mkdirSync as hl,mkdtempSync as Ex,readdirSync as Rx,rmSync as uh,writeFileSync as mh}from"node:fs";import{dirname as ph,join as dt}from"node:path";import{homedir as Yi,release as Tx,tmpdir as Cx}from"node:os";import{setTimeout as Ox}from"node:timers/promises";function Ki(){let e=Nm(process.platform,process.arch,Tx());if(e)throw new Error(e)}function Xi(){let e=dt(Yi(),"Library/LaunchAgents"),t=[];try{t=Rx(e).filter(_m)}catch{}let o=t.flatMap(n=>{let s=dt(e,n);try{return[{file:s,plist:Bt("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Dm(e,o)}function br(e){return`gui/${process.getuid()}/${e.label}`}async function wl(e){try{Bt("launchctl",["bootout",br(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Bt("launchctl",["print",br(e)],{stdio:"pipe"})}catch{return}await Ox(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function fh(e){if(!yl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Bt("launchctl",["print",br(e)],{stdio:"pipe"})}catch{t=!1}t||Bt("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Bt("launchctl",["kickstart",br(e)],{stdio:"pipe"})}function Ix(){let e=Fm();if(e&&yl(dt(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 xs=new Ax("desktop").description("install and control the macOS desktop assistant");xs.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=>{Ki();let t=T(),o=jm(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=Ix(),i=dt(Yi(),"Applications"),{keep:a,remove:c}=Xi();if(console.log(`Desktop assistant \u2192 ${dt(i,Ai)}
1
+ import{a as ch,b as zi,g as lh}from"./chunk-GSQ2RCOZ.js";import{b as rh}from"./chunk-7EMPPP3E.js";import{$ as Bf,A as xf,B as Sf,C as Af,E as co,G as Tf,H as Cf,I as jf,J as Pf,L as _f,M as Df,N as Mf,O as ul,P as Lf,U as qf,V as Ff,W as ml,X as Uf,_ as Wf,aa as Jf,ba as Hf,ca as Kf,da as Xf,ea as Vf,ga as pl,ha as Qf,ja as Zf,ka as eh,l as ff,la as th,m as hf,q as wf,r as yf,t as bf,v as ks,w as vs,x as $f,y as kf,z as vf}from"./chunk-P7K5ZQVT.js";import{n as fl}from"./chunk-YTS54UZ5.js";import{a as oh,b as nh,d as yr,e as sh}from"./chunk-OJ53ATNN.js";import{a as ih,b as ah}from"./chunk-PN42ECV3.js";import"./chunk-EFGAPAYZ.js";import{d as Of,e as gl,h as If,i as Nf}from"./chunk-CTN4KYE6.js";import{a as Gf,c as zf,d as Yf}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as jt}from"./chunk-A4PW7EIK.js";import{a as Ef,c as Rf}from"./chunk-Z5DHUJIL.js";import{a as ll}from"./chunk-LNY6N73E.js";import{a as km,b as Bc}from"./chunk-CZMVJP7O.js";import{a as Lc,b as om}from"./chunk-RKPAVWXF.js";import{$ as Wp,A as pp,Aa as il,B as Xc,Ba as lf,C as fp,Ca as gf,D as hp,Da as cl,E as wp,Ea as mf,F as yp,Fa as Hi,G as bp,Ga as $s,H as $p,Ha as Gi,I as Mi,Ia as dl,J as kp,Ja as pf,K as Vc,L as vp,M as xp,N as Sp,O as Ap,P as Ep,Q as Li,R as Ip,S as Pp,T as _p,U as Dp,V as Mp,W as Lp,X as Zc,Y as qp,Z as Fp,_ as Up,a as vm,aa as Bp,b as xm,ba as Jp,ca as Hp,da as Gp,ea as Zp,fa as Ui,ga as Eo,h as xi,ha as Wo,i as Rm,ia as ws,j as mr,ja as Wi,k as Si,ka as Bi,l as Cm,la as rl,m as Im,ma as ef,n as Bm,na as tf,o as Jm,oa as of,p as Oi,pa as nf,q as zc,qa as sf,r as Vm,ra as rf,s as cp,sa as ys,t as lp,ta as bs,u as dp,ua as af,v as gp,va as hr,w as Di,wa as cf,x as up,xa as lt,y as mp,ya as Ji,z as Kc,za as wr}from"./chunk-2HZXLYWQ.js";import{$a as Yp,Gb as df,Hb as al,Oa as pr,Q as np,Ra as el,S as Pi,Sa as qi,T as sp,Ta as zp,Vb as ao,W as rp,X as _i,Xb as uf,_a as Uo,ab as tl,cb as ol,ea as Rp,eb as Kp,fa as Tp,fb as Xp,ga as Cp,gb as fr,ha as Qc,ka as Op,kb as Fi,nb as Vp,ob as Qp,pb as nl,v as Om,wb as sl}from"./chunk-LZVQ4N2Z.js";import"./chunk-GTJIKXDB.js";import{a as Sm,c as Jc,e as Am,f as Em}from"./chunk-NBWSZ53L.js";import"./chunk-ZVP6GB4G.js";import{F as Ri,G as Um,H as Wm,L as ip,M as ap,a as Dc,b as Xu,e as Vu,f as Qu,n as Ai,o as Ei,p as Nm,q as jm,r as Pm,t as _m,u as Dm,w as Mm,x as Lm,y as qm,z as Fm}from"./chunk-DSIPKP2D.js";import"./chunk-IMLAPB7G.js";import"./chunk-VZLIBDLH.js";import{a as Np,b as jp}from"./chunk-EKJG63EJ.js";import"./chunk-NHW4IY6N.js";import{c as Hm}from"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import{b as Gc}from"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import{c as Gm,e as Ti,g as Ci}from"./chunk-LQE73AZR.js";import{a as zm,b as Ym,c as Km,d as Xm}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-JJ7FHH53.js";import{d as Qm,e as hn,f as Zm,g as Ii,j as ep,k as tp,m as op,n as Yc,q as Ni,r as Ao,s as ji}from"./chunk-BLWVMGSJ.js";import"./chunk-PPUN7YHA.js";import"./chunk-A5GYG56I.js";import{a as Hc,p as Tm}from"./chunk-2V6ZGE74.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Nt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import{a as io}from"./chunk-MNG2AMKZ.js";import{a as dm,b as gm,c as um,d as mm,e as Fc,f as pm,g as Uc,h as Wc,l as fm,m as hm}from"./chunk-RX5O5637.js";import{f as wm,i as ym,l as bm,m as $m}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{a as Mc,d as Zu,e as vi}from"./chunk-QPABR72X.js";import{a as ur,e as nm,f as sm,g as qc,i as rm,j as im,l as am,m as cm,n as lm}from"./chunk-V4IOGISL.js";import{b as hs,e as tm}from"./chunk-AJ5HMDRW.js";import{c as em}from"./chunk-KP7KDLZ2.js";import{B as Ic,C as Ou,O as Fo,U as Hu,X as zu,Y as Yu,g as vu,r as xu,ya as Ku}from"./chunk-UASRZKZQ.js";import{I as gs,J as $i,K as ki,L as us,M as Nu,N as Lo,P as qo,b as ds,fa as Bu,r as xo,s as Nc,t as Iu,u as jc,ua as Ju,w as So,wa as Gu,x as bi}from"./chunk-2GIYVYIM.js";import{b as pn}from"./chunk-MEFPXHQJ.js";import"./chunk-2LTZUZJU.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as Pu}from"./chunk-SZDACK6O.js";import{f as _u,g as Du,h as Pc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as Lu,f as fn,k as ps}from"./chunk-VJVXEVZ7.js";import{a as Tu,k as Mu,n as Wu}from"./chunk-RTIGD4NG.js";import{a as Tt,b as de,c as qe,d as fs,e as qu}from"./chunk-NS2HSAHF.js";import{a as Fu,b as _c,h as Uu}from"./chunk-3UOTLMXD.js";import{i as Au,j as Eu}from"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import{a as Oc,b as Ru}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Cu}from"./chunk-X5C5W3E4.js";import{a as ms}from"./chunk-GV7S5BAX.js";import{e as ju}from"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import{a as Cc}from"./chunk-FJMTCU4S.js";import"./chunk-BITVUKT7.js";import{c as Su}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-V6QFBL6F.js";import"./chunk-JTFCU5LH.js";import{g as Mo,i as yi}from"./chunk-56F5UTTA.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-R2KSORSK.js";import{a as xc,b as zg,c as mx,d as li,e as Yg,f as pu,g as vx,h as fu,i as xx,m as ls,n as wu,q as yu,u as bu,y as ro,z as gr}from"./chunk-LR4QUAJT.js";import{a as vo,b as cs,e as gu,f as dr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as wi,b as hu}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as Do,j as $u}from"./chunk-QUFIUXMQ.js";import{n as ku}from"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as so,b as ux}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as mi,$a as Tc,F as Ac,G as wx,Gb as oe,Qa as au,Ra as cr,Ta as Rc,U as nu,V as yx,_ as ui,_a as cu,bb as lu,c as di,ca as su,cb as $x,d as Kg,da as ru,e as mn,ea as pi,f as Sc,fa as Ec,h as Xg,hb as du,i as gi,j as px,oa as iu,pa as bx,r as Qg,s as Zg,t as eu,u as tu,v as ou,vb as fi,w as hx,wb as lr,xb as T,zb as hi}from"./chunk-BZJF7DJR.js";import"./chunk-VJ5HC63R.js";import{j as $t,r as as}from"./chunk-UEEB3UTU.js";import{a as Vg,e as fx}from"./chunk-VQRY4IDI.js";import{g as uu,k as mu,l as kx}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Sx}from"commander";var dh=new Sx().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 xm({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 Ax}from"commander";import{execFileSync as Bt}from"node:child_process";import{cpSync as gh,existsSync as yl,mkdirSync as hl,mkdtempSync as Ex,readdirSync as Rx,rmSync as uh,writeFileSync as mh}from"node:fs";import{dirname as ph,join as dt}from"node:path";import{homedir as Yi,release as Tx,tmpdir as Cx}from"node:os";import{setTimeout as Ox}from"node:timers/promises";function Ki(){let e=Nm(process.platform,process.arch,Tx());if(e)throw new Error(e)}function Xi(){let e=dt(Yi(),"Library/LaunchAgents"),t=[];try{t=Rx(e).filter(_m)}catch{}let o=t.flatMap(n=>{let s=dt(e,n);try{return[{file:s,plist:Bt("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Dm(e,o)}function br(e){return`gui/${process.getuid()}/${e.label}`}async function wl(e){try{Bt("launchctl",["bootout",br(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Bt("launchctl",["print",br(e)],{stdio:"pipe"})}catch{return}await Ox(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function fh(e){if(!yl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Bt("launchctl",["print",br(e)],{stdio:"pipe"})}catch{t=!1}t||Bt("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Bt("launchctl",["kickstart",br(e)],{stdio:"pipe"})}function Ix(){let e=Fm();if(e&&yl(dt(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 xs=new Ax("desktop").description("install and control the macOS desktop assistant");xs.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=>{Ki();let t=T(),o=jm(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=Ix(),i=dt(Yi(),"Applications"),{keep:a,remove:c}=Xi();if(console.log(`Desktop assistant \u2192 ${dt(i,Ai)}
2
2
  Computer-use helper \u2192 ${dt(i,Ei)}
3
3
  Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -65,7 +65,7 @@ Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choos
65
65
  `)[0]}. Run this from the folder that holds agentx.json.`),!1}let n=e==="agent"?!!o.agents?.[t]:t===cr||(o.people??[]).some(s=>s.id===t);return n||An(e==="agent"?`No agent "${t}" in agentx.json.`:`No person "${t}" in agentx.json: agentx people list`),n}async function Vw(e,t,o){if(Xw(e,t))try{await bm(process.cwd(),e,t,km(o)),console.log(Sn.green(` \u2713 picture set for ${e} "${t}". Pages show it on their next load.`))}catch(n){if(n instanceof wm){An(n.message);return}throw n}}function Qw(e,t){Xw(e,t)&&console.log($m(process.cwd(),e,t)?Sn.green(` \u2713 picture removed for ${e} "${t}"; the initials show again.`):Sn.dim(` ${e} "${t}" has no picture.`))}function Jl(e){let t=e.agent?.trim()||So();return t||An("Say which agent: --agent <id>"),t}function Zw(){let e=new Kw("picture").description("an agent's profile picture: set, remove or show (an agent may set its own)");return e.command("set <file>").description("set the picture from a PNG, JPEG or WebP file (1 MB at most); it is cut to a square, metadata dropped").option("--agent <id>","which agent (default: the agent running this command)").action(async(t,o)=>{if(So()){let s=await Bc(t,o.agent?.trim(),{daemonUrl:Yw()});return s.ok?console.log(Sn.green(` \u2713 ${s.message}`)):An(s.message)}let n=Jl(o);n&&await Vw("agent",n,t)}),e.command("remove").alias("rm").description("remove the picture: the initials show again").option("--agent <id>","which agent (default: the agent running this command)").action(async t=>{if(So()){let n=await Bc(null,t.agent?.trim(),{daemonUrl:Yw()});return n.ok?console.log(Sn.green(` \u2713 ${n.message}`)):An(n.message)}let o=Jl(t);o&&Qw("agent",o)}),e.command("show").description("say whether the agent has a picture").option("--agent <id>","which agent (default: the agent running this command)").action(t=>{let o=Jl(t);if(!o)return;let n=ym(process.cwd(),"agent",o);console.log(n?` ${o}: picture set (.agentx/pictures/agent/${o}.${n}.webp)`:Sn.dim(` ${o}: no picture, the initials show`))}),e}function ey(){let e=new Kw("picture").description("a person's profile picture: set or remove (the owner only)"),t=()=>{let o=So();return o&&An(`Only the owner sets a person's picture; agent "${o}" asked.`),!o};return e.command("set <id> <file>").description("set the picture from a PNG, JPEG or WebP file (1 MB at most); it is cut to a square, metadata dropped").action(async(o,n)=>{t()&&await Vw("person",o,n)}),e.command("remove <id>").alias("rm").description("remove the picture: the initials show again").action(o=>{t()&&Qw("person",o)}),e}function Re(){let e=ie(process.cwd(),"agentx.json");if(!Je(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ho(e,"utf-8"))}function ft(e){return de(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(y.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(y.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(y.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var mo=new uo().name("agent").description("manage agents \u2014 add, list, remove, pause, resume");mo.command("list").alias("ls").description("list configured agents").action(()=>{let e=Re();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${y.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(y.dim(` workspace: ${o.workspace}`)),n&&console.log(y.dim(` mentions: ${n}`))}console.log()});mo.command("add").description("add a new agent interactively").action(async()=>{let e=Re(),t=await at([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:g=>/^[a-z0-9-]+$/.test(g)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:ie(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:Jo(t.workspace,t.id);go(ie(o,".claude/skills"),{recursive:!0});let n={name:t.name,workspace:o,tier:t.tier,model:t.model,mentions:t.mentions?.map(g=>g.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",(...g)=>{console.log(y.dim(` ${g.join(" ")}`))}),i=ie(process.cwd(),"src/wiki/SKILL.md"),a=ie(jS(PS(import.meta.url)),"../wiki/SKILL.md"),c=Je(i)?i:a;Je(c)&&(go(ie(o,".claude/skills/wiki"),{recursive:!0}),Hl(c,ie(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await ft(e),console.log(y.green(`
66
66
  Agent "${t.id}" added`)),console.log(y.dim(` Workspace: ${o}`)),console.log(y.dim(` Created: ${r.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`));let l=bi(xo(),[t.id]);l&&console.log(y.yellow(` Created by agent "${l}": it starts once the owner approves it (agentx approvals approve agent:${t.id}).`)),console.log()});mo.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=Re();if(!t.agents?.[e]){console.log(y.red(` Agent "${e}" not found`));return}delete t.agents[e],await ft(t),jc(xo(),e),console.log(y.green(` Agent "${e}" removed from config (workspace preserved)`))});mo.addCommand(Zw());function ty(e){let t=So();return t?(console.log(y.red(` Only the owner can ${e}; agent "${t}" asked. Ask the owner, or raise a card.`)),process.exitCode=1,!1):!0}mo.command("pause <id>").description("pause an agent: it starts no run until resumed (applies at once)").action(e=>{if(ty("pause an agent")){if(!Re().agents?.[e]){console.log(y.red(` Agent "${e}" not found`)),process.exitCode=1;return}if(Nc(xo())[e]?.kind==="approval"){console.log(y.yellow(` "${e}" waits for your approval and does not run yet: agentx approvals list`));return}Iu(xo(),e,"paused","the owner"),console.log(y.green(` "${e}" paused. Messages and schedules for it are refused until you run: agentx agent resume ${e}`))}});mo.command("resume <id>").description("resume a paused agent").action(e=>{if(!ty("resume an agent"))return;let t=Nc(xo())[e];if(t?.kind==="approval"){console.log(y.yellow(` "${e}" was created by ${t.by} and waits for your approval: agentx approvals approve agent:${e}`));return}console.log(jc(xo(),e,"paused")?y.green(` "${e}" resumed`):y.dim(` "${e}" was not paused`))});mo.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=Re(),n=o.agents?.[e];if(n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log(y.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):y.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":y.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||y.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(y.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(y.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(y.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(y.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=r,s.push(`maxExecutionMinutes=${r}`)}s.length===0&&(console.log(y.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await ft(o),console.log(y.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(y.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Cr=new uo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Cr.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,t)=>{let n=Re().agents?.[e];n||(console.log(y.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(y.dim(`
67
67
  ${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
68
- `));return}console.log(),console.log(y.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]?y.green(`${g}:${d}=set`):y.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(y.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(y.dim(`sessionDir:${d}`));let l=Object.entries(r.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${i?y.cyan(r.kind.padEnd(14)):y.dim(r.kind.padEnd(14))} ${y.bold(r.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${y.dim(l)}`),i||console.log(` ${y.dim("(disabled)")}`)}console.log()});Cr.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=Re();o.agents?.[e]||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-BMYFEAO5.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await at({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(p=>({title:p,value:p}))})).kind||"").trim()),r||(console.log(y.red(" --kind is required")),process.exit(1));let i=String(t.label||"").trim();!i&&n&&(i=((await at({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),i||(console.log(y.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 at({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});f.scheme==="tokenEnv"?a=((await at({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():f.scheme==="keyring"?c="keyring":f.scheme==="sessionDir"&&(l=((await at({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 at({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(y.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(y.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(y.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 ft(o),console.log(y.green(` \u2713 ${e}: added ${r} integration "${i}"`)),a&&!process.env[a]&&console.log(y.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Cr.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=Re(),n=o.agents?.[e];n||(console.log(y.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(y.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await ft(o),console.log(y.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Cr.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=Re().agents?.[e];n||(console.log(y.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(y.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(` ${y.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${y.dim(g)}`)}else console.log(` ${y.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),i>0&&process.exit(1)});mo.addCommand(Cr);var da=new uo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");da.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Re();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(y.bold(" Telegram:"));for(let[r,i]of Object.entries(t.accounts||{}))console.log(` ${y.cyan(r)} -> agent: ${i.agentBinding}`)}else console.log(y.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(y.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let r of o.routes||[]){let i=r.contact?`contact ${r.contact}`:`group "${r.group}"`;console.log(` ${i} -> agent: ${r.agent}`)}}else console.log(y.dim(" WhatsApp: disabled"));let n=e.channels?.email;if(n?.enabled&&Object.keys(n.accounts||{}).length){console.log(y.bold(" Email:"));for(let[r,i]of Object.entries(n.accounts))console.log(` ${r}: ${i.address} -> agent: ${i.agent}, replies ${i.send==="auto"?"sent at once":"wait for approval"}`)}else console.log(y.dim(" Email: disabled (agentx connect email)"));let s=e.channels?.gitlab;if(s?.enabled){console.log(y.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let r of s.routes||[])console.log(` ${r.project} -> agent: ${r.agent}`)}else console.log(y.dim(" GitLab: disabled"));console.log()});da.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=Re(),t=Object.keys(e.agents||{});if(!t.length){console.log(y.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 at({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 at([{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(y.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(y.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 ft(e),console.log(y.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await at([{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 at([{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 ft(e),go(ie(process.cwd(),s.sessionDir),{recursive:!0}),console.log(y.green(` WhatsApp enabled (${r.length} routes, default: ${s.defaultAgent})`)),console.log(y.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await at([{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 at([{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 ft(e),console.log(y.green(` GitLab enabled (${r.length} routes, webhook :${s.webhookPort})`)),console.log(y.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(y.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(y.dim(` Secret token: ${s.webhookSecret}`)),console.log(y.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(y.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var js=new uo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");js.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Re();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?y.green("\u25CF"):y.dim("\u25CB");console.log(` ${n} ${y.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(y.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(y.dim(" No cron jobs configured")),console.log()});js.command("add").description("add a cron job").action(async()=>{let e=Re(),t=Object.keys(e.agents||{}),o=await at([{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 ft(e),console.log(y.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});js.command("enable <id>").description("enable a cron job").action(async e=>{let t=Re();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(y.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await ft(t),console.log(y.green(` Cron "${e}" enabled`))});js.command("disable <id>").description("disable a cron job").action(async e=>{let t=Re();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await ft(t),console.log(y.green(` Cron "${e}" disabled`))});var Dt=new uo().name("mesh").description("manage mesh peers \u2014 add, list, remove");Dt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Re();if(console.log(),!e.mesh?.enabled)console.log(y.dim(" Mesh: disabled"));else{console.log(y.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=y.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=y.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${y.cyan(t.name)} ${y.dim(t.url)} ${o}`)}}console.log()});Dt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Re(),t=await at([{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(y.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(y.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 ft(e),console.log(y.green(` Peer "${t.name}" added`)),console.log()}});Dt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=Re();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await ft(t),console.log(y.green(` Peer "${e}" removed`)))});Dt.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=Re();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(y.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(y.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(y.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await ft(t),console.log(y.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(y.dim(" Restart the daemon for the new cadence to take effect."))});Dt.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=T().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(y.red(` Announcement refused (${r.status}): ${i.error||"unknown error"}`)),process.exit(1)),console.log(y.green(` \u2713 Announced from ${i.event?.node??"this machine"}`)+y.dim(` (event ${i.event?.id??"?"})`))}catch(r){console.log(y.red(` Could not reach the daemon at ${o}: ${r?.message||r}`)),process.exit(1)}});var oy=e=>{let t=e||"";if(!t)try{t=T().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function ga(e,t,o={}){let n=oy(),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(y.red(` ${i.error||`HTTP ${r.status}`}`)),process.exit(1));let a=i.grant;console.log(y.green(` \u2713 ${a?.name??e}: ${a?.state}${i.stopped?`, ${i.stopped} running turn(s) stopped`:""}`))}catch(r){console.log(y.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 En=Dt.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");En.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-FY2TIT7I.js"),i=T(),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(y.red(` ${a.error}`)),process.exit(1));let c=(e.url||oy()).replace(/\/+$/,"");console.log(),console.log(` Grant ${y.bold(a.grant.name)} for ${y.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(y.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(` ${y.cyan(c)}`),console.log(` ${y.bold(n(a.code))}`),console.log(),console.log(` They run: ${y.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()});En.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(y.dim(`
68
+ `));return}console.log(),console.log(y.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]?y.green(`${g}:${d}=set`):y.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(y.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(y.dim(`sessionDir:${d}`));let l=Object.entries(r.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${i?y.cyan(r.kind.padEnd(14)):y.dim(r.kind.padEnd(14))} ${y.bold(r.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${y.dim(l)}`),i||console.log(` ${y.dim("(disabled)")}`)}console.log()});Cr.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=Re();o.agents?.[e]||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-RHCIE7VE.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await at({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(p=>({title:p,value:p}))})).kind||"").trim()),r||(console.log(y.red(" --kind is required")),process.exit(1));let i=String(t.label||"").trim();!i&&n&&(i=((await at({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),i||(console.log(y.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 at({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});f.scheme==="tokenEnv"?a=((await at({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():f.scheme==="keyring"?c="keyring":f.scheme==="sessionDir"&&(l=((await at({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 at({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(y.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(y.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(y.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 ft(o),console.log(y.green(` \u2713 ${e}: added ${r} integration "${i}"`)),a&&!process.env[a]&&console.log(y.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Cr.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=Re(),n=o.agents?.[e];n||(console.log(y.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(y.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await ft(o),console.log(y.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Cr.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=Re().agents?.[e];n||(console.log(y.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(y.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(` ${y.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${y.dim(g)}`)}else console.log(` ${y.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),i>0&&process.exit(1)});mo.addCommand(Cr);var da=new uo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");da.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Re();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(y.bold(" Telegram:"));for(let[r,i]of Object.entries(t.accounts||{}))console.log(` ${y.cyan(r)} -> agent: ${i.agentBinding}`)}else console.log(y.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(y.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let r of o.routes||[]){let i=r.contact?`contact ${r.contact}`:`group "${r.group}"`;console.log(` ${i} -> agent: ${r.agent}`)}}else console.log(y.dim(" WhatsApp: disabled"));let n=e.channels?.email;if(n?.enabled&&Object.keys(n.accounts||{}).length){console.log(y.bold(" Email:"));for(let[r,i]of Object.entries(n.accounts))console.log(` ${r}: ${i.address} -> agent: ${i.agent}, replies ${i.send==="auto"?"sent at once":"wait for approval"}`)}else console.log(y.dim(" Email: disabled (agentx connect email)"));let s=e.channels?.gitlab;if(s?.enabled){console.log(y.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let r of s.routes||[])console.log(` ${r.project} -> agent: ${r.agent}`)}else console.log(y.dim(" GitLab: disabled"));console.log()});da.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=Re(),t=Object.keys(e.agents||{});if(!t.length){console.log(y.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 at({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 at([{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(y.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(y.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 ft(e),console.log(y.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await at([{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 at([{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 ft(e),go(ie(process.cwd(),s.sessionDir),{recursive:!0}),console.log(y.green(` WhatsApp enabled (${r.length} routes, default: ${s.defaultAgent})`)),console.log(y.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await at([{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 at([{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 ft(e),console.log(y.green(` GitLab enabled (${r.length} routes, webhook :${s.webhookPort})`)),console.log(y.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(y.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(y.dim(` Secret token: ${s.webhookSecret}`)),console.log(y.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(y.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var js=new uo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");js.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Re();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?y.green("\u25CF"):y.dim("\u25CB");console.log(` ${n} ${y.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(y.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(y.dim(" No cron jobs configured")),console.log()});js.command("add").description("add a cron job").action(async()=>{let e=Re(),t=Object.keys(e.agents||{}),o=await at([{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 ft(e),console.log(y.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});js.command("enable <id>").description("enable a cron job").action(async e=>{let t=Re();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(y.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await ft(t),console.log(y.green(` Cron "${e}" enabled`))});js.command("disable <id>").description("disable a cron job").action(async e=>{let t=Re();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await ft(t),console.log(y.green(` Cron "${e}" disabled`))});var Dt=new uo().name("mesh").description("manage mesh peers \u2014 add, list, remove");Dt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Re();if(console.log(),!e.mesh?.enabled)console.log(y.dim(" Mesh: disabled"));else{console.log(y.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=y.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=y.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${y.cyan(t.name)} ${y.dim(t.url)} ${o}`)}}console.log()});Dt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Re(),t=await at([{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(y.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(y.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 ft(e),console.log(y.green(` Peer "${t.name}" added`)),console.log()}});Dt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=Re();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await ft(t),console.log(y.green(` Peer "${e}" removed`)))});Dt.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=Re();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(y.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(y.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(y.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await ft(t),console.log(y.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(y.dim(" Restart the daemon for the new cadence to take effect."))});Dt.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=T().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(y.red(` Announcement refused (${r.status}): ${i.error||"unknown error"}`)),process.exit(1)),console.log(y.green(` \u2713 Announced from ${i.event?.node??"this machine"}`)+y.dim(` (event ${i.event?.id??"?"})`))}catch(r){console.log(y.red(` Could not reach the daemon at ${o}: ${r?.message||r}`)),process.exit(1)}});var oy=e=>{let t=e||"";if(!t)try{t=T().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function ga(e,t,o={}){let n=oy(),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(y.red(` ${i.error||`HTTP ${r.status}`}`)),process.exit(1));let a=i.grant;console.log(y.green(` \u2713 ${a?.name??e}: ${a?.state}${i.stopped?`, ${i.stopped} running turn(s) stopped`:""}`))}catch(r){console.log(y.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 En=Dt.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");En.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-COGXFWO3.js"),i=T(),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(y.red(` ${a.error}`)),process.exit(1));let c=(e.url||oy()).replace(/\/+$/,"");console.log(),console.log(` Grant ${y.bold(a.grant.name)} for ${y.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(y.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(` ${y.cyan(c)}`),console.log(` ${y.bold(n(a.code))}`),console.log(),console.log(` They run: ${y.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()});En.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(y.dim(`
69
69
  No guest grants. Open one: agentx mesh guests invite --name \u2026 --guest \u2026 --agent \u2026
70
70
  `));return}console.log();for(let n of o){let s=n.state==="active"?y.green("active"):n.state==="pending"?y.yellow(n.guestNode?"waiting for your approval":"not joined yet"):n.state==="paused"?y.yellow("paused"):y.red(`ended${n.endedReason?`: ${n.endedReason}`:""}`);console.log(` ${y.cyan(n.id)} ${y.bold(n.name)} ${n.guest} \u2192 ${n.agentId} ${n.level} ${s}`),console.log(y.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()});En.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(y.red(` No grant "${e}". See \`agentx mesh guests\`.`)),process.exit(1)),console.log(),console.log(` ${y.bold(n.name)} (${n.id}) \xB7 ${n.state}`),console.log(` guest: ${n.guest}${n.guestNode?` \xB7 node ${n.guestNode.name??n.guestNode.id??"?"} at ${n.guestNode.address??"?"}`:""}`),console.log(` agent: ${n.agentId} \xB7 level: ${n.level} \xB7 until ${n.expiresAt.slice(0,10)}`),console.log(` folders: ${n.folders.join(", ")||"none"}
71
71
  skills: ${n.skills.join(", ")||"none"}
@@ -76,7 +76,7 @@ Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choos
76
76
  Not a guest anywhere. Join with: agentx mesh join <url> --code \u2026 --name \u2026
77
77
  `));return}console.log();for(let n of o){let s=await t(n),r=s.ok?s.grant.state==="active"?y.green("active"):y.yellow(String(s.grant.state)):s.status===403?y.yellow(s.error):y.red(s.error);console.log(` ${y.cyan(n.name)} ${y.dim(n.url)} ${n.agentId} until ${n.expiresAt.slice(0,10)} ${r}`)}console.log()});Dt.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(y.red(` No host "${e}". See \`agentx mesh hosts\`.`)),process.exit(1));let r=await n(s,t.join(" "));r.error&&(console.log(y.red(` ${r.error}`)),process.exit(1)),console.log(`
78
78
  ${r.content}
79
- `)});Dt.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(y.red(` No host "${e}".`)),process.exit(1)),console.log(y.green(` \u2713 Left ${e}`))});var Rn=new uo().name("skill").description("manage skills \u2014 add to agent(s), list");Rn.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=Re(),n=ie(e);if(!Je(n)){console.log(y.red(` Skill not found: ${n}`));return}let s=Je(Jo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),r;if(t.all)r=Object.keys(o.agents||{});else if(t.agent)r=t.agent;else{let i=Object.keys(o.agents||{});r=(await at({type:"multiselect",name:"agents",message:"Install to which agents?",choices:i.map(c=>({title:`${c} (${o.agents[c].name})`,value:c}))})).agents||[]}for(let i of r){let a=o.agents[i];if(!a){console.log(y.yellow(` Agent "${i}" not found, skipping`));continue}let c=ks(a.tier,a.workspace);if(!c){console.log(y.yellow(` ${i}: its runtime (${a.tier}) does not use skills, skipping`));continue}let l=ie(c,s);go(l,{recursive:!0}),Je(Jo(n,"SKILL.md"))?Hl(n,l,{recursive:!0}):n.endsWith(".md")&&Hl(n,Jo(l,"SKILL.md")),console.log(y.green(` ${s} -> ${i} (${a.workspace})`))}console.log()});Rn.command("list").alias("ls").description("list skills per agent").action(()=>{let e=Re();console.log();for(let[t,o]of Object.entries(e.agents||{})){if(!ks(o.tier,o.workspace)){console.log(` ${y.cyan(t)}: ${y.dim(`(${o.tier} does not use skills)`)}`);continue}let n=vs(o.tier,o.workspace).map(s=>s.name);console.log(` ${y.cyan(t)}: ${n.length?n.join(", "):y.dim("(none)")}`)}console.log()});Rn.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]:[ie(n,"src",e,"SKILL.md"),ie(n,"skills",e,"SKILL.md")],r=s.find(b=>Je(b));if(!r){console.log(y.red(` No SKILL.md found for "${e}". Searched:`));for(let b of s)console.log(y.dim(` ${b}`));return}let i=Ho(r,"utf-8"),a=o("sha256").update(i).digest("hex").slice(0,12),c=(i.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=T()}catch(b){console.log(y.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(y.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(y.bold(` Skill sync \u2014 ${e}`)),console.log(y.dim(` Source: ${r}`)),console.log(y.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(y.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||!Je(v)){console.log(` ${y.yellow("\u2717")} ${b.padEnd(22)} ${y.dim("(workspace missing: "+(v||"undefined")+")")}`),h++;continue}let S=ks($.tier,v);if(!S){console.log(` ${y.dim("\xB7")} ${b.padEnd(22)} ${y.dim(`(skipped \u2014 ${$.tier} does not use skills)`)}`),h++;continue}let x=vs($.tier,v).find(I=>I.name===e)?.dir??ie(S,e),k=ie(x,"SKILL.md");if(!Je(k)){if(!t.allWorkspaces){console.log(` ${y.dim("\xB7")} ${b.padEnd(22)} ${y.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}t.dryRun||(go(x,{recursive:!0}),Ns(k,i)),console.log(` ${y.green("+")} ${b.padEnd(22)} ${y.dim("\u2192 seeded v"+c)}`),f++;continue}let A=Ho(k,"utf-8");if(o("sha256").update(A).digest("hex").slice(0,12)===a){console.log(` ${y.dim("=")} ${b.padEnd(22)} ${y.dim("up to date (v"+c+")")}`),u++;continue}let O=(A.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||Ns(k,i),console.log(` ${y.yellow("\u21BB")} ${b.padEnd(22)} ${y.dim(`v${O} \u2192 v${c}`)}`),p++}console.log();let w=t.dryRun?"would":"did";console.log(y.dim(` Summary: ${w} seed ${f}, ${w} update ${p}, ${u} already current, ${h} skipped.`)),t.dryRun&&(f>0||p>0)&&console.log(y.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Rn.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=Re().agents?.[e.workspace];p||(console.log(y.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),r.push(ie(p.workspace))}else if(e.allWorkspaces){let f=Re();for(let p of Object.values(f.agents||{}))p?.workspace&&r.push(ie(p.workspace))}else r.push(ie(e.cwd));let i=ie(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"?y.green("PASS "):p.verdict==="REVIEW"?y.yellow("REVIEW "):y.red("FAILING");console.log(` ${u} ${y.bold(p.name)}${p.skill?.path?y.dim(` (${p.skill.path})`):""}`);for(let h of p.reasons)console.log(` ${y.dim("\xB7")} ${h}`)}console.log(),console.log(` ${y.green(`${f.PASS} PASS`)} ${y.yellow(`${f.REVIEW} REVIEW`)} ${y.red(`${f.FAILING} FAILING`)}`),console.log()}process.exit(d.some(f=>f.verdict==="FAILING")?1:0)});Rn.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=Re(),n=Object.entries(o.agents||{}),[s,r]=t.agent?n.find(([g])=>g===t.agent)??[]:n[0]??[];r||(console.log(y.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:i}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-PMNHXNKI.js"),c=await i(r.workspace);if(c.length===0){console.log(y.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(` ${y.green("\u2192")} ${y.bold(l.skill.frontmatter.name)} ${y.dim(`\xB7 ${l.reason}`)}`),console.log(` ${y.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${y.yellow("\xB7")} no skill for this ${y.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(y.dim(`
79
+ `)});Dt.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(y.red(` No host "${e}".`)),process.exit(1)),console.log(y.green(` \u2713 Left ${e}`))});var Rn=new uo().name("skill").description("manage skills \u2014 add to agent(s), list");Rn.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=Re(),n=ie(e);if(!Je(n)){console.log(y.red(` Skill not found: ${n}`));return}let s=Je(Jo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),r;if(t.all)r=Object.keys(o.agents||{});else if(t.agent)r=t.agent;else{let i=Object.keys(o.agents||{});r=(await at({type:"multiselect",name:"agents",message:"Install to which agents?",choices:i.map(c=>({title:`${c} (${o.agents[c].name})`,value:c}))})).agents||[]}for(let i of r){let a=o.agents[i];if(!a){console.log(y.yellow(` Agent "${i}" not found, skipping`));continue}let c=ks(a.tier,a.workspace);if(!c){console.log(y.yellow(` ${i}: its runtime (${a.tier}) does not use skills, skipping`));continue}let l=ie(c,s);go(l,{recursive:!0}),Je(Jo(n,"SKILL.md"))?Hl(n,l,{recursive:!0}):n.endsWith(".md")&&Hl(n,Jo(l,"SKILL.md")),console.log(y.green(` ${s} -> ${i} (${a.workspace})`))}console.log()});Rn.command("list").alias("ls").description("list skills per agent").action(()=>{let e=Re();console.log();for(let[t,o]of Object.entries(e.agents||{})){if(!ks(o.tier,o.workspace)){console.log(` ${y.cyan(t)}: ${y.dim(`(${o.tier} does not use skills)`)}`);continue}let n=vs(o.tier,o.workspace).map(s=>s.name);console.log(` ${y.cyan(t)}: ${n.length?n.join(", "):y.dim("(none)")}`)}console.log()});Rn.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]:[ie(n,"src",e,"SKILL.md"),ie(n,"skills",e,"SKILL.md")],r=s.find(b=>Je(b));if(!r){console.log(y.red(` No SKILL.md found for "${e}". Searched:`));for(let b of s)console.log(y.dim(` ${b}`));return}let i=Ho(r,"utf-8"),a=o("sha256").update(i).digest("hex").slice(0,12),c=(i.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=T()}catch(b){console.log(y.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(y.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(y.bold(` Skill sync \u2014 ${e}`)),console.log(y.dim(` Source: ${r}`)),console.log(y.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(y.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||!Je(v)){console.log(` ${y.yellow("\u2717")} ${b.padEnd(22)} ${y.dim("(workspace missing: "+(v||"undefined")+")")}`),h++;continue}let S=ks($.tier,v);if(!S){console.log(` ${y.dim("\xB7")} ${b.padEnd(22)} ${y.dim(`(skipped \u2014 ${$.tier} does not use skills)`)}`),h++;continue}let x=vs($.tier,v).find(I=>I.name===e)?.dir??ie(S,e),k=ie(x,"SKILL.md");if(!Je(k)){if(!t.allWorkspaces){console.log(` ${y.dim("\xB7")} ${b.padEnd(22)} ${y.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),h++;continue}t.dryRun||(go(x,{recursive:!0}),Ns(k,i)),console.log(` ${y.green("+")} ${b.padEnd(22)} ${y.dim("\u2192 seeded v"+c)}`),f++;continue}let A=Ho(k,"utf-8");if(o("sha256").update(A).digest("hex").slice(0,12)===a){console.log(` ${y.dim("=")} ${b.padEnd(22)} ${y.dim("up to date (v"+c+")")}`),u++;continue}let O=(A.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||Ns(k,i),console.log(` ${y.yellow("\u21BB")} ${b.padEnd(22)} ${y.dim(`v${O} \u2192 v${c}`)}`),p++}console.log();let w=t.dryRun?"would":"did";console.log(y.dim(` Summary: ${w} seed ${f}, ${w} update ${p}, ${u} already current, ${h} skipped.`)),t.dryRun&&(f>0||p>0)&&console.log(y.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Rn.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=Re().agents?.[e.workspace];p||(console.log(y.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),r.push(ie(p.workspace))}else if(e.allWorkspaces){let f=Re();for(let p of Object.values(f.agents||{}))p?.workspace&&r.push(ie(p.workspace))}else r.push(ie(e.cwd));let i=ie(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"?y.green("PASS "):p.verdict==="REVIEW"?y.yellow("REVIEW "):y.red("FAILING");console.log(` ${u} ${y.bold(p.name)}${p.skill?.path?y.dim(` (${p.skill.path})`):""}`);for(let h of p.reasons)console.log(` ${y.dim("\xB7")} ${h}`)}console.log(),console.log(` ${y.green(`${f.PASS} PASS`)} ${y.yellow(`${f.REVIEW} REVIEW`)} ${y.red(`${f.FAILING} FAILING`)}`),console.log()}process.exit(d.some(f=>f.verdict==="FAILING")?1:0)});Rn.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=Re(),n=Object.entries(o.agents||{}),[s,r]=t.agent?n.find(([g])=>g===t.agent)??[]:n[0]??[];r||(console.log(y.red(` no such agent${t.agent?` "${t.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:i}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-D2VUSUCJ.js"),c=await i(r.workspace);if(c.length===0){console.log(y.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(` ${y.green("\u2192")} ${y.bold(l.skill.frontmatter.name)} ${y.dim(`\xB7 ${l.reason}`)}`),console.log(` ${y.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${y.yellow("\xB7")} no skill for this ${y.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(y.dim(`
80
80
  shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(y.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(y.dim(`
81
81
  (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Or=new uo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Or.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(y.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let o=ie(t.cwd),n=ie(o,"references/example"),s=ie(o,"references/recipes/example.yaml");Je(n)||(console.log(y.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let r=ie(o,".agentx/references",e),i=ie(o,".agentx/references/recipes");go(r,{recursive:!0}),go(i,{recursive:!0});let a=NS(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let f=Jo(r,d);if(Je(f)&&!t.force){console.log(y.dim(` skip ${f} (exists; --force to overwrite)`)),l++;continue}let u=Ho(Jo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Ns(f,u),console.log(y.green(` + ${f}`)),c++}let g=Jo(i,`${e}.yaml`);if(Je(g)&&!t.force)console.log(y.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(Je(s)){let d=Ho(s,"utf-8").replaceAll("example.",`${e}.`);Ns(g,d),console.log(y.green(` + ${g}`)),c++}console.log(),console.log(y.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(y.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(y.dim(" 2. agentx skill audit # verify references resolve")),console.log(y.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Or.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(y.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=ie(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(y.yellow(` No skills matched filter [${i.join(", ")}] under ${r}`)),console.log(y.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(y.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([h,w])=>[h,w.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=ie(t.referencesCwd||t.cwd),f=ie(d,".agentx/references",e);if(!t.write){console.log(),console.log(y.dim(` Dry-run \u2014 would write to ${f}/`));for(let[h,w]of Object.entries(g))console.log(y.cyan(`
82
82
  --- ${h} ---`)),console.log(w.split(`
@@ -85,7 +85,7 @@ ${r.content}
85
85
  `).length>30&&console.log(y.dim(` \u2026 (${w.split(`
86
86
  `).length-30} more lines truncated in preview)`));console.log(),console.log(y.dim(` Re-run with --write to commit these to ${f}/`)),console.log();return}go(f,{recursive:!0});let p=0,u=0;for(let[h,w]of Object.entries(g)){let b=Jo(f,h);if(Je(b)&&!t.force){console.log(y.dim(` skip ${b} (exists; --force to overwrite)`)),u++;continue}Ns(b,w),console.log(y.green(` + ${b}`)),p++}console.log(),console.log(y.dim(` ${p} written, ${u} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(y.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Or.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(ie(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(y.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(` ${y.cyan(s.id)} ${y.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),r&&console.log(y.dim(` ${r}`))}console.log(),console.log(y.dim(` ${n.length} reference(s) loaded.`)),console.log()});var zl=new uo().name("hook").description("manage hooks \u2014 add to agent workspace");zl.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=Re().agents?.[e];if(!o){console.log(y.red(` Agent "${e}" not found`));return}let n=ie(o.workspace,".claude/settings.json"),s=Je(n)?JSON.parse(Ho(n,"utf-8")):{},r=await at([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!r.event||!r.value)return;s.hooks=s.hooks||{},s.hooks[r.event]=s.hooks[r.event]||[];let a={hooks:[{type:r.type,...r.type==="command"?{command:r.value}:{url:r.value}}]};r.matcher&&(a.matcher=r.matcher),s.hooks[r.event].push(a),go(ie(o.workspace,".claude"),{recursive:!0}),Ns(n,JSON.stringify(s,null,2)),console.log(y.green(` Hook added to ${e}: ${r.event} -> ${r.type}`)),console.log()});var Yl=new uo().name("migrate").description("import configuration from OpenClaw or other tools");Yl.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,ie(process.env.HOME||"",".openclaw/openclaw.json"),ie(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let p of o)if(p&&Je(p)){n=p;break}if(!n){console.log(y.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(y.dim(` Reading: ${n}`));let s=JSON.parse(Ho(n,"utf-8")),r=Je(ie(process.cwd(),"agentx.json"))?Re():{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(w=>w===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){go(ie(p.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-HAV4CQV7.js");w(u,r.agents[u])}}console.log(` ${y.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 w=c[p]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.channels.telegram.accounts[p]={token:u.botToken,agentBinding:w},r.channels.telegram.enabled=!0,d++}console.log(` ${y.green(d)} Telegram accounts imported`);let f=ie(n,"../cron/jobs.json");if(Je(f)){let p=JSON.parse(Ho(f,"utf-8")),u=0;for(let h of p.jobs||[]){let w=h.name||h.id,b=h.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.crons[w]={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(` ${y.green(u)} cron jobs imported`)}t.dryRun?(console.log(y.yellow(`
87
87
  Dry run \u2014 nothing written`)),console.log(JSON.stringify(r,null,2))):(await ft(r),console.log(y.green(`
88
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Go=new uo().name("config").description("validate and inspect configuration");Go.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=T(e.config);console.log(y.green(" \u2713 Config valid")),console.log(y.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(y.dim(` Bind: ${t.node.bind}`)),console.log(y.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(y.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(y.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(y.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(y.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=hi(t);if(n.length){console.log(),console.log(y.yellow(" Warnings:"));for(let s of n)console.log(y.yellow(` \u26A0 ${s}`))}else console.log(y.green(" \u2713 All workspaces valid"));console.log();for(let[s,r]of Object.entries(t.agents)){let i=r.workspace,a=Je(ie(i,".claude")),c=Je(ie(i,"CLAUDE.md")),l=Je(ie(i,".claude/settings.json")),g=vs(r.tier,i).length,d=[a?y.green("\u2713"):y.red("\u2717"),".claude",c?y.green("\u2713"):y.yellow("\u25CB"),"CLAUDE.md",l?y.green("\u2713"):y.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${y.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(y.red(` \u2717 ${t.message}`))}console.log()});Go.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=T(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(y.red(t.message))}});function _S(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 Gl(e){return e===void 0?y.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Go.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-S5SGBNOG.js"),{expandEnvVars:i}=await import("./config-BMYFEAO5.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(y.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(Gl(g))});Go.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-S5SGBNOG.js"),i=_S(t,!!o.string),a=await n(l=>{s(l,e,i)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(y.red(` \u2717 ${a.error}`)),process.exit(1));let c=r(a.after,e);o.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would become: ${Gl(c)}`)):(console.log(y.green(` \u2713 ${y.cyan(e)} = ${Gl(c)}`)),a.reloaded?console.log(y.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(y.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Go.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-S5SGBNOG.js"),r=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(r.success||(console.log(y.red(` \u2717 ${r.error}`)),process.exit(1)),n(r.after,e)!==void 0){console.log(y.dim(` (no-op) ${y.cyan(e)} was not set`));return}t.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would be removed`)):(console.log(y.green(` \u2713 ${y.cyan(e)} removed`)),r.reloaded&&console.log(y.dim(" Daemon hot-reloaded.")))});Go.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=T(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(y.bold(" Governance flags")),console.log(),n&&(console.log(y.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?y.green:s==="shadow"?y.cyan:s==="off"?y.dim:y.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":y.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?y.green("active"):i?y.yellow("env=true but business.enabled=false \u2192 inactive"):y.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(y.dim(` business.enabled ${t?y.green("true"):y.dim("false")}`)),console.log(y.dim(` business.projects[] ${o}`)),console.log(),console.log(y.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(y.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});as();import{Command as DS}from"commander";import zo from"chalk";import{resolve as Yo}from"path";import{existsSync as MS}from"fs";var To=new DS().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Tn(e){let t=Yo(e,".agentx/db.sqlite");MS(t)||(console.log(zo.red(` No SQLite at ${t}`)),console.log(zo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=$t({path:t});return o||(console.log(zo.red(` Could not open ${t}`)),console.log(zo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function Cn(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(zo.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])))}To.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=Tn(Yo(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=`
88
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Go=new uo().name("config").description("validate and inspect configuration");Go.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=T(e.config);console.log(y.green(" \u2713 Config valid")),console.log(y.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(y.dim(` Bind: ${t.node.bind}`)),console.log(y.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(y.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(y.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(y.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(y.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=hi(t);if(n.length){console.log(),console.log(y.yellow(" Warnings:"));for(let s of n)console.log(y.yellow(` \u26A0 ${s}`))}else console.log(y.green(" \u2713 All workspaces valid"));console.log();for(let[s,r]of Object.entries(t.agents)){let i=r.workspace,a=Je(ie(i,".claude")),c=Je(ie(i,"CLAUDE.md")),l=Je(ie(i,".claude/settings.json")),g=vs(r.tier,i).length,d=[a?y.green("\u2713"):y.red("\u2717"),".claude",c?y.green("\u2713"):y.yellow("\u25CB"),"CLAUDE.md",l?y.green("\u2713"):y.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${y.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(y.red(` \u2717 ${t.message}`))}console.log()});Go.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=T(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(y.red(t.message))}});function _S(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 Gl(e){return e===void 0?y.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Go.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-JQ2R4J5Z.js"),{expandEnvVars:i}=await import("./config-RHCIE7VE.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(y.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(Gl(g))});Go.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-JQ2R4J5Z.js"),i=_S(t,!!o.string),a=await n(l=>{s(l,e,i)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(y.red(` \u2717 ${a.error}`)),process.exit(1));let c=r(a.after,e);o.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would become: ${Gl(c)}`)):(console.log(y.green(` \u2713 ${y.cyan(e)} = ${Gl(c)}`)),a.reloaded?console.log(y.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(y.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Go.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-JQ2R4J5Z.js"),r=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(r.success||(console.log(y.red(` \u2717 ${r.error}`)),process.exit(1)),n(r.after,e)!==void 0){console.log(y.dim(` (no-op) ${y.cyan(e)} was not set`));return}t.dryRun?console.log(y.yellow(` (dry-run) ${y.cyan(e)} would be removed`)):(console.log(y.green(` \u2713 ${y.cyan(e)} removed`)),r.reloaded&&console.log(y.dim(" Daemon hot-reloaded.")))});Go.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=T(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(y.bold(" Governance flags")),console.log(),n&&(console.log(y.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?y.green:s==="shadow"?y.cyan:s==="off"?y.dim:y.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":y.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?y.green("active"):i?y.yellow("env=true but business.enabled=false \u2192 inactive"):y.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(y.dim(` business.enabled ${t?y.green("true"):y.dim("false")}`)),console.log(y.dim(` business.projects[] ${o}`)),console.log(),console.log(y.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(y.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});as();import{Command as DS}from"commander";import zo from"chalk";import{resolve as Yo}from"path";import{existsSync as MS}from"fs";var To=new DS().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Tn(e){let t=Yo(e,".agentx/db.sqlite");MS(t)||(console.log(zo.red(` No SQLite at ${t}`)),console.log(zo.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=$t({path:t});return o||(console.log(zo.red(` Could not open ${t}`)),console.log(zo.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function Cn(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(zo.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])))}To.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=Tn(Yo(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.day&&(o.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(o.push("status = @status"),n.status=e.status);let s=`
89
89
  SELECT agent_id, channel, status, duration_ms,
90
90
  input_tokens, output_tokens,
91
91
  substr(message_preview, 1, 60) AS message,
@@ -507,14 +507,14 @@ return aid ?? null`}function $R(e,t){if(e.kind==="path"){let s=e.pts,r=s[Math.fl
507
507
  `);console.log(B.dim(" ok: the log shows it. not ok: the log shows the opposite. not seen: the lesson did not reach that point. by eye: only the screen can tell.")),console.log()}catch(t){console.log(B.red(` ${t.message}`)),process.exit(1)}});qt.command("card").description("the answer shown in the pill: how long it stays open and how tall it grows").option("--timeout <seconds>",`seconds it stays open once spoken, ${rl.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${rl.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let t=en(e.config),o={};e.timeout!==void 0&&(o.timeout=Number(e.timeout)),e.maxHeight!==void 0&&(o.maxHeight=Number(e.maxHeight)),Object.keys(o).length&&Ln(t,{general:{card:o}});let n=T(t).voice.card,s=n.timeout===0?"until closed":`${n.timeout} s after it is spoken`;console.log(` Answer card: open ${s}, at most ${n.maxHeight} pt tall`),Object.keys(o).length&&console.log(B.dim(" AgentX Voice picks this up within a few seconds."))}catch(t){console.log(B.red(` ${t.message}`)),process.exit(1)}});import{Command as dT}from"commander";import L from"chalk";var tn=new dT().name("attach").description("wear an agentx agent identity in this Claude Code session"),_a=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${wn()}`;function Da(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function Ma(e,t,o){let n=await fetch(`${e}${t}`,{method:o?"POST":"GET",headers:{"Content-Type":"application/json"},body:o?JSON.stringify(o):void 0}),s=await n.text(),r=null;try{r=s?JSON.parse(s):null}catch{}if(!n.ok)throw new Error(r?.error||s||`HTTP ${n.status}`);return r}function La(e){let t=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(t)?`daemon not reachable \u2014 start it with ${L.cyan("agentx daemon start")}`:t}function Hb(e){return e==="auto"?L.yellow:e==="manual"?L.gray:L.green}function gT(e,t=!1){let o=e.agentIds.length?e.agentIds.join(", "):L.gray("(not bound)"),n=e.pending?L.yellow(`${e.pending} pending`):L.gray("empty"),s=t?L.cyan(" \u2190 this session"):"";console.log(` ${L.bold(o)} ${Hb(e.mode)(e.mode)} ${n} ${L.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${L.gray(e.cwd)}`)}function uT(e){let t=e.filter(n=>n.agentIds.length>0),o=e.filter(n=>n.watch&&n.agentIds.length===0);return{bound:t,watching:o,idle:e.length-t.length-o.length}}function mT(e,t=!1){let o=e.watch?.subscriptions.map(s=>s.kinds.join("|")).join(", ")||"default",n=t?L.cyan(" \u2190 this session"):"";console.log(` ${L.bold("watching")} ${L.gray(o)} ${L.gray(e.sessionId)}${n}`),e.cwd&&console.log(` ${L.gray(e.cwd)}`)}tn.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Ic.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",_a).action(async(e,t)=>{let o=Da(t.session);o||(console.error(L.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${L.cyan("--session <id>")} (list them with ${L.cyan("agentx attach list")}).`),process.exit(1)),Ou(t.mode)||(console.error(L.red(`Invalid mode "${t.mode}". Expected one of: ${Ic.join(", ")}`)),process.exit(1)),kr()||(console.error(L.yellow("Attach hooks are not installed yet.")),console.error(`Run ${L.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await Ma(t.url,"/attach/bind",{sessionId:o,agentId:e,mode:t.mode,cwd:process.cwd()});console.log(`${L.green("\u2713")} This session is now wearing ${L.bold(e)} (${Hb(t.mode)(t.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(L.yellow(` ${s} message(s) already queued for it.`)),console.log(L.gray(t.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":t.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(L.red(`Bind failed: ${La(n)}`)),process.exit(1)}});function Jb(e){let t=(e??"").split(",").map(o=>o.trim()).filter(Boolean);return t.length?t:void 0}function pT(e){let t=Jb(e.kinds),o=Jb(e.agents);if(!t&&!o&&!e.match)return;let n={kinds:t??["*"]};return o&&(n.agents=o),e.match&&(n.match=e.match),[n]}tn.command("watch").description("watch this session: no identity, no messages, a short event digest on each prompt").option("--kinds <list>","event kinds or types to include, comma separated (default: failures, completions, approvals waiting, peers down)").option("--agents <list>","only events for these agents, comma separated").option("--match <text>","only events whose summary contains this text").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",_a).action(async e=>{let t=Da(e.session);t||(console.error(L.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${L.cyan("--session <id>")}.`),process.exit(1)),kr()||(console.error(L.yellow("Attach hooks are not installed yet.")),console.error(`Run ${L.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{await Ma(e.url,"/attach/watch",{sessionId:t,cwd:process.cwd(),subscriptions:pT(e)}),console.log(`${L.green("\u2713")} This session is now ${L.bold("watching")}. It answers for no agent.`),console.log(L.gray(" Each time you send a prompt, it gets a short list of new events.")),console.log(L.gray(` Stop with ${L.cyan("agentx attach detach")}.`))}catch(o){console.error(L.red(`Watch failed: ${La(o)}`)),process.exit(1)}});tn.command("detach").description("stop wearing an identity or watching in this session (queued work falls back to spawned agents)").option("--agent <id>","release only this identity (default: all)").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",_a).action(async e=>{let t=Da(e.session);t||(console.error(L.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await Ma(e.url,"/attach/detach",{sessionId:t,agentId:e.agent}),console.log(`${L.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(o){console.error(L.red(`Detach failed: ${La(o)}`)),process.exit(1)}});tn.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",_a).option("--json","raw JSON output").action(async e=>{let t=Da();try{let n=(await Ma(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:kr(),sessions:n},null,2));return}console.log(),console.log(kr()?`${L.green("\u2713")} Attach hooks installed ${L.gray($r())}`:`${L.yellow("!")} Attach hooks not installed \u2014 run ${L.cyan("agentx attach install")}`),console.log();let{bound:s,watching:r,idle:i}=uT(n);if(console.log(L.bold(" Identities")),s.length===0)console.log(L.gray(" No session is wearing an identity right now."));else for(let a of s)gT(a,a.sessionId===t);if(r.length>0){console.log(),console.log(L.bold(" Watchers"));for(let a of r)mT(a,a.sessionId===t)}i>0&&console.log(L.gray(`
508
508
  ${i} registered session(s) with no binding.`)),console.log()}catch(o){console.error(L.red(`Could not read attach state: ${La(o)}`)),process.exit(1)}});tn.command("install").description("wire the attach hooks into ~/.claude/settings.json (one time, all sessions)").option("--port <n>","daemon port the hooks should call (default: node.bind in agentx.json)").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--no-guard","skip the PreToolUse guard hook (not recommended)").action(e=>{try{let t=String(e.port||wn()),o=bh(t,{path:e.path,withGuard:e.guard});console.log(o.changed?`${L.green("\u2713")} Installed attach hooks in ${L.gray(o.path)}`:`${L.green("\u2713")} Attach hooks already up to date in ${L.gray(o.path)}`),console.log(L.gray(` Events: ${o.events.join(", ")} \u2192 127.0.0.1:${t}`)),o.guardInstalled?(console.log(L.gray(" PreToolUse guard installed at user scope.")),console.log(L.gray(` (An attached session runs under your permissions, not the agent's workspace
509
509
  settings \u2014 without this an attached production identity would be less
510
- guarded than a spawned one.)`))):console.log(L.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${L.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(t){console.error(L.red(`Install failed: ${t?.message??t}`)),process.exit(1)}});tn.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let t=$h({path:e.path,keepGuard:!e.removeGuard});console.log(t.changed?`${L.green("\u2713")} Removed attach hooks from ${L.gray(t.path)} (${t.events.join(", ")})`:`${L.gray("Nothing to remove.")}`),e.removeGuard||console.log(L.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(t){console.error(L.red(`Uninstall failed: ${t?.message??t}`)),process.exit(1)}});oe();import{Command as fT}from"commander";import Ue from"chalk";var qa=new fT().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function zb(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=T(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return t||(t="http://localhost:18800"),{baseUrl:t.replace(/\/+$/,""),token:o}}function Yb(e,t){let o={};return e&&(o.Authorization=`Bearer ${e}`),t&&(o["Content-Type"]=t),o}function Gb(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s`:t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function hT(e){return e==="busy"?Ue.magenta:e==="warm-hot"?Ue.green:e==="warm-cold"?Ue.cyan:e==="idle"?Ue.yellow:e==="dead"?Ue.red:Ue.dim}qa.command("list").description("list every live persistent claude process").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)").option("--json","emit JSON").action(async e=>{let{baseUrl:t,token:o}=zb(e),n;try{n=await fetch(`${t}/api/processes`,{headers:Yb(o)})}catch(i){console.log(Ue.red(` could not reach daemon at ${t}: ${i.message||i}`)),process.exit(1)}if(n.status===503){console.log(Ue.dim(` daemon at ${t} has no agents with persistentProcess: true`));return}n.ok||(console.log(Ue.red(` HTTP ${n.status} from ${t}/processes`)),process.exit(1));let r=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(Ue.dim(" (no processes)"));return}for(let i of r){let a=hT(i.state)(i.state.padEnd(9)),c=Gb(i.spawnedAt),l=i.lastTurnAt?Gb(i.lastTurnAt)+" ago":"\u2014",g=i.lastInputTokens?Ue.dim(`last_in=${i.lastInputTokens} tok`):"",d=i.claudeSessionId?Ue.dim(`sess=${i.claudeSessionId.slice(0,8)}\u2026`):Ue.dim("sess=\u2014"),f=i.pendingTaskId?Ue.cyan(`task=${String(i.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${Ue.bold(i.key.agentId)}${Ue.dim(":"+i.key.channel+":"+i.key.chatId)} ${Ue.dim("\xB7")} pid=${i.pid??"?"} age=${c} turn#${i.turnCount} last=${l} ${d} ${g} ${f}`),i.deadReason&&console.log(` ${Ue.red("dead:")} ${i.deadReason}`)}});qa.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").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)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,t,o,n)=>{let{baseUrl:s,token:r}=zb(n),i;try{i=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Yb(r,"application/json"),body:JSON.stringify({agentId:e,channel:t,chatId:o,reason:n.reason})})}catch(a){console.log(Ue.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(i.status===503){console.log(Ue.dim(" daemon has no persistent-process registry"));return}if(!i.ok){let a=`HTTP ${i.status}`;try{let c=await i.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(Ue.red(` ${a}`)),process.exit(1)}console.log(Ue.green(` killed ${e}:${t}:${o}`))});oe();import{Command as wT}from"commander";import H from"chalk";var Fn=new wT().name("signal").description("stop a running agent task with a resume plan, and resume it later");function yT(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=T(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return t||(t="http://localhost:18800"),{baseUrl:t.replace(/\/+$/,""),token:o}}async function qn(e,t,o,n){let{baseUrl:s,token:r}=yT(e),i={"Content-Type":"application/json"};r&&(i.Authorization=`Bearer ${r}`);let a;try{a=await fetch(`${s}${o}`,{method:t,headers:i,...n?{body:JSON.stringify(n)}:{}})}catch(l){console.log(H.red(` could not reach daemon at ${s}: ${l.message||l}`)),process.exit(1)}let c=await a.json().catch(()=>({}));return a.ok||(console.log(H.red(` HTTP ${a.status}${c.error?` \u2014 ${c.error}`:""}`)),process.exit(1)),c}var Fr=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)").option("--peer <name>","send to this mesh node instead");Fr(Fn.command("stop [taskId]").description("stop a running task; the agent writes a resume plan").option("--agent <id>","with --channel and --chat: the agent's only task on that chat").option("--channel <channel>","the task's channel").option("--chat <chatId>","the task's chat id").option("--all","stop every running task on this node; each resumes from its plan after the next restart").option("--mesh","with --all: on every healthy mesh node too").option("--no-wait","with --all: answer at once, without waiting for the plans").option("-r, --reason <reason>","why: shown to the agent and on the live page")).action(async(e,t)=>{if(t.all){(e||t.agent)&&(console.log(H.red(" --all stops every task: give no task id or --agent")),process.exit(1)),await bT(t);return}!e&&!(t.agent&&t.channel&&t.chat)&&(console.log(H.red(" give a task id, or --agent, --channel and --chat")),process.exit(1));let o=await qn(t,"POST","/api/signals/stop",{taskId:e,agentId:t.agent,channel:t.channel,chatId:t.chat,reason:t.reason,node:t.peer});console.log(H.green(` stopped ${o.agentId} task ${o.id}`)+H.dim(" \u2014 writing its resume plan")),console.log(H.dim(` see it: agentx signal show ${o.id}${t.peer?` --peer ${t.peer}`:""}`))});function Kb(e,t){if(!e.length){console.log(H.dim(`${t}no running tasks`));return}for(let o of e){let n=o.plan==="agent"?H.green("plan by the agent"):o.plan==="machine"?H.yellow("plan by AgentX"):"",s=o.state==="refused"?H.red(`not stopped: ${o.error}`):o.state==="winding-down"?H.cyan("writing its plan"):n||o.state,r=o.builders,i=r?H.dim(` \xB7 ${r.count} builder(s) stopped${r.saved?`, ${r.saved} folder(s) saved on a WIP branch`:""}`)+(r.notSaved?H.red(`, ${r.notSaved} folder(s) not saved`):""):"";console.log(`${t}${H.bold(o.agentId)} ${H.dim(o.id)} ${s}${i}`)}}async function bT(e){let t=e.wait!==!1;t&&console.log(H.dim(" stopping every task and waiting for the resume plans\u2026"));let o={reason:e.reason,mesh:!!e.mesh,wait:t},n=e.peer?await qn(e,"POST","/api/signals/stop-all",{...o,mesh:!1,node:e.peer}):await qn(e,"POST","/api/signals/stop-all",o);console.log(` ${H.bold(n.node)} ${H.dim(n.orderId)}`),Kb(n.tasks||[]," ");for(let s of n.peers||[])console.log(` ${H.bold(s.node)}${s.ok?"":` ${H.red(s.error)}`}`),s.ok&&Kb(s.tasks||[]," ");t?n.safeToRestart?console.log(H.green(" safe to restart: every task resumes from its plan when AgentX starts again")):[n,...n.peers||[]].some(s=>(s.tasks||[]).some(r=>r.state==="refused"))?console.log(H.yellow(' not safe to restart: a task marked "not stopped" is still running, and a restart would cut it off')):console.log(H.yellow(" not every plan is confirmed saved; check the lines above before you restart")):console.log(H.dim(" see the plans: agentx signal list"))}Fr(Fn.command("list").description("stopped tasks and their resume plans").option("--all","include tasks already resumed").option("--agent <id>","only this agent's")).action(async e=>{let t=new URLSearchParams({limit:"50"});e.agent&&t.set("agent",e.agent),e.peer&&t.set("node",e.peer);let n=((await qn(e,"GET",`/api/signals/stopped?${t}`)).tasks||[]).filter(s=>e.all||s.state!=="resumed");if(!n.length){console.log(H.dim(" no stopped tasks"));return}for(let s of n){let r=s.state==="stopped"?H.yellow(s.state):s.state==="resumed"?H.green(s.state):H.cyan(s.state);console.log(` ${r} ${H.bold(s.id)} ${s.agentId}${H.dim(`:${s.channel}:${s.chatId}`)} ${H.dim(`by ${s.stoppedBy} ${s.stoppedAt}`)}`),s.workflow&&console.log(` ${H.dim("workflow run:")} ${s.workflow.runId} (${s.workflow.workflowId}) paused at step ${s.workflow.nodeId}`),console.log(` ${H.dim("asked:")} ${s.request}`),s.plan&&console.log(` ${H.dim(`plan (${s.plan.author}):`)} ${String(s.plan.text).split(`
510
+ guarded than a spawned one.)`))):console.log(L.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${L.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(t){console.error(L.red(`Install failed: ${t?.message??t}`)),process.exit(1)}});tn.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let t=$h({path:e.path,keepGuard:!e.removeGuard});console.log(t.changed?`${L.green("\u2713")} Removed attach hooks from ${L.gray(t.path)} (${t.events.join(", ")})`:`${L.gray("Nothing to remove.")}`),e.removeGuard||console.log(L.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(t){console.error(L.red(`Uninstall failed: ${t?.message??t}`)),process.exit(1)}});oe();import{Command as fT}from"commander";import Ue from"chalk";var qa=new fT().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function zb(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=T(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return t||(t="http://localhost:18800"),{baseUrl:t.replace(/\/+$/,""),token:o}}function Yb(e,t){let o={};return e&&(o.Authorization=`Bearer ${e}`),t&&(o["Content-Type"]=t),o}function Gb(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s`:t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function hT(e){return e==="busy"?Ue.magenta:e==="warm-hot"?Ue.green:e==="warm-cold"?Ue.cyan:e==="idle"?Ue.yellow:e==="dead"?Ue.red:Ue.dim}qa.command("list").description("list every live persistent claude process").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)").option("--json","emit JSON").action(async e=>{let{baseUrl:t,token:o}=zb(e),n;try{n=await fetch(`${t}/api/processes`,{headers:Yb(o)})}catch(i){console.log(Ue.red(` could not reach daemon at ${t}: ${i.message||i}`)),process.exit(1)}if(n.status===503){console.log(Ue.dim(` daemon at ${t} has no agents with persistentProcess: true`));return}n.ok||(console.log(Ue.red(` HTTP ${n.status} from ${t}/api/processes`)),process.exit(1));let r=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(Ue.dim(" (no processes)"));return}for(let i of r){let a=hT(i.state)(i.state.padEnd(9)),c=Gb(i.spawnedAt),l=i.lastTurnAt?Gb(i.lastTurnAt)+" ago":"\u2014",g=i.lastInputTokens?Ue.dim(`last_in=${i.lastInputTokens} tok`):"",d=i.claudeSessionId?Ue.dim(`sess=${i.claudeSessionId.slice(0,8)}\u2026`):Ue.dim("sess=\u2014"),f=i.pendingTaskId?Ue.cyan(`task=${String(i.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${Ue.bold(i.key.agentId)}${Ue.dim(":"+i.key.channel+":"+i.key.chatId)} ${Ue.dim("\xB7")} pid=${i.pid??"?"} age=${c} turn#${i.turnCount} last=${l} ${d} ${g} ${f}`),i.deadReason&&console.log(` ${Ue.red("dead:")} ${i.deadReason}`)}});qa.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").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)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,t,o,n)=>{let{baseUrl:s,token:r}=zb(n),i;try{i=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Yb(r,"application/json"),body:JSON.stringify({agentId:e,channel:t,chatId:o,reason:n.reason})})}catch(a){console.log(Ue.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(i.status===503){console.log(Ue.dim(" daemon has no persistent-process registry"));return}if(!i.ok){let a=`HTTP ${i.status}`;try{let c=await i.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(Ue.red(` ${a}`)),process.exit(1)}console.log(Ue.green(` killed ${e}:${t}:${o}`))});oe();import{Command as wT}from"commander";import H from"chalk";var Fn=new wT().name("signal").description("stop a running agent task with a resume plan, and resume it later");function yT(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=T(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return t||(t="http://localhost:18800"),{baseUrl:t.replace(/\/+$/,""),token:o}}async function qn(e,t,o,n){let{baseUrl:s,token:r}=yT(e),i={"Content-Type":"application/json"};r&&(i.Authorization=`Bearer ${r}`);let a;try{a=await fetch(`${s}${o}`,{method:t,headers:i,...n?{body:JSON.stringify(n)}:{}})}catch(l){console.log(H.red(` could not reach daemon at ${s}: ${l.message||l}`)),process.exit(1)}let c=await a.json().catch(()=>({}));return a.ok||(console.log(H.red(` HTTP ${a.status}${c.error?` \u2014 ${c.error}`:""}`)),process.exit(1)),c}var Fr=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)").option("--peer <name>","send to this mesh node instead");Fr(Fn.command("stop [taskId]").description("stop a running task; the agent writes a resume plan").option("--agent <id>","with --channel and --chat: the agent's only task on that chat").option("--channel <channel>","the task's channel").option("--chat <chatId>","the task's chat id").option("--all","stop every running task on this node; each resumes from its plan after the next restart").option("--mesh","with --all: on every healthy mesh node too").option("--no-wait","with --all: answer at once, without waiting for the plans").option("-r, --reason <reason>","why: shown to the agent and on the live page")).action(async(e,t)=>{if(t.all){(e||t.agent)&&(console.log(H.red(" --all stops every task: give no task id or --agent")),process.exit(1)),await bT(t);return}!e&&!(t.agent&&t.channel&&t.chat)&&(console.log(H.red(" give a task id, or --agent, --channel and --chat")),process.exit(1));let o=await qn(t,"POST","/api/signals/stop",{taskId:e,agentId:t.agent,channel:t.channel,chatId:t.chat,reason:t.reason,node:t.peer});console.log(H.green(` stopped ${o.agentId} task ${o.id}`)+H.dim(" \u2014 writing its resume plan")),console.log(H.dim(` see it: agentx signal show ${o.id}${t.peer?` --peer ${t.peer}`:""}`))});function Kb(e,t){if(!e.length){console.log(H.dim(`${t}no running tasks`));return}for(let o of e){let n=o.plan==="agent"?H.green("plan by the agent"):o.plan==="machine"?H.yellow("plan by AgentX"):"",s=o.state==="refused"?H.red(`not stopped: ${o.error}`):o.state==="winding-down"?H.cyan("writing its plan"):n||o.state,r=o.builders,i=r?H.dim(` \xB7 ${r.count} builder(s) stopped${r.saved?`, ${r.saved} folder(s) saved on a WIP branch`:""}`)+(r.notSaved?H.red(`, ${r.notSaved} folder(s) not saved`):""):"";console.log(`${t}${H.bold(o.agentId)} ${H.dim(o.id)} ${s}${i}`)}}async function bT(e){let t=e.wait!==!1;t&&console.log(H.dim(" stopping every task and waiting for the resume plans\u2026"));let o={reason:e.reason,mesh:!!e.mesh,wait:t},n=e.peer?await qn(e,"POST","/api/signals/stop-all",{...o,mesh:!1,node:e.peer}):await qn(e,"POST","/api/signals/stop-all",o);console.log(` ${H.bold(n.node)} ${H.dim(n.orderId)}`),Kb(n.tasks||[]," ");for(let s of n.peers||[])console.log(` ${H.bold(s.node)}${s.ok?"":` ${H.red(s.error)}`}`),s.ok&&Kb(s.tasks||[]," ");t?n.safeToRestart?console.log(H.green(" safe to restart: every task resumes from its plan when AgentX starts again")):[n,...n.peers||[]].some(s=>(s.tasks||[]).some(r=>r.state==="refused"))?console.log(H.yellow(' not safe to restart: a task marked "not stopped" is still running, and a restart would cut it off')):console.log(H.yellow(" not every plan is confirmed saved; check the lines above before you restart")):console.log(H.dim(" see the plans: agentx signal list"))}Fr(Fn.command("list").description("stopped tasks and their resume plans").option("--all","include tasks already resumed").option("--agent <id>","only this agent's")).action(async e=>{let t=new URLSearchParams({limit:"50"});e.agent&&t.set("agent",e.agent),e.peer&&t.set("node",e.peer);let n=((await qn(e,"GET",`/api/signals/stopped?${t}`)).tasks||[]).filter(s=>e.all||s.state!=="resumed");if(!n.length){console.log(H.dim(" no stopped tasks"));return}for(let s of n){let r=s.state==="stopped"?H.yellow(s.state):s.state==="resumed"?H.green(s.state):H.cyan(s.state);console.log(` ${r} ${H.bold(s.id)} ${s.agentId}${H.dim(`:${s.channel}:${s.chatId}`)} ${H.dim(`by ${s.stoppedBy} ${s.stoppedAt}`)}`),s.workflow&&console.log(` ${H.dim("workflow run:")} ${s.workflow.runId} (${s.workflow.workflowId}) paused at step ${s.workflow.nodeId}`),console.log(` ${H.dim("asked:")} ${s.request}`),s.plan&&console.log(` ${H.dim(`plan (${s.plan.author}):`)} ${String(s.plan.text).split(`
511
511
  `)[0]}`),s.builders&&console.log(` ${H.dim("builders:")} ${s.builders.helpers} stopped${s.builders.folders.length?`; ${s.builders.folders.map(i=>i.wipBranch?`${i.path} \u2192 ${i.wipBranch}`:i.error?`${i.path} not saved`:i.path).join(", ")}`:""}`)}});Fr(Fn.command("show <id>").description("one stopped task with its whole resume plan")).action(async(e,t)=>{let o=t.peer?`?node=${encodeURIComponent(t.peer)}`:"",{task:n}=await qn(t,"GET",`/api/signals/stopped/${encodeURIComponent(e)}${o}`);if(console.log(` ${H.bold(n.id)} ${n.agentId}${H.dim(`:${n.channel}:${n.chatId}`)} \u2014 ${n.state}`),console.log(` stopped by ${n.stoppedBy} at ${n.stoppedAt}${n.reason?` (${n.reason})`:""}`),n.workflow&&console.log(` step ${n.workflow.nodeId} of workflow run ${n.workflow.runId} (${n.workflow.workflowId})`),n.resumedAt&&console.log(` resumed by ${n.resumedBy} at ${n.resumedAt}`),console.log(H.dim(`
512
512
  Request:`)),console.log(` ${n.originalMessage}`),console.log(H.dim(`
513
513
  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(`
514
514
  `).map(s=>` ${s}`).join(`
515
515
  `):" not written yet"),n.builders){console.log(H.dim(`
516
516
  Background builders it had started (${n.builders.helpers.length}), stopped with it:`)),n.builders.helpers.forEach((s,r)=>console.log(` ${r+1}. ${s}`));for(let s of n.builders.folders){let r=s.wipBranch?H.green(`saved on ${s.wipBranch} (${String(s.wipCommit).slice(0,12)})`):s.error?H.red(`not saved: ${s.error}`):H.dim("nothing to save: its commits are in the clone");console.log(` - ${s.path} (${s.branch??"no branch"}): ${r}`)}}});Fr(Fn.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 qn(t,"POST","/api/signals/resume",{id:e,reason:t.reason,node:t.peer});console.log(H.green(` resumed ${o.agentId} task ${o.id}`)),o.delivery&&console.log(H.dim(` its answer goes to ${o.delivery}`))});Fr(Fn.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 qn(t,"POST","/api/signals/drop",{id:e,node:t.peer});console.log(H.green(` dropped ${o.agentId} task ${o.id}`))});oe();import{Command as $T}from"commander";import ht from"chalk";var Fa=new $T().name("review-gate").description("independent pre-merge review of agent PRs against their linked issue");function kT(e){let t=e.node||"",o=e.token||"";if(!t||!o)try{let s=T(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 Xb(e,t,o,n){let{baseUrl:s,headers:r}=kT(e),i;try{i=await fetch(`${s}${o}`,{method:t,headers:r,...n?{body:JSON.stringify(n)}:{}})}catch(a){console.log(ht.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(!i.ok){let a=await i.json().catch(()=>({}));console.log(ht.red(` HTTP ${i.status}${a.error?` \u2014 ${a.error}`:""}`)),process.exit(1)}return i}var Vb=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)"),Qb=e=>e==="success"?ht.green(e):e==="failure"?ht.red(e):ht.yellow(e);Vb(Fa.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 Xb(e,"GET",`/api/review-gate/reviews?${t}`)).json(),n=o.summary;console.log(ht.bold(` Last ${o.days} days: ${n.reviews} reviews on ${n.prs} PRs`)+ht.dim(` \u2014 ${n.byState.success} passed, ${n.byState.failure} failed, ${n.byState.error} errors`)),console.log(ht.dim(` cost $${n.costUsd}${n.unpriced?` (+${n.unpriced} unpriced)`:""}, ${n.minutes} min, ${n.tokens} tokens`+(n.p90SincePushMinutes!==void 0?`, push \u2192 status p90 ${n.p90SincePushMinutes} min`:"")));for(let s of o.reviews)console.log(` ${s.at.slice(0,16).replace("T"," ")} ${s.repo}${s.forge==="gitlab"?"!":"#"}${s.pr} ${s.sha.slice(0,7)} ${Qb(s.state)} ${ht.dim(s.reason)}${s.replay?ht.dim(" (replay)"):""}`)});Vb(Fa.command("replay <repo> <prs...>").description("review past PRs at their head commit without posting anything; counts how many get flagged").option("--gitlab","the repo is a GitLab project and the numbers are merge requests")).action(async(e,t,o)=>{let s=(await Xb(o,"POST","/api/review-gate/replay",{repo:e,prs:t.map(Number),...o.gitlab?{forge:"gitlab"}:{}})).body.getReader(),r=new TextDecoder,i="";for(;;){let{done:a,value:c}=await s.read();c&&(i+=r.decode(c,{stream:!0}));let l;for(;(l=i.indexOf(`
517
- `))>=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(ht.bold(` flagged ${d.flagged} of ${d.of}`)):d.error?console.log(` #${d.pr} ${ht.yellow("error")} ${ht.dim(d.error)}`):console.log(` #${d.pr} ${Qb(d.state)}${d.flagged?ht.red(" flagged"):""} ${ht.dim(d.reason)}`)}if(a)break}});oe();import{Command as vT}from"commander";import Un from"chalk";import{resolve as xT}from"path";var Ua=new vT().name("cloud-sessions").description("list and close the Claude cloud sessions that block their GitHub issue"),Zb=e=>e.option("--file <path>","session file",".agentx/cloud-sessions.json").option("-c, --config <path>","daemon config file, for each agent's openHours");function e$(e){return new Yu(xT(process.cwd(),e.file||".agentx/cloud-sessions.json"))}function ST(e){let t={};try{t=T(e.config).agents}catch{}return o=>t[o]?.cloudSessions?.openHours??zu.openHours}function AT(e){let t=e.trim().match(/^([^\/\s#:]+\/[^\/\s#:]+)(?:#|:(?:issue|pull):)(\d+)$/);if(!t)return;let o=Number(t[2]);return o>0?{repo:t[1],number:o}:void 0}Zb(Ua.command("list").description("cloud sessions still open for their issue, newest first").option("--all","include sessions whose open time is over")).action(e=>{let t=ST(e),o=Date.now(),n=e$(e).all().map(s=>({s,open:o-s.startedAt<t(s.agentId)*36e5})).filter(s=>e.all||s.open).sort((s,r)=>r.s.startedAt-s.s.startedAt);if(!n.length){console.log(Un.dim(` no ${e.all?"":"open "}cloud sessions`));return}for(let{s,open:r}of n){let i=new Date(s.startedAt).toISOString().slice(0,16).replace("T"," ");console.log(` ${s.repo}#${s.number} ${s.sessionId} ${Un.dim(`${s.agentId}, started ${i}`)} ${r?Un.yellow("open"):Un.dim("over")}`)}});Zb(Ua.command("close <refs...>").description("forget the session for each issue (owner/repo#42), so its next comment runs normally")).action((e,t)=>{let o=e$(t),n=!1;for(let s of e){let r=AT(s);if(!r){console.log(Un.red(` ${s}: expected owner/repo#number`)),n=!0;continue}o.close(r.repo,r.number)?console.log(Un.green(` closed ${r.repo}#${r.number}`)):console.log(Un.dim(` ${r.repo}#${r.number}: no session recorded`))}n&&(process.exitCode=1)});import{Command as ET}from"commander";import ut from"chalk";import{existsSync as Od,rmSync as RT}from"fs";import{resolve as Id}from"path";var Bs=new ET().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Bs.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(ut.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),r=await _u(e,t,{verbose:n}),i=Date.now()-s;console.log(ut.green(` \u2713 indexed ${r.docs} doc(s) for ${ut.bold(e)} in ${i}ms`)),console.log(ut.dim(` \u2192 ${r.path}`))});Bs.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=Id(e.cwd,".agentx","rag");if(!Od(t)){console.log(ut.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>Od(Id(t,s,"index.json")));if(n.length===0){console.log(ut.dim(" (no indexes)"));return}for(let s of n.sort()){let r=Pc(s);console.log(` ${ut.bold(s)} ${r.docs} doc(s) ${ut.dim(r.path)}`)}});Bs.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=Du(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let r=Pc(e);r.exists?console.log(ut.dim(` (no hits in ${r.docs} indexed docs)`)):console.log(ut.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let r of s)console.log(` ${ut.bold(r.title)} ${ut.dim(`(${r.score.toFixed(2)})`)}`),console.log(` ${ut.dim(r.path)}`),console.log(` ${ut.dim(r.snippet.slice(0,200))}`)});Bs.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=Id(process.cwd(),".agentx","rag",e);if(!Od(t)){console.log(ut.dim(` no index for ${e} \u2014 nothing to clear`));return}RT(t,{recursive:!0,force:!0}),console.log(ut.green(` \u2713 cleared index for ${e}`))});oe();import{Command as TT}from"commander";import pe from"chalk";import Js from"prompts";var Wn=new TT().name("backlog").description("manage the local backlog used by business workSource=backlog");function Ur(e){let t=T(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new df(n)}}function CT(e){return e?pe.cyan(`${e.type}:${e.project}#${e.iid}`):pe.dim("manual")}function OT(e){return{todo:pe.gray("todo"),doing:pe.yellow("doing"),blocked:pe.red("blocked"),done:pe.green("done")}[e]}Wn.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}=Ur(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(pe.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?pe.magenta(`@${n.assignee}`):pe.dim("unassigned");console.log(` ${OT(n.status).padEnd(7)} ${CT(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(pe.dim(` ${n.source.url}`))}console.log(),console.log(pe.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});Wn.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=Ur(o.config);n.store.findById(e)||(console.error(pe.red(` item ${e} not found`)),process.exit(1));let r=n.store.update(e,{assignee:t,status:"doing"});if(console.log(pe.green(` claimed: ${r.title} -> ${t}`)),r.source){let i=Cp([t],r.source,n.config),a=await Qc(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(pe.dim(" sync:"),...c));console.log(a.ok?pe.dim(` synced -> ${a.url??r.source.type}`):pe.yellow(` sync failed: ${a.error}`))}});Wn.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=Ur(t.config);o.store.findById(e)||(console.error(pe.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(pe.green(` done: ${s.title}`)),s.source){let r=await Qc(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...i)=>console.log(pe.dim(" sync:"),...i));console.log(r.ok?pe.dim(` synced -> ${r.url??s.source.type}`):pe.yellow(` sync failed: ${r.error}`))}});Wn.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}=Ur(t.config);o.remove(e)||(console.error(pe.red(` item ${e} not found`)),process.exit(1)),console.log(pe.green(` removed ${e}`))});Wn.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=Ur(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(pe.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 w=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Js({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!o&&(console.error(pe.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(pe.red(" channels.github.token not configured")),process.exit(1));let r=e.project;if(!r){let w=s==="gitlab"?NT(t.config):jT(t.config);w.length?(r=(await Js({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map($=>({title:$,value:$})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,r==="__CUSTOM__"&&(r=(await Js({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):r=(await Js({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!r)return;let a=((await Js({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(pe.dim(` fetching open issues from ${s}:${r}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await PT(t.config,r,a):await _T(t.config,r,a);if(!c.length){console.log(pe.yellow(" no open issues matched"));return}console.log(pe.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=r,g=new Set(t.store.list().map(w=>w.id)),d=c.map(w=>{let b=al({type:s,project:l,iid:w.iid,url:w.url}),$=g.has(b),v=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${v}${$?pe.dim(" (already imported)"):""}`,value:w,disabled:$}}),p=(await Js({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(pe.dim(" nothing selected"));return}let u=p.map(w=>{let b={type:s,host:s==="gitlab"?IT(t.config):void 0,project:l,iid:w.iid,url:w.url};return{id:al(b),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:b,importedAt:new Date().toISOString()}}),h=t.store.addMany(u);console.log(pe.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let w of h)console.log(pe.dim(` ${w.id} \u2014 ${w.title}`))});function IT(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function NT(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 jT(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 PT(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 _T(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(t$)}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(t$):[]}function t$(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 DT}from"commander";import X from"chalk";import{existsSync as MT,readFileSync as LT}from"fs";import{resolve as qT}from"path";import FT from"prompts";oe();function o$(e){let t=e||qT(process.cwd(),"agentx.json");return MT(t)||(console.log(X.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(LT(t,"utf-8"))}async function UT(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(X.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:r,accountId:i}=await FT([{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(X.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Co=new DT().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Co.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--no-deliver","send only failures to --notify, not each run's answer").option("--only-exceptions","the run decides: an answer of NOTHING_TO_REPORT sends nothing to --notify").option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${ur})`,ur).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){Co.help();return}t.agent||(console.log(X.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(X.red(' --do "<prompt>" is required')),process.exit(1));let o=Lc(e);o||(console.log(X.red(` Couldn't parse: "${e}"`)),console.log(X.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(X.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(X.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=o$(t.config),s=lr(n);n.agents?.[t.agent]||(console.log(X.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(X.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let r=await UT(t.notify,s),i=t.id||om(o.matched,t.agent),a=sm({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:r,deliverResult:t.deliver,report:t.onlyExceptions?"exceptions":void 0,onError:nm(t.onError),enabled:!t.disabled}),c=a.onError,l=await de(d=>qe(d,`crons.${i}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(X.red(` \u2717 ${l.error}`)),process.exit(1));let g=t.dryRun?"would add":"Added";console.log(X.green(` \u2713 ${g} cron ${X.cyan(i)}`)),console.log(X.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(X.dim(` Agent: ${t.agent}`)),r&&console.log(X.dim(` Notify: ${r.channel} ${r.chatId} ${qc(a)}`)),c.length&&console.log(X.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(X.dim(" Daemon hot-reloaded."))});Co.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=o$(e.config).crons||{},n=Object.entries(o),s=new Set;try{let{loadDaemonConfig:r}=await import("./config-BMYFEAO5.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(X.dim(" No scheduled jobs"));return}console.log();for(let[r,i]of n){let a=i.approval?X.yellow("\u25D0"):i.enabled?X.green("\u25CF"):X.dim("\u25CB"),c=i.schedule;try{c=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${a} ${X.cyan(r.padEnd(32))} ${X.dim(i.schedule.padEnd(14))} ${X.dim("\u2192")} ${i.agent}`),console.log(X.dim(` ${c} (${i.timezone||"UTC"})`)),i.notify&&console.log(X.dim(` notify: ${i.notify.channel} ${i.notify.chatId} ${qc(i)}`)),i.createdBy&&console.log(X.dim(` created by agent: ${i.createdBy}`)),s.has(r)&&console.log(X.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=im(rm(i.schedule,l),l);console.log(X.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${g}`)),console.log(X.dim(` agentx schedule approve ${r} | agentx schedule reject ${r}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])Co.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await lm(o,t);n.success||(console.log(X.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(X.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(X.dim(" Daemon hot-reloaded."))});Co.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await de(o=>{if(!fs(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);qu(o,`crons.${e}`)});t.success||(console.log(X.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(X.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(X.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",am,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",cm,"reject an agent's pending create/delete request (drops the request)"]])Co.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(X.red(` \u2717 ${r.message}`)),process.exit(1)),console.log(X.green(` \u2713 ${r.message}`)),r.result?.reloaded&&console.log(X.dim(" Daemon hot-reloaded."))});Co.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=Lc(t);o||(console.log(X.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(X.green(` "${t}"`)),console.log(X.dim(` \u2192 ${o.cron}`)),console.log(X.dim(` \u2192 ${o.human}`))});import{Command as aC}from"commander";import w$ from"chalk";import{existsSync as cC,readFileSync as lC}from"fs";import{resolve as b$}from"path";import{existsSync as WT,readFileSync as BT,writeFileSync as JT}from"fs";import{join as Pd}from"path";var Nd="leads.md",n$="opt-outs.md",s$=864e5,jd=/\d{4}-\d{2}-\d{2}/;function HT(e){return e.split(`
517
+ `))>=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(ht.bold(` flagged ${d.flagged} of ${d.of}`)):d.error?console.log(` #${d.pr} ${ht.yellow("error")} ${ht.dim(d.error)}`):console.log(` #${d.pr} ${Qb(d.state)}${d.flagged?ht.red(" flagged"):""} ${ht.dim(d.reason)}`)}if(a)break}});oe();import{Command as vT}from"commander";import Un from"chalk";import{resolve as xT}from"path";var Ua=new vT().name("cloud-sessions").description("list and close the Claude cloud sessions that block their GitHub issue"),Zb=e=>e.option("--file <path>","session file",".agentx/cloud-sessions.json").option("-c, --config <path>","daemon config file, for each agent's openHours");function e$(e){return new Yu(xT(process.cwd(),e.file||".agentx/cloud-sessions.json"))}function ST(e){let t={};try{t=T(e.config).agents}catch{}return o=>t[o]?.cloudSessions?.openHours??zu.openHours}function AT(e){let t=e.trim().match(/^([^\/\s#:]+\/[^\/\s#:]+)(?:#|:(?:issue|pull):)(\d+)$/);if(!t)return;let o=Number(t[2]);return o>0?{repo:t[1],number:o}:void 0}Zb(Ua.command("list").description("cloud sessions still open for their issue, newest first").option("--all","include sessions whose open time is over")).action(e=>{let t=ST(e),o=Date.now(),n=e$(e).all().map(s=>({s,open:o-s.startedAt<t(s.agentId)*36e5})).filter(s=>e.all||s.open).sort((s,r)=>r.s.startedAt-s.s.startedAt);if(!n.length){console.log(Un.dim(` no ${e.all?"":"open "}cloud sessions`));return}for(let{s,open:r}of n){let i=new Date(s.startedAt).toISOString().slice(0,16).replace("T"," ");console.log(` ${s.repo}#${s.number} ${s.sessionId} ${Un.dim(`${s.agentId}, started ${i}`)} ${r?Un.yellow("open"):Un.dim("over")}`)}});Zb(Ua.command("close <refs...>").description("forget the session for each issue (owner/repo#42), so its next comment runs normally")).action((e,t)=>{let o=e$(t),n=!1;for(let s of e){let r=AT(s);if(!r){console.log(Un.red(` ${s}: expected owner/repo#number`)),n=!0;continue}o.close(r.repo,r.number)?console.log(Un.green(` closed ${r.repo}#${r.number}`)):console.log(Un.dim(` ${r.repo}#${r.number}: no session recorded`))}n&&(process.exitCode=1)});import{Command as ET}from"commander";import ut from"chalk";import{existsSync as Od,rmSync as RT}from"fs";import{resolve as Id}from"path";var Bs=new ET().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Bs.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(ut.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!o.verbose,s=Date.now(),r=await _u(e,t,{verbose:n}),i=Date.now()-s;console.log(ut.green(` \u2713 indexed ${r.docs} doc(s) for ${ut.bold(e)} in ${i}ms`)),console.log(ut.dim(` \u2192 ${r.path}`))});Bs.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=Id(e.cwd,".agentx","rag");if(!Od(t)){console.log(ut.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:o}=await import("fs"),n=o(t).filter(s=>Od(Id(t,s,"index.json")));if(n.length===0){console.log(ut.dim(" (no indexes)"));return}for(let s of n.sort()){let r=Pc(s);console.log(` ${ut.bold(s)} ${r.docs} doc(s) ${ut.dim(r.path)}`)}});Bs.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=Du(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let r=Pc(e);r.exists?console.log(ut.dim(` (no hits in ${r.docs} indexed docs)`)):console.log(ut.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let r of s)console.log(` ${ut.bold(r.title)} ${ut.dim(`(${r.score.toFixed(2)})`)}`),console.log(` ${ut.dim(r.path)}`),console.log(` ${ut.dim(r.snippet.slice(0,200))}`)});Bs.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=Id(process.cwd(),".agentx","rag",e);if(!Od(t)){console.log(ut.dim(` no index for ${e} \u2014 nothing to clear`));return}RT(t,{recursive:!0,force:!0}),console.log(ut.green(` \u2713 cleared index for ${e}`))});oe();import{Command as TT}from"commander";import pe from"chalk";import Js from"prompts";var Wn=new TT().name("backlog").description("manage the local backlog used by business workSource=backlog");function Ur(e){let t=T(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new df(n)}}function CT(e){return e?pe.cyan(`${e.type}:${e.project}#${e.iid}`):pe.dim("manual")}function OT(e){return{todo:pe.gray("todo"),doing:pe.yellow("doing"),blocked:pe.red("blocked"),done:pe.green("done")}[e]}Wn.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}=Ur(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(pe.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?pe.magenta(`@${n.assignee}`):pe.dim("unassigned");console.log(` ${OT(n.status).padEnd(7)} ${CT(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(pe.dim(` ${n.source.url}`))}console.log(),console.log(pe.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});Wn.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=Ur(o.config);n.store.findById(e)||(console.error(pe.red(` item ${e} not found`)),process.exit(1));let r=n.store.update(e,{assignee:t,status:"doing"});if(console.log(pe.green(` claimed: ${r.title} -> ${t}`)),r.source){let i=Cp([t],r.source,n.config),a=await Qc(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(pe.dim(" sync:"),...c));console.log(a.ok?pe.dim(` synced -> ${a.url??r.source.type}`):pe.yellow(` sync failed: ${a.error}`))}});Wn.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=Ur(t.config);o.store.findById(e)||(console.error(pe.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(pe.green(` done: ${s.title}`)),s.source){let r=await Qc(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...i)=>console.log(pe.dim(" sync:"),...i));console.log(r.ok?pe.dim(` synced -> ${r.url??s.source.type}`):pe.yellow(` sync failed: ${r.error}`))}});Wn.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}=Ur(t.config);o.remove(e)||(console.error(pe.red(` item ${e} not found`)),process.exit(1)),console.log(pe.green(` removed ${e}`))});Wn.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=Ur(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(pe.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 w=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Js({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!o&&(console.error(pe.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(pe.red(" channels.github.token not configured")),process.exit(1));let r=e.project;if(!r){let w=s==="gitlab"?NT(t.config):jT(t.config);w.length?(r=(await Js({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map($=>({title:$,value:$})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,r==="__CUSTOM__"&&(r=(await Js({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):r=(await Js({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!r)return;let a=((await Js({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(pe.dim(` fetching open issues from ${s}:${r}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await PT(t.config,r,a):await _T(t.config,r,a);if(!c.length){console.log(pe.yellow(" no open issues matched"));return}console.log(pe.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=r,g=new Set(t.store.list().map(w=>w.id)),d=c.map(w=>{let b=al({type:s,project:l,iid:w.iid,url:w.url}),$=g.has(b),v=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${v}${$?pe.dim(" (already imported)"):""}`,value:w,disabled:$}}),p=(await Js({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(pe.dim(" nothing selected"));return}let u=p.map(w=>{let b={type:s,host:s==="gitlab"?IT(t.config):void 0,project:l,iid:w.iid,url:w.url};return{id:al(b),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:b,importedAt:new Date().toISOString()}}),h=t.store.addMany(u);console.log(pe.green(` imported ${h.length} item${h.length===1?"":"s"}`));for(let w of h)console.log(pe.dim(` ${w.id} \u2014 ${w.title}`))});function IT(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function NT(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 jT(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 PT(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 _T(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(t$)}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(t$):[]}function t$(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 DT}from"commander";import X from"chalk";import{existsSync as MT,readFileSync as LT}from"fs";import{resolve as qT}from"path";import FT from"prompts";oe();function o$(e){let t=e||qT(process.cwd(),"agentx.json");return MT(t)||(console.log(X.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(LT(t,"utf-8"))}async function UT(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(X.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:r,accountId:i}=await FT([{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(X.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Co=new DT().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Co.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--no-deliver","send only failures to --notify, not each run's answer").option("--only-exceptions","the run decides: an answer of NOTHING_TO_REPORT sends nothing to --notify").option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${ur})`,ur).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){Co.help();return}t.agent||(console.log(X.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(X.red(' --do "<prompt>" is required')),process.exit(1));let o=Lc(e);o||(console.log(X.red(` Couldn't parse: "${e}"`)),console.log(X.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(X.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(X.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=o$(t.config),s=lr(n);n.agents?.[t.agent]||(console.log(X.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(X.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let r=await UT(t.notify,s),i=t.id||om(o.matched,t.agent),a=sm({parsed:o,agent:t.agent,prompt:t.do,timezone:t.timezone,timeout:parseInt(t.timeout,10),model:t.model,notify:r,deliverResult:t.deliver,report:t.onlyExceptions?"exceptions":void 0,onError:nm(t.onError),enabled:!t.disabled}),c=a.onError,l=await de(d=>qe(d,`crons.${i}`,a),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(X.red(` \u2717 ${l.error}`)),process.exit(1));let g=t.dryRun?"would add":"Added";console.log(X.green(` \u2713 ${g} cron ${X.cyan(i)}`)),console.log(X.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(X.dim(` Agent: ${t.agent}`)),r&&console.log(X.dim(` Notify: ${r.channel} ${r.chatId} ${qc(a)}`)),c.length&&console.log(X.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(X.dim(" Daemon hot-reloaded."))});Co.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=o$(e.config).crons||{},n=Object.entries(o),s=new Set;try{let{loadDaemonConfig:r}=await import("./config-RHCIE7VE.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(X.dim(" No scheduled jobs"));return}console.log();for(let[r,i]of n){let a=i.approval?X.yellow("\u25D0"):i.enabled?X.green("\u25CF"):X.dim("\u25CB"),c=i.schedule;try{c=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${a} ${X.cyan(r.padEnd(32))} ${X.dim(i.schedule.padEnd(14))} ${X.dim("\u2192")} ${i.agent}`),console.log(X.dim(` ${c} (${i.timezone||"UTC"})`)),i.notify&&console.log(X.dim(` notify: ${i.notify.channel} ${i.notify.chatId} ${qc(i)}`)),i.createdBy&&console.log(X.dim(` created by agent: ${i.createdBy}`)),s.has(r)&&console.log(X.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=im(rm(i.schedule,l),l);console.log(X.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${g}`)),console.log(X.dim(` agentx schedule approve ${r} | agentx schedule reject ${r}`))}}console.log()});for(let[e,t]of[["on",!0],["off",!1]])Co.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await lm(o,t);n.success||(console.log(X.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(X.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(X.dim(" Daemon hot-reloaded."))});Co.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await de(o=>{if(!fs(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);qu(o,`crons.${e}`)});t.success||(console.log(X.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(X.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(X.dim(" Daemon hot-reloaded."))});for(let[e,t,o]of[["approve",am,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",cm,"reject an agent's pending create/delete request (drops the request)"]])Co.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(X.red(` \u2717 ${r.message}`)),process.exit(1)),console.log(X.green(` \u2713 ${r.message}`)),r.result?.reloaded&&console.log(X.dim(" Daemon hot-reloaded."))});Co.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=Lc(t);o||(console.log(X.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(X.green(` "${t}"`)),console.log(X.dim(` \u2192 ${o.cron}`)),console.log(X.dim(` \u2192 ${o.human}`))});import{Command as aC}from"commander";import w$ from"chalk";import{existsSync as cC,readFileSync as lC}from"fs";import{resolve as b$}from"path";import{existsSync as WT,readFileSync as BT,writeFileSync as JT}from"fs";import{join as Pd}from"path";var Nd="leads.md",n$="opt-outs.md",s$=864e5,jd=/\d{4}-\d{2}-\d{2}/;function HT(e){return e.split(`
518
518
  `).map(t=>t.trim()).filter(t=>/^[-*]\s+\S/.test(t)).map(t=>t.replace(/^[-*]\s+/,"").split("|").map(o=>o.trim()))}function GT(e){return e.split(`
519
519
  `).filter(t=>/^\s*[-*]\s+\S/.test(t)).map(t=>{let[o,n="",...s]=t.trim().replace(/^[-*]\s+/,"").split("|").map(i=>i.trim()),r={name:o,company:n,line:t.trim()};for(let i of s){let a=i.toLowerCase();a.startsWith("last contact")?r.lastContact=i.match(jd)?.[0]:a.startsWith("added")?r.added=i.match(jd)?.[0]:a.startsWith("offered:")?r.offered=i.slice(8).trim():a.startsWith("next:")&&(r.next=i.slice(5).trim())}return r}).filter(t=>t.name)}function r$(e){return HT(e).map(([t="",o="",n,s])=>({name:t,company:o,date:n?.match(jd)?.[0],reason:s||void 0})).filter(t=>t.name)}var Wa=e=>e.trim().toLowerCase().replace(/\s+/g," ");function Wr(e,t){return t.some(o=>Wa(o.name)===Wa(e.name)&&(!o.company||Wa(o.company)===Wa(e.company)))}var zT=e=>/^done\b/i.test(e.next??""),Hs=e=>Date.parse(`${e}T00:00:00Z`);function i$(e,t,o,n=7){let s=Hs(o)-n*s$;return e.filter(r=>{if(zT(r)||Wr(r,t))return!1;let i=r.lastContact??r.added;return!i||Hs(i)<=s})}function a$(e,t,o,n=1){let s=Hs(o)-(n-1)*s$;return e.filter(r=>r.added&&Hs(r.added)>=s&&Hs(r.added)<=Hs(o)&&!Wr(r,t))}function _d(e){return WT(e)?BT(e,"utf-8"):""}function c$(e){return GT(_d(Pd(e,Nd)))}function l$(e){return r$(_d(Pd(e,n$)))}var YT=`# Opt-outs
520
520
 
@@ -551,7 +551,7 @@ People who asked not to be contacted. The sales agent never drafts a message to
551
551
  Plan ${P.dim(`[${r.state}] by ${r.createdBy}, ${Hn(r.createdAt)}`)}`),L$(s.steps(e)),console.log(`
552
552
  Log`);for(let i of s.events(e))console.log(P.dim(` ${Hn(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});on.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(P.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=Jr();if(!s)return;let r=Ga();if(!r){process.exitCode=1;return}let i=Number(t),a=kp(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(P.red(` ${a}`)),process.exitCode=1;return}console.log(P.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+P.dim(" (the daemon goes on within a minute)")),L$(r.steps(e))});function q$(e,t,o,n){let s=on.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=Jr();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(P.red(` ${n}`)),process.exitCode=1;return}let l=a.get(r);if(!l||l.state==="candidate"){console.error(P.red(` no request "${r}"`)),process.exitCode=1;return}if(!a.close(r,e==="done"?"done":"dropped",c,Date.now())){console.error(P.red(` ${r} is already closed (${zd[l.state]??l.state})`)),process.exitCode=1;return}console.log(P.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}q$("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>");q$("drop","drop a request you no longer want","--reason <text>","");on.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 (${ui.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 w=Number(h);if(!(w>0))throw new Error(`${u} must be a positive number`);return w},g=(u,h)=>u===void 0?void 0:u===h?[]:u.split(",").map(w=>w.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=>!ui.includes(h));if(u.length)throw new Error(`unknown check ${u.join(", ")}: use ${ui.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(P.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(t).some(l=>l!==void 0)){let l=await sp(t);if(!l.success){console.error(P.red(` ${l.error}`)),process.exitCode=1;return}console.log(P.green(" \u2713 saved")+(l.reloaded?P.dim(" (daemon reloaded)"):""))}let o=Pi();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??Mi;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??Mi.requireOverMinutes,i=s.requireForWork??Mi.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??mi;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 LC}from"commander";import Ys from"chalk";oe();var F$=new LC("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",ml.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(Ys.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await de(r=>{n=Uf(r,e,t==="on")});s.success||(console.error(Ys.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(Ys.green(`\u2713 ${n}`)),s.reloaded&&console.log(Ys.dim(" daemon hot-reloaded"))}let o=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of ml)console.log(` ${n.padEnd(8)} ${o.includes(n)?Ys.green("on"):Ys.dim("off")}`)});import{Command as mO}from"commander";import Ks from"chalk";import ye from"chalk";import Hr from"prompts";import{readFileSync as qC,writeFileSync as FC,existsSync as UC}from"fs";import{resolve as U$}from"path";var WC=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function BC(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Kd(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function W$(e=".env"){let t=U$(e);if(!UC(t))return[];let o=qC(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(WC);r?n.push({kind:"kv",key:r[1],value:BC(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function JC(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Kd(t.value)}`:t.raw).join(`
553
553
  `)+`
554
- `}function Gn(e,t,o=".env"){let n=U$(o),s=W$(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Kd(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Kd(t)}`})),FC(n,JC(s))}function Xd(e,t=".env"){return W$(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var B$="https://t.me/BotFather";async function HC(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 GC(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 J$(e={}){console.log(),console.log(ye.bold(" Connect Telegram")),console.log(),console.log(ye.dim(` 1. Open ${B$}`)),console.log(ye.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ye.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Hr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Ro(B$);let{token:o}=await Hr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:S=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(S.trim())||"That doesn't look like a Telegram token"});o||(console.log(ye.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await HC(o.trim());n||(console.log(ye.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ye.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(ye.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(ye.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Hr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),g||(console.log(ye.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await Hr({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ye.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Gn(p,o.trim()),process.env[p]=o.trim();let u=await de(S=>{qe(S,"channels.telegram.enabled",!0),qe(S,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let x=fs(S,`agents.${g}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),qe(S,`agents.${g}.mentions`,x))},{configPath:e.configPath});if(u.success||(console.log(ye.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(ye.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ye.dim(` Token stored in .env as ${p}`)),console.log(ye.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(ye.dim(" Daemon hot-reloaded.")):console.log(ye.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Hr({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(ye.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ye.dim(" Waiting up to 90s..."));let w=await GC(o.trim(),9e4);if(!w){console.log(ye.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ye.dim(" agentx config set notifications.destination.channel telegram")),console.log(ye.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ye.dim(` agentx config set notifications.destination.accountId ${f}`));return}let b={channel:"telegram",chatId:String(w.chatId),accountId:f},$=[],v=await de(S=>{qe(S,"notifications.destination",b),$=sa(S,b)},{configPath:e.configPath});if(!v.success){console.log(ye.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(ye.green(" \u2713 Default --notify target set")),console.log(ye.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ye.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(ye.dim(` Schedules that now report here: ${$.join(", ")}`)),v.reloaded&&console.log(ye.dim(" Daemon hot-reloaded."))}import Pe from"chalk";import Vd from"prompts";import{existsSync as Zd,mkdirSync as zC,readdirSync as YC,readFileSync as H$}from"fs";import{resolve as Qd}from"path";var KC=".agentx/whatsapp-sessions";function XC(){let e=Qd(process.cwd(),".agentx/daemon.pid");if(!Zd(e))return!1;try{let t=parseInt(H$(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function VC(e){if(!Zd(e))return!1;try{return YC(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function QC(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Pe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Pe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;zC(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(Pe.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(Pe.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(Pe.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(Pe.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function G$(e={}){if(console.log(),console.log(Pe.bold(" Connect WhatsApp")),console.log(),XC()){console.log(Pe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Pe.dim(" agentx daemon stop")),console.log();let{cont:l}=await Vd({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Pe.red(" Aborted")),process.exit(1))}let t=e.configPath||Qd(process.cwd(),"agentx.json");Zd(t)||(console.log(Pe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(H$(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||KC,s=Qd(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Pe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Vd({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(Pe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(VC(s)&&a){let{keep:l}=await Vd({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(Pe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await QC(s,g=>console.log(g))||(console.log(Pe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(l=>{qe(l,"channels.whatsapp.enabled",!0),qe(l,"channels.whatsapp.sessionDir",n),qe(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Pe.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Pe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Pe.dim(` Session: ${n}`)),console.log(Pe.dim(" Start the daemon to begin receiving:")),console.log(Pe.dim(" agentx daemon start")),console.log(Pe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Pe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Pe.dim(" Add routes later with:")),console.log(Pe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import At from"chalk";import ZC from"prompts";import{existsSync as eO,readFileSync as tO}from"fs";import{resolve as oO}from"path";async function nO(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function sO(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Io(e){console.log(At.red(` ${e}`)),process.exit(1)}async function zn(e){return(await ZC(e,{onCancel:()=>Io("Aborted")}))[e.name]}async function z$(e={}){console.log(),console.log(At.bold(" Connect email")),console.log();let t=e.configPath||oO(process.cwd(),"agentx.json");eO(t)||Io(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(tO(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Io("No agents configured. Run: agentx agent add");let s=e.agent??await zn({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(b=>({title:b,value:b}))});o.agents?.[s]||Io(`No agent "${s}" in ${t}`);let r=(e.address??await zn({type:"text",name:"address",message:"Email address customers write to:",validate:b=>/^\S+@\S+\.\S+$/.test(b.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=Bf(r),c=e.imapHost??a?.imapHost??await zn({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await zn({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),g=e.smtpHost??a?.smtpHost??await zn({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await zn({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Io("Ports must be numbers.");let f=e.passwordEnv||Hf(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&Io(`${e.passwordEnv} is not set in the environment.`),p||(a?.imapHost==="imap.gmail.com"&&(console.log(At.dim(` Gmail needs an app password, not your account password: ${Wf}`)),console.log(At.dim(" (2-step verification must be on for that page to show.)"))),p=(await zn({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||Io("Aborted");let u={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:g,smtpPort:d,user:e.user,passwordEnv:f,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let b=await nO(u,p);b&&(console.log(At.red("\u2717")),Io(b)),console.log(At.green("\u2713"))}e.passwordEnv||(Gn(f,p),process.env[f]=p);let h=await de(b=>{qe(b,"channels.email.enabled",!0),qe(b,`channels.email.accounts.${i}`,Jf(u))},{configPath:e.configPath});h.success||Io(`Config save failed: ${h.error}`),console.log(),console.log(At.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(At.dim(` Password stored in .env as ${f}`)),console.log(At.dim(` Who may write: ${u.allowFrom.join(", ")}${u.allowFrom.includes("*")?" (anyone)":""}`));let w=sO(o.agents[s]?.tier,u.allowFrom);w&&console.log(At.yellow(` ${w}`)),console.log(u.send==="auto"?At.yellow(" Replies are sent as soon as the agent writes them."):At.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(At.dim(" Only mail that arrives from now on is answered.")),console.log(At.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as rO}from"crypto";import ze from"chalk";import Y$ from"prompts";var za="agentx-mesh:",Ya="//join/";function iO(e){return Buffer.from(e,"utf-8").toString("base64url")}function aO(e){return Buffer.from(e,"base64url").toString("utf-8")}function cO(e){return`${za}${Ya}${iO(JSON.stringify(e))}`}function lO(e){if(!e.startsWith(`${za}${Ya}`))throw new Error(`Not a mesh invite link \u2014 expected ${za}${Ya}\u2026`);let t=e.slice(za.length+Ya.length),o=JSON.parse(aO(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 dO(){return rO(32).toString("hex")}function gO(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function uO(e){return e?.node?.name||e?.node?.id||"node"}async function K$(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(ze.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Xd("MESH_TOKEN");i||(i=dO(),Gn("MESH_TOKEN",i),console.log(ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||gO(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Y$({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(ze.red(" Aborted")),process.exit(1)),a=d}let l=await de(d=>{qe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ze.red(` \u2717 ${l.error}`)),process.exit(1));let g=cO({url:a,token:i,name:uO(r),version:1});console.log(),console.log(ze.bold(" Mesh invite")),console.log(),console.log(` ${ze.cyan(g)}`),console.log(),console.log(ze.dim(" Run on the other node:")),console.log(ze.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ze.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function X$(e,t={}){let o;try{o=lO(e)}catch(r){console.log(ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Xd("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Y$({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(ze.red(" Aborted (keeping existing .env)")),process.exit(1))}Gn("MESH_TOKEN",o.token);let s=await de(r=>{qe(r,"mesh.enabled",!0);let i=fs(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),qe(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(ze.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ze.green(" \u2713 Joined mesh")),console.log(ze.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(ze.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ze.dim(" Daemon hot-reloaded.")):console.log(ze.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(ze.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(ze.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(ze.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Yn=new mO().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Yn.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 J$({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Yn.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 G$({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});Yn.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await z$({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var V$=Yn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");V$.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 K$({url:e.url,configPath:e.config})});V$.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 X$(e,{configPath:t.config})});Yn.action(()=>{console.log(),console.log(Ks.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ks.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ks.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ks.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ks.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ks.dim(" GitLab connect is the next slice.")),console.log()});oe();import{Command as pO}from"commander";import se from"chalk";var Kn=new pO().name("usage").description("token usage analysis and reporting");Kn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[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(se.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(se.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${se.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: ${se.red(String(s.totalErrors))}`),console.log(),console.log(se.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(` ${se.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${se.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${e.message}`))}});Kn.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=T(),[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.`:se.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(se.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(se.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`:"",w=l.has(d.window)?se.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,w].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(se.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${t.message}`))}});Kn.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(se.red(` Script not found: ${s}`)),console.log(se.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(se.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(se.red(" Analysis failed. Is Python 3 installed?"))}});Kn.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(se.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(se.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(se.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(se.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(se.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,w]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(w),S=b!==null&&v?`${((b-v)/v*100).toFixed(0)}%`:"-";$+=` ${l(v).padStart(9)} ${S.padStart(7)}`}console.log($)}console.log(),c&&console.log(se.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(se.dim(` Saved ${e.save}`)),console.log()});Kn.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-BHDAV67G.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(se.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${se.dim("\xB7")} ${d}`);console.log(),console.log(se.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(se.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(se.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(se.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(se.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(se.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=se.dim(`${r.days}d`);console.log(` ${se.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(se.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as fO}from"commander";import We from"chalk";import{readFileSync as hO}from"fs";import{resolve as wO}from"path";oe();var nn=new fO().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");nn.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{$u(wO(process.cwd(),".env"))}catch{}let t=yO(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-3CMB3NPI.js");o(t)}catch(t){console.log(We.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(We.dim(t.stack)),process.exit(1)}});function yO(e,t){try{let o=T();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(We.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(We.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
554
+ `}function Gn(e,t,o=".env"){let n=U$(o),s=W$(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Kd(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Kd(t)}`})),FC(n,JC(s))}function Xd(e,t=".env"){return W$(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var B$="https://t.me/BotFather";async function HC(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 GC(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 J$(e={}){console.log(),console.log(ye.bold(" Connect Telegram")),console.log(),console.log(ye.dim(` 1. Open ${B$}`)),console.log(ye.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ye.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Hr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Ro(B$);let{token:o}=await Hr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:S=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(S.trim())||"That doesn't look like a Telegram token"});o||(console.log(ye.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await HC(o.trim());n||(console.log(ye.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ye.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(ye.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(ye.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Hr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),g||(console.log(ye.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await Hr({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ye.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Gn(p,o.trim()),process.env[p]=o.trim();let u=await de(S=>{qe(S,"channels.telegram.enabled",!0),qe(S,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let x=fs(S,`agents.${g}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),qe(S,`agents.${g}.mentions`,x))},{configPath:e.configPath});if(u.success||(console.log(ye.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(ye.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ye.dim(` Token stored in .env as ${p}`)),console.log(ye.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(ye.dim(" Daemon hot-reloaded.")):console.log(ye.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Hr({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(ye.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ye.dim(" Waiting up to 90s..."));let w=await GC(o.trim(),9e4);if(!w){console.log(ye.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ye.dim(" agentx config set notifications.destination.channel telegram")),console.log(ye.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ye.dim(` agentx config set notifications.destination.accountId ${f}`));return}let b={channel:"telegram",chatId:String(w.chatId),accountId:f},$=[],v=await de(S=>{qe(S,"notifications.destination",b),$=sa(S,b)},{configPath:e.configPath});if(!v.success){console.log(ye.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(ye.green(" \u2713 Default --notify target set")),console.log(ye.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ye.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(ye.dim(` Schedules that now report here: ${$.join(", ")}`)),v.reloaded&&console.log(ye.dim(" Daemon hot-reloaded."))}import Pe from"chalk";import Vd from"prompts";import{existsSync as Zd,mkdirSync as zC,readdirSync as YC,readFileSync as H$}from"fs";import{resolve as Qd}from"path";var KC=".agentx/whatsapp-sessions";function XC(){let e=Qd(process.cwd(),".agentx/daemon.pid");if(!Zd(e))return!1;try{let t=parseInt(H$(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function VC(e){if(!Zd(e))return!1;try{return YC(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function QC(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Pe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Pe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;zC(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(Pe.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(Pe.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(Pe.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(Pe.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function G$(e={}){if(console.log(),console.log(Pe.bold(" Connect WhatsApp")),console.log(),XC()){console.log(Pe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Pe.dim(" agentx daemon stop")),console.log();let{cont:l}=await Vd({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Pe.red(" Aborted")),process.exit(1))}let t=e.configPath||Qd(process.cwd(),"agentx.json");Zd(t)||(console.log(Pe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(H$(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||KC,s=Qd(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Pe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Vd({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(Pe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(VC(s)&&a){let{keep:l}=await Vd({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(Pe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await QC(s,g=>console.log(g))||(console.log(Pe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(l=>{qe(l,"channels.whatsapp.enabled",!0),qe(l,"channels.whatsapp.sessionDir",n),qe(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Pe.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Pe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Pe.dim(` Session: ${n}`)),console.log(Pe.dim(" Start the daemon to begin receiving:")),console.log(Pe.dim(" agentx daemon start")),console.log(Pe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Pe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Pe.dim(" Add routes later with:")),console.log(Pe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import At from"chalk";import ZC from"prompts";import{existsSync as eO,readFileSync as tO}from"fs";import{resolve as oO}from"path";async function nO(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function sO(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Io(e){console.log(At.red(` ${e}`)),process.exit(1)}async function zn(e){return(await ZC(e,{onCancel:()=>Io("Aborted")}))[e.name]}async function z$(e={}){console.log(),console.log(At.bold(" Connect email")),console.log();let t=e.configPath||oO(process.cwd(),"agentx.json");eO(t)||Io(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(tO(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Io("No agents configured. Run: agentx agent add");let s=e.agent??await zn({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(b=>({title:b,value:b}))});o.agents?.[s]||Io(`No agent "${s}" in ${t}`);let r=(e.address??await zn({type:"text",name:"address",message:"Email address customers write to:",validate:b=>/^\S+@\S+\.\S+$/.test(b.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=Bf(r),c=e.imapHost??a?.imapHost??await zn({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await zn({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),g=e.smtpHost??a?.smtpHost??await zn({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await zn({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Io("Ports must be numbers.");let f=e.passwordEnv||Hf(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&Io(`${e.passwordEnv} is not set in the environment.`),p||(a?.imapHost==="imap.gmail.com"&&(console.log(At.dim(` Gmail needs an app password, not your account password: ${Wf}`)),console.log(At.dim(" (2-step verification must be on for that page to show.)"))),p=(await zn({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||Io("Aborted");let u={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:g,smtpPort:d,user:e.user,passwordEnv:f,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let b=await nO(u,p);b&&(console.log(At.red("\u2717")),Io(b)),console.log(At.green("\u2713"))}e.passwordEnv||(Gn(f,p),process.env[f]=p);let h=await de(b=>{qe(b,"channels.email.enabled",!0),qe(b,`channels.email.accounts.${i}`,Jf(u))},{configPath:e.configPath});h.success||Io(`Config save failed: ${h.error}`),console.log(),console.log(At.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(At.dim(` Password stored in .env as ${f}`)),console.log(At.dim(` Who may write: ${u.allowFrom.join(", ")}${u.allowFrom.includes("*")?" (anyone)":""}`));let w=sO(o.agents[s]?.tier,u.allowFrom);w&&console.log(At.yellow(` ${w}`)),console.log(u.send==="auto"?At.yellow(" Replies are sent as soon as the agent writes them."):At.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(At.dim(" Only mail that arrives from now on is answered.")),console.log(At.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as rO}from"crypto";import ze from"chalk";import Y$ from"prompts";var za="agentx-mesh:",Ya="//join/";function iO(e){return Buffer.from(e,"utf-8").toString("base64url")}function aO(e){return Buffer.from(e,"base64url").toString("utf-8")}function cO(e){return`${za}${Ya}${iO(JSON.stringify(e))}`}function lO(e){if(!e.startsWith(`${za}${Ya}`))throw new Error(`Not a mesh invite link \u2014 expected ${za}${Ya}\u2026`);let t=e.slice(za.length+Ya.length),o=JSON.parse(aO(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 dO(){return rO(32).toString("hex")}function gO(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function uO(e){return e?.node?.name||e?.node?.id||"node"}async function K$(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(ze.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Xd("MESH_TOKEN");i||(i=dO(),Gn("MESH_TOKEN",i),console.log(ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||gO(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Y$({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(ze.red(" Aborted")),process.exit(1)),a=d}let l=await de(d=>{qe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ze.red(` \u2717 ${l.error}`)),process.exit(1));let g=cO({url:a,token:i,name:uO(r),version:1});console.log(),console.log(ze.bold(" Mesh invite")),console.log(),console.log(` ${ze.cyan(g)}`),console.log(),console.log(ze.dim(" Run on the other node:")),console.log(ze.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ze.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function X$(e,t={}){let o;try{o=lO(e)}catch(r){console.log(ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Xd("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Y$({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(ze.red(" Aborted (keeping existing .env)")),process.exit(1))}Gn("MESH_TOKEN",o.token);let s=await de(r=>{qe(r,"mesh.enabled",!0);let i=fs(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),qe(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(ze.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ze.green(" \u2713 Joined mesh")),console.log(ze.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(ze.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ze.dim(" Daemon hot-reloaded.")):console.log(ze.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(ze.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(ze.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(ze.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Yn=new mO().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Yn.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 J$({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Yn.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 G$({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});Yn.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await z$({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var V$=Yn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");V$.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 K$({url:e.url,configPath:e.config})});V$.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 X$(e,{configPath:t.config})});Yn.action(()=>{console.log(),console.log(Ks.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ks.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ks.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ks.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ks.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ks.dim(" GitLab connect is the next slice.")),console.log()});oe();import{Command as pO}from"commander";import se from"chalk";var Kn=new pO().name("usage").description("token usage analysis and reporting");Kn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[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(se.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(se.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${se.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: ${se.red(String(s.totalErrors))}`),console.log(),console.log(se.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(` ${se.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${se.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${e.message}`))}});Kn.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=T(),[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.`:se.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(se.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(se.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`:"",w=l.has(d.window)?se.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,w].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(se.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${t.message}`))}});Kn.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(se.red(` Script not found: ${s}`)),console.log(se.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(se.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(se.red(" Analysis failed. Is Python 3 installed?"))}});Kn.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(se.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(se.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(se.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(se.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(se.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,w]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(w),S=b!==null&&v?`${((b-v)/v*100).toFixed(0)}%`:"-";$+=` ${l(v).padStart(9)} ${S.padStart(7)}`}console.log($)}console.log(),c&&console.log(se.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(se.dim(` Saved ${e.save}`)),console.log()});Kn.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-2DFU4DCC.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(se.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${se.dim("\xB7")} ${d}`);console.log(),console.log(se.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(se.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(se.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(se.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(se.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(se.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=se.dim(`${r.days}d`);console.log(` ${se.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(se.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as fO}from"commander";import We from"chalk";import{readFileSync as hO}from"fs";import{resolve as wO}from"path";oe();var nn=new fO().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");nn.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{$u(wO(process.cwd(),".env"))}catch{}let t=yO(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-TCZ3RAQR.js");o(t)}catch(t){console.log(We.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(We.dim(t.stack)),process.exit(1)}});function yO(e,t){try{let o=T();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(We.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(We.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
555
555
  `)),{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}}}}nn.command("list").description("list configured boards").action(()=>{try{let e=T();if(!e.boards?.length){console.log(We.dim(`
556
556
  No boards configured.
557
557
  `));return}console.log();for(let t of e.boards){console.log(` ${We.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(We.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(We.dim(` primary label: ${t.primaryToolLabel}`)),console.log(We.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(We.red(` ${e.message}`)),process.exit(1)}});nn.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{Gr(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(We.red(` ${o.message}`)),process.exit(1)}});nn.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{Gr(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(We.red(` ${o.message}`)),process.exit(1)}});var eg=nn.command("column").description("manage a board's columns (add / remove / edit / list)");eg.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(hO("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(We.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(` ${We.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${We.dim(r)}`)}}catch(t){console.log(We.red(` ${t.message}`)),process.exit(1)}});eg.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{Gr(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(We.red(` ${n.message}`)),process.exit(1)}});eg.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Gr(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(We.red(` ${o.message}`)),process.exit(1)}});nn.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Gr(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(We.red(` ${t.message}`)),process.exit(1)}});function Gr(e){let{summary:t,backupPath:o}=jt(n=>e(n));console.log(We.green(`
@@ -581,19 +581,19 @@ An edit that breaks these rules is refused and the note is deferred.
581
581
 
582
582
  ${t}
583
583
  `}function tk(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=Ka(a.reason||"no reason given");if(a.outcome!=="patched")return{id:i.id,outcome:a.outcome,reason:c,patched:[]};let l=bO(a.edits,o,n.paths,n.agentId);if("refused"in l)return{id:i.id,outcome:"deferred",reason:Ka(`patch refused: ${l.refused}. Absorb said: ${c}`),patched:[]};let g=[],d="";for(let[p,{article:u,content:h}]of l.articles){let w=!1;try{w=o.writeArticle(p,{...u.meta,lastUpdated:s,sources:[...new Set([...u.meta.sources??[],og(i.id)])]},h,n.agentId)}catch(b){d=`${p}: ${b?.message??b}`}if(!w){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:Ka(`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:Ka(`${c} (edited ${f.join(", ")})`),patched:f}})}function bO(e,t,o,n){if(e.length===0)return{refused:"patched with no edits"};if(e.length>zr.edits)return{refused:`more than ${zr.edits} edits`};let s=new Map;for(let r of e){if(!o.has(r.path))return{refused:`${r.path} is not an article shown in full`};let i=s.get(r.path);if(!i){let c=t.readArticle(r.path);if(!c)return{refused:`${r.path} is not an existing article`};if(t.canWrite&&!t.canWrite(c.meta,n))return{refused:`no permission to write ${r.path}`};i={article:c,content:c.content,replaced:0},s.set(r.path,i)}if(!r.find.trim())return{refused:`an edit to ${r.path} quotes nothing`};if(r.find.length>zr.find||r.replace.length>zr.replace)return{refused:`an edit to ${r.path} is too long for a patch`};if(i.replaced+=r.find.length,i.replaced>i.article.content.length*zr.share)return{refused:`the edits replace most of ${r.path}; a note only patches`};let a=i.content.indexOf(r.find);if(a<0)return{refused:`the quoted passage is not in ${r.path}`};if(i.content.indexOf(r.find,a+1)>=0)return{refused:`the quoted passage appears more than once in ${r.path}`};i.content=i.content.slice(0,a)+r.replace+i.content.slice(a+r.find.length)}for(let[r,{article:i,content:a}]of s){let c=[...$O(i.content,a),...SO(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 $O(e,t){let o=yr(e,t),n=yr(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 kO=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,vO=/(?<![\w@.])@[A-Za-z0-9_]{3,}/g,xO=/^\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 SO(e,t){let o=t.toLowerCase(),n=[];for(let s of e.matchAll(kO))o.includes(s[0].toLowerCase())||n.push(`email ${s[0]}`);for(let s of e.matchAll(vO))o.includes(s[0].toLowerCase())||n.push(`handle ${s[0]}`);for(let s of e.matchAll(xO)){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 Ka(e){return e.length>_c.reason?`${e.slice(0,_c.reason-1)}\u2026`:e}import He from"chalk";import{resolve as AO}from"path";var EO=e=>e||AO(process.cwd(),".agentx/wiki");async function Xs(e){let{FactLedger:t}=await import("./ledger-P62U3FHT.js");return new t(EO(e))}function Vs(e){return async(...t)=>{try{await e(...t)}catch(o){o?.name!=="LedgerCorruptError"&&console.error(He.red(` ${o?.message??o}`)),process.exitCode=1}}}function ok(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(Vs(async n=>{let{isStaleFact:s}=await import("./ledger-P62U3FHT.js"),r=(await Xs(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(He.dim(" no facts recorded"));return}for(let i of r){let a=i.undated?He.yellow(" UNCHECKED"):s(i)?He.yellow(" STALE"):"";console.log(` ${He.cyan(i.id)} ${He.bold(i.subject)} \xB7 ${i.attribute}: ${i.value}${a}`),console.log(He.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(Vs(async(n,s)=>{let r=(await Xs(s.dir)).get(n);if(!r){console.error(He.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: ${Oc.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(Vs(async n=>{if(n.class&&!Ru(n.class)){console.error(He.red(` --class must be one of ${Oc.join(", ")}`)),process.exitCode=1;return}let r=(await Xs(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(He.yellow(` not replaced: the wiki says "${r.fact.value}" (checked ${r.fact.verifiedAt.slice(0,10)}), ${i}.`)),console.log(r.questionId?He.dim(` Queued question ${r.questionId}: agentx wiki questions \xB7 agentx wiki answer ${r.questionId} "<true value>"`):r.questionClosed?He.dim(` A person already ${r.questionClosed} this same claim, so it is not asked again.`):He.red(" No question could be queued: the questions file is unreadable. Repair .agentx/wiki/_questions.json.")),process.exitCode=2;return}console.log(He.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(Vs(async n=>{let{listFactProposals:s}=await import("./fact-proposals-X2O4W7VN.js"),r=s(await Xs(n.dir),n.all?void 0:"pending");if(n.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(He.dim(" no fact proposals waiting"));return}for(let i of r)console.log(` ${He.cyan(i.id)} ${i.status==="pending"?"":He.dim(`[${i.status}] `)}${i.claim}`),console.log(He.dim(` ${i.agentId} \xB7 ${i.origin} \xB7 ${i.source} \xB7 ${i.verifiedAt.slice(0,10)}`));console.log(He.dim(`
584
- 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(Vs(async(n,s)=>{let{approveFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),{write:i}=r(await Xs(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(He.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(Vs(async(n,s)=>{let{rejectFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),i=r(await Xs(s.dir),n,s.by,s.reason);console.log(He.dim(` rejected: ${i.claim}`))}))}import Ve from"chalk";import{existsSync as nk,readFileSync as sk}from"fs";import{resolve as sg}from"path";var ng=e=>e||sg(process.cwd(),".agentx/wiki");function RO(e){if(e)return e.replace(/\/+$/,"");if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL.replace(/\/+$/,"");try{let t=sg(process.cwd(),"agentx.json");if(nk(t)){let o=JSON.parse(sk(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 yo(e){console.error(Ve.red(` ${e}`)),process.exitCode=1}function Xa(e){return async(...t)=>{try{await e(...t)}catch(o){yo(o?.message??String(o))}}}function rk(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(Xa(async o=>{if(!o.from){yo("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){yo("--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){yo(l.error);return}s={ok:!0,...new a(ng(o.dir)).add(l.note)}}else{let a=RO(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){yo(`could not reach the daemon at ${a}: ${l?.message??l}`);return}if(s=await c.json().catch(()=>({})),!c.ok){yo(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?Ve.dim(` already in the inbox${i}: ${r?.id} (${r?.status})`):Ve.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(Xa(async o=>{let{NoteStore:n}=await import("./notes-WJJEJ4CJ.js"),s=["waiting","open","patched","rejected","deferred","expired","all"];if(!s.includes(o.status)){yo(`--status must be one of ${s.join(", ")}`);return}let r=new n(ng(o.dir)),i=r.load();if(i.unreadable){yo(`${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(Ve.dim(` no ${o.status==="all"?"":`${o.status} `}notes`));return}for(let c of a){let l=c.status==="open"?Ve.yellow("open"):c.status==="deferred"?Ve.yellow("deferred"):Ve.dim(c.status);console.log(` ${Ve.cyan(c.id)} ${l} \xB7 from ${c.from}${c.fromNode?` on ${c.fromNode}`:""} \xB7 ${c.date}`),console.log(` ${c.change}`),console.log(Ve.dim(` source: ${c.source}`)),c.listedIn?.length&&console.log(Ve.dim(` given to: ${c.listedIn.at(-1)}${c.listedIn.length>1?` (+${c.listedIn.length-1} earlier)`:""}`)),c.handled&&console.log(Ve.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(Ve.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(Xa(async(o,n)=>{let{NoteStore:s}=await import("./notes-WJJEJ4CJ.js"),r=new s(ng(n.dir)).handle(o,n.outcome,n.reason,n.by,n.run);console.log(Ve.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(Xa(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){yo("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-N6W52YXB.js"),{summary:l}=c(g=>n(g,r));console.log(Ve.green(` ${l}`))}let i=sg(process.cwd(),"agentx.json");if(!nk(i)){yo(`agentx.json not found at ${i}`);return}let a=s(JSON.parse(sk(i,"utf-8"))?.wikiNotes);if(o.json){console.log(JSON.stringify(a,null,2));return}console.log(` wiki notes: ${a.enabled?Ve.green("on"):Ve.dim("off")}`),console.log(` inbox agent: ${a.inbox||Ve.dim("not set")}`),console.log(` schedules that read it: ${a.crons.length?a.crons.join(", "):Ve.dim("none on this node")}`),console.log(` absorb that reads it: ${a.absorbAgent?`wiki absorb for ${a.absorbAgent}`:Ve.dim("none")}`),console.log(` most notes per run: ${a.maxNotesPerRun}`),console.log(` deferrals before a note expires: ${a.maxDeferrals}`)}))}import sn from"chalk";import{resolve as TO}from"path";var rg=e=>e||TO(process.cwd(),".agentx/wiki");function ik(e){let t=e.command("ontology").description("the wiki's pillars, types, typed relations and page lenses (show, init, check)");t.command("init").description("write the default ontology to ontology.yaml in the wiki, to edit").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{writeDefaultOntology:n}=await import("./load-Q3HCFXDT.js");try{let s=n(rg(o.dir));console.log(sn.green(` wrote ${s}`))}catch(s){console.error(sn.red(` ${s.message}`)),process.exitCode=1}}),t.command("check").description("report problems in ontology.yaml").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{loadOntology:n}=await import("./load-Q3HCFXDT.js"),{file:s,errors:r}=n(rg(o.dir));if(!s){console.log(sn.dim(" no ontology.yaml: the built-in defaults are in use"));return}if(r.length===0){console.log(sn.green(` ${s}: no problems`));return}console.log(sn.yellow(` ${s}: ${r.length} problem(s)`));for(let i of r)console.log(` - ${i}`);process.exitCode=1}),t.command("show").description("pages per pillar and type, as the wiki view groups them").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--json","print JSON").action(async o=>{let{loadOntology:n}=await import("./load-Q3HCFXDT.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{WikiHub:r}=await import("./hub-FVAPTKTF.js"),i=rg(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(sn.bold(` ${d.entities.size} entities`));for(let p of c.pillars){let u=c.types.filter(w=>w.pillar===p.id),h=u.reduce((w,b)=>w+(f.get(b.id)??0),0);console.log(` ${p.label.padEnd(26)} ${String(h).padStart(6)} ${sn.dim(u.map(w=>`${w.id} ${f.get(w.id)??0}`).join(" \xB7 "))}`)}l.length&&console.log(sn.yellow(` ontology.yaml has ${l.length} problem(s): agentx wiki ontology check`))})}import tt from"chalk";import{resolve as CO}from"path";var ig=e=>e||CO(process.cwd(),".agentx/wiki"),OO=()=>new Date().toISOString().slice(0,10);async function ag(e){let{WikiHub:t}=await import("./hub-FVAPTKTF.js"),{GraphCache:o}=await import("./graph-ZVKV3JBD.js"),{loadOntology:n}=await import("./load-Q3HCFXDT.js"),{loadRoster:s}=await import("./roster-BZGKG2ZA.js"),r=new t(e,()=>{}),{ontology:i}=n(e),a=new o().get(r,i,s(e,r.listAgents([]),i.agent_names));return{hub:r,g:a}}function ak(e,t){let o=Number(e);return Number.isInteger(o)&&o>=1?o:(console.error(tt.red(` ${t} must be a whole number, 1 or more`)),process.exitCode=1,null)}function ck(e){let t=e.command("events").description("give each event page an importance level (minor, normal, major) and the pages it is about").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--about <titles...>","only events linked to or naming these pages (a pilot)").option("--max <n>","most events per run","200").option("--batch <n>","events per model call","20").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","haiku").option("--rules-only","use only the importance rules in ontology.yaml; no model call").option("--force","redo events whose level this job set earlier").option("--dry-run","show what would be written, write nothing").option("--json","print the run as JSON").action(async o=>{let{runEvents:n,summariseAbout:s}=await import("./event-levels-PCFARGKL.js"),{claudeCall:r}=await import("./wiki-enrich-GTUSSLCD.js"),i=ak(o.max,"--max"),a=ak(o.batch,"--batch");if(i===null||a===null)return;let c=Number(o.maxCost);if(!Number.isFinite(c)||c<=0){console.error(tt.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let{hub:l,g}=await ag(ig(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(tt.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:OO()}),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"?tt.green("\u2713"):b.status==="dry-run"?tt.cyan("~"):tt.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} ${tt.dim(`${b.by??b.status}${b.about.length?` \xB7 about ${b.about.join(", ")}`:""}${b.why?` \xB7 ${b.why}`:""}`)}`);for(let S of b.dropped.slice(0,4))console.log(tt.dim(` dropped: ${S}`))}for(let b of h)console.log(tt.bold(` ${b.title}`)+tt.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 w=u.outcomes.filter(b=>b.importance).length;u.outcomes.length===0&&console.log(tt.dim(" nothing to do: every event in scope already has a level (--force redoes the ones this job set)")),console.log(tt.dim(` ${w} event${w===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-PCFARGKL.js"),{IMPORTANCE_LEVELS:a}=await import("./types-YZX46RES.js"),c=n.toLowerCase();if(!a.includes(c)){console.error(tt.red(` level must be one of ${a.join(", ")}`)),process.exitCode=1;return}let{hub:l,g}=await ag(ig(r.optsWithGlobals().dir)),d=i(l,g,o,c);d.ok?console.log(tt.green(` ${d.title} is now ${c}`)+tt.dim(` (${d.page})`)):(console.error(tt.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 ag(ig(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} ${tt.dim(`now ${a.importance}, proposed ${a.importanceProposed}`)}`);console.log(tt.dim(i.length?` ${i.length} waiting. Decide each with: agentx wiki events set "<title>" major (or normal)`:" none waiting"))})}import It from"chalk";import{resolve as IO}from"path";var NO=e=>e||IO(process.cwd(),".agentx/wiki");function lk(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-FVAPTKTF.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{loadOntology:r}=await import("./load-Q3HCFXDT.js"),{loadRoster:i}=await import("./roster-BZGKG2ZA.js"),{loadRulesState:a,ruleWordsPattern:c,runRules:l,saveRulesState:g}=await import("./rules-FBOLGE2S.js"),d=NO(o.dir),f=Number(o.max);if(!Number.isInteger(f)||f<1){console.error(It.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(It.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let u=o.words?.split(",").map(S=>S.trim()).filter(Boolean);if(o.words!==void 0&&!u?.length){console.error(It.red(" --words needs at least one word")),process.exitCode=1;return}let h=new n(d,()=>{}),{ontology:w}=r(d);if(!w.types.some(S=>S.id==="obligation")){console.error(It.red(" ontology.yaml has no `obligation` type; add it back to write rule pages")),process.exitCode=1;return}let b=new s().get(h,w,i(d,h.listAgents([]),w.agent_names)),$=a(d),v=await l(h,b,ih(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:S=>g(d,S)},$);if(o.json){console.log(JSON.stringify(v,null,2));return}for(let S of v.outcomes){let x=S.status==="written"?It.green("\u2713"):S.status==="dry-run"?It.cyan("~"):It.yellow("\xB7");console.log(` ${x} ${S.title} ${It.dim(`${S.status} \xB7 ${S.page??"no page"} \xB7 ${S.rules.length} rules \xB7 $${S.costUsd.toFixed(3)}`)}`);for(let k of S.rules){let A=[k.deadline?"":"no deadline",k.penalty?"":"no penalty"].filter(Boolean);console.log(` ${k.created?"new":"updated"}: ${k.title} ${It.dim(`\xB7 ${k.page}${A.length?` \xB7 ${A.join(", ")}`:""}${k.linked.length?` \xB7 linked from ${k.linked.join(", ")}`:""}`)}`),k.preview&&console.log(It.dim(k.preview.split(`
584
+ 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(Vs(async(n,s)=>{let{approveFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),{write:i}=r(await Xs(s.dir),n,s.by,{subject:s.subject,attribute:s.attribute,value:s.value,source:s.source});console.log(He.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(Vs(async(n,s)=>{let{rejectFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),i=r(await Xs(s.dir),n,s.by,s.reason);console.log(He.dim(` rejected: ${i.claim}`))}))}import Ve from"chalk";import{existsSync as nk,readFileSync as sk}from"fs";import{resolve as sg}from"path";var ng=e=>e||sg(process.cwd(),".agentx/wiki");function RO(e){if(e)return e.replace(/\/+$/,"");if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL.replace(/\/+$/,"");try{let t=sg(process.cwd(),"agentx.json");if(nk(t)){let o=JSON.parse(sk(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 yo(e){console.error(Ve.red(` ${e}`)),process.exitCode=1}function Xa(e){return async(...t)=>{try{await e(...t)}catch(o){yo(o?.message??String(o))}}}function rk(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(Xa(async o=>{if(!o.from){yo("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){yo("--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){yo(l.error);return}s={ok:!0,...new a(ng(o.dir)).add(l.note)}}else{let a=RO(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){yo(`could not reach the daemon at ${a}: ${l?.message??l}`);return}if(s=await c.json().catch(()=>({})),!c.ok){yo(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?Ve.dim(` already in the inbox${i}: ${r?.id} (${r?.status})`):Ve.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(Xa(async o=>{let{NoteStore:n}=await import("./notes-WJJEJ4CJ.js"),s=["waiting","open","patched","rejected","deferred","expired","all"];if(!s.includes(o.status)){yo(`--status must be one of ${s.join(", ")}`);return}let r=new n(ng(o.dir)),i=r.load();if(i.unreadable){yo(`${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(Ve.dim(` no ${o.status==="all"?"":`${o.status} `}notes`));return}for(let c of a){let l=c.status==="open"?Ve.yellow("open"):c.status==="deferred"?Ve.yellow("deferred"):Ve.dim(c.status);console.log(` ${Ve.cyan(c.id)} ${l} \xB7 from ${c.from}${c.fromNode?` on ${c.fromNode}`:""} \xB7 ${c.date}`),console.log(` ${c.change}`),console.log(Ve.dim(` source: ${c.source}`)),c.listedIn?.length&&console.log(Ve.dim(` given to: ${c.listedIn.at(-1)}${c.listedIn.length>1?` (+${c.listedIn.length-1} earlier)`:""}`)),c.handled&&console.log(Ve.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(Ve.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(Xa(async(o,n)=>{let{NoteStore:s}=await import("./notes-WJJEJ4CJ.js"),r=new s(ng(n.dir)).handle(o,n.outcome,n.reason,n.by,n.run);console.log(Ve.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(Xa(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){yo("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-HCYXR2WP.js"),{summary:l}=c(g=>n(g,r));console.log(Ve.green(` ${l}`))}let i=sg(process.cwd(),"agentx.json");if(!nk(i)){yo(`agentx.json not found at ${i}`);return}let a=s(JSON.parse(sk(i,"utf-8"))?.wikiNotes);if(o.json){console.log(JSON.stringify(a,null,2));return}console.log(` wiki notes: ${a.enabled?Ve.green("on"):Ve.dim("off")}`),console.log(` inbox agent: ${a.inbox||Ve.dim("not set")}`),console.log(` schedules that read it: ${a.crons.length?a.crons.join(", "):Ve.dim("none on this node")}`),console.log(` absorb that reads it: ${a.absorbAgent?`wiki absorb for ${a.absorbAgent}`:Ve.dim("none")}`),console.log(` most notes per run: ${a.maxNotesPerRun}`),console.log(` deferrals before a note expires: ${a.maxDeferrals}`)}))}import sn from"chalk";import{resolve as TO}from"path";var rg=e=>e||TO(process.cwd(),".agentx/wiki");function ik(e){let t=e.command("ontology").description("the wiki's pillars, types, typed relations and page lenses (show, init, check)");t.command("init").description("write the default ontology to ontology.yaml in the wiki, to edit").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{writeDefaultOntology:n}=await import("./load-Q3HCFXDT.js");try{let s=n(rg(o.dir));console.log(sn.green(` wrote ${s}`))}catch(s){console.error(sn.red(` ${s.message}`)),process.exitCode=1}}),t.command("check").description("report problems in ontology.yaml").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{loadOntology:n}=await import("./load-Q3HCFXDT.js"),{file:s,errors:r}=n(rg(o.dir));if(!s){console.log(sn.dim(" no ontology.yaml: the built-in defaults are in use"));return}if(r.length===0){console.log(sn.green(` ${s}: no problems`));return}console.log(sn.yellow(` ${s}: ${r.length} problem(s)`));for(let i of r)console.log(` - ${i}`);process.exitCode=1}),t.command("show").description("pages per pillar and type, as the wiki view groups them").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--json","print JSON").action(async o=>{let{loadOntology:n}=await import("./load-Q3HCFXDT.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{WikiHub:r}=await import("./hub-HXVIO4U5.js"),i=rg(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(sn.bold(` ${d.entities.size} entities`));for(let p of c.pillars){let u=c.types.filter(w=>w.pillar===p.id),h=u.reduce((w,b)=>w+(f.get(b.id)??0),0);console.log(` ${p.label.padEnd(26)} ${String(h).padStart(6)} ${sn.dim(u.map(w=>`${w.id} ${f.get(w.id)??0}`).join(" \xB7 "))}`)}l.length&&console.log(sn.yellow(` ontology.yaml has ${l.length} problem(s): agentx wiki ontology check`))})}import tt from"chalk";import{resolve as CO}from"path";var ig=e=>e||CO(process.cwd(),".agentx/wiki"),OO=()=>new Date().toISOString().slice(0,10);async function ag(e){let{WikiHub:t}=await import("./hub-HXVIO4U5.js"),{GraphCache:o}=await import("./graph-ZVKV3JBD.js"),{loadOntology:n}=await import("./load-Q3HCFXDT.js"),{loadRoster:s}=await import("./roster-BZGKG2ZA.js"),r=new t(e,()=>{}),{ontology:i}=n(e),a=new o().get(r,i,s(e,r.listAgents([]),i.agent_names));return{hub:r,g:a}}function ak(e,t){let o=Number(e);return Number.isInteger(o)&&o>=1?o:(console.error(tt.red(` ${t} must be a whole number, 1 or more`)),process.exitCode=1,null)}function ck(e){let t=e.command("events").description("give each event page an importance level (minor, normal, major) and the pages it is about").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--about <titles...>","only events linked to or naming these pages (a pilot)").option("--max <n>","most events per run","200").option("--batch <n>","events per model call","20").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","haiku").option("--rules-only","use only the importance rules in ontology.yaml; no model call").option("--force","redo events whose level this job set earlier").option("--dry-run","show what would be written, write nothing").option("--json","print the run as JSON").action(async o=>{let{runEvents:n,summariseAbout:s}=await import("./event-levels-PCFARGKL.js"),{claudeCall:r}=await import("./wiki-enrich-LDI67VQU.js"),i=ak(o.max,"--max"),a=ak(o.batch,"--batch");if(i===null||a===null)return;let c=Number(o.maxCost);if(!Number.isFinite(c)||c<=0){console.error(tt.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let{hub:l,g}=await ag(ig(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(tt.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:OO()}),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"?tt.green("\u2713"):b.status==="dry-run"?tt.cyan("~"):tt.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} ${tt.dim(`${b.by??b.status}${b.about.length?` \xB7 about ${b.about.join(", ")}`:""}${b.why?` \xB7 ${b.why}`:""}`)}`);for(let S of b.dropped.slice(0,4))console.log(tt.dim(` dropped: ${S}`))}for(let b of h)console.log(tt.bold(` ${b.title}`)+tt.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 w=u.outcomes.filter(b=>b.importance).length;u.outcomes.length===0&&console.log(tt.dim(" nothing to do: every event in scope already has a level (--force redoes the ones this job set)")),console.log(tt.dim(` ${w} event${w===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-PCFARGKL.js"),{IMPORTANCE_LEVELS:a}=await import("./types-YZX46RES.js"),c=n.toLowerCase();if(!a.includes(c)){console.error(tt.red(` level must be one of ${a.join(", ")}`)),process.exitCode=1;return}let{hub:l,g}=await ag(ig(r.optsWithGlobals().dir)),d=i(l,g,o,c);d.ok?console.log(tt.green(` ${d.title} is now ${c}`)+tt.dim(` (${d.page})`)):(console.error(tt.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 ag(ig(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} ${tt.dim(`now ${a.importance}, proposed ${a.importanceProposed}`)}`);console.log(tt.dim(i.length?` ${i.length} waiting. Decide each with: agentx wiki events set "<title>" major (or normal)`:" none waiting"))})}import It from"chalk";import{resolve as IO}from"path";var NO=e=>e||IO(process.cwd(),".agentx/wiki");function lk(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-HXVIO4U5.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{loadOntology:r}=await import("./load-Q3HCFXDT.js"),{loadRoster:i}=await import("./roster-BZGKG2ZA.js"),{loadRulesState:a,ruleWordsPattern:c,runRules:l,saveRulesState:g}=await import("./rules-FBOLGE2S.js"),d=NO(o.dir),f=Number(o.max);if(!Number.isInteger(f)||f<1){console.error(It.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(It.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let u=o.words?.split(",").map(S=>S.trim()).filter(Boolean);if(o.words!==void 0&&!u?.length){console.error(It.red(" --words needs at least one word")),process.exitCode=1;return}let h=new n(d,()=>{}),{ontology:w}=r(d);if(!w.types.some(S=>S.id==="obligation")){console.error(It.red(" ontology.yaml has no `obligation` type; add it back to write rule pages")),process.exitCode=1;return}let b=new s().get(h,w,i(d,h.listAgents([]),w.agent_names)),$=a(d),v=await l(h,b,ih(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:S=>g(d,S)},$);if(o.json){console.log(JSON.stringify(v,null,2));return}for(let S of v.outcomes){let x=S.status==="written"?It.green("\u2713"):S.status==="dry-run"?It.cyan("~"):It.yellow("\xB7");console.log(` ${x} ${S.title} ${It.dim(`${S.status} \xB7 ${S.page??"no page"} \xB7 ${S.rules.length} rules \xB7 $${S.costUsd.toFixed(3)}`)}`);for(let k of S.rules){let A=[k.deadline?"":"no deadline",k.penalty?"":"no penalty"].filter(Boolean);console.log(` ${k.created?"new":"updated"}: ${k.title} ${It.dim(`\xB7 ${k.page}${A.length?` \xB7 ${A.join(", ")}`:""}${k.linked.length?` \xB7 linked from ${k.linked.join(", ")}`:""}`)}`),k.preview&&console.log(It.dim(k.preview.split(`
585
585
  `).map(R=>` | ${R}`).join(`
586
- `)))}for(let k of S.dropped.slice(0,6))console.log(It.dim(` dropped: ${k}`))}v.outcomes.length===0&&console.log(It.dim(" nothing to do: no page that states rules changed since the last run (--force reads them again)")),console.log(It.dim(` spent $${v.costUsd.toFixed(3)} of $${p}${v.capped?" \xB7 stopped at the cap":""}`))})}import Va from"chalk";import{resolve as jO}from"path";var PO=e=>e||jO(process.cwd(),".agentx/wiki");function dk(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-H2CBE4SM.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-BMYFEAO5.js");r=g().wiki.summaries}catch{}let i=new o(PO(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 gk,dirname as uk}from"path";import{exec as DO,execSync as Xn}from"child_process";import{promisify as MO}from"util";import{appendFileSync as LO,statSync as qO,writeFileSync as Ft,mkdirSync as eo,readFileSync as Ut,readdirSync as FO,renameSync as Qa,rmSync as lg,existsSync as ot}from"fs";var yk=MO(DO);function ve(e,t){return new Cc(yt(e),void 0,t||"graph")}async function bk(e){let t=[];try{let{loadDaemonConfig:n}=await import("./config-BMYFEAO5.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 $k(){try{let{loadDaemonConfig:e}=await import("./config-BMYFEAO5.js"),t=Object.keys(e().agents||{});return t.length?new Set(t):null}catch{return null}}async function mk(){try{let{loadDaemonConfig:e}=await import("./config-BMYFEAO5.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 UO(){try{let{loadDaemonConfig:e}=await import("./config-BMYFEAO5.js");return Kf(e().agents||{})}catch{return new Set}}function Vn(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 pk(){let{sharedQueryEnabled:e}=await import("./query-W7OBMMVM.js");return e()}async function kk(e){let{loadQuerySettings:t}=await import("./query-settings-PTA2SA63.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 yt(e){return e||F(process.cwd(),".agentx/wiki")}function dg(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var z=new _O().name("wiki").description("wiki knowledge base management");ok(z);rk(z);ik(z);ah(z);ck(z);lk(z);dk(z);z.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=ve(e.dir,t),n=o.summary(),r=o.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${dg(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())});z.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=ve(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(yt(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()});z.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=tg(e.model)}catch(R){console.log(m.red(` ${R.message}`)),process.exitCode=1;return}let n=ve(e.dir,t),s=await $k(),{agents:r,skipped:i}=Xf(n.listAgents().filter(R=>!s||s.has(R)),{only:e.agent,off:await UO()}),a=i.length&&e.notes!==!1?(await mk())?.absorbAgent:void 0;for(let R of i)console.log(` ${m.cyan(R)}: ${m.dim(Vf(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 ot(R)?new Mo({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(_=>typeof _=="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 _ of R){let J=O.find(Ne=>Ne.id===_);if(!J)continue;let W=p(J);if(!W?.length)continue;let V=W.join("/"),Q=I.get(V);Q?Q.n++:I.set(V,{path:W,n:1})}if(I.size===0)return;let D;for(let _ of I.values())(!D||_.n>D.n)&&(D=_);return D?.path},h=0,w=0,b=0,$=F(n.getBaseDir(),"_absorb-runs.jsonl"),v=typeof e.runLabel=="string"&&e.runLabel.trim()?e.runLabel.trim():void 0,S=R=>{if(!e.dryRun)try{LO($,`${JSON.stringify(R)}
586
+ `)))}for(let k of S.dropped.slice(0,6))console.log(It.dim(` dropped: ${k}`))}v.outcomes.length===0&&console.log(It.dim(" nothing to do: no page that states rules changed since the last run (--force reads them again)")),console.log(It.dim(` spent $${v.costUsd.toFixed(3)} of $${p}${v.capped?" \xB7 stopped at the cap":""}`))})}import Va from"chalk";import{resolve as jO}from"path";var PO=e=>e||jO(process.cwd(),".agentx/wiki");function dk(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-RFDU6SVD.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-RHCIE7VE.js");r=g().wiki.summaries}catch{}let i=new o(PO(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 gk,dirname as uk}from"path";import{exec as DO,execSync as Xn}from"child_process";import{promisify as MO}from"util";import{appendFileSync as LO,statSync as qO,writeFileSync as Ft,mkdirSync as eo,readFileSync as Ut,readdirSync as FO,renameSync as Qa,rmSync as lg,existsSync as ot}from"fs";var yk=MO(DO);function ve(e,t){return new Cc(yt(e),void 0,t||"graph")}async function bk(e){let t=[];try{let{loadDaemonConfig:n}=await import("./config-RHCIE7VE.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 $k(){try{let{loadDaemonConfig:e}=await import("./config-RHCIE7VE.js"),t=Object.keys(e().agents||{});return t.length?new Set(t):null}catch{return null}}async function mk(){try{let{loadDaemonConfig:e}=await import("./config-RHCIE7VE.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 UO(){try{let{loadDaemonConfig:e}=await import("./config-RHCIE7VE.js");return Kf(e().agents||{})}catch{return new Set}}function Vn(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 pk(){let{sharedQueryEnabled:e}=await import("./query-J5NRZZUQ.js");return e()}async function kk(e){let{loadQuerySettings:t}=await import("./query-settings-NT6ACLQY.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 yt(e){return e||F(process.cwd(),".agentx/wiki")}function dg(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var z=new _O().name("wiki").description("wiki knowledge base management");ok(z);rk(z);ik(z);ah(z);ck(z);lk(z);dk(z);z.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=ve(e.dir,t),n=o.summary(),r=o.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${dg(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())});z.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=ve(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(yt(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()});z.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=tg(e.model)}catch(R){console.log(m.red(` ${R.message}`)),process.exitCode=1;return}let n=ve(e.dir,t),s=await $k(),{agents:r,skipped:i}=Xf(n.listAgents().filter(R=>!s||s.has(R)),{only:e.agent,off:await UO()}),a=i.length&&e.notes!==!1?(await mk())?.absorbAgent:void 0;for(let R of i)console.log(` ${m.cyan(R)}: ${m.dim(Vf(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 ot(R)?new Mo({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(_=>typeof _=="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 _ of R){let J=O.find(Ne=>Ne.id===_);if(!J)continue;let W=p(J);if(!W?.length)continue;let V=W.join("/"),Q=I.get(V);Q?Q.n++:I.set(V,{path:W,n:1})}if(I.size===0)return;let D;for(let _ of I.values())(!D||_.n>D.n)&&(D=_);return D?.path},h=0,w=0,b=0,$=F(n.getBaseDir(),"_absorb-runs.jsonl"),v=typeof e.runLabel=="string"&&e.runLabel.trim()?e.runLabel.trim():void 0,S=R=>{if(!e.dryRun)try{LO($,`${JSON.stringify(R)}
587
587
  `)}catch{}},x=new Date().toISOString(),k=e.notes===!1?null:await mk(),A=k?new Uu(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():"",_=n.getUnabsorbedEntries(R).filter(le=>!I||(le.date??"")>=I).filter(le=>!D||(le.date??"").slice(0,10)<=D).slice(0,l),J=!!(k&&A&&k.absorbAgent===R),W=`absorb/${R}/${x.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)),_.length===0&&V.length===0){console.log(` ${m.cyan(R)}: ${m.green("all absorbed")}`);continue}console.log(),console.log(m.bold(` ${m.cyan(R)}: ${_.length} entries to absorb`));for(let le of _.slice(0,3))console.log(m.dim(` [${le.date} via ${le.source}] ${le.content.slice(0,80)}...`));if(_.length>3&&console.log(m.dim(` ... and ${_.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 Q=n.getAgentWiki(R),Ne=Q.rebuildIndex(),Ye=Q.getWorldview()||n.getSharedStore().getWorldview()||"",M=_.map(le=>`--- ENTRY ${le.id} [${le.date} ${le.agentId} via ${le.source}] ---
588
588
  ${le.content}
589
589
  --- END ENTRY ---`).join(`
590
590
 
591
- `),ce="";if(e.facts!==!1){let{extractHints:le,resolveFacts:dn,mergeRecords:ns,renderFactsBlock:ss,installPrompts:ci,defaultSources:rs,recordsFromEntries:gn}=await import("./facts-ALJBF7IA.js");if(!f){let q=new Set;for(let Be of n.listAgents())for(let bt of n.getAgentWiki(Be).listArticles(Be))bt.meta.type==="person"&&q.add(bt.meta.title);f=[...q]}let un=le(_.map(q=>({context:q.sourceContext,content:q.content,sender:typeof q.meta?.sender=="string"?q.meta.sender:void 0})),{known:f}),is=gn(_);if(un.length>0||is.length>0){let q=rs(),{records:Be,results:bt}=un.length>0?await dn(un,{sources:q}):{records:[],results:[]},Se=ns([...is,...Be]);ce=ss(Se);let it=[...is.length>0?[`entries:${is.length}`]:[],...bt.filter(Le=>Le.records.length>0).map(Le=>`${Le.source}:${Le.records.length}`)];console.log(m.dim(` Facts: ${un.length} entities \u2192 ${Se.length} resolved${it.length?` (${it.join(" ")})`:""}`));for(let Le of ci(bt,q))console.log(m.yellow(` ! ${Le.source} ${Le.kind} \u2014 would supply ${Le.provides.join(", ")}`)),console.log(m.dim(` ${Le.hint}`))}}let _e=Ne.articles.filter(le=>le.path&&!le.path.includes("/_versions/")),ue=await oh([..._,...V.map(le=>({id:og(le.id),content:le.change}))],Q,R,_e);ue.length>0&&console.log(m.dim(` Existing: ${ue.map(le=>le.path).join(", ")}`));let N=nh(ue),$e=ek(V),rt=Hc(t,R,Ye,Ne.articles,M,_.length,ce,N,$e);console.log(m.dim(` Mode: ${dg(t)}`));let no=F(Q.baseDir,"_tmp");eo(no,{recursive:!0});let De=F(no,"absorb-prompt.txt");Ft(De,rt),console.log(m.dim(` Compiling with Claude (${o})...`));let Me={kind:"call",at:"",label:v,agent:R,model:o,entries:_.length,articles:0,refused:0,failed:!0,wallMs:0,promptChars:rt.length,promptParts:{entries:M.length,catalog:rt.length-Hc(t,R,Ye,[],M,_.length,ce,N,$e).length,catalogArticles:Ne.articles.length,covering:N.length,facts:ce.length,worldview:Ye.length,notes:$e.length},...V.length?{notes:V.length}:{}},ko=Date.now();Me.prepMs=ko-O;try{let le,dn=!1;try{le=Xn(`cat '${De}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Do(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(q){if(le=q.stdout||"",!le)throw q;dn=!0}let ns=le;try{let q=JSON.parse(le);Object.assign(Me,fl(q)),q.is_error===!0&&(dn=!0),ns=q.result||q.content||"",ns||(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 ss=Q$(ns);if("error"in ss){V.length>0&&console.log(m.yellow(` ${V.length} wiki note(s) stay waiting`)),console.log(m.red(` ${ss.error}`)),console.log(m.dim(` First 500 chars: ${ns.slice(0,500)}`));continue}let{articles:ci,gaps:rs}=ss,gn=new Set,un=new Set,is=new Set(_.map(q=>q.id));for(let q of ci){let Be=new Date().toISOString().slice(0,10),bt=Array.isArray(q.sources)?q.sources:[],Se=V.length>0?bt.filter(_o=>is.has(_o)):bt;if(V.length>0&&Se.length===0){console.log(m.yellow(` ! refused ${q.path}: cites no entry from this batch; a wiki note only patches`)),Me.refused++;continue}let it=sh(q,_e);it!==q.path&&(console.log(m.dim(` ~ ${q.path} \u2192 ${it} (an article with this title exists)`)),q.path=it);let Le=Q.readArticle(q.path);if(Le){let _o=yr(Le.content,String(q.content??""));if(_o.length>0){console.log(m.yellow(` ! refused ${q.path}: the rewrite drops ${_o.length} fact(s) the article has`)),console.log(m.dim(` ${_o.slice(0,8).join("; ")}${_o.length>8?"; \u2026":""}`));for(let gx of Se)gn.add(gx);Me.refused++;continue}}let vc=u(Se,_)??Le?.meta.graphPath;Q.writeArticle(q.path,{title:q.title,type:q.type,related:Array.isArray(q.related)?q.related:void 0,tags:q.tags||[],owner:R,access:Le?.meta.access??"public",sharedWith:Le?.meta.sharedWith?.length?Le.meta.sharedWith:void 0,created:Le?.meta.created||Be,lastUpdated:Be,sources:[...new Set([...Le?.meta.sources??[],...Se])],graphPath:vc},q.content,R);let lx=q.type?m.magenta(`[${q.type}]`)+" ":"",dx=Array.isArray(q.related)&&q.related.length?` \u2192 ${q.related.slice(0,3).join(", ")}${q.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(Le?"~":"+")} ${lx}${q.path}: ${q.title}${m.dim(dx)}`);let Gg=(q.tags||[]).slice(0,4).join(", ");Gg&&console.log(m.dim(` tags: ${Gg}`)),vc?.length&&(console.log(m.dim(` graphPath: ${vc.join(" \u203A ")}`)),w++),h++,Me.articles++;for(let _o of Se)un.add(_o)}if(V.length>0&&!dn){let q=V.filter(Se=>{let it=A.get(Se.id);return it&&it.status!=="open"&&it.status!=="deferred"?(console.log(m.dim(` note ${Se.id} already ${it.status} by ${it.handled?.by??"another run"}; left as it is`)),!1):it?.handled&&it.handled.at>x?(console.log(m.dim(` note ${Se.id} already deferred by ${it.handled.by} during this run; left as it is`)),!1):!0}),Be=tk(q,Z$(ss.notes),Q,{agentId:R,paths:new Set(ue.map(Se=>Se.path))}),bt=0;for(let Se of Be){try{A.handle(Se.id,Se.outcome,Se.reason,R,W),bt++}catch(Le){console.log(m.yellow(` ! note ${Se.id}: could not record ${Se.outcome}: ${Le?.message??Le}`))}let it=Se.outcome==="patched"?m.green("~"):Se.outcome==="rejected"?m.red("x"):m.yellow("\u2026");console.log(` ${it} note ${Se.id} ${Se.outcome}: ${m.dim(Se.reason.slice(0,160))}`)}Me.notesPatched=Be.filter(Se=>Se.outcome==="patched").length,Me.notesRecorded=bt}else V.length>0&&console.log(m.yellow(` ${V.length} wiki note(s) stay waiting`));if(Me.failed=dn,Me.heldCited=[...gn].filter(q=>un.has(q)).length,dn)console.log(m.yellow(` Run reported an error \u2014 ${_.length} entries stay queued`));else{let q=_.map(Be=>Be.id).filter(Be=>!gn.has(Be));gn.size>0&&console.log(m.yellow(` ${_.length-q.length} entries stay queued behind refused saves`)),n.markProcessed(R,q,ci.flatMap(Be=>Be.sources||[]).filter(Be=>!gn.has(Be)))}if(rs.length>0){console.log(),console.log(m.yellow(` Gaps detected (${rs.length} missing pieces):`));for(let q of rs)console.log(m.yellow(` ? ${q}`));try{let{QuestionStore:q}=await import("./questions-ZATLU5AW.js"),Be=new q(yt(e.dir)).add(rs.map(bt=>({kind:"article",agentId:R,path:"",subject:String(bt).slice(0,120),question:`No article yet for: ${String(bt).slice(0,160)}`})));Be.added>0&&console.log(m.dim(` queued ${Be.added} for follow-up (agentx wiki questions)`))}catch{}}Q.rebuildIndex()}catch(le){console.log(m.red(` Absorb failed: ${le.message?.slice(0,200)}`)),le.stderr&&console.log(m.dim(String(le.stderr).slice(0,300))),le.stdout&&console.log(m.dim("stdout: "+String(le.stdout).slice(0,300)))}finally{Me.at=new Date().toISOString(),Me.wallMs=Date.now()-ko,Me.failed&&b++,S(Me)}}if(S({kind:"run",label:v,startedAt:x,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(w/h*100):0;console.log(m.dim(` ${w}/${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()});z.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-HYGBAPXS.js"),{extractJson:l}=await import("./extract-json-7775Q7KO.js"),g=ve(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 w=[];for(let M of d)for(let ce of g.getAgentWiki(M).listArticles(M))w.push({key:`${M}/${ce.path}`,agent:M,article:ce});let b=new Map;for(let M of w)for(let ce of M.article.meta.sources??[]){let _e=b.get(ce);_e?_e.push(M.article.content):b.set(ce,[M.article.content])}let $=M=>{if(!p)return!0;try{return qO(F(g.getAgentWiki(M.agent).baseDir,M.article.path)).mtimeMs>p.getTime()}catch{return!1}},v=w.filter(M=>!f||(M.article.meta.lastUpdated??"")>=f.slice(0,10)).filter($),S=String(e.seed),x;if(e.sample&&ot(e.sample)){let M=JSON.parse(Ut(e.sample,"utf-8"));S=M.seed??S;let ce=new Map(w.map(ue=>[ue.key,ue]));x=M.keys.map(ue=>ce.get(ue)).filter(ue=>!!ue);let _e=M.keys.length-x.length;_e>0&&console.error(m.yellow(` ${_e} sampled article(s) no longer exist`))}else x=t(v.map(M=>({...M,path:M.key})),parseInt(e.n),S),e.sample&&(Ft(e.sample,`${JSON.stringify({seed:S,since:u||void 0,keys:x.map(M=>M.key)},null,2)}
591
+ `),ce="";if(e.facts!==!1){let{extractHints:le,resolveFacts:dn,mergeRecords:ns,renderFactsBlock:ss,installPrompts:ci,defaultSources:rs,recordsFromEntries:gn}=await import("./facts-ALJBF7IA.js");if(!f){let q=new Set;for(let Be of n.listAgents())for(let bt of n.getAgentWiki(Be).listArticles(Be))bt.meta.type==="person"&&q.add(bt.meta.title);f=[...q]}let un=le(_.map(q=>({context:q.sourceContext,content:q.content,sender:typeof q.meta?.sender=="string"?q.meta.sender:void 0})),{known:f}),is=gn(_);if(un.length>0||is.length>0){let q=rs(),{records:Be,results:bt}=un.length>0?await dn(un,{sources:q}):{records:[],results:[]},Se=ns([...is,...Be]);ce=ss(Se);let it=[...is.length>0?[`entries:${is.length}`]:[],...bt.filter(Le=>Le.records.length>0).map(Le=>`${Le.source}:${Le.records.length}`)];console.log(m.dim(` Facts: ${un.length} entities \u2192 ${Se.length} resolved${it.length?` (${it.join(" ")})`:""}`));for(let Le of ci(bt,q))console.log(m.yellow(` ! ${Le.source} ${Le.kind} \u2014 would supply ${Le.provides.join(", ")}`)),console.log(m.dim(` ${Le.hint}`))}}let _e=Ne.articles.filter(le=>le.path&&!le.path.includes("/_versions/")),ue=await oh([..._,...V.map(le=>({id:og(le.id),content:le.change}))],Q,R,_e);ue.length>0&&console.log(m.dim(` Existing: ${ue.map(le=>le.path).join(", ")}`));let N=nh(ue),$e=ek(V),rt=Hc(t,R,Ye,Ne.articles,M,_.length,ce,N,$e);console.log(m.dim(` Mode: ${dg(t)}`));let no=F(Q.baseDir,"_tmp");eo(no,{recursive:!0});let De=F(no,"absorb-prompt.txt");Ft(De,rt),console.log(m.dim(` Compiling with Claude (${o})...`));let Me={kind:"call",at:"",label:v,agent:R,model:o,entries:_.length,articles:0,refused:0,failed:!0,wallMs:0,promptChars:rt.length,promptParts:{entries:M.length,catalog:rt.length-Hc(t,R,Ye,[],M,_.length,ce,N,$e).length,catalogArticles:Ne.articles.length,covering:N.length,facts:ce.length,worldview:Ye.length,notes:$e.length},...V.length?{notes:V.length}:{}},ko=Date.now();Me.prepMs=ko-O;try{let le,dn=!1;try{le=Xn(`cat '${De}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Do(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(q){if(le=q.stdout||"",!le)throw q;dn=!0}let ns=le;try{let q=JSON.parse(le);Object.assign(Me,fl(q)),q.is_error===!0&&(dn=!0),ns=q.result||q.content||"",ns||(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 ss=Q$(ns);if("error"in ss){V.length>0&&console.log(m.yellow(` ${V.length} wiki note(s) stay waiting`)),console.log(m.red(` ${ss.error}`)),console.log(m.dim(` First 500 chars: ${ns.slice(0,500)}`));continue}let{articles:ci,gaps:rs}=ss,gn=new Set,un=new Set,is=new Set(_.map(q=>q.id));for(let q of ci){let Be=new Date().toISOString().slice(0,10),bt=Array.isArray(q.sources)?q.sources:[],Se=V.length>0?bt.filter(_o=>is.has(_o)):bt;if(V.length>0&&Se.length===0){console.log(m.yellow(` ! refused ${q.path}: cites no entry from this batch; a wiki note only patches`)),Me.refused++;continue}let it=sh(q,_e);it!==q.path&&(console.log(m.dim(` ~ ${q.path} \u2192 ${it} (an article with this title exists)`)),q.path=it);let Le=Q.readArticle(q.path);if(Le){let _o=yr(Le.content,String(q.content??""));if(_o.length>0){console.log(m.yellow(` ! refused ${q.path}: the rewrite drops ${_o.length} fact(s) the article has`)),console.log(m.dim(` ${_o.slice(0,8).join("; ")}${_o.length>8?"; \u2026":""}`));for(let gx of Se)gn.add(gx);Me.refused++;continue}}let vc=u(Se,_)??Le?.meta.graphPath;Q.writeArticle(q.path,{title:q.title,type:q.type,related:Array.isArray(q.related)?q.related:void 0,tags:q.tags||[],owner:R,access:Le?.meta.access??"public",sharedWith:Le?.meta.sharedWith?.length?Le.meta.sharedWith:void 0,created:Le?.meta.created||Be,lastUpdated:Be,sources:[...new Set([...Le?.meta.sources??[],...Se])],graphPath:vc},q.content,R);let lx=q.type?m.magenta(`[${q.type}]`)+" ":"",dx=Array.isArray(q.related)&&q.related.length?` \u2192 ${q.related.slice(0,3).join(", ")}${q.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(Le?"~":"+")} ${lx}${q.path}: ${q.title}${m.dim(dx)}`);let Gg=(q.tags||[]).slice(0,4).join(", ");Gg&&console.log(m.dim(` tags: ${Gg}`)),vc?.length&&(console.log(m.dim(` graphPath: ${vc.join(" \u203A ")}`)),w++),h++,Me.articles++;for(let _o of Se)un.add(_o)}if(V.length>0&&!dn){let q=V.filter(Se=>{let it=A.get(Se.id);return it&&it.status!=="open"&&it.status!=="deferred"?(console.log(m.dim(` note ${Se.id} already ${it.status} by ${it.handled?.by??"another run"}; left as it is`)),!1):it?.handled&&it.handled.at>x?(console.log(m.dim(` note ${Se.id} already deferred by ${it.handled.by} during this run; left as it is`)),!1):!0}),Be=tk(q,Z$(ss.notes),Q,{agentId:R,paths:new Set(ue.map(Se=>Se.path))}),bt=0;for(let Se of Be){try{A.handle(Se.id,Se.outcome,Se.reason,R,W),bt++}catch(Le){console.log(m.yellow(` ! note ${Se.id}: could not record ${Se.outcome}: ${Le?.message??Le}`))}let it=Se.outcome==="patched"?m.green("~"):Se.outcome==="rejected"?m.red("x"):m.yellow("\u2026");console.log(` ${it} note ${Se.id} ${Se.outcome}: ${m.dim(Se.reason.slice(0,160))}`)}Me.notesPatched=Be.filter(Se=>Se.outcome==="patched").length,Me.notesRecorded=bt}else V.length>0&&console.log(m.yellow(` ${V.length} wiki note(s) stay waiting`));if(Me.failed=dn,Me.heldCited=[...gn].filter(q=>un.has(q)).length,dn)console.log(m.yellow(` Run reported an error \u2014 ${_.length} entries stay queued`));else{let q=_.map(Be=>Be.id).filter(Be=>!gn.has(Be));gn.size>0&&console.log(m.yellow(` ${_.length-q.length} entries stay queued behind refused saves`)),n.markProcessed(R,q,ci.flatMap(Be=>Be.sources||[]).filter(Be=>!gn.has(Be)))}if(rs.length>0){console.log(),console.log(m.yellow(` Gaps detected (${rs.length} missing pieces):`));for(let q of rs)console.log(m.yellow(` ? ${q}`));try{let{QuestionStore:q}=await import("./questions-ZATLU5AW.js"),Be=new q(yt(e.dir)).add(rs.map(bt=>({kind:"article",agentId:R,path:"",subject:String(bt).slice(0,120),question:`No article yet for: ${String(bt).slice(0,160)}`})));Be.added>0&&console.log(m.dim(` queued ${Be.added} for follow-up (agentx wiki questions)`))}catch{}}Q.rebuildIndex()}catch(le){console.log(m.red(` Absorb failed: ${le.message?.slice(0,200)}`)),le.stderr&&console.log(m.dim(String(le.stderr).slice(0,300))),le.stdout&&console.log(m.dim("stdout: "+String(le.stdout).slice(0,300)))}finally{Me.at=new Date().toISOString(),Me.wallMs=Date.now()-ko,Me.failed&&b++,S(Me)}}if(S({kind:"run",label:v,startedAt:x,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(w/h*100):0;console.log(m.dim(` ${w}/${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()});z.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-EAGXITJH.js"),{extractJson:l}=await import("./extract-json-7775Q7KO.js"),g=ve(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 w=[];for(let M of d)for(let ce of g.getAgentWiki(M).listArticles(M))w.push({key:`${M}/${ce.path}`,agent:M,article:ce});let b=new Map;for(let M of w)for(let ce of M.article.meta.sources??[]){let _e=b.get(ce);_e?_e.push(M.article.content):b.set(ce,[M.article.content])}let $=M=>{if(!p)return!0;try{return qO(F(g.getAgentWiki(M.agent).baseDir,M.article.path)).mtimeMs>p.getTime()}catch{return!1}},v=w.filter(M=>!f||(M.article.meta.lastUpdated??"")>=f.slice(0,10)).filter($),S=String(e.seed),x;if(e.sample&&ot(e.sample)){let M=JSON.parse(Ut(e.sample,"utf-8"));S=M.seed??S;let ce=new Map(w.map(ue=>[ue.key,ue]));x=M.keys.map(ue=>ce.get(ue)).filter(ue=>!!ue);let _e=M.keys.length-x.length;_e>0&&console.error(m.yellow(` ${_e} sampled article(s) no longer exist`))}else x=t(v.map(M=>({...M,path:M.key})),parseInt(e.n),S),e.sample&&(Ft(e.sample,`${JSON.stringify({seed:S,since:u||void 0,keys:x.map(M=>M.key)},null,2)}
592
592
  `),console.error(m.dim(` sample saved to ${e.sample}`)));if(x.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 ce=g.getAgentWiki(M.agent).getVersions(M.article.path),_e=u?ce.filter(N=>N.timestamp>=u):ce.slice(0,1),ue=_e[_e.length-1];if(ue)try{return k(Ut(ue.path,"utf-8"))}catch{return}},R=x.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,ce=>b.get(ce)??[])),I=new Set(x.map(M=>M.key)),D=d.flatMap(M=>n(w.filter(ce=>ce.agent===M).map(ce=>({path:ce.key,title:ce.article.meta.title,type:ce.article.meta.type,sources:ce.article.meta.sources})),I)),_=[];if(e.judge){let M;try{M=tg(e.judgeModel)}catch(ue){console.log(m.red(` ${ue.message}`)),process.exitCode=1;return}let ce=F(g.getBaseDir(),"_tmp");eo(ce,{recursive:!0});let _e=R.map((ue,N)=>({a:ue,i:N}));await Promise.all(Array.from({length:Math.min(3,_e.length)},async()=>{for(let ue=_e.shift();ue;ue=_e.shift()){let{a:N,i:$e}=ue,rt=N.sources.map(De=>h.get(De)).filter(De=>!!De),no=F(ce,`absorb-eval-${process.pid}-${$e}.txt`);Ft(no,s(N,rt));try{let{stdout:De}=await yk(`cat '${no}' | claude -p - --output-format json --max-turns 1 --model '${M}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Do(),encoding:"utf-8",timeout:3e5,maxBuffer:4194304}),Me=De;try{Me=JSON.parse(De).result??De}catch{}let ko=r(l(Me));ko?_.push({path:N.path,verdict:ko}):console.error(m.yellow(` judge reply for ${N.path} was not usable`))}catch(De){console.error(m.yellow(` judge failed for ${N.path}: ${String(De?.message??De).slice(0,160)}`))}finally{lg(no,{force:!0})}}})),_.sort((ue,N)=>ue.path.localeCompare(N.path))}let J=new Set(w.flatMap(M=>M.article.meta.sources??[])),W=[];for(let M of d){let ce=F(g.getBaseDir(),"agents",M,"_absorbed.json");if(!ot(ce))continue;let _e={};try{_e=JSON.parse(Ut(ce,"utf-8")).entries??{}}catch{continue}for(let[ue,N]of Object.entries(_e)){if(J.has(ue)||u&&String(N.at??"")<u)continue;let $e=h.get(ue);$e&&W.push($e)}}let V=w.map(M=>M.article.content).join(`
593
- `),Q=c(W,V),Ne=i(O,D,{seed:S,since:u||void 0},_,5,{entries:W.length,lost:Q}),Ye=a(Ne);e.out&&Ft(e.out,Ye),e.json?console.log(JSON.stringify({card:Ne,checks:O},null,2)):e.out?console.log(m.green(` scorecard written to ${e.out}`)):console.log(Ye)});z.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(yt(e.dir),t);if(!ot(n)){console.log(m.yellow(` no queries recorded yet (${n})`));return}let s=o(Ut(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()});z.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-HYGBAPXS.js"),o=F(yt(e.dir),"_absorb-runs.jsonl");if(!ot(o)){console.log(m.yellow(` no absorb runs recorded yet (${o})`));return}let n=Ut(o,"utf-8").split(`
594
- `).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()});z.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=WO(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-LKFIKTY6.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!ot(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(!ot(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 Tm({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 Za=z.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function ec(e){return e?F(e):F(process.cwd(),".agentx","wiki")}Za.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(ec(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}`))}});Za.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(ec(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(`
593
+ `),Q=c(W,V),Ne=i(O,D,{seed:S,since:u||void 0},_,5,{entries:W.length,lost:Q}),Ye=a(Ne);e.out&&Ft(e.out,Ye),e.json?console.log(JSON.stringify({card:Ne,checks:O},null,2)):e.out?console.log(m.green(` scorecard written to ${e.out}`)):console.log(Ye)});z.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(yt(e.dir),t);if(!ot(n)){console.log(m.yellow(` no queries recorded yet (${n})`));return}let s=o(Ut(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()});z.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-EAGXITJH.js"),o=F(yt(e.dir),"_absorb-runs.jsonl");if(!ot(o)){console.log(m.yellow(` no absorb runs recorded yet (${o})`));return}let n=Ut(o,"utf-8").split(`
594
+ `).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()});z.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=WO(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-MMNDJOTD.js"),{default:c}=await import("better-sqlite3"),l=F(process.cwd(),".agentx/db.sqlite");if(!ot(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(!ot(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 Tm({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 Za=z.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function ec(e){return e?F(e):F(process.cwd(),".agentx","wiki")}Za.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(ec(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}`))}});Za.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(ec(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(`
595
595
  `).map(s=>` ${s}`).join(`
596
- `)),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>)`))}});Za.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-LXKF6A24.js"),n=o(ec(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`))});Za.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-LXKF6A24.js"),n=o(ec(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 WO(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)}z.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-W7OBMMVM.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:r,join:i}=await import("path"),a=ve(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 w of p){let b=i(d,w),$=[];try{$=o(b).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of $){if(f.length>=g)break;try{let S=JSON.parse(n(i(b,v),"utf-8")),x=S.message||S.task?.message;typeof x=="string"&&x.trim().length>10&&f.push({id:S.id||v.replace(".json",""),message:x.trim(),ts:S.at||S.timestamp||w})}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 w=0;w<f.length;w++){let b=f[w];process.stdout.write(m.dim(` [${w+1}/${f.length}] querying... `));let v=l.findRelevant(b.message,c,3).map(x=>`- **${x.meta.title}** [${x.meta.type||"?"}] (${x.path})`).join(`
596
+ `)),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>)`))}});Za.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-D24WO52J.js"),n=o(ec(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`))});Za.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-D24WO52J.js"),n=o(ec(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 WO(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)}z.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-J5NRZZUQ.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:r,join:i}=await import("path"),a=ve(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 w of p){let b=i(d,w),$=[];try{$=o(b).filter(v=>v.endsWith(".json")).sort().reverse()}catch{continue}for(let v of $){if(f.length>=g)break;try{let S=JSON.parse(n(i(b,v),"utf-8")),x=S.message||S.task?.message;typeof x=="string"&&x.trim().length>10&&f.push({id:S.id||v.replace(".json",""),message:x.trim(),ts:S.at||S.timestamp||w})}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 w=0;w<f.length;w++){let b=f[w];process.stdout.write(m.dim(` [${w+1}/${f.length}] querying... `));let v=l.findRelevant(b.message,c,3).map(x=>`- **${x.meta.title}** [${x.meta.type||"?"}] (${x.path})`).join(`
597
597
  `)||"_(none returned)_",S;try{let x=await t(b.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(x.status!=="ok")S=`_(status: ${x.status}${x.error?" \u2014 "+x.error:""})_`;else{let k=x.citations.map(A=>`\`${A.title}\` [${A.type||"?"}]`).join(", ");S=`**Answer:**
598
598
 
599
599
  ${x.answer}
@@ -610,14 +610,14 @@ Q: ${N.q}
610
610
  A: ${N.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(`
611
611
  `),S=F(a.baseDir,"_tmp");eo(S,{recursive:!0});let x=F(S,`interview-${o().slice(0,8)}.txt`);Ft(x,v),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let k="";try{let N=`cat '${x}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,$e=Xn(N,{env:Do(),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let rt=JSON.parse($e);k=String(rt.result||rt.content||"")}catch{k=$e}}catch(N){console.log(m.red(` synthesis failed: ${N.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 N of O[1].split(`
612
612
  `)){let $e=N.match(/^(\w+):\s*(.+)$/);$e&&(I[$e[1]]=$e[2].trim().replace(/^"(.*)"$/,"$1"))}let D=O[2],_=I.title||g,J=_.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 Q=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),Q==="scrap"||Q==="/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 ${x} (prompt only; no article file)`));return}let Ne=D,Ye={title:_,type:I.type||d,related:I.related?I.related.replace(/^\[|\]$/g,"").split(",").map(N=>N.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:I.tags?I.tags.replace(/^\[|\]$/g,"").split(",").map(N=>N.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(Q==="edit"){let N=process.env.EDITOR||"vi",$e=F(S,`draft-${o().slice(0,8)}.md`);Ft($e,k);try{Xn(`${N} '${$e}'`,{stdio:"inherit"});let no=Ut($e,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(no){let De={};for(let Me of no[1].split(`
613
- `)){let ko=Me.match(/^(\w+):\s*(.+)$/);ko&&(De[ko[1]]=ko[2].trim().replace(/^"(.*)"$/,"$1"))}Ne=no[2],Ye={...Ye,title:De.title||Ye.title,type:De.type||Ye.type,access:De.access||Ye.access,related:De.related?De.related.replace(/^\[|\]$/g,"").split(",").map(Me=>Me.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Ye.related,tags:De.tags?De.tags.replace(/^\[|\]$/g,"").split(",").map(Me=>Me.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Ye.tags}}}catch(rt){console.log(m.red(` editor failed: ${rt.message}`));return}}if(!a.writeArticle(V,Ye,Ne,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${V} saved.`));let ce=a.extractWikilinks(Ne),_e=new Map;for(let N of a.listArticles(e.agent))_e.set(N.meta.title.toLowerCase(),!0);let ue=ce.filter(N=>!_e.has(N.toLowerCase()));if(ue.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let N of ue.slice(0,8))console.log(m.dim(` - ${N}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});z.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-W7OBMMVM.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=ve(e.dir);if(e.commit!==!1&&Vn(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=Ut(e.script,"utf-8").split(/\n\s*\n/).map(h=>h.trim()).filter(Boolean);i=[];for(let h of u){let w=h.split(/\r?\n/).filter(v=>v.trim());if(w.length<2)continue;let b=w[0].replace(/^Q:\s*/i,"").trim(),$=w.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 w;try{w=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")),w.status!=="ok")console.log(m.yellow(` (status: ${w.status}${w.error?" \u2014 "+w.error:""})`));else{let W=w.citations.map(V=>`${V.title} [${V.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
613
+ `)){let ko=Me.match(/^(\w+):\s*(.+)$/);ko&&(De[ko[1]]=ko[2].trim().replace(/^"(.*)"$/,"$1"))}Ne=no[2],Ye={...Ye,title:De.title||Ye.title,type:De.type||Ye.type,access:De.access||Ye.access,related:De.related?De.related.replace(/^\[|\]$/g,"").split(",").map(Me=>Me.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Ye.related,tags:De.tags?De.tags.replace(/^\[|\]$/g,"").split(",").map(Me=>Me.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Ye.tags}}}catch(rt){console.log(m.red(` editor failed: ${rt.message}`));return}}if(!a.writeArticle(V,Ye,Ne,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${V} saved.`));let ce=a.extractWikilinks(Ne),_e=new Map;for(let N of a.listArticles(e.agent))_e.set(N.meta.title.toLowerCase(),!0);let ue=ce.filter(N=>!_e.has(N.toLowerCase()));if(ue.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let N of ue.slice(0,8))console.log(m.dim(` - ${N}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});z.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-J5NRZZUQ.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=ve(e.dir);if(e.commit!==!1&&Vn(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=Ut(e.script,"utf-8").split(/\n\s*\n/).map(h=>h.trim()).filter(Boolean);i=[];for(let h of u){let w=h.split(/\r?\n/).filter(v=>v.trim());if(w.length<2)continue;let b=w[0].replace(/^Q:\s*/i,"").trim(),$=w.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 w;try{w=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")),w.status!=="ok")console.log(m.yellow(` (status: ${w.status}${w.error?" \u2014 "+w.error:""})`));else{let W=w.citations.map(V=>`${V.title} [${V.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
614
614
  `)),console.log(m.dim(" citations: "+W))}i||(h=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+h);let b={q:u,answer:w.answer,citations:w.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(),S=($[2]||"").trim();if(d.push(b),v==="/ok"||v==="/skip")continue;if(!S){console.log(m.yellow(` ${v} without note \u2014 skipping.`));continue}let x=w.citations[0];if(!x){console.log(m.yellow(" no cited article to patch."));continue}let k=r.readArticle(x.path);if(!k){console.log(m.red(` can't read ${x.path} to patch.`));continue}console.log(m.dim(` patching ${x.title} (${x.path})...`));let A=GO(k.content,v,S,k.meta.title,k.meta.type),R=F(r.baseDir,"_tmp");eo(R,{recursive:!0});let O=F(R,`quiz-patch-${o().slice(0,8)}.txt`);Ft(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=Xn(W,{env:Do(),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ne=JSON.parse(V);I=String(Ne.result||Ne.content||"")}catch{I=V}let Q=I.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);Q&&(I=Q[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(`
615
615
  `).length,_=I.split(`
616
616
  `).length;if(console.log(m.dim(` diff: ${D} \u2192 ${_} lines (${_-D>=0?"+":""}${_-D})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),b.patched=x.path+" (dry)";continue}if(!r.writeArticle(x.path,{...k.meta,lastUpdated:new Date().toISOString().slice(0,10)},I,e.agent)){console.log(m.red(" write failed (permission?)"));continue}f++,b.patched=x.path,console.log(m.green(` \u2713 patched ${x.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(w=>`\`${w.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${h.verdict}\``+(h.patched?` \u2192 patched \`${h.patched}\``:""),"")}Ft(e.out,p.join(`
617
- `)),console.log(m.dim(` Transcript written to ${e.out}`))}});z.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=ve(o.dir);if(Vn(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=Kr(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{Xn(`${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 BO(){let{loadDaemonConfig:e}=await import("./config-BMYFEAO5.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 JO(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}`))}z.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=ve(n.dir);if(Vn(s,e))return;let r=Kr(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 BO(),c=async(f,p,u)=>{let h=await fetch(i+p,{method:f,headers:a,...u?{body:JSON.stringify(u)}:{}}),w=await h.json().catch(()=>({}));if(!h.ok)throw new Error(w.error||`HTTP ${h.status}`);return w},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)&&JO(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."))});z.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=ve(o.dir).getAgentWiki(e),s=Kr(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}`)});z.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=ve(n.dir);if(Vn(s,e))return;let r=s.getAgentWiki(e),i=Kr(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 Su))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}.`))});z.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-BMYFEAO5.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-N6W52YXB.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"}`)});z.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=ve(n.dir);if(Vn(i,e))return;let a;try{a=i.getAgentWiki(e)}catch(S){console.log(m.red(` can't open wiki for agent "${e}": ${S.message}`));return}let c=Kr(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=HO(l.content,l.meta.title,l.meta.type,o),d=F(a.baseDir,"_tmp");eo(d,{recursive:!0});let f=F(d,`patch-${r().slice(0,8)}.txt`);Ft(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 S=`cat '${f}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,x=Xn(S,{env:Do(),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let A=JSON.parse(x);p=String(A.result||A.content||"")}catch{p=x}let k=p.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(p=k[1].trim()),p=p.trim()}catch(S){console.log(m.red(` patch failed: ${S.message?.slice(0,150)}`));return}if(!p||p.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let u=l.content.split(`
617
+ `)),console.log(m.dim(` Transcript written to ${e.out}`))}});z.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=ve(o.dir);if(Vn(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=Kr(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{Xn(`${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 BO(){let{loadDaemonConfig:e}=await import("./config-RHCIE7VE.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 JO(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}`))}z.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=ve(n.dir);if(Vn(s,e))return;let r=Kr(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 BO(),c=async(f,p,u)=>{let h=await fetch(i+p,{method:f,headers:a,...u?{body:JSON.stringify(u)}:{}}),w=await h.json().catch(()=>({}));if(!h.ok)throw new Error(w.error||`HTTP ${h.status}`);return w},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)&&JO(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."))});z.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=ve(o.dir).getAgentWiki(e),s=Kr(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}`)});z.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=ve(n.dir);if(Vn(s,e))return;let r=s.getAgentWiki(e),i=Kr(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 Su))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}.`))});z.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-RHCIE7VE.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-HCYXR2WP.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"}`)});z.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=ve(n.dir);if(Vn(i,e))return;let a;try{a=i.getAgentWiki(e)}catch(S){console.log(m.red(` can't open wiki for agent "${e}": ${S.message}`));return}let c=Kr(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=HO(l.content,l.meta.title,l.meta.type,o),d=F(a.baseDir,"_tmp");eo(d,{recursive:!0});let f=F(d,`patch-${r().slice(0,8)}.txt`);Ft(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 S=`cat '${f}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,x=Xn(S,{env:Do(),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let A=JSON.parse(x);p=String(A.result||A.content||"")}catch{p=x}let k=p.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);k&&(p=k[1].trim()),p=p.trim()}catch(S){console.log(m.red(` patch failed: ${S.message?.slice(0,150)}`));return}if(!p||p.length<20){console.log(m.yellow(" patch returned nothing usable."));return}let u=l.content.split(`
618
618
  `).length,h=p.split(`
619
- `).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 w=rh(l.content,p);if(w.length){for(let S of w)console.log(m.yellow(` ! ${S}`));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 S=s.createInterface({input:process.stdin,output:process.stdout}),x=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),b=x==="y"||x==="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 fk=z.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-KRES5F2V.js"),o=ve(e.dir),n=yt(e.dir),s={},r={};try{let{loadDaemonConfig:d}=await import("./config-BMYFEAO5.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(ot(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");eo(u,{recursive:!0});let h=F(u,`contribute-${process.pid}-${Date.now()}.txt`);Ft(h,f);try{let{stdout:w}=await yk(`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:Do(),timeout:18e4,maxBuffer:4194304});try{let b=JSON.parse(w);return{text:String(b.result||b.content||""),costUsd:fl(b).costUsd}}catch{return{text:w}}}finally{lg(h,{force:!0})}},g=[];try{for(let d of i){if(Vn(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 w of u.patches){let b=w.attribute?`${w.attribute}: ${w.previous?`${w.previous} \u2192 `:""}${w.value??""}`:w.summary??"";console.log(m.dim(` ${w.kind.padEnd(8)} ${w.page} \xB7 ${b} (${w.source}, ${w.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]])fk.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-S5SGBNOG.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={...fk.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 Yr=z.command("contributions").description("the daily merge of agents' wiki patches (list, merge, held, approve, reject)");Yr.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-KRES5F2V.js"),s=yt(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()});Yr.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-KRES5F2V.js"),o=t(ve(e.dir),yt(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()});Yr.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-KRES5F2V.js"),o=t(yt(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(`
620
- agentx wiki contributions approve <id> \xB7 agentx wiki contributions reject <id>`)),console.log()});Yr.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-KRES5F2V.js"),n=o(ve(t.dir),yt(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.`))});Yr.command("reject <id>").description("drop a held patch").option("--dir <path>","wiki directory").action(async(e,t)=>{let{rejectHeld:o}=await import("./contributions-KRES5F2V.js"),n=o(yt(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 Kr(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 HO(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(`
619
+ `).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 w=rh(l.content,p);if(w.length){for(let S of w)console.log(m.yellow(` ! ${S}`));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 S=s.createInterface({input:process.stdin,output:process.stdout}),x=(await S.question(m.cyan(" apply? [y/N] "))).trim().toLowerCase();S.close(),b=x==="y"||x==="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 fk=z.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-R4HXLJXU.js"),o=ve(e.dir),n=yt(e.dir),s={},r={};try{let{loadDaemonConfig:d}=await import("./config-RHCIE7VE.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(ot(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");eo(u,{recursive:!0});let h=F(u,`contribute-${process.pid}-${Date.now()}.txt`);Ft(h,f);try{let{stdout:w}=await yk(`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:Do(),timeout:18e4,maxBuffer:4194304});try{let b=JSON.parse(w);return{text:String(b.result||b.content||""),costUsd:fl(b).costUsd}}catch{return{text:w}}}finally{lg(h,{force:!0})}},g=[];try{for(let d of i){if(Vn(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 w of u.patches){let b=w.attribute?`${w.attribute}: ${w.previous?`${w.previous} \u2192 `:""}${w.value??""}`:w.summary??"";console.log(m.dim(` ${w.kind.padEnd(8)} ${w.page} \xB7 ${b} (${w.source}, ${w.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]])fk.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-JQ2R4J5Z.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={...fk.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 Yr=z.command("contributions").description("the daily merge of agents' wiki patches (list, merge, held, approve, reject)");Yr.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-R4HXLJXU.js"),s=yt(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()});Yr.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-R4HXLJXU.js"),o=t(ve(e.dir),yt(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()});Yr.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-R4HXLJXU.js"),o=t(yt(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(`
620
+ agentx wiki contributions approve <id> \xB7 agentx wiki contributions reject <id>`)),console.log()});Yr.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-R4HXLJXU.js"),n=o(ve(t.dir),yt(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.`))});Yr.command("reject <id>").description("drop a held patch").option("--dir <path>","wiki directory").action(async(e,t)=>{let{rejectHeld:o}=await import("./contributions-R4HXLJXU.js"),n=o(yt(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 Kr(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 HO(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(`
621
621
  `)}function GO(e,t,o,n,s){let r={"/correct":`The operator says the article contains an error:
622
622
 
623
623
  ${o}
@@ -672,17 +672,17 @@ Output (JSON array, one entry per input article, same order):
672
672
  [
673
673
  {"path": "path/to/article.md", "type": "project"},
674
674
  ...
675
- ]`}z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ve(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()});z.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 bk(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(),Zf(t,o,e.agent,n,e.mode)});z.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-DAMUB3CU.js"),c=ve(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),f=[];e:for(let w of l){let b=c.getAgentWiki(w);for(let $ of b.listArticles(w)){if(f.length>=g)break e;let v=b.readArticle($.path);if(!v||e.type&&v.meta.type!==e.type)continue;let S={...t(v.meta.type),...e.fields?r(v.meta.type):{}},x=await a(s,o({path:$.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),S,{links:[{kind:"article",id:$.path}],features:{agent:w,type:v.meta.type??"?"}});if(!x){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let k=n(x.answers),A=e.fields?i(v.meta.type,x.answers):null;k.completeness>=d&&!(A&&!A.fit)||f.push({agent:w,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((w,b)=>parseFloat(w.score)-parseFloat(b.score));let p=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],u=p.map(w=>Math.max(w.length,...f.map(b=>String(b[w]).length))),h=w=>w.map((b,$)=>String(b).padEnd(u[$])).join(" ");console.log(),console.log(m.bold(h(p)));for(let w of f)console.log(h(p.map(b=>w[b])));if(e.fields){let w=f.filter(b=>b.missing!=="-").length;console.log(m.dim(`
675
+ ]`}z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ve(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()});z.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 bk(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(),Zf(t,o,e.agent,n,e.mode)});z.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-E6F56TUM.js"),c=ve(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),f=[];e:for(let w of l){let b=c.getAgentWiki(w);for(let $ of b.listArticles(w)){if(f.length>=g)break e;let v=b.readArticle($.path);if(!v||e.type&&v.meta.type!==e.type)continue;let S={...t(v.meta.type),...e.fields?r(v.meta.type):{}},x=await a(s,o({path:$.path,title:v.meta.title,type:v.meta.type,tags:v.meta.tags,body:v.content}),S,{links:[{kind:"article",id:$.path}],features:{agent:w,type:v.meta.type??"?"}});if(!x){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let k=n(x.answers),A=e.fields?i(v.meta.type,x.answers):null;k.completeness>=d&&!(A&&!A.fit)||f.push({agent:w,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((w,b)=>parseFloat(w.score)-parseFloat(b.score));let p=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],u=p.map(w=>Math.max(w.length,...f.map(b=>String(b[w]).length))),h=w=>w.map((b,$)=>String(b).padEnd(u[$])).join(" ");console.log(),console.log(m.bold(h(p)));for(let w of f)console.log(h(p.map(b=>w[b])));if(e.fields){let w=f.filter(b=>b.missing!=="-").length;console.log(m.dim(`
676
676
  ${f.length} article(s) flagged; ${w} 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(`
677
- ${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."))});z.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-W7OBMMVM.js"),{noteSourceFor:n}=await import("./query-settings-PTA2SA63.js"),{QUERY_RUNS_FILE:s,queryFailed:r,recordQueryRun:i,timedQuery:a}=await import("./query-runs-VXS572PQ.js"),c=await kk(t);if(!c)return;let l=ve(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 pk()?p:null;for(let v of u?[]:g){let S=l.getAgentWiki(v),x=F(S.baseDir,"_index.md");try{if((await import("fs")).existsSync(x)){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,w=l.getAgentWiki(h),b=t.ownOnly||!await pk()?void 0:l.sharedScope(h),$=await a(d,h,"cli",()=>o(e,w,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 S=v.type?m.magenta(` [${v.type}]`):"";console.log(m.dim(` - ${v.title}${S} (${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(S=>!$.candidates.some(x=>x.path===S.path));console.log(m.dim(` followed: ${v.map(S=>`${S.title}@h${S.hop}`).join(" | ")}`))}console.log()}});z.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=x=>`${Math.round(x*100)}%`,i=x=>x===void 0?"?":`${(x/1e3).toFixed(1)}s`,a=x=>x===void 0?"?":`$${x.toFixed(3)}`,c=x=>`${i(x.meanMs)} and ${a(x.meanCostUsd)} per question${x.unpriced?` (${x.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[x,k]=e.compare.map(R=>JSON.parse(Ut(F(R),"utf-8"))),A=n(x,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(Ut(F(e.questions),"utf-8")),{agenticQuery:d,CATALOG_SELECTOR_MODEL:f,CATALOG_SYNTH_MODEL:p}=await import("./query-W7OBMMVM.js"),{noteSourceFor:u}=await import("./query-settings-PTA2SA63.js"),{meteredModelCall:h}=await import("./model-call-HMVMUAXS.js"),w=await kk(e);if(!w)return;let b=ve(e.dir),$=!e.ownOnly,v=[];for(let x of g){let k={calls:0,usd:0,unpriced:0},A=Date.now(),R=await d(x.question,b.getAgentWiki(l),l,{selectorModel:e.selectorModel,synthModel:e.synthModel,shared:$?b.sharedScope(l):void 0,method:w.method,summaries:w.summaries,notes:u(w,l),call:h(k)}),O=Date.now()-A,I=R.method==="summaries"&&k.unpriced===0?k.usd:void 0;v.push({q:x,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(` ${x.id} ${R.status} ${i(O)} ${a(I)}
677
+ ${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."))});z.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-J5NRZZUQ.js"),{noteSourceFor:n}=await import("./query-settings-NT6ACLQY.js"),{QUERY_RUNS_FILE:s,queryFailed:r,recordQueryRun:i,timedQuery:a}=await import("./query-runs-VXS572PQ.js"),c=await kk(t);if(!c)return;let l=ve(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 pk()?p:null;for(let v of u?[]:g){let S=l.getAgentWiki(v),x=F(S.baseDir,"_index.md");try{if((await import("fs")).existsSync(x)){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,w=l.getAgentWiki(h),b=t.ownOnly||!await pk()?void 0:l.sharedScope(h),$=await a(d,h,"cli",()=>o(e,w,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 S=v.type?m.magenta(` [${v.type}]`):"";console.log(m.dim(` - ${v.title}${S} (${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(S=>!$.candidates.some(x=>x.path===S.path));console.log(m.dim(` followed: ${v.map(S=>`${S.title}@h${S.hop}`).join(" | ")}`))}console.log()}});z.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=x=>`${Math.round(x*100)}%`,i=x=>x===void 0?"?":`${(x/1e3).toFixed(1)}s`,a=x=>x===void 0?"?":`$${x.toFixed(3)}`,c=x=>`${i(x.meanMs)} and ${a(x.meanCostUsd)} per question${x.unpriced?` (${x.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[x,k]=e.compare.map(R=>JSON.parse(Ut(F(R),"utf-8"))),A=n(x,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(Ut(F(e.questions),"utf-8")),{agenticQuery:d,CATALOG_SELECTOR_MODEL:f,CATALOG_SYNTH_MODEL:p}=await import("./query-J5NRZZUQ.js"),{noteSourceFor:u}=await import("./query-settings-NT6ACLQY.js"),{meteredModelCall:h}=await import("./model-call-HMVMUAXS.js"),w=await kk(e);if(!w)return;let b=ve(e.dir),$=!e.ownOnly,v=[];for(let x of g){let k={calls:0,usd:0,unpriced:0},A=Date.now(),R=await d(x.question,b.getAgentWiki(l),l,{selectorModel:e.selectorModel,synthModel:e.synthModel,shared:$?b.sharedScope(l):void 0,method:w.method,summaries:w.summaries,notes:u(w,l),call:h(k)}),O=Date.now()-A,I=R.method==="summaries"&&k.unpriced===0?k.usd:void 0;v.push({q:x,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(` ${x.id} ${R.status} ${i(O)} ${a(I)}
678
678
  `))}let S=o({questions:e.questions,agent:l,shared:$,settings:{method:w.method,linkedPages:w.summaries.linkedPages,linkedChars:w.summaries.linkedChars,live:w.summaries.live.enabled,notes:w.notes.enabled,navigatorModel:e.selectorModel??w.summaries.navigatorModel,answerModel:e.synthModel??w.summaries.answerModel,catalogSelectorModel:e.selectorModel??f,catalogSynthModel:e.synthModel??p}},v);if(e.out&&Ft(F(e.out),`${JSON.stringify(S,null,2)}
679
679
  `),e.json){console.log(JSON.stringify(S,null,2));return}console.log(),console.log(m.bold(` ${l}: ${r(S.score)} \xB7 ${S.full}/${S.results.length} questions fully answered${$?"":" (own articles only)"}`)),console.log(m.dim(` ${c(s(S))}`));for(let x of S.results){let k=x.missing.length===0?m.green("\u2713"):x.found.length?m.yellow("~"):m.red("\u2717");console.log(` ${k} ${x.id} ${r(x.score)} ${m.dim(x.question.slice(0,80))}`),x.missing.length&&console.log(m.dim(` missing: ${x.missing.join(", ")}`))}e.out&&console.log(m.dim(`
680
- report saved to ${e.out}`)),console.log()});z.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=ve(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()});z.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=ve(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=F(process.cwd(),".agentx/graph");if(!ot(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Mo({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])),w=0,b=0,$=0;for(let v of p){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;w++,c++;let S=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("/"),_=S.get(D);_?_.n++:S.set(D,{path:I,n:1})}if(S.size===0)continue;b++,l++;let x;for(let k of S.values())(!x||k.n>x.n)&&(x=k);x&&(e.dryRun||(f.writeArticle(v.path,{...v.meta,graphPath:x.path},v.content,d),$++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(p.length)} articles \xB7 ${w} 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()});z.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=ve(e.dir),o=t.getSharedStore(),n=await bk(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 $k();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 w of h.agents||[])w.totalEntries>0&&console.log(m.dim(` ${w.agentId}: ${w.totalEntries} entries, ${w.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()});z.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 Cc(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),f=l.getAgentEntries(o),p=l.getUnabsorbedEntries(o),u=new Set,h=0,w=new Set;for(let $ of d.articles){for(let v of $.tags||[])u.add(v);h+=$.tags?.length||0;for(let v of $.sources||[])w.add(v)}let b=new Set(d.articles.map($=>$.path.includes("/")?$.path.split("/")[0]:"/"));return{mode:c,label:dg(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:w.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()});z.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");ot(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=ot(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${KO(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});z.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-DAMUB3CU.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=ve(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 _ of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&_.needsHuman||(e.ask&&_.needsHuman&&g.push({kind:"field",agentId:k,path:R.path,subject:O.meta.title,field:_.field,tier:_.tier,question:`${O.meta.title} (${O.meta.type??"?"}) \u2014 ${_.label}?`}),u.push({tier:_.tier,need:_.field,how:_.needsHuman?m.yellow("ask"):_.sources.join("/"),uncertain:_.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(yt(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 w=["tier","need","how","uncertain","agent","article"],b=k=>String(k).replace(/\u001b\[[0-9;]*m/g,""),$=w.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(w.map((k,A)=>v(k,A)).join(" ")));for(let k of u)console.log(w.map((A,R)=>v(k[A],R)).join(" "));let S=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(` ${S} can be closed by a lookup; ${u.length-S} need a person.`));let x=u[0]?.tier;if(x&&console.log(m.dim(` Start at ${x} \u2014 ${r[x]}.`)),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-BMYFEAO5.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 _=R.slice(0,10).map(Q=>`\u2022 ${Q.question}`).join(`
680
+ report saved to ${e.out}`)),console.log()});z.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=ve(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()});z.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=ve(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=F(process.cwd(),".agentx/graph");if(!ot(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Mo({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])),w=0,b=0,$=0;for(let v of p){if(a++,v.meta.graphPath?.length||!v.meta.sources?.length)continue;w++,c++;let S=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("/"),_=S.get(D);_?_.n++:S.set(D,{path:I,n:1})}if(S.size===0)continue;b++,l++;let x;for(let k of S.values())(!x||k.n>x.n)&&(x=k);x&&(e.dryRun||(f.writeArticle(v.path,{...v.meta,graphPath:x.path},v.content,d),$++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(p.length)} articles \xB7 ${w} 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()});z.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=ve(e.dir),o=t.getSharedStore(),n=await bk(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 $k();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 w of h.agents||[])w.totalEntries>0&&console.log(m.dim(` ${w.agentId}: ${w.totalEntries} entries, ${w.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()});z.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 Cc(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),f=l.getAgentEntries(o),p=l.getUnabsorbedEntries(o),u=new Set,h=0,w=new Set;for(let $ of d.articles){for(let v of $.tags||[])u.add(v);h+=$.tags?.length||0;for(let v of $.sources||[])w.add(v)}let b=new Set(d.articles.map($=>$.path.includes("/")?$.path.split("/")[0]:"/"));return{mode:c,label:dg(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:w.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()});z.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");ot(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=ot(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${KO(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});z.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-E6F56TUM.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=ve(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 _ of s(D,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&_.needsHuman||(e.ask&&_.needsHuman&&g.push({kind:"field",agentId:k,path:R.path,subject:O.meta.title,field:_.field,tier:_.tier,question:`${O.meta.title} (${O.meta.type??"?"}) \u2014 ${_.label}?`}),u.push({tier:_.tier,need:_.field,how:_.needsHuman?m.yellow("ask"):_.sources.join("/"),uncertain:_.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(yt(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 w=["tier","need","how","uncertain","agent","article"],b=k=>String(k).replace(/\u001b\[[0-9;]*m/g,""),$=w.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(w.map((k,A)=>v(k,A)).join(" ")));for(let k of u)console.log(w.map((A,R)=>v(k[A],R)).join(" "));let S=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(` ${S} can be closed by a lookup; ${u.length-S} need a person.`));let x=u[0]?.tier;if(x&&console.log(m.dim(` Start at ${x} \u2014 ${r[x]}.`)),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-RHCIE7VE.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 _=R.slice(0,10).map(Q=>`\u2022 ${Q.question}`).join(`
681
681
  `),J=R.length>10?`
682
682
  \u2026and ${R.length-10} more`:"",W=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
683
683
  ${_}${J}
684
684
 
685
- agentx wiki questions`,V=I?.daemon?.port??I?.port??18800;try{let Q=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(Q.ok?m.cyan(` Pushed ${R.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${Q.status}) \u2014 questions are still queued.`))}catch(Q){console.log(m.yellow(` Push failed (${String(Q?.message??Q).slice(0,80)}) \u2014 questions are still queued.`))}}}}});z.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-DAMUB3CU.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ALJBF7IA.js"),{backfillArticle:f}=await import("./backfill-7TCF4SHG.js"),p=ve(e.dir,e.mode),u=e.agent?[e.agent]:p.listAgents(),h=parseInt(e.limit),w=g(),b=c(d(p.getSharedStore().listEntries())),$=new Map(b.map(I=>[I.name.toLowerCase().trim(),I])),v=0,S=0,x=[],k=!1;e:for(let I of u){let D=p.getAgentWiki(I);for(let _ of D.listArticles(I)){if(v>=h)break e;if(_.meta.type!=="person")continue;let J=D.readArticle(_.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:_.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 Q=o(J.meta.type,W.answers).missing.filter(N=>r.includes(N));if(Q.length===0)continue;let{records:Ne,results:Ye}=await a([{name:J.meta.title,type:"person"}],{sources:w}),M=$.get(J.meta.title.toLowerCase().trim());if(!k){for(let N of l(Ye,w))console.log(m.yellow(` ! ${N.source} ${N.kind} \u2014 would supply ${N.provides.join(", ")}`)),console.log(m.dim(` ${N.hint}`));k=!0}let ce=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([N,$e])=>[N,$e.value]))}]:[],...Ne]);if(ce.length===0)continue;let{content:_e,edits:ue}=f(J.content,ce[0],Q);if(ue.length!==0){for(let N of ue)x.push({agent:I,article:J.meta.title.slice(0,32),field:N.field,action:N.replaced?"replace":"add",got:`${N.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(_.path,J.meta,_e,I)?S++:console.log(m.red(` could not write ${_.path}`)))}}}if(e.json){console.log(JSON.stringify(x,null,2));return}if(x.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,...x.map(D=>String(D[I]).length))),O=I=>I.map((D,_)=>String(D).padEnd(R[_])).join(" ");console.log(),console.log(m.bold(O(A)));for(let I of x)console.log(O(A.map(D=>I[D])));console.log(),e.apply?(console.log(m.green(` ${x.length} field(s) written across ${S} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${x.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});z.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(yt(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`))});z.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(yt(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"),w=new h(yt(o.dir));try{let b=w.get(c.factId);if(b){let $=w.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=ve(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}`))});z.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-DAMUB3CU.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=ve(e.dir,"graph").getSharedStore(),u=p.listEntries(),h=new Set(p.getUnabsorbedEntries().map(J=>J.id)),{labeled:w,backlog:b}=i(u,h),$=a(w,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},S=[],x=0,k=Date.now();if(e.load){let{readFileSync:J}=await import("fs");S.push(...JSON.parse(J(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${S.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.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){x++;continue}let V=W.answers;S.push({entry:J,verdict:s(W.answers,v),citeWorthy:V.citeWorthy?.noul})}if(S.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(S)),console.log(m.dim(` saved ${S.length} outcome(s) to ${e.save}`))}let A=c(S,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(S,"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:x,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 _=A.positiveMeans;if(console.log(m.dim(` positives avg: worth ${_.worth.toFixed(2)} \xB7 durability ${_.durability.toFixed(2)} \xB7 typeConf ${_.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${I}s, ${x} 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(S,{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 Q=V.slice().sort((Ne,Ye)=>Ye.recall-Ne.recall)[0];Q&&console.log(m.dim(` Best recall available: ${D(Q.recall)} at ${Q.requireTyped?`type>=${Q.minType}`:"type gate OFF"} worth>=${Q.minWorth} dur>=${Q.minDurability}, filtering ${D(Q.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});z.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);ot(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");ot(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 KO(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"}hu();import{Command as XO}from"commander";import U from"chalk";import{resolve as tc}from"path";import{existsSync as VO}from"fs";oe();var Qs=new XO().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Qs.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=T();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 Mo({baseDir:tc(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],w=yi(h.path,c)||h.path.join(" \u203A ");process.stdout.write(` [${u+1}/${i.length}] ${U.cyan(h.msgHash.slice(0,8))} ${U.dim(w)} ... `);let b=QO(h,a,c),$=null;try{$=await ZO(n,o,b,t.dashboard?.token)}catch(x){f++,console.log(U.red(`ERR ${x.message?.slice(0,80)}`));continue}if(!$||!$.decision){f++,console.log(U.red("ERR no decision"));continue}let v=String($.decision).toLowerCase().trim(),S=($.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(U.green("APPROVE")+" "+U.dim(S)),e.dryRun)l++;else try{e1(r,h,a,c,o),r.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:o,reviewReason:S}),l++}catch(x){console.log(U.yellow(` (commit failed, staying pending: ${x.message?.slice(0,100)})`)),f++}else v==="reject"?(console.log(U.red("REJECT")+" "+U.dim(S)),e.dryRun||r.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:o,reviewReason:S}),g++):(console.log(U.yellow("SKIP")+" "+U.dim(S||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()});Qs.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=T();if(!t.graph){console.log(U.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=tc(process.cwd(),t.graph.baseDir);if(!VO(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 Mo({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()});Qs.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=T();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 Mo({baseDir:tc(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,w=new Map;h.levels.forEach((A,R)=>w.set(A.id,R));let b=[...g].sort((A,R)=>(w.get(A.level)??99)-(w.get(R.level)??99)),$=0,v=0,S=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){S++,console.log(U.yellow(` skip node ${A.id}: ${R.message?.slice(0,100)}`))}}console.log(U.dim(` nodes: +${$} added \xB7 ${v} already-present \xB7 ${S} failed`));let x=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){x++;continue}r.setFingerprint(A.msgHash,{path:A.path,leaf:A.leaf||{}}),x++}console.log(U.dim(` fingerprints: +${x} 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 QO(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(`
685
+ agentx wiki questions`,V=I?.daemon?.port??I?.port??18800;try{let Q=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(Q.ok?m.cyan(` Pushed ${R.length} question(s) to ${D.channel}.`):m.yellow(` Push failed (${Q.status}) \u2014 questions are still queued.`))}catch(Q){console.log(m.yellow(` Push failed (${String(Q?.message??Q).slice(0,80)}) \u2014 questions are still queued.`))}}}}});z.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-E6F56TUM.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ALJBF7IA.js"),{backfillArticle:f}=await import("./backfill-7TCF4SHG.js"),p=ve(e.dir,e.mode),u=e.agent?[e.agent]:p.listAgents(),h=parseInt(e.limit),w=g(),b=c(d(p.getSharedStore().listEntries())),$=new Map(b.map(I=>[I.name.toLowerCase().trim(),I])),v=0,S=0,x=[],k=!1;e:for(let I of u){let D=p.getAgentWiki(I);for(let _ of D.listArticles(I)){if(v>=h)break e;if(_.meta.type!=="person")continue;let J=D.readArticle(_.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:_.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 Q=o(J.meta.type,W.answers).missing.filter(N=>r.includes(N));if(Q.length===0)continue;let{records:Ne,results:Ye}=await a([{name:J.meta.title,type:"person"}],{sources:w}),M=$.get(J.meta.title.toLowerCase().trim());if(!k){for(let N of l(Ye,w))console.log(m.yellow(` ! ${N.source} ${N.kind} \u2014 would supply ${N.provides.join(", ")}`)),console.log(m.dim(` ${N.hint}`));k=!0}let ce=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([N,$e])=>[N,$e.value]))}]:[],...Ne]);if(ce.length===0)continue;let{content:_e,edits:ue}=f(J.content,ce[0],Q);if(ue.length!==0){for(let N of ue)x.push({agent:I,article:J.meta.title.slice(0,32),field:N.field,action:N.replaced?"replace":"add",got:`${N.value.split(";").length} value(s)`});e.apply&&(D.writeArticle(_.path,J.meta,_e,I)?S++:console.log(m.red(` could not write ${_.path}`)))}}}if(e.json){console.log(JSON.stringify(x,null,2));return}if(x.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,...x.map(D=>String(D[I]).length))),O=I=>I.map((D,_)=>String(D).padEnd(R[_])).join(" ");console.log(),console.log(m.bold(O(A)));for(let I of x)console.log(O(A.map(D=>I[D])));console.log(),e.apply?(console.log(m.green(` ${x.length} field(s) written across ${S} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${x.length} field(s) would be written across ${v} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});z.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(yt(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`))});z.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(yt(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"),w=new h(yt(o.dir));try{let b=w.get(c.factId);if(b){let $=w.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=ve(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}`))});z.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-E6F56TUM.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=ve(e.dir,"graph").getSharedStore(),u=p.listEntries(),h=new Set(p.getUnabsorbedEntries().map(J=>J.id)),{labeled:w,backlog:b}=i(u,h),$=a(w,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},S=[],x=0,k=Date.now();if(e.load){let{readFileSync:J}=await import("fs");S.push(...JSON.parse(J(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${S.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.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){x++;continue}let V=W.answers;S.push({entry:J,verdict:s(W.answers,v),citeWorthy:V.citeWorthy?.noul})}if(S.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(S)),console.log(m.dim(` saved ${S.length} outcome(s) to ${e.save}`))}let A=c(S,{minType:v.minTypeConfidence,minWorth:v.minWorth,minDurability:v.minDurability}),R=l(S,"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:x,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 _=A.positiveMeans;if(console.log(m.dim(` positives avg: worth ${_.worth.toFixed(2)} \xB7 durability ${_.durability.toFixed(2)} \xB7 typeConf ${_.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${I}s, ${x} 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(S,{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 Q=V.slice().sort((Ne,Ye)=>Ye.recall-Ne.recall)[0];Q&&console.log(m.dim(` Best recall available: ${D(Q.recall)} at ${Q.requireTyped?`type>=${Q.minType}`:"type gate OFF"} worth>=${Q.minWorth} dur>=${Q.minDurability}, filtering ${D(Q.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});z.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);ot(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");ot(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 KO(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"}hu();import{Command as XO}from"commander";import U from"chalk";import{resolve as tc}from"path";import{existsSync as VO}from"fs";oe();var Qs=new XO().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Qs.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=T();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 Mo({baseDir:tc(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],w=yi(h.path,c)||h.path.join(" \u203A ");process.stdout.write(` [${u+1}/${i.length}] ${U.cyan(h.msgHash.slice(0,8))} ${U.dim(w)} ... `);let b=QO(h,a,c),$=null;try{$=await ZO(n,o,b,t.dashboard?.token)}catch(x){f++,console.log(U.red(`ERR ${x.message?.slice(0,80)}`));continue}if(!$||!$.decision){f++,console.log(U.red("ERR no decision"));continue}let v=String($.decision).toLowerCase().trim(),S=($.reason||"").toString().slice(0,180);if(v==="approve")if(console.log(U.green("APPROVE")+" "+U.dim(S)),e.dryRun)l++;else try{e1(r,h,a,c,o),r.updateClassificationStatus(h.msgHash,{status:"approved",reviewer:o,reviewReason:S}),l++}catch(x){console.log(U.yellow(` (commit failed, staying pending: ${x.message?.slice(0,100)})`)),f++}else v==="reject"?(console.log(U.red("REJECT")+" "+U.dim(S)),e.dryRun||r.updateClassificationStatus(h.msgHash,{status:"rejected",reviewer:o,reviewReason:S}),g++):(console.log(U.yellow("SKIP")+" "+U.dim(S||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()});Qs.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=T();if(!t.graph){console.log(U.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=tc(process.cwd(),t.graph.baseDir);if(!VO(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 Mo({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()});Qs.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=T();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 Mo({baseDir:tc(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,w=new Map;h.levels.forEach((A,R)=>w.set(A.id,R));let b=[...g].sort((A,R)=>(w.get(A.level)??99)-(w.get(R.level)??99)),$=0,v=0,S=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){S++,console.log(U.yellow(` skip node ${A.id}: ${R.message?.slice(0,100)}`))}}console.log(U.dim(` nodes: +${$} added \xB7 ${v} already-present \xB7 ${S} failed`));let x=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){x++;continue}r.setFingerprint(A.msgHash,{path:A.path,leaf:A.leaf||{}}),x++}console.log(U.dim(` fingerprints: +${x} 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 QO(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(`
686
686
  `),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(`
687
687
  `)}async function ZO(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 wi((c?.content||"").toString())}finally{clearTimeout(i)}}function e1(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function gg(){let e=T();if(!e.graph?.baseDir)return console.log(U.red(" graph.baseDir is not configured")),null;let t=tc(process.cwd(),e.graph.baseDir);return{store:new Mo({baseDir:t}),baseDir:t}}var ug=Qs.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");ug.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=gg();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(yi(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]"))});ug.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=gg();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}: ${yi(i[0].path,c)||i[0].path.join(" \u203A ")}`)),o.path&&console.log(U.dim(` should have been: ${o.path}`))});ug.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let t=gg();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 i1}from"commander";import ae from"chalk";import{Command as xk}from"commander";import Ce from"chalk";import{existsSync as t1}from"fs";import{resolve as o1}from"path";import n1 from"better-sqlite3";function s1(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(Ce.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function r1(e){let t=o1(process.cwd(),e);return t1(t)||(console.log(Ce.red(` No db at ${t}`)),process.exit(1)),new n1(t,{readonly:!0})}var Sk=new xk().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(mr)).option("--max <n>","max clusters distilled per run",String(Si)).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(Ce.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let t=r1(e.path),o=await Cm(t,{since:s1(e.since),agentId:e.agent,sessions:new xu(process.cwd()),minOccurrences:Number(e.minOccurrences)||mr,max:Number(e.max)||Si,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(Ce.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(` ${Ce.cyan(n.key)} ${Ce.bold(`\xD7${n.count}`)} ${Ce.dim(n.status)}`),n.sampleMessage&&console.log(Ce.dim(` "${n.sampleMessage.slice(0,100)}"`));if(o.nearMisses.length){console.log(Ce.dim(`
688
688
  near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of o.nearMisses.slice(0,5))console.log(Ce.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of o.drafted)console.log(Ce.green(` \u2713 draft written: ${n.id}`)+Ce.dim(` (${n.count} occurrences)`));for(let n of o.skipped)console.log(Ce.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of o.warnings)console.log(Ce.yellow(` \u26A0 ${n}`));o.dryRun?console.log(Ce.dim(`
@@ -753,7 +753,7 @@ ${e.body||""}`)}function U1(e){return e.startsWith("test/")||/\.test\.[cm]?[jt]s
753
753
 
754
754
  `))>=0;){let p=l.slice(0,f);l=l.slice(f+2),tI(p)}}}catch(i){console.error(be.red(` disconnected: ${i.message||i}`)),process.exit(1)}});function tI(e){let t="message",o="";for(let r of e.split(`
755
755
  `))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?be.dim(new Date(n.at).toLocaleTimeString()):"";switch(t){case"run":{let r=be.cyan(n.phase?.padEnd(9)??"run"),i=be.bold(n.workflowId??""),a=be.dim((n.runId??"").slice(0,8)),c=n.nodeId?be.yellow(n.nodeId):"",l=n.note?be.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${r} ${i} ${a} ${c} ${l}`);break}case"task":{let r=be.magenta(`task.${n.phase}`.padEnd(14)),i=be.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?be.dim(`"${n.title}"`):"";console.log(`${s} ${r} ${i} ${be.cyan(a)} ${c}`);break}case"signal":{let r=be.green("signal".padEnd(9)),i=be.bold(n.name),a=be.dim(`(${n.scope})`),c=n.workflowId?be.dim(n.workflowId):"";console.log(`${s} ${r} ${i} ${a} ${c}`);break}case"mesh":{let r=be.blue("mesh".padEnd(9)),i=be.bold(n.peer),a=n.healthy?be.green("\u2713 healthy"):be.red("\u2717 lost");console.log(`${s} ${r} ${i} ${a} ${be.dim(n.delta??"")}`);break}case"channel":{let r=be.yellow("channel".padEnd(9)),i=n.direction==="in"?be.cyan("\u2190"):be.magenta("\u2192"),a=be.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?be.dim(n.textPreview):"";console.log(`${s} ${r} ${i} ${a} ${c}`);break}case"status":{console.log(be.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 Tv}from"commander";import $o from"chalk";function oI(e,t){let o=e.replace(/\/+$/,""),n=new URLSearchParams;if(t.since&&n.set("since",t.since),t.limit&&n.set("limit",t.limit),t.agent){let s=n.toString();return`${o}/agents/${encodeURIComponent(t.agent)}/events${s?`?${s}`:""}`}return t.kind&&n.set("kind",t.kind),t.limit||n.set("limit","50"),`${o}/events/recent?${n}`}function nI(e,t,o=process.env){let n={name:e};t.summary&&(n.summary=t.summary),t.ref&&(n.ref=t.ref);let s=t.by||o.AGENTX_AGENT_ID;return s&&(n.by=s),o.AGENTX_AGENT_ID&&(n.senderAgentId=o.AGENTX_AGENT_ID),o.AGENTX_TASK_ID&&(n.callerTaskId=o.AGENTX_TASK_ID),o.AGENTX_CHANNEL&&(n.callerChannel=o.AGENTX_CHANNEL),o.AGENTX_CHAT_ID&&(n.callerChatId=o.AGENTX_CHAT_ID),n}function Cv(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=T(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return{baseUrl:(t||"http://localhost:18800").replace(/\/+$/,""),token:o}}var sI=new Tv().name("emit").description("publish a named event (for example render:ready) that wakes the agents subscribed to it").argument("<name>","event name: letters, digits and : . _ -").option("--summary <text>","one short line on what happened").option("--ref <ref>","pointer to the details: an issue, a path, a run id").option("--by <name>","who emitted it (an agent id or a person's name; default: the running agent)").action(async(e,t,o)=>{let n=o.optsWithGlobals(),{baseUrl:s,token:r}=Cv(n),i={"Content-Type":"application/json"};r&&(i.Authorization=`Bearer ${r}`);try{let a=await fetch(`${s}/events`,{method:"POST",headers:i,body:JSON.stringify(nI(e,n)),signal:AbortSignal.timeout(1e4)}),c=await a.json().catch(()=>({}));if(!a.ok){console.error($o.red(` Event refused (${a.status}): ${c.error||"unknown error"}`)),process.exitCode=1;return}if(n.json){console.log(JSON.stringify(c,null,2));return}console.log($o.green(` \u2713 Emitted ${c.event?.type??e} on ${c.event?.node??"this machine"}`)+$o.dim(` (event ${c.event?.id??"?"})`))}catch(a){console.error($o.red(` daemon unreachable at ${s}: ${a?.message||a}`)),process.exitCode=1}}),Ov=new Tv().name("events").description("recent events on this node, or those matching one agent's subscriptions").option("-c, --config <path>","daemon config file").option("-a, --agent <id>","only events matching this agent's subscriptions").option("-s, --since <id|iso>","only events after this event id or ISO time").option("-k, --kind <kind>","only this event kind (without --agent)").option("-n, --limit <n>","most events to show (with --agent: default 20, max 50)").option("--json","machine-readable output").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").addCommand(sI).action(async e=>{let{baseUrl:t,token:o}=Cv(e),n={};o&&(n.Authorization=`Bearer ${o}`);let s;try{let a=await fetch(oI(t,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error($o.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error($o.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($o.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(r.length===0){console.log($o.dim(" no events"));return}for(let a of r)console.log(` ${Cu(a)} ${$o.dim(a.id)}`);let i=s.next??r[r.length-1].id;console.log($o.dim(`
756
- ${r.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${i}`))});import{Command as iI}from"commander";import ei from"chalk";import{spawn as aI}from"node:child_process";import{execFileSync as rI}from"node:child_process";function Iv(e=()=>rI("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 Nv=new iI().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(ei.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-CMQZO22V.js"),o=t({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Iv();if(n?.ok){let{fetchAgents:l}=await import("./client-CMQZO22V.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(ei.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:h}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:w}=await import("./opencode-launch-ECMEY2QZ.js");await w({agentId:d,env:u,cwd:process.cwd(),pool:h,spawnImpl:aI,log:b=>console.error(ei.dim(b))});return}n&&!n.ok&&(console.error(ei.yellow(n.reason)),console.error(ei.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-777XBP22.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 cI}from"commander";import ge from"chalk";import{randomUUID as _v}from"crypto";import{createInterface as lI}from"node:readline/promises";import dI from"ora";import mc from"chalk";function jv(e){console.error(),console.error(mc.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(mc.dim(` ${e.why}`)),console.error(),console.error(` Use ${mc.cyan(e.instead)} instead.`),e.note&&console.error(mc.dim(` ${e.note}`)),console.error()}var Pv={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 Dv=new cI().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)=>{jv({what:"agentx chat",...Pv});let o=ch({node:t.node,token:t.token,config:t.config}),n=(e??"").replace(/^@/,"").trim(),s=t.channel,r=t.chatId||`chat-cli:${_v().slice(0,12)}`,i=[];try{i=await zi(o)}catch(g){console.error(ge.red(` cannot reach daemon at ${o.baseUrl}: ${g?.message||g}`)),console.error(ge.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(i.length===0&&(console.error(ge.red(" no agents registered with the daemon")),process.exit(1)),n?i.find(g=>g.id===n)||(console.error(ge.red(` unknown agent: @${n}`)),console.error(ge.dim(` registered: ${i.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=i[0].id,console.log(ge.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-ZYMF5HSR.js"),f=(await import("react")).default;await g(f.createElement(d,{conn:o,agentId:n,channel:s,chatId:r,agents:i})).waitUntilExit();return}uI(o.baseUrl,n,r,s);let a=lI({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(ge.dim(`
756
+ ${r.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${i}`))});import{Command as iI}from"commander";import ei from"chalk";import{spawn as aI}from"node:child_process";import{execFileSync as rI}from"node:child_process";function Iv(e=()=>rI("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 Nv=new iI().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(ei.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-57TCFIV5.js"),o=t({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Iv();if(n?.ok){let{fetchAgents:l}=await import("./client-57TCFIV5.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(ei.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:h}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:w}=await import("./opencode-launch-ECMEY2QZ.js");await w({agentId:d,env:u,cwd:process.cwd(),pool:h,spawnImpl:aI,log:b=>console.error(ei.dim(b))});return}n&&!n.ok&&(console.error(ei.yellow(n.reason)),console.error(ei.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-WIHCYMHM.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 cI}from"commander";import ge from"chalk";import{randomUUID as _v}from"crypto";import{createInterface as lI}from"node:readline/promises";import dI from"ora";import mc from"chalk";function jv(e){console.error(),console.error(mc.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(mc.dim(` ${e.why}`)),console.error(),console.error(` Use ${mc.cyan(e.instead)} instead.`),e.note&&console.error(mc.dim(` ${e.note}`)),console.error()}var Pv={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 Dv=new cI().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)=>{jv({what:"agentx chat",...Pv});let o=ch({node:t.node,token:t.token,config:t.config}),n=(e??"").replace(/^@/,"").trim(),s=t.channel,r=t.chatId||`chat-cli:${_v().slice(0,12)}`,i=[];try{i=await zi(o)}catch(g){console.error(ge.red(` cannot reach daemon at ${o.baseUrl}: ${g?.message||g}`)),console.error(ge.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(i.length===0&&(console.error(ge.red(" no agents registered with the daemon")),process.exit(1)),n?i.find(g=>g.id===n)||(console.error(ge.red(` unknown agent: @${n}`)),console.error(ge.dim(` registered: ${i.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=i[0].id,console.log(ge.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-V3UASKNG.js"),f=(await import("react")).default;await g(f.createElement(d,{conn:o,agentId:n,channel:s,chatId:r,agents:i})).waitUntilExit();return}uI(o.baseUrl,n,r,s);let a=lI({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(ge.dim(`
757
757
  bye`)),process.exit(0)});;){let g;try{g=(await a.question(ge.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(ge.dim(` @${n} chatId=${r} channel=${s}`));continue}if(g==="/clear"){r=`chat-cli:${_v().slice(0,12)}`,console.log(ge.dim(` fresh chatId=${r} (warm process dropped)`));continue}if(g==="/agents"){try{let u=await zi(o);for(let h of u){let w=h.id===n?ge.green("\u25CF"):ge.dim("\u25CB");console.log(` ${w} @${h.id} ${ge.dim(h.tier)} ${h.model??""}`)}}catch(u){console.error(ge.red(` failed to list agents: ${u?.message||u}`))}continue}if(g.startsWith("/agent ")){let u=g.slice(7).replace(/^@/,"").trim();if(!u){console.log(ge.red(" usage: /agent <id>"));continue}try{if(!(await zi(o)).find(w=>w.id===u)){console.log(ge.red(` unknown agent: @${u}`));continue}n=u,console.log(ge.dim(` now talking to @${n}`))}catch(h){console.error(ge.red(` failed to switch agent: ${h?.message||h}`))}continue}if(g.startsWith("/")){console.log(ge.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(ge.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=dI({text:`@${n}\u2026`,color:"cyan"}).start(),f=Date.now(),p=gI(n);try{let u=await lh(o,n,g,{channel:s,chatId:r,onText:w=>{d.stop(),p.text(w)},onThinking:()=>{},onTool:w=>{d.stop(),p.tool(w)}});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(ge.dim(" bye"));return}}});function gI(e){let t=!1,o=!0,n=!1,s=new Set,r=()=>{t||(process.stdout.write(`${ge.green(`@${e}`)}
758
758
  `),t=!0)};return{text(i){if(i){r(),n=!0;for(let a of i)o&&a!==`
759
759
  `&&(process.stdout.write(" "),o=!1),process.stdout.write(a),a===`
@@ -853,7 +853,7 @@ Restart the daemon to activate.
853
853
  dist/
854
854
  *.log
855
855
  .env
856
- `}import{Command as KI}from"commander";import st from"chalk";import{writeFileSync as XI,mkdirSync as VI,existsSync as bc,readFileSync as Vv,appendFileSync as Qv}from"fs";import{resolve as rr,dirname as tx}from"path";import{homedir as Fg}from"os";var ox=new KI().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-BHDAV67G.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=eN(o);break;case"bash":s=rN(o);break;case"fish":s=iN(o);break;default:console.error(st.red(`unsupported shell: ${n}`)),console.error(st.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?rr(String(e.output)):QI(n);VI(tx(r),{recursive:!0}),XI(r,s),console.log(st.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),ZI(n,r,!!e.yes)});function QI(e){let t=Fg();switch(e){case"zsh":return rr(t,".zsh","completions","_agentx");case"bash":return rr(t,".bash_completion.d","agentx.bash");case"fish":return rr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function ZI(e,t,o){if(e==="zsh"){let n=rr(Fg(),".zshrc"),s=tx(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=bc(n)?Vv(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(st.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&bc(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),Qv(n,g.join(`
856
+ `}import{Command as KI}from"commander";import st from"chalk";import{writeFileSync as XI,mkdirSync as VI,existsSync as bc,readFileSync as Vv,appendFileSync as Qv}from"fs";import{resolve as rr,dirname as tx}from"path";import{homedir as Fg}from"os";var ox=new KI().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-2DFU4DCC.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=eN(o);break;case"bash":s=rN(o);break;case"fish":s=iN(o);break;default:console.error(st.red(`unsupported shell: ${n}`)),console.error(st.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?rr(String(e.output)):QI(n);VI(tx(r),{recursive:!0}),XI(r,s),console.log(st.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),ZI(n,r,!!e.yes)});function QI(e){let t=Fg();switch(e){case"zsh":return rr(t,".zsh","completions","_agentx");case"bash":return rr(t,".bash_completion.d","agentx.bash");case"fish":return rr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function ZI(e,t,o){if(e==="zsh"){let n=rr(Fg(),".zshrc"),s=tx(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=bc(n)?Vv(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(st.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&bc(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),Qv(n,g.join(`
857
857
  `)+`
858
858
  `),console.log(st.green("\u2713 Patched ~/.zshrc")),console.log(st.dim("Reload your shell: exec zsh"));return}console.log(st.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(st.cyan(` ${r}`)),l&&console.log(st.cyan(` ${i}`)),console.log(),console.log(st.dim("Then reload: exec zsh")),console.log(st.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=rr(Fg(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((bc(n)?Vv(n,"utf-8"):"").includes(t)){console.log(st.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&bc(n)){Qv(n,`
859
859
  # agentx completion
@@ -869,4 +869,4 @@ ${aN({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
869
869
  ${o.url}`)}catch(t){console.error(ar.red(` ${t.message}`)),process.exitCode=1}});ai.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",Wg).action(async(e,t)=>{try{let o=await Hg(t.models);if(!Bg(t.model,o)){console.log(Jg(t.model,o)),process.exitCode=1;return}let n=e==="-"?await dN():await lN(e,"utf8"),s=JSON.parse(n),{version:r}=await xi(),i=ix({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(ar.red(` ${o.message}`)),process.exitCode=1}});async function dN(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function o3(){let e=await xi(),t=new gN().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=zf(n);Yf(s)&&Gf("cli",s)});for(let o of[Ww,tw,ew,Yn,xs,lo,Pt,Rf,mo,da,Co,vn,Bn,wo,on,F$,tn,ta,Nv,Vo,My,Ly,zy,Lr,sb,lb,Py,ub,mb,Ob,Pb,_b,qt,Kn,Lv,Rr,Go,ox,ai])t.addCommand(o);for(let o of cx)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=cx.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,uN(o,74," "),""].join(`
870
870
  `)}),t}var cx=[z,Qs,jo,to,Or,Bs,Qe,No,nn,Wn,es,er,Ko,kt,_s,xa,qa,Fn,Fa,Ua,Rv,Ov,To,Zr,Dt,dh,Rn,ri,zl,cn,wt,js,Yl,cc,bo,Po,Jv,nr,Hv,Dv];function uN(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(`
871
871
  `)}export{o3 as buildProgram};
872
- //# sourceMappingURL=program-BHDAV67G.js.map
872
+ //# sourceMappingURL=program-2DFU4DCC.js.map