agentix-cli 0.173.0 → 0.174.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 (130) hide show
  1. package/dist/{App-2LXSOVIN.js → App-DYS5IYTQ.js} +2 -2
  2. package/dist/{ChatApp-4TRWF5SI.js → ChatApp-ZZHEP2P7.js} +2 -2
  3. package/dist/{absorb-eval-TF3OMPHG.js → absorb-eval-YMRCIJCC.js} +2 -2
  4. package/dist/{adapter-WSN6XAKV.js → adapter-YTOLYEJ4.js} +2 -2
  5. package/dist/{agent-IQUF5TDP.js → agent-5FQHQ7NG.js} +2 -2
  6. package/dist/{board-dashboard-6VWNYJZ7.js → board-dashboard-ORELMK25.js} +4 -4
  7. package/dist/{chunk-Z37662LA.js → chunk-2OGM6LGX.js} +2 -2
  8. package/dist/{chunk-VAH526K6.js → chunk-3KHPKKRT.js} +2 -2
  9. package/dist/{chunk-ZZR34W4V.js → chunk-5OPKQY36.js} +2 -2
  10. package/dist/{chunk-T3V4CUOO.js → chunk-6OXJGHWA.js} +2 -2
  11. package/dist/{chunk-NWKTI6AZ.js → chunk-6VJLN66C.js} +2 -2
  12. package/dist/{chunk-KN2IZ6C3.js → chunk-A4L7WH3R.js} +2 -2
  13. package/dist/{chunk-22SO5H73.js → chunk-A6SVCE62.js} +2 -2
  14. package/dist/{chunk-IC5CL2DW.js → chunk-C3RSVAKB.js} +2 -2
  15. package/dist/{chunk-VNOTN6N5.js → chunk-DAILRO2V.js} +2 -2
  16. package/dist/{chunk-B6JE7TKU.js → chunk-DGWLDVU2.js} +2 -2
  17. package/dist/{chunk-SP2JS67T.js → chunk-DMLES42J.js} +2 -2
  18. package/dist/{chunk-GIPEXI3C.js → chunk-EMIEBF5B.js} +2 -2
  19. package/dist/{chunk-5EI44WB7.js → chunk-H6I42JBS.js} +2 -2
  20. package/dist/{chunk-EJQHTD5U.js → chunk-ICXHX2QO.js} +2 -2
  21. package/dist/{chunk-EJQHTD5U.js.map → chunk-ICXHX2QO.js.map} +1 -1
  22. package/dist/{chunk-UG6S2QED.js → chunk-KZKTVGL7.js} +2 -2
  23. package/dist/{chunk-HXINT6DB.js → chunk-LGAZ66CL.js} +2 -2
  24. package/dist/{chunk-E6BIV3EM.js → chunk-LWMKOWIX.js} +2 -2
  25. package/dist/{chunk-WMQBY45T.js → chunk-MABUBCEL.js} +2 -2
  26. package/dist/{chunk-KAVZPYK4.js → chunk-PBEO46ER.js} +2 -2
  27. package/dist/{chunk-WS2F726P.js → chunk-SMKVNZVI.js} +2 -2
  28. package/dist/{chunk-QJPLPN3G.js → chunk-T3T4CT3A.js} +2 -2
  29. package/dist/{chunk-RY2YN3WA.js → chunk-VCGTZS3T.js} +2 -2
  30. package/dist/{chunk-KUMCHMGE.js → chunk-W26TO6HY.js} +3 -3
  31. package/dist/{chunk-TB752ZN4.js → chunk-X3I2VJ5H.js} +2 -2
  32. package/dist/{chunk-6W5262KN.js → chunk-XJA4ABH4.js} +2 -2
  33. package/dist/{chunk-Z73KECFS.js → chunk-XPMDJJI4.js} +204 -204
  34. package/dist/{chunk-Z73KECFS.js.map → chunk-XPMDJJI4.js.map} +1 -1
  35. package/dist/{chunk-ZRHDAJS5.js → chunk-Y7MYDM4V.js} +2 -2
  36. package/dist/{chunk-O2ZDYZXI.js → chunk-YBAGESBG.js} +5 -5
  37. package/dist/cli.js +1 -1
  38. package/dist/{client-Y63KZEDJ.js → client-HZKF3XY6.js} +2 -2
  39. package/dist/{config-GPCTV4AD.js → config-WBW2WCS2.js} +2 -2
  40. package/dist/{config-mutate-S56W3EGU.js → config-mutate-YJI2JEMP.js} +2 -2
  41. package/dist/config-mutator-GOYUMGWG.js +2 -0
  42. package/dist/{contributions-LK72ZY6S.js → contributions-HJPRWHSN.js} +2 -2
  43. package/dist/{doctor-DL7MBZXQ.js → doctor-NM45LR6S.js} +2 -2
  44. package/dist/{follow-up-tool-CTP5XACV.js → follow-up-tool-S7GBNJE6.js} +2 -2
  45. package/dist/{hub-WRXWDBUZ.js → hub-QN4HRLGZ.js} +2 -2
  46. package/dist/index.d.ts +8 -0
  47. package/dist/index.js +1 -1
  48. package/dist/{program-5CHM6EPW.js → program-MDS4XDAY.js} +23 -23
  49. package/dist/program-MDS4XDAY.js.map +1 -0
  50. package/dist/{promote-B2QIPGIF.js → promote-6BZBQZ2E.js} +2 -2
  51. package/dist/{query-KMRMTYL6.js → query-AFQMYQTS.js} +2 -2
  52. package/dist/{query-settings-M3HVXUMQ.js → query-settings-U32L6542.js} +2 -2
  53. package/dist/{registry-VQCSFMIJ.js → registry-TRZF4LKY.js} +2 -2
  54. package/dist/{request-planner-HGGCC3VR.js → request-planner-PAZEWNOG.js} +2 -2
  55. package/dist/{review-candidates-OR3GP2SU.js → review-candidates-C5BXFQLG.js} +2 -2
  56. package/dist/{routing-47DKYUQW.js → routing-2JCE3J3Q.js} +2 -2
  57. package/dist/schedule-tool-GQ7DMQEV.js +2 -0
  58. package/dist/{scheduler-KL4R5UPC.js → scheduler-OLAKDG7M.js} +2 -2
  59. package/dist/{seat-FFDCUGCG.js → seat-G6YNXTEY.js} +2 -2
  60. package/dist/{select-BDZ44G5B.js → select-3QH2DHIN.js} +2 -2
  61. package/dist/{set-enabled-CX7AOZAU.js → set-enabled-N4FB3DTD.js} +2 -2
  62. package/dist/{sprint-tool-25JPVUH2.js → sprint-tool-ZESTW34W.js} +2 -2
  63. package/dist/{tool-CZCY6ZBQ.js → tool-CSZO7F77.js} +2 -2
  64. package/dist/{tool-CMFZK2HQ.js → tool-G2DHKUGN.js} +2 -2
  65. package/dist/{tool-VMTEK3DF.js → tool-RIUS7A5P.js} +2 -2
  66. package/dist/{wiki-LMVIRMSR.js → wiki-4CT7SXMO.js} +2 -2
  67. package/dist/wiki-enrich-IN7UANOJ.js +2 -0
  68. package/package.json +1 -1
  69. package/dist/config-mutator-G2MEPNGH.js +0 -2
  70. package/dist/program-5CHM6EPW.js.map +0 -1
  71. package/dist/schedule-tool-LENFAYB6.js +0 -2
  72. package/dist/wiki-enrich-JS6WC6ER.js +0 -2
  73. /package/dist/{App-2LXSOVIN.js.map → App-DYS5IYTQ.js.map} +0 -0
  74. /package/dist/{ChatApp-4TRWF5SI.js.map → ChatApp-ZZHEP2P7.js.map} +0 -0
  75. /package/dist/{absorb-eval-TF3OMPHG.js.map → absorb-eval-YMRCIJCC.js.map} +0 -0
  76. /package/dist/{adapter-WSN6XAKV.js.map → adapter-YTOLYEJ4.js.map} +0 -0
  77. /package/dist/{agent-IQUF5TDP.js.map → agent-5FQHQ7NG.js.map} +0 -0
  78. /package/dist/{board-dashboard-6VWNYJZ7.js.map → board-dashboard-ORELMK25.js.map} +0 -0
  79. /package/dist/{chunk-Z37662LA.js.map → chunk-2OGM6LGX.js.map} +0 -0
  80. /package/dist/{chunk-VAH526K6.js.map → chunk-3KHPKKRT.js.map} +0 -0
  81. /package/dist/{chunk-ZZR34W4V.js.map → chunk-5OPKQY36.js.map} +0 -0
  82. /package/dist/{chunk-T3V4CUOO.js.map → chunk-6OXJGHWA.js.map} +0 -0
  83. /package/dist/{chunk-NWKTI6AZ.js.map → chunk-6VJLN66C.js.map} +0 -0
  84. /package/dist/{chunk-KN2IZ6C3.js.map → chunk-A4L7WH3R.js.map} +0 -0
  85. /package/dist/{chunk-22SO5H73.js.map → chunk-A6SVCE62.js.map} +0 -0
  86. /package/dist/{chunk-IC5CL2DW.js.map → chunk-C3RSVAKB.js.map} +0 -0
  87. /package/dist/{chunk-VNOTN6N5.js.map → chunk-DAILRO2V.js.map} +0 -0
  88. /package/dist/{chunk-B6JE7TKU.js.map → chunk-DGWLDVU2.js.map} +0 -0
  89. /package/dist/{chunk-SP2JS67T.js.map → chunk-DMLES42J.js.map} +0 -0
  90. /package/dist/{chunk-GIPEXI3C.js.map → chunk-EMIEBF5B.js.map} +0 -0
  91. /package/dist/{chunk-5EI44WB7.js.map → chunk-H6I42JBS.js.map} +0 -0
  92. /package/dist/{chunk-UG6S2QED.js.map → chunk-KZKTVGL7.js.map} +0 -0
  93. /package/dist/{chunk-HXINT6DB.js.map → chunk-LGAZ66CL.js.map} +0 -0
  94. /package/dist/{chunk-E6BIV3EM.js.map → chunk-LWMKOWIX.js.map} +0 -0
  95. /package/dist/{chunk-WMQBY45T.js.map → chunk-MABUBCEL.js.map} +0 -0
  96. /package/dist/{chunk-KAVZPYK4.js.map → chunk-PBEO46ER.js.map} +0 -0
  97. /package/dist/{chunk-WS2F726P.js.map → chunk-SMKVNZVI.js.map} +0 -0
  98. /package/dist/{chunk-QJPLPN3G.js.map → chunk-T3T4CT3A.js.map} +0 -0
  99. /package/dist/{chunk-RY2YN3WA.js.map → chunk-VCGTZS3T.js.map} +0 -0
  100. /package/dist/{chunk-KUMCHMGE.js.map → chunk-W26TO6HY.js.map} +0 -0
  101. /package/dist/{chunk-TB752ZN4.js.map → chunk-X3I2VJ5H.js.map} +0 -0
  102. /package/dist/{chunk-6W5262KN.js.map → chunk-XJA4ABH4.js.map} +0 -0
  103. /package/dist/{chunk-ZRHDAJS5.js.map → chunk-Y7MYDM4V.js.map} +0 -0
  104. /package/dist/{chunk-O2ZDYZXI.js.map → chunk-YBAGESBG.js.map} +0 -0
  105. /package/dist/{client-Y63KZEDJ.js.map → client-HZKF3XY6.js.map} +0 -0
  106. /package/dist/{config-GPCTV4AD.js.map → config-WBW2WCS2.js.map} +0 -0
  107. /package/dist/{config-mutate-S56W3EGU.js.map → config-mutate-YJI2JEMP.js.map} +0 -0
  108. /package/dist/{config-mutator-G2MEPNGH.js.map → config-mutator-GOYUMGWG.js.map} +0 -0
  109. /package/dist/{contributions-LK72ZY6S.js.map → contributions-HJPRWHSN.js.map} +0 -0
  110. /package/dist/{doctor-DL7MBZXQ.js.map → doctor-NM45LR6S.js.map} +0 -0
  111. /package/dist/{follow-up-tool-CTP5XACV.js.map → follow-up-tool-S7GBNJE6.js.map} +0 -0
  112. /package/dist/{hub-WRXWDBUZ.js.map → hub-QN4HRLGZ.js.map} +0 -0
  113. /package/dist/{promote-B2QIPGIF.js.map → promote-6BZBQZ2E.js.map} +0 -0
  114. /package/dist/{query-KMRMTYL6.js.map → query-AFQMYQTS.js.map} +0 -0
  115. /package/dist/{query-settings-M3HVXUMQ.js.map → query-settings-U32L6542.js.map} +0 -0
  116. /package/dist/{registry-VQCSFMIJ.js.map → registry-TRZF4LKY.js.map} +0 -0
  117. /package/dist/{request-planner-HGGCC3VR.js.map → request-planner-PAZEWNOG.js.map} +0 -0
  118. /package/dist/{review-candidates-OR3GP2SU.js.map → review-candidates-C5BXFQLG.js.map} +0 -0
  119. /package/dist/{routing-47DKYUQW.js.map → routing-2JCE3J3Q.js.map} +0 -0
  120. /package/dist/{schedule-tool-LENFAYB6.js.map → schedule-tool-GQ7DMQEV.js.map} +0 -0
  121. /package/dist/{scheduler-KL4R5UPC.js.map → scheduler-OLAKDG7M.js.map} +0 -0
  122. /package/dist/{seat-FFDCUGCG.js.map → seat-G6YNXTEY.js.map} +0 -0
  123. /package/dist/{select-BDZ44G5B.js.map → select-3QH2DHIN.js.map} +0 -0
  124. /package/dist/{set-enabled-CX7AOZAU.js.map → set-enabled-N4FB3DTD.js.map} +0 -0
  125. /package/dist/{sprint-tool-25JPVUH2.js.map → sprint-tool-ZESTW34W.js.map} +0 -0
  126. /package/dist/{tool-CZCY6ZBQ.js.map → tool-CSZO7F77.js.map} +0 -0
  127. /package/dist/{tool-CMFZK2HQ.js.map → tool-G2DHKUGN.js.map} +0 -0
  128. /package/dist/{tool-VMTEK3DF.js.map → tool-RIUS7A5P.js.map} +0 -0
  129. /package/dist/{wiki-LMVIRMSR.js.map → wiki-4CT7SXMO.js.map} +0 -0
  130. /package/dist/{wiki-enrich-JS6WC6ER.js.map → wiki-enrich-IN7UANOJ.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as Lf,b as qi,g as qf}from"./chunk-HXINT6DB.js";import{b as _f}from"./chunk-TB752ZN4.js";import{$ as Of,A as gf,B as uf,C as mf,D as ol,E as pf,J as ff,K as hf,L as nl,M as wf,P as yf,Q as bf,R as $f,S as kf,T as Af,U as Ef,V as Rf,X as sl,Y as Tf,_ as Cf,a as Jp,aa as If,b as Hp,f as Gp,g as zp,i as Yp,k as ps,l as fs,m as Kp,n as Xp,o as Vp,p as Qp,q as Zp,r as ef,t as co,v as nf,w as sf,x as lf,y as df}from"./chunk-22SO5H73.js";import{n as rl}from"./chunk-IC5CL2DW.js";import{a as Nf,b as jf,d as ur,e as Pf}from"./chunk-GIPEXI3C.js";import{a as Df,b as Mf}from"./chunk-VNOTN6N5.js";import"./chunk-XVTD6I34.js";import{d as rf,e as tl,h as af,i as cf}from"./chunk-CTN4KYE6.js";import{a as vf,c as xf,d as Sf}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-MTX4UPNB.js";import{a as jt}from"./chunk-SP2JS67T.js";import{a as tf,c as of}from"./chunk-ZRHDAJS5.js";import{a as Zc}from"./chunk-LNY6N73E.js";import"./chunk-DMCMV4UJ.js";import{a as Cc,b as qu}from"./chunk-RKPAVWXF.js";import{$ as yp,A as Jm,Aa as Xc,B as Fc,Ba as Lp,C as Hm,Ca as Fp,D as Gm,Da as Qc,E as zm,Ea as Wp,F as Ym,Fa as Mi,G as Km,Ga as ms,H as Xm,Ha as Li,I as Ci,Ia as el,J as Vm,Ja as Bp,K as Uc,L as Qm,M as Zm,N as ep,O as tp,P as op,Q as Oi,R as ap,S as dp,T as gp,U as up,V as mp,W as pp,X as Bc,Y as fp,Z as hp,_ as wp,a as em,aa as bp,b as tm,ba as $p,ca as kp,da as vp,ea as Cp,fa as ji,ga as vo,h as fi,ha as Fo,i as rm,ia as ds,j as ar,ja as Pi,k as hi,ka as _i,l as am,la as Kc,m as lm,ma as Op,n as km,na as Ip,o as vm,oa as Np,p as vi,pa as jp,q as Mc,qa as Pp,r as Cm,ra as _p,s as Lm,sa as gs,t as qm,ta as us,u as Fm,ua as Dp,v as Um,va as dr,w as Ti,wa as Mp,x as Wm,xa as lt,y as Bm,ya as Di,z as qc,za as gr}from"./chunk-Z73KECFS.js";import{$a as Ni,Da as cr,Ga as Jc,Ha as Ii,Ia as xp,Kb as ao,Mb as Up,Pa as qo,Q as _m,Qa as Sp,Ra as Hc,S as Ei,T as Dm,Ta as Gc,Va as Ap,W as Mm,Wa as Ep,X as Ri,Xa as lr,cb as Rp,db as Tp,ea as np,eb as zc,fa as sp,ga as rp,ha as Wc,ja as ip,lb as Yc,v as cm,vb as qp,wb as Vc}from"./chunk-KAVZPYK4.js";import"./chunk-GTJIKXDB.js";import{a as om,c as Pc,e as nm,f as sm}from"./chunk-6W5262KN.js";import"./chunk-ZVP6GB4G.js";import{F as bi,G as bm,H as $m,a as Rc,b as ju,e as Pu,f as _u,n as wi,o as yi,p as dm,q as gm,r as um,t as mm,u as pm,w as fm,x as hm,y as wm,z as ym}from"./chunk-ZZR34W4V.js";import{a as cp,b as lp}from"./chunk-EKJG63EJ.js";import"./chunk-E6BIV3EM.js";import"./chunk-N6VBEITO.js";import"./chunk-IMLAPB7G.js";import{c as xm}from"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import{b as Dc}from"./chunk-5HLD66CW.js";import{c as Sm,e as $i,g as ki}from"./chunk-LQE73AZR.js";import{a as Am,b as Em,c as Rm,d as Tm}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-FRR6DRLY.js";import{a as Om,b as un,c as Im,d as xi,g as Nm,h as jm,j as Pm,k as Lc,n as Si,o as mn,p as Ai}from"./chunk-LQS27HSV.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-A5GYG56I.js";import{a as _c,p as im}from"./chunk-RY2YN3WA.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Nt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-IS2IWRP7.js";import{a as io}from"./chunk-MNG2AMKZ.js";import{a as zu,b as Yu,c as Ku,d as Xu,e as Ic,f as Vu,g as Nc,h as jc,l as Qu,m as Zu}from"./chunk-RX5O5637.js";import"./chunk-X7UQY7CH.js";import{a as Tc,d as Du,e as pi}from"./chunk-QPABR72X.js";import{a as ir,e as Fu,f as Uu,g as Oc,i as Wu,j as Bu,l as Ju,m as Hu,n as Gu}from"./chunk-UG6S2QED.js";import{b as ls,e as Lu}from"./chunk-AJ5HMDRW.js";import{c as Mu}from"./chunk-KP7KDLZ2.js";import{B as vc,C as fu,O as Lo,U as Ou,g as au,r as cu,va as Nu}from"./chunk-O2ZDYZXI.js";import{I as ss,J as ui,K as mi,L as rs,M as wu,N as Do,P as Mo,b as ns,fa as Tu,r as ko,s as xc,t as hu,u as Sc,ua as Cu,w as di,wa as Iu,x as gi}from"./chunk-B6JE7TKU.js";import{b as dn}from"./chunk-MEFPXHQJ.js";import"./chunk-QJPLPN3G.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as bu}from"./chunk-SZDACK6O.js";import{f as $u,g as ku,h as Ac}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as xu,f as gn,k as as}from"./chunk-VJVXEVZ7.js";import{a as mu,k as vu,n as Ru}from"./chunk-WMQBY45T.js";import{a as Tt,b as de,c as qe,d as cs,e as Su}from"./chunk-WS2F726P.js";import{a as Au,b as Ec,h as Eu}from"./chunk-3UOTLMXD.js";import{i as du,j as gu}from"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import{a as kc,b as uu}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as pu}from"./chunk-X5C5W3E4.js";import{a as is}from"./chunk-GV7S5BAX.js";import{e as yu}from"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import{a as $c}from"./chunk-VAH526K6.js";import"./chunk-KN2IZ6C3.js";import{c as lu}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-KUMCHMGE.js";import"./chunk-JTFCU5LH.js";import{g as _o,i as li}from"./chunk-Z37662LA.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-NWKTI6AZ.js";import{a as pc,b as _g,c as Pv,d as oi,e as Dg,f as Zg,g as Bv,h as eu,i as Jv,m as os,n as ou,q as nu,u as su,y as ro,z as rr}from"./chunk-T3V4CUOO.js";import{a as $o,b as ts,e as Xg,f as sr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as ci,b as tu}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as Po,j as ru}from"./chunk-QUFIUXMQ.js";import{n as iu}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 jv}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{Ha as zg,Ia as wc,Ka as yc,M as Bg,N as Lv,Ra as Fv,S as ni,Sa as bc,T as si,Ua as Yg,Va as Uv,W as Jg,X as Hg,Y as ri,Z as hc,_a as Kg,fa as Gg,ga as qv,j as Lg,k as qg,l as Fg,m as Ug,mb as ii,n as Wg,nb as nr,o as Dv,ob as T,qb as ai,x as fc,xb as ne,y as Mv}from"./chunk-EJQHTD5U.js";import"./chunk-VJ5HC63R.js";import{j as bt,r as es}from"./chunk-UEEB3UTU.js";import{a as Mg,e as _v}from"./chunk-VQRY4IDI.js";import{g as Vg,k as Qg,l as Wv}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Hv}from"commander";var Ff=new Hv().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 tm({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()});ne();import{Command as Gv}from"commander";import{execFileSync as Bt}from"node:child_process";import{cpSync as Uf,existsSync as cl,mkdirSync as il,mkdtempSync as zv,readdirSync as Yv,rmSync as Wf,writeFileSync as Bf}from"node:fs";import{dirname as Jf,join as dt}from"node:path";import{homedir as Fi,release as Kv,tmpdir as Xv}from"node:os";import{setTimeout as Vv}from"node:timers/promises";function Ui(){let e=dm(process.platform,process.arch,Kv());if(e)throw new Error(e)}function Wi(){let e=dt(Fi(),"Library/LaunchAgents"),t=[];try{t=Yv(e).filter(mm)}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 pm(e,o)}function mr(e){return`gui/${process.getuid()}/${e.label}`}async function al(e){try{Bt("launchctl",["bootout",mr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Bt("launchctl",["print",mr(e)],{stdio:"pipe"})}catch{return}await Vv(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Hf(e){if(!cl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Bt("launchctl",["print",mr(e)],{stdio:"pipe"})}catch{t=!1}t||Bt("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Bt("launchctl",["kickstart",mr(e)],{stdio:"pipe"})}function Qv(){let e=ym();if(e&&cl(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 hs=new Gv("desktop").description("install and control the macOS desktop assistant");hs.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=>{Ui();let t=T(),o=gm(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=Qv(),i=dt(Fi(),"Applications"),{keep:a,remove:c}=Wi();if(console.log(`Desktop assistant \u2192 ${dt(i,wi)}
1
+ import{a as Lf,b as qi,g as qf}from"./chunk-LGAZ66CL.js";import{b as _f}from"./chunk-X3I2VJ5H.js";import{$ as Of,A as gf,B as uf,C as mf,D as ol,E as pf,J as ff,K as hf,L as nl,M as wf,P as yf,Q as bf,R as $f,S as kf,T as Af,U as Ef,V as Rf,X as sl,Y as Tf,_ as Cf,a as Jp,aa as If,b as Hp,f as Gp,g as zp,i as Yp,k as ps,l as fs,m as Kp,n as Xp,o as Vp,p as Qp,q as Zp,r as ef,t as co,v as nf,w as sf,x as lf,y as df}from"./chunk-A6SVCE62.js";import{n as rl}from"./chunk-C3RSVAKB.js";import{a as Nf,b as jf,d as ur,e as Pf}from"./chunk-EMIEBF5B.js";import{a as Df,b as Mf}from"./chunk-DAILRO2V.js";import"./chunk-XVTD6I34.js";import{d as rf,e as tl,h as af,i as cf}from"./chunk-CTN4KYE6.js";import{a as vf,c as xf,d as Sf}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-MTX4UPNB.js";import{a as jt}from"./chunk-DMLES42J.js";import{a as tf,c as of}from"./chunk-Y7MYDM4V.js";import{a as Zc}from"./chunk-LNY6N73E.js";import"./chunk-DMCMV4UJ.js";import{a as Cc,b as qu}from"./chunk-RKPAVWXF.js";import{$ as yp,A as Jm,Aa as Xc,B as Fc,Ba as Lp,C as Hm,Ca as Fp,D as Gm,Da as Qc,E as zm,Ea as Wp,F as Ym,Fa as Mi,G as Km,Ga as ms,H as Xm,Ha as Li,I as Ci,Ia as el,J as Vm,Ja as Bp,K as Uc,L as Qm,M as Zm,N as ep,O as tp,P as op,Q as Oi,R as ap,S as dp,T as gp,U as up,V as mp,W as pp,X as Bc,Y as fp,Z as hp,_ as wp,a as em,aa as bp,b as tm,ba as $p,ca as kp,da as vp,ea as Cp,fa as ji,ga as vo,h as fi,ha as Fo,i as rm,ia as ds,j as ar,ja as Pi,k as hi,ka as _i,l as am,la as Kc,m as lm,ma as Op,n as km,na as Ip,o as vm,oa as Np,p as vi,pa as jp,q as Mc,qa as Pp,r as Cm,ra as _p,s as Lm,sa as gs,t as qm,ta as us,u as Fm,ua as Dp,v as Um,va as dr,w as Ti,wa as Mp,x as Wm,xa as lt,y as Bm,ya as Di,z as qc,za as gr}from"./chunk-XPMDJJI4.js";import{$a as Ni,Da as cr,Ga as Jc,Ha as Ii,Ia as xp,Kb as ao,Mb as Up,Pa as qo,Q as _m,Qa as Sp,Ra as Hc,S as Ei,T as Dm,Ta as Gc,Va as Ap,W as Mm,Wa as Ep,X as Ri,Xa as lr,cb as Rp,db as Tp,ea as np,eb as zc,fa as sp,ga as rp,ha as Wc,ja as ip,lb as Yc,v as cm,vb as qp,wb as Vc}from"./chunk-PBEO46ER.js";import"./chunk-GTJIKXDB.js";import{a as om,c as Pc,e as nm,f as sm}from"./chunk-XJA4ABH4.js";import"./chunk-ZVP6GB4G.js";import{F as bi,G as bm,H as $m,a as Rc,b as ju,e as Pu,f as _u,n as wi,o as yi,p as dm,q as gm,r as um,t as mm,u as pm,w as fm,x as hm,y as wm,z as ym}from"./chunk-5OPKQY36.js";import{a as cp,b as lp}from"./chunk-EKJG63EJ.js";import"./chunk-LWMKOWIX.js";import"./chunk-N6VBEITO.js";import"./chunk-IMLAPB7G.js";import{c as xm}from"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import{b as Dc}from"./chunk-5HLD66CW.js";import{c as Sm,e as $i,g as ki}from"./chunk-LQE73AZR.js";import{a as Am,b as Em,c as Rm,d as Tm}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-FRR6DRLY.js";import{a as Om,b as un,c as Im,d as xi,g as Nm,h as jm,j as Pm,k as Lc,n as Si,o as mn,p as Ai}from"./chunk-LQS27HSV.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-A5GYG56I.js";import{a as _c,p as im}from"./chunk-VCGTZS3T.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Nt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-IS2IWRP7.js";import{a as io}from"./chunk-MNG2AMKZ.js";import{a as zu,b as Yu,c as Ku,d as Xu,e as Ic,f as Vu,g as Nc,h as jc,l as Qu,m as Zu}from"./chunk-RX5O5637.js";import"./chunk-X7UQY7CH.js";import{a as Tc,d as Du,e as pi}from"./chunk-QPABR72X.js";import{a as ir,e as Fu,f as Uu,g as Oc,i as Wu,j as Bu,l as Ju,m as Hu,n as Gu}from"./chunk-KZKTVGL7.js";import{b as ls,e as Lu}from"./chunk-AJ5HMDRW.js";import{c as Mu}from"./chunk-KP7KDLZ2.js";import{B as vc,C as fu,O as Lo,U as Ou,g as au,r as cu,va as Nu}from"./chunk-YBAGESBG.js";import{I as ss,J as ui,K as mi,L as rs,M as wu,N as Do,P as Mo,b as ns,fa as Tu,r as ko,s as xc,t as hu,u as Sc,ua as Cu,w as di,wa as Iu,x as gi}from"./chunk-DGWLDVU2.js";import{b as dn}from"./chunk-MEFPXHQJ.js";import"./chunk-T3T4CT3A.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as bu}from"./chunk-SZDACK6O.js";import{f as $u,g as ku,h as Ac}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as xu,f as gn,k as as}from"./chunk-VJVXEVZ7.js";import{a as mu,k as vu,n as Ru}from"./chunk-MABUBCEL.js";import{a as Tt,b as de,c as qe,d as cs,e as Su}from"./chunk-SMKVNZVI.js";import{a as Au,b as Ec,h as Eu}from"./chunk-3UOTLMXD.js";import{i as du,j as gu}from"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import{a as kc,b as uu}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as pu}from"./chunk-X5C5W3E4.js";import{a as is}from"./chunk-GV7S5BAX.js";import{e as yu}from"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import{a as $c}from"./chunk-3KHPKKRT.js";import"./chunk-A4L7WH3R.js";import{c as lu}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-W26TO6HY.js";import"./chunk-JTFCU5LH.js";import{g as _o,i as li}from"./chunk-2OGM6LGX.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-6VJLN66C.js";import{a as pc,b as _g,c as Pv,d as oi,e as Dg,f as Zg,g as Bv,h as eu,i as Jv,m as os,n as ou,q as nu,u as su,y as ro,z as rr}from"./chunk-6OXJGHWA.js";import{a as $o,b as ts,e as Xg,f as sr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as ci,b as tu}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as Po,j as ru}from"./chunk-QUFIUXMQ.js";import{n as iu}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 jv}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{Ha as zg,Ia as wc,Ka as yc,M as Bg,N as Lv,Ra as Fv,S as ni,Sa as bc,T as si,Ua as Yg,Va as Uv,W as Jg,X as Hg,Y as ri,Z as hc,_a as Kg,fa as Gg,ga as qv,j as Lg,k as qg,l as Fg,m as Ug,mb as ii,n as Wg,nb as nr,o as Dv,ob as T,qb as ai,x as fc,xb as ne,y as Mv}from"./chunk-ICXHX2QO.js";import"./chunk-VJ5HC63R.js";import{j as bt,r as es}from"./chunk-UEEB3UTU.js";import{a as Mg,e as _v}from"./chunk-VQRY4IDI.js";import{g as Vg,k as Qg,l as Wv}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Hv}from"commander";var Ff=new Hv().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 tm({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()});ne();import{Command as Gv}from"commander";import{execFileSync as Bt}from"node:child_process";import{cpSync as Uf,existsSync as cl,mkdirSync as il,mkdtempSync as zv,readdirSync as Yv,rmSync as Wf,writeFileSync as Bf}from"node:fs";import{dirname as Jf,join as dt}from"node:path";import{homedir as Fi,release as Kv,tmpdir as Xv}from"node:os";import{setTimeout as Vv}from"node:timers/promises";function Ui(){let e=dm(process.platform,process.arch,Kv());if(e)throw new Error(e)}function Wi(){let e=dt(Fi(),"Library/LaunchAgents"),t=[];try{t=Yv(e).filter(mm)}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 pm(e,o)}function mr(e){return`gui/${process.getuid()}/${e.label}`}async function al(e){try{Bt("launchctl",["bootout",mr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Bt("launchctl",["print",mr(e)],{stdio:"pipe"})}catch{return}await Vv(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Hf(e){if(!cl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Bt("launchctl",["print",mr(e)],{stdio:"pipe"})}catch{t=!1}t||Bt("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Bt("launchctl",["kickstart",mr(e)],{stdio:"pipe"})}function Qv(){let e=ym();if(e&&cl(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 hs=new Gv("desktop").description("install and control the macOS desktop assistant");hs.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=>{Ui();let t=T(),o=gm(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=Qv(),i=dt(Fi(),"Applications"),{keep:a,remove:c}=Wi();if(console.log(`Desktop assistant \u2192 ${dt(i,wi)}
2
2
  Computer-use helper \u2192 ${dt(i,yi)}
3
3
  Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -64,7 +64,7 @@ Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choos
64
64
  `))});function vw(e){let t=bt();return t||(console.log(ee.red(" The database (.agentx/db.sqlite) can't be opened here.")),process.exit(1)),e(new Zc(t))}function G0(){let e=bt({quiet:!0});if(!e)return[];let t=new Map;for(let o of new Zc(e).list()){if(!Dc(o.deviceId))continue;let n=t.get(o.deviceId)??{deviceId:o.deviceId,deviceName:o.deviceName,createdAt:o.createdAt,subscriptions:0};n.subscriptions++,n.createdAt=Math.max(n.createdAt,o.createdAt),t.set(o.deviceId,n)}return[...t.values()]}function z0(e){let t=Math.round(Sm/6e4),o=[` Pairing code: ${ee.bold.cyan($i(e.code))}`,ee.dim(` Open the app from the phone's home screen and type this code. It works once, for ${t} minutes.`)," Or scan the QR code with the phone's camera and open the link.",` Device ${ee.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,ee.yellow(" \u26A0 Anyone who scans the QR code or types the code can use the app. Clear the terminal when done.")];return e.origin.startsWith("https://")||o.push(ee.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),o}function Il(){let e;try{e=JSON.parse(kw("tailscale",["status","--json"],{encoding:"utf-8",timeout:5e3}))}catch{throw new Error("Could not read this machine's Tailscale name. Is Tailscale running? Or pass --url https://<address>.")}let t=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!t)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${t}`}var Y0=new Set(["/app","/api/app","/member","/api/member"]),$w="/.well-known/assetlinks.json";function K0(){let e=new Set(["localhost","0.0.0.0","::","::1"]);try{let t=J0().toLowerCase().replace(/\.$/,"");t&&e.add(t).add(t.replace(/\.local$/,"")).add(`${t.replace(/\.local$/,"")}.local`)}catch{}try{for(let t of Object.values(H0()))for(let o of t??[])e.add(xw(o.address.toLowerCase().replace(/%.*$/,"")))}catch{}return e}var X0={http:80,https:443,"https+insecure":443};function V0(e){let t=e.match(/^(\d+)(\/[^?#]*)?$/);if(t)return{host:"localhost",port:Number(t[1]),path:t[2]??""};let o=e.match(/^(?:([a-z][a-z0-9+.-]*):\/\/)?(?:[^@/?#]*@)?(\[[^\]]*\]|[^/:?#]*)(?::(\d+))?([^?#]*)/i);if(!o)return null;let n=o[3]?Number(o[3]):X0[(o[1]??"http").toLowerCase()];return n?{host:xw(o[2].replace(/^\[|\]$/g,"").replace(/%.*$/,"").replace(/\.$/,"").toLowerCase()),port:n,path:o[4]}:null}function xw(e){let t=e.includes(":");if(!t&&!/^[0-9a-fx.]+$/.test(e))return e;let o;try{o=new URL(`http://${t?`[${e}]`:e}/`).hostname.replace(/^\[|\]$/g,"")}catch{return e}let n=o.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);if(!n)return o;let[s,r]=[parseInt(n[1],16),parseInt(n[2],16)];return`::ffff:${s>>8}.${s&255}.${r>>8}.${r&255}`}function Q0(e,t){let o=e.replace(/^::ffff:/,"");return t.has(e)||t.has(o)||e===""||e.endsWith(".localhost")||/^127\.\d+\.\d+\.\d+$/.test(o)||o==="0.0.0.0"}function Nl(e,t,o=K0()){let n=[e,...Object.values(e?.Foreground??{})],s=[];for(let c of n){s.push({label:"",cfg:c});for(let[l,g]of Object.entries(c?.Services??{}))s.push({label:`${l} `,cfg:g})}let r=new Set(o);for(let{cfg:c}of s){for(let l of Object.keys(c?.Web??{}))r.add(l.replace(/:\d+$/,"").replace(/\.$/,"").toLowerCase());for(let l of Object.values(c?.TCP??{}))l?.TerminateTLS&&r.add(String(l.TerminateTLS).replace(/\.$/,"").toLowerCase())}let i=c=>{let l=V0(c.trim());return l&&l.port===t&&Q0(l.host,r)?l:null},a=[];for(let{label:c,cfg:l}of s){for(let[g,d]of Object.entries(l?.Web??{}))for(let[f,p]of Object.entries(d?.Handlers??{})){if(p?.Proxy==null)continue;let u=i(String(p.Proxy));if(!u)continue;let h=f.replace(/\/+$/,"")||"/",w=h===$w&&u.path===$w;!Y0.has(h)&&!w&&a.push(`${c}${g}${f}`)}for(let[g,d]of Object.entries(l?.TCP??{}))d?.TCPForward==null||!i(String(d.TCPForward))||a.push(`${c}TCP port ${g}`)}return a}function jl(){try{return JSON.parse(kw("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function vr(){try{return T().dashboard.port||4202}catch{return 4202}}ne();import{Command as uo}from"commander";import y from"chalk";import at from"prompts";import{readFileSync as Bo,writeFileSync as As,existsSync as Je,mkdirSync as go,cpSync as Pl,readdirSync as Z0}from"fs";import{resolve as ie,join as Wo,dirname as eS}from"path";import{fileURLToPath as tS}from"url";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(Bo(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 So=new uo().name("agent").description("manage agents \u2014 add, list, remove, pause, resume");So.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()});So.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:Wo(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(eS(tS(import.meta.url)),"../wiki/SKILL.md"),c=Je(i)?i:a;Je(c)&&(go(ie(o,".claude/skills/wiki"),{recursive:!0}),Pl(c,ie(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await ft(e),console.log(y.green(`
65
65
  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=gi(ko(),[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()});So.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),Sc(ko(),e),console.log(y.green(` Agent "${e}" removed from config (workspace preserved)`))});function Sw(e){let t=di();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}So.command("pause <id>").description("pause an agent: it starts no run until resumed (applies at once)").action(e=>{if(Sw("pause an agent")){if(!Re().agents?.[e]){console.log(y.red(` Agent "${e}" not found`)),process.exitCode=1;return}if(xc(ko())[e]?.kind==="approval"){console.log(y.yellow(` "${e}" waits for your approval and does not run yet: agentx approvals list`));return}hu(ko(),e,"paused","the owner"),console.log(y.green(` "${e}" paused. Messages and schedules for it are refused until you run: agentx agent resume ${e}`))}});So.command("resume <id>").description("resume a paused agent").action(e=>{if(!Sw("resume an agent"))return;let t=xc(ko())[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(Sc(ko(),e,"paused")?y.green(` "${e}" resumed`):y.dim(` "${e}" was not paused`))});So.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 xr=new uo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");xr.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(`
66
66
  ${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
67
- `));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()});xr.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-GPCTV4AD.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`))});xr.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}`))});xr.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)});So.addCommand(xr);var oa=new uo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");oa.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()});oa.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 Es=new uo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Es.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()});Es.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())});Es.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`))});Es.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 Aw=e=>{let t=e||"";if(!t)try{t=T().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function na(e,t,o={}){let n=Aw(),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 kn=Dt.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");kn.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-Z332LOTO.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||Aw()).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()});kn.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(`
67
+ `));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()});xr.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-WBW2WCS2.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`))});xr.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}`))});xr.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)});So.addCommand(xr);var oa=new uo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");oa.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()});oa.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 Es=new uo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Es.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()});Es.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())});Es.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`))});Es.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 Aw=e=>{let t=e||"";if(!t)try{t=T().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function na(e,t,o={}){let n=Aw(),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 kn=Dt.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");kn.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-Z332LOTO.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||Aw()).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()});kn.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
68
  No guest grants. Open one: agentx mesh guests invite --name \u2026 --guest \u2026 --agent \u2026
69
69
  `));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()});kn.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"}
70
70
  skills: ${n.skills.join(", ")||"none"}
@@ -75,7 +75,7 @@ Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choos
75
75
  Not a guest anywhere. Join with: agentx mesh join <url> --code \u2026 --name \u2026
76
76
  `));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(`
77
77
  ${r.content}
78
- `)});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 vn=new uo().name("skill").description("manage skills \u2014 add to agent(s), list");vn.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(Wo(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=ps(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(Wo(n,"SKILL.md"))?Pl(n,l,{recursive:!0}):n.endsWith(".md")&&Pl(n,Wo(l,"SKILL.md")),console.log(y.green(` ${s} -> ${i} (${a.workspace})`))}console.log()});vn.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(!ps(o.tier,o.workspace)){console.log(` ${y.cyan(t)}: ${y.dim(`(${o.tier} does not use skills)`)}`);continue}let n=fs(o.tier,o.workspace).map(s=>s.name);console.log(` ${y.cyan(t)}: ${n.length?n.join(", "):y.dim("(none)")}`)}console.log()});vn.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=Bo(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=ps($.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=fs($.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}),As(k,i)),console.log(` ${y.green("+")} ${b.padEnd(22)} ${y.dim("\u2192 seeded v"+c)}`),f++;continue}let A=Bo(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||As(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()});vn.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)});vn.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-BDZ44G5B.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(`
78
+ `)});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 vn=new uo().name("skill").description("manage skills \u2014 add to agent(s), list");vn.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(Wo(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=ps(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(Wo(n,"SKILL.md"))?Pl(n,l,{recursive:!0}):n.endsWith(".md")&&Pl(n,Wo(l,"SKILL.md")),console.log(y.green(` ${s} -> ${i} (${a.workspace})`))}console.log()});vn.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(!ps(o.tier,o.workspace)){console.log(` ${y.cyan(t)}: ${y.dim(`(${o.tier} does not use skills)`)}`);continue}let n=fs(o.tier,o.workspace).map(s=>s.name);console.log(` ${y.cyan(t)}: ${n.length?n.join(", "):y.dim("(none)")}`)}console.log()});vn.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=Bo(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=ps($.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=fs($.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}),As(k,i)),console.log(` ${y.green("+")} ${b.padEnd(22)} ${y.dim("\u2192 seeded v"+c)}`),f++;continue}let A=Bo(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||As(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()});vn.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)});vn.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-3QH2DHIN.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
79
  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(`
80
80
  (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Sr=new uo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Sr.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=Z0(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let f=Wo(r,d);if(Je(f)&&!t.force){console.log(y.dim(` skip ${f} (exists; --force to overwrite)`)),l++;continue}let u=Bo(Wo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);As(f,u),console.log(y.green(` + ${f}`)),c++}let g=Wo(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=Bo(s,"utf-8").replaceAll("example.",`${e}.`);As(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()});Sr.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(`
81
81
  --- ${h} ---`)),console.log(w.split(`
@@ -84,7 +84,7 @@ ${r.content}
84
84
  `).length>30&&console.log(y.dim(` \u2026 (${w.split(`
85
85
  `).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=Wo(f,h);if(Je(b)&&!t.force){console.log(y.dim(` skip ${b} (exists; --force to overwrite)`)),u++;continue}As(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()});Sr.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 Dl=new uo().name("hook").description("manage hooks \u2014 add to agent workspace");Dl.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(Bo(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}),As(n,JSON.stringify(s,null,2)),console.log(y.green(` Hook added to ${e}: ${r.event} -> ${r.type}`)),console.log()});var Ml=new uo().name("migrate").description("import configuration from OpenClaw or other tools");Ml.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(Bo(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(Bo(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(`
86
86
  Dry run \u2014 nothing written`)),console.log(JSON.stringify(r,null,2))):(await ft(r),console.log(y.green(`
87
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Jo=new uo().name("config").description("validate and inspect configuration");Jo.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=ai(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=fs(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()});Jo.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 oS(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 _l(e){return e===void 0?y.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Jo.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-G2MEPNGH.js"),{expandEnvVars:i}=await import("./config-GPCTV4AD.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(_l(g))});Jo.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-G2MEPNGH.js"),i=oS(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: ${_l(c)}`)):(console.log(y.green(` \u2713 ${y.cyan(e)} = ${_l(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})`)))});Jo.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-G2MEPNGH.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.")))});Jo.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()});es();import{Command as nS}from"commander";import Ho from"chalk";import{resolve as Go}from"path";import{existsSync as sS}from"fs";var Ao=new nS().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function xn(e){let t=Go(e,".agentx/db.sqlite");sS(t)||(console.log(Ho.red(` No SQLite at ${t}`)),console.log(Ho.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=bt({path:t});return o||(console.log(Ho.red(` Could not open ${t}`)),console.log(Ho.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function Sn(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Ho.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])))}Ao.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=xn(Go(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=`
87
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Jo=new uo().name("config").description("validate and inspect configuration");Jo.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=ai(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=fs(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()});Jo.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 oS(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 _l(e){return e===void 0?y.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Jo.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-GOYUMGWG.js"),{expandEnvVars:i}=await import("./config-WBW2WCS2.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(_l(g))});Jo.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-GOYUMGWG.js"),i=oS(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: ${_l(c)}`)):(console.log(y.green(` \u2713 ${y.cyan(e)} = ${_l(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})`)))});Jo.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-GOYUMGWG.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.")))});Jo.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()});es();import{Command as nS}from"commander";import Ho from"chalk";import{resolve as Go}from"path";import{existsSync as sS}from"fs";var Ao=new nS().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function xn(e){let t=Go(e,".agentx/db.sqlite");sS(t)||(console.log(Ho.red(` No SQLite at ${t}`)),console.log(Ho.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=bt({path:t});return o||(console.log(Ho.red(` Could not open ${t}`)),console.log(Ho.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function Sn(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Ho.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])))}Ao.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=xn(Go(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
88
  SELECT agent_id, channel, status, duration_ms,
89
89
  input_tokens, output_tokens,
90
90
  substr(message_preview, 1, 60) AS message,
@@ -513,7 +513,7 @@ return aid ?? null`}function UE(e,t){if(e.kind==="path"){let s=e.pts,r=s[Math.fl
513
513
  `).map(s=>` ${s}`).join(`
514
514
  `):" not written yet"),n.builders){console.log(H.dim(`
515
515
  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}`)}}});Pr(_n.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 Pn(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}`))});Pr(_n.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 Pn(t,"POST","/api/signals/drop",{id:e,node:t.peer});console.log(H.green(` dropped ${o.agentId} task ${o.id}`))});ne();import{Command as UR}from"commander";import ht from"chalk";var Na=new UR().name("review-gate").description("independent pre-merge review of agent PRs against their linked issue");function WR(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 bb(e,t,o,n){let{baseUrl:s,headers:r}=WR(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 $b=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)"),kb=e=>e==="success"?ht.green(e):e==="failure"?ht.red(e):ht.yellow(e);$b(Na.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 bb(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)} ${kb(s.state)} ${ht.dim(s.reason)}${s.replay?ht.dim(" (replay)"):""}`)});$b(Na.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 bb(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(`
516
- `))>=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} ${kb(d.state)}${d.flagged?ht.red(" flagged"):""} ${ht.dim(d.reason)}`)}if(a)break}});import{Command as BR}from"commander";import ut from"chalk";import{existsSync as bd,rmSync as JR}from"fs";import{resolve as $d}from"path";var Ds=new BR().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Ds.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}`))});Ds.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=$d(e.cwd,".agentx","rag");if(!bd(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=>bd($d(t,s,"index.json")));if(n.length===0){console.log(ut.dim(" (no indexes)"));return}for(let s of n.sort()){let r=Ac(s);console.log(` ${ut.bold(s)} ${r.docs} doc(s) ${ut.dim(r.path)}`)}});Ds.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=ku(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let r=Ac(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))}`)});Ds.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=$d(process.cwd(),".agentx","rag",e);if(!bd(t)){console.log(ut.dim(` no index for ${e} \u2014 nothing to clear`));return}JR(t,{recursive:!0,force:!0}),console.log(ut.green(` \u2713 cleared index for ${e}`))});ne();import{Command as HR}from"commander";import pe from"chalk";import Ms from"prompts";var Dn=new HR().name("backlog").description("manage the local backlog used by business workSource=backlog");function _r(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 qp(n)}}function GR(e){return e?pe.cyan(`${e.type}:${e.project}#${e.iid}`):pe.dim("manual")}function zR(e){return{todo:pe.gray("todo"),doing:pe.yellow("doing"),blocked:pe.red("blocked"),done:pe.green("done")}[e]}Dn.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}=_r(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(` ${zR(n.status).padEnd(7)} ${GR(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()}`))});Dn.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=_r(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=rp([t],r.source,n.config),a=await Wc(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}`))}});Dn.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=_r(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 Wc(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}`))}});Dn.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}=_r(t.config);o.remove(e)||(console.error(pe.red(` item ${e} not found`)),process.exit(1)),console.log(pe.green(` removed ${e}`))});Dn.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=_r(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 Ms({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"?KR(t.config):XR(t.config);w.length?(r=(await Ms({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 Ms({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):r=(await Ms({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!r)return;let a=((await Ms({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 VR(t.config,r,a):await QR(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=Vc({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 Ms({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"?YR(t.config):void 0,project:l,iid:w.iid,url:w.url};return{id:Vc(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 YR(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function KR(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 XR(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 VR(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 QR(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(vb)}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(vb):[]}function vb(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 ZR}from"commander";import X from"chalk";import{existsSync as eT,readFileSync as tT}from"fs";import{resolve as oT}from"path";import nT from"prompts";ne();function xb(e){let t=e||oT(process.cwd(),"agentx.json");return eT(t)||(console.log(X.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(tT(t,"utf-8"))}async function sT(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 nT([{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 Eo=new ZR().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Eo.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: ${ir})`,ir).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){Eo.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=Cc(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=xb(t.config),s=nr(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 sT(t.notify,s),i=t.id||qu(o.matched,t.agent),a=Uu({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:Fu(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} ${Oc(a)}`)),c.length&&console.log(X.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(X.dim(" Daemon hot-reloaded."))});Eo.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=xb(e.config).crons||{},n=Object.entries(o),s=new Set;try{let{loadDaemonConfig:r}=await import("./config-GPCTV4AD.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} ${Oc(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=Bu(Wu(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]])Eo.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await Gu(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."))});Eo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await de(o=>{if(!cs(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);Su(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",Ju,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Hu,"reject an agent's pending create/delete request (drops the request)"]])Eo.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."))});Eo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=Cc(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 ST}from"commander";import Lb from"chalk";import{existsSync as AT,readFileSync as ET}from"fs";import{resolve as Fb}from"path";import{existsSync as rT,readFileSync as iT,writeFileSync as aT}from"fs";import{join as xd}from"path";var kd="leads.md",Sb="opt-outs.md",Ab=864e5,vd=/\d{4}-\d{2}-\d{2}/;function cT(e){return e.split(`
516
+ `))>=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} ${kb(d.state)}${d.flagged?ht.red(" flagged"):""} ${ht.dim(d.reason)}`)}if(a)break}});import{Command as BR}from"commander";import ut from"chalk";import{existsSync as bd,rmSync as JR}from"fs";import{resolve as $d}from"path";var Ds=new BR().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Ds.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}`))});Ds.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let t=$d(e.cwd,".agentx","rag");if(!bd(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=>bd($d(t,s,"index.json")));if(n.length===0){console.log(ut.dim(" (no indexes)"));return}for(let s of n.sort()){let r=Ac(s);console.log(` ${ut.bold(s)} ${r.docs} doc(s) ${ut.dim(r.path)}`)}});Ds.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=ku(e,t,{k:n});if(o.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let r=Ac(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))}`)});Ds.command("clear <agentId>").description("delete an agent's index").action(e=>{let t=$d(process.cwd(),".agentx","rag",e);if(!bd(t)){console.log(ut.dim(` no index for ${e} \u2014 nothing to clear`));return}JR(t,{recursive:!0,force:!0}),console.log(ut.green(` \u2713 cleared index for ${e}`))});ne();import{Command as HR}from"commander";import pe from"chalk";import Ms from"prompts";var Dn=new HR().name("backlog").description("manage the local backlog used by business workSource=backlog");function _r(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 qp(n)}}function GR(e){return e?pe.cyan(`${e.type}:${e.project}#${e.iid}`):pe.dim("manual")}function zR(e){return{todo:pe.gray("todo"),doing:pe.yellow("doing"),blocked:pe.red("blocked"),done:pe.green("done")}[e]}Dn.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}=_r(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(` ${zR(n.status).padEnd(7)} ${GR(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()}`))});Dn.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=_r(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=rp([t],r.source,n.config),a=await Wc(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}`))}});Dn.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=_r(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 Wc(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}`))}});Dn.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}=_r(t.config);o.remove(e)||(console.error(pe.red(` item ${e} not found`)),process.exit(1)),console.log(pe.green(` removed ${e}`))});Dn.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=_r(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 Ms({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"?KR(t.config):XR(t.config);w.length?(r=(await Ms({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 Ms({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):r=(await Ms({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!r)return;let a=((await Ms({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 VR(t.config,r,a):await QR(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=Vc({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 Ms({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"?YR(t.config):void 0,project:l,iid:w.iid,url:w.url};return{id:Vc(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 YR(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function KR(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 XR(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 VR(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 QR(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(vb)}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(vb):[]}function vb(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 ZR}from"commander";import X from"chalk";import{existsSync as eT,readFileSync as tT}from"fs";import{resolve as oT}from"path";import nT from"prompts";ne();function xb(e){let t=e||oT(process.cwd(),"agentx.json");return eT(t)||(console.log(X.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(tT(t,"utf-8"))}async function sT(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 nT([{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 Eo=new ZR().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Eo.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: ${ir})`,ir).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){Eo.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=Cc(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=xb(t.config),s=nr(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 sT(t.notify,s),i=t.id||qu(o.matched,t.agent),a=Uu({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:Fu(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} ${Oc(a)}`)),c.length&&console.log(X.dim(` On error: ${c.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(X.dim(" Daemon hot-reloaded."))});Eo.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=xb(e.config).crons||{},n=Object.entries(o),s=new Set;try{let{loadDaemonConfig:r}=await import("./config-WBW2WCS2.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} ${Oc(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=Bu(Wu(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]])Eo.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await Gu(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."))});Eo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await de(o=>{if(!cs(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);Su(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",Ju,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Hu,"reject an agent's pending create/delete request (drops the request)"]])Eo.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."))});Eo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=Cc(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 ST}from"commander";import Lb from"chalk";import{existsSync as AT,readFileSync as ET}from"fs";import{resolve as Fb}from"path";import{existsSync as rT,readFileSync as iT,writeFileSync as aT}from"fs";import{join as xd}from"path";var kd="leads.md",Sb="opt-outs.md",Ab=864e5,vd=/\d{4}-\d{2}-\d{2}/;function cT(e){return e.split(`
517
517
  `).map(t=>t.trim()).filter(t=>/^[-*]\s+\S/.test(t)).map(t=>t.replace(/^[-*]\s+/,"").split("|").map(o=>o.trim()))}function lT(e){return e.split(`
518
518
  `).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(vd)?.[0]:a.startsWith("added")?r.added=i.match(vd)?.[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 Eb(e){return cT(e).map(([t="",o="",n,s])=>({name:t,company:o,date:n?.match(vd)?.[0],reason:s||void 0})).filter(t=>t.name)}var ja=e=>e.trim().toLowerCase().replace(/\s+/g," ");function Dr(e,t){return t.some(o=>ja(o.name)===ja(e.name)&&(!o.company||ja(o.company)===ja(e.company)))}var dT=e=>/^done\b/i.test(e.next??""),Ls=e=>Date.parse(`${e}T00:00:00Z`);function Rb(e,t,o,n=7){let s=Ls(o)-n*Ab;return e.filter(r=>{if(dT(r)||Dr(r,t))return!1;let i=r.lastContact??r.added;return!i||Ls(i)<=s})}function Tb(e,t,o,n=1){let s=Ls(o)-(n-1)*Ab;return e.filter(r=>r.added&&Ls(r.added)>=s&&Ls(r.added)<=Ls(o)&&!Dr(r,t))}function Sd(e){return rT(e)?iT(e,"utf-8"):""}function Cb(e){return lT(Sd(xd(e,kd)))}function Ob(e){return Eb(Sd(xd(e,Sb)))}var gT=`# Opt-outs
519
519
 
@@ -550,7 +550,7 @@ People who asked not to be contacted. The sales agent never drafts a message to
550
550
  Plan ${P.dim(`[${r.state}] by ${r.createdBy}, ${qn(r.createdAt)}`)}`),i$(s.steps(e)),console.log(`
551
551
  Log`);for(let i of s.events(e))console.log(P.dim(` ${qn(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});en.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=Mr();if(!s)return;let r=Ma();if(!r){process.exitCode=1;return}let i=Number(t),a=Vm(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)")),i$(r.steps(e))});function a$(e,t,o,n){let s=en.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=Mr();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 (${Dd[l.state]??l.state})`)),process.exitCode=1;return}console.log(P.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}a$("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>");a$("drop","drop a request you no longer want","--reason <text>","");en.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 (${ni.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=>!ni.includes(h));if(u.length)throw new Error(`unknown check ${u.join(", ")}: use ${ni.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 Dm(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=Ei();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??Ci;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??Ci.requireOverMinutes,i=s.requireForWork??Ci.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??si;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 tC}from"commander";import Us from"chalk";ne();var c$=new tC("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",nl.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(Us.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await de(r=>{n=wf(r,e,t==="on")});s.success||(console.error(Us.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(Us.green(`\u2713 ${n}`)),s.reloaded&&console.log(Us.dim(" daemon hot-reloaded"))}let o=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of nl)console.log(` ${n.padEnd(8)} ${o.includes(n)?Us.green("on"):Us.dim("off")}`)});import{Command as OC}from"commander";import Ws from"chalk";import we from"chalk";import Lr from"prompts";import{readFileSync as oC,writeFileSync as nC,existsSync as sC}from"fs";import{resolve as l$}from"path";var rC=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function iC(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Ld(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function d$(e=".env"){let t=l$(e);if(!sC(t))return[];let o=oC(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(rC);r?n.push({kind:"kv",key:r[1],value:iC(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function aC(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Ld(t.value)}`:t.raw).join(`
552
552
  `)+`
553
- `}function Fn(e,t,o=".env"){let n=l$(o),s=d$(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Ld(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Ld(t)}`})),nC(n,aC(s))}function qd(e,t=".env"){return d$(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var g$="https://t.me/BotFather";async function cC(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 lC(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 u$(e={}){console.log(),console.log(we.bold(" Connect Telegram")),console.log(),console.log(we.dim(` 1. Open ${g$}`)),console.log(we.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(we.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Lr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&xo(g$);let{token:o}=await Lr({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(we.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await cC(o.trim());n||(console.log(we.red("\u2717 invalid or revoked")),process.exit(1)),console.log(we.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(we.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(we.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Lr({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(we.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await Lr({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(we.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Fn(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=cs(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(we.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(we.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(we.dim(` Token stored in .env as ${p}`)),console.log(we.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(we.dim(" Daemon hot-reloaded.")):console.log(we.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Lr({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(we.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(we.dim(" Waiting up to 90s..."));let w=await lC(o.trim(),9e4);if(!w){console.log(we.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(we.dim(" agentx config set notifications.destination.channel telegram")),console.log(we.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(we.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),$=Xi(S,b)},{configPath:e.configPath});if(!v.success){console.log(we.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(we.green(" \u2713 Default --notify target set")),console.log(we.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(we.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(we.dim(` Schedules that now report here: ${$.join(", ")}`)),v.reloaded&&console.log(we.dim(" Daemon hot-reloaded."))}import je from"chalk";import Fd from"prompts";import{existsSync as Wd,mkdirSync as dC,readdirSync as gC,readFileSync as m$}from"fs";import{resolve as Ud}from"path";var uC=".agentx/whatsapp-sessions";function mC(){let e=Ud(process.cwd(),".agentx/daemon.pid");if(!Wd(e))return!1;try{let t=parseInt(m$(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function pC(e){if(!Wd(e))return!1;try{return gC(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function fC(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(je.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(je.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;dC(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(je.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(je.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(je.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(je.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function p$(e={}){if(console.log(),console.log(je.bold(" Connect WhatsApp")),console.log(),mC()){console.log(je.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(je.dim(" agentx daemon stop")),console.log();let{cont:l}=await Fd({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(je.red(" Aborted")),process.exit(1))}let t=e.configPath||Ud(process.cwd(),"agentx.json");Wd(t)||(console.log(je.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(m$(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||uC,s=Ud(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(je.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Fd({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(je.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(pC(s)&&a){let{keep:l}=await Fd({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(je.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await fC(s,g=>console.log(g))||(console.log(je.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(je.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(je.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(je.dim(` Session: ${n}`)),console.log(je.dim(" Start the daemon to begin receiving:")),console.log(je.dim(" agentx daemon start")),console.log(je.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(je.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(je.dim(" Add routes later with:")),console.log(je.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import At from"chalk";import hC from"prompts";import{existsSync as wC,readFileSync as yC}from"fs";import{resolve as bC}from"path";async function $C(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 kC(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 Co(e){console.log(At.red(` ${e}`)),process.exit(1)}async function Un(e){return(await hC(e,{onCancel:()=>Co("Aborted")}))[e.name]}async function f$(e={}){console.log(),console.log(At.bold(" Connect email")),console.log();let t=e.configPath||bC(process.cwd(),"agentx.json");wC(t)||Co(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(yC(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Co("No agents configured. Run: agentx agent add");let s=e.agent??await Un({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(b=>({title:b,value:b}))});o.agents?.[s]||Co(`No agent "${s}" in ${t}`);let r=(e.address??await Un({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 Un({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await Un({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),g=e.smtpHost??a?.smtpHost??await Un({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await Un({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Co("Ports must be numbers.");let f=e.passwordEnv||kf(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&Co(`${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: ${yf}`)),console.log(At.dim(" (2-step verification must be on for that page to show.)"))),p=(await Un({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||Co("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 $C(u,p);b&&(console.log(At.red("\u2717")),Co(b)),console.log(At.green("\u2713"))}e.passwordEnv||(Fn(f,p),process.env[f]=p);let h=await de(b=>{qe(b,"channels.email.enabled",!0),qe(b,`channels.email.accounts.${i}`,$f(u))},{configPath:e.configPath});h.success||Co(`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=kC(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 vC}from"crypto";import ze from"chalk";import h$ from"prompts";var La="agentx-mesh:",qa="//join/";function xC(e){return Buffer.from(e,"utf-8").toString("base64url")}function SC(e){return Buffer.from(e,"base64url").toString("utf-8")}function AC(e){return`${La}${qa}${xC(JSON.stringify(e))}`}function EC(e){if(!e.startsWith(`${La}${qa}`))throw new Error(`Not a mesh invite link \u2014 expected ${La}${qa}\u2026`);let t=e.slice(La.length+qa.length),o=JSON.parse(SC(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 RC(){return vC(32).toString("hex")}function TC(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function CC(e){return e?.node?.name||e?.node?.id||"node"}async function w$(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=qd("MESH_TOKEN");i||(i=RC(),Fn("MESH_TOKEN",i),console.log(ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||TC(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await h$({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=AC({url:a,token:i,name:CC(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 y$(e,t={}){let o;try{o=EC(e)}catch(r){console.log(ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=qd("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await h$({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))}Fn("MESH_TOKEN",o.token);let s=await de(r=>{qe(r,"mesh.enabled",!0);let i=cs(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 Wn=new OC().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Wn.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 u$({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Wn.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 p$({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});Wn.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 f$({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 b$=Wn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");b$.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 w$({url:e.url,configPath:e.config})});b$.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 y$(e,{configPath:t.config})});Wn.action(()=>{console.log(),console.log(Ws.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ws.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ws.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ws.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ws.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ws.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as IC}from"commander";import se from"chalk";var Bn=new IC().name("usage").description("token usage analysis and reporting");Bn.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}`))}});Bn.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}`))}});Bn.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?"))}});Bn.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()});Bn.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-5CHM6EPW.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 NC}from"commander";import We from"chalk";import{readFileSync as jC}from"fs";import{resolve as PC}from"path";ne();var tn=new NC().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");tn.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{ru(PC(process.cwd(),".env"))}catch{}let t=_C(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-6VWNYJZ7.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 _C(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.
553
+ `}function Fn(e,t,o=".env"){let n=l$(o),s=d$(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Ld(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Ld(t)}`})),nC(n,aC(s))}function qd(e,t=".env"){return d$(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var g$="https://t.me/BotFather";async function cC(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 lC(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 u$(e={}){console.log(),console.log(we.bold(" Connect Telegram")),console.log(),console.log(we.dim(` 1. Open ${g$}`)),console.log(we.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(we.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Lr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&xo(g$);let{token:o}=await Lr({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(we.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await cC(o.trim());n||(console.log(we.red("\u2717 invalid or revoked")),process.exit(1)),console.log(we.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(we.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(we.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Lr({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(we.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await Lr({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(we.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Fn(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=cs(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(we.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(we.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(we.dim(` Token stored in .env as ${p}`)),console.log(we.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(we.dim(" Daemon hot-reloaded.")):console.log(we.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Lr({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(we.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(we.dim(" Waiting up to 90s..."));let w=await lC(o.trim(),9e4);if(!w){console.log(we.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(we.dim(" agentx config set notifications.destination.channel telegram")),console.log(we.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(we.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),$=Xi(S,b)},{configPath:e.configPath});if(!v.success){console.log(we.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(we.green(" \u2713 Default --notify target set")),console.log(we.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(we.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(we.dim(` Schedules that now report here: ${$.join(", ")}`)),v.reloaded&&console.log(we.dim(" Daemon hot-reloaded."))}import je from"chalk";import Fd from"prompts";import{existsSync as Wd,mkdirSync as dC,readdirSync as gC,readFileSync as m$}from"fs";import{resolve as Ud}from"path";var uC=".agentx/whatsapp-sessions";function mC(){let e=Ud(process.cwd(),".agentx/daemon.pid");if(!Wd(e))return!1;try{let t=parseInt(m$(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function pC(e){if(!Wd(e))return!1;try{return gC(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function fC(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(je.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(je.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;dC(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(je.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(je.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(je.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(je.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function p$(e={}){if(console.log(),console.log(je.bold(" Connect WhatsApp")),console.log(),mC()){console.log(je.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(je.dim(" agentx daemon stop")),console.log();let{cont:l}=await Fd({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(je.red(" Aborted")),process.exit(1))}let t=e.configPath||Ud(process.cwd(),"agentx.json");Wd(t)||(console.log(je.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(m$(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||uC,s=Ud(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(je.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Fd({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(je.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(pC(s)&&a){let{keep:l}=await Fd({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(je.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await fC(s,g=>console.log(g))||(console.log(je.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(je.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(je.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(je.dim(` Session: ${n}`)),console.log(je.dim(" Start the daemon to begin receiving:")),console.log(je.dim(" agentx daemon start")),console.log(je.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(je.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(je.dim(" Add routes later with:")),console.log(je.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import At from"chalk";import hC from"prompts";import{existsSync as wC,readFileSync as yC}from"fs";import{resolve as bC}from"path";async function $C(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 kC(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 Co(e){console.log(At.red(` ${e}`)),process.exit(1)}async function Un(e){return(await hC(e,{onCancel:()=>Co("Aborted")}))[e.name]}async function f$(e={}){console.log(),console.log(At.bold(" Connect email")),console.log();let t=e.configPath||bC(process.cwd(),"agentx.json");wC(t)||Co(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(yC(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Co("No agents configured. Run: agentx agent add");let s=e.agent??await Un({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(b=>({title:b,value:b}))});o.agents?.[s]||Co(`No agent "${s}" in ${t}`);let r=(e.address??await Un({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 Un({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await Un({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),g=e.smtpHost??a?.smtpHost??await Un({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await Un({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Co("Ports must be numbers.");let f=e.passwordEnv||kf(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&Co(`${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: ${yf}`)),console.log(At.dim(" (2-step verification must be on for that page to show.)"))),p=(await Un({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||Co("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 $C(u,p);b&&(console.log(At.red("\u2717")),Co(b)),console.log(At.green("\u2713"))}e.passwordEnv||(Fn(f,p),process.env[f]=p);let h=await de(b=>{qe(b,"channels.email.enabled",!0),qe(b,`channels.email.accounts.${i}`,$f(u))},{configPath:e.configPath});h.success||Co(`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=kC(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 vC}from"crypto";import ze from"chalk";import h$ from"prompts";var La="agentx-mesh:",qa="//join/";function xC(e){return Buffer.from(e,"utf-8").toString("base64url")}function SC(e){return Buffer.from(e,"base64url").toString("utf-8")}function AC(e){return`${La}${qa}${xC(JSON.stringify(e))}`}function EC(e){if(!e.startsWith(`${La}${qa}`))throw new Error(`Not a mesh invite link \u2014 expected ${La}${qa}\u2026`);let t=e.slice(La.length+qa.length),o=JSON.parse(SC(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 RC(){return vC(32).toString("hex")}function TC(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function CC(e){return e?.node?.name||e?.node?.id||"node"}async function w$(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=qd("MESH_TOKEN");i||(i=RC(),Fn("MESH_TOKEN",i),console.log(ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||TC(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await h$({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=AC({url:a,token:i,name:CC(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 y$(e,t={}){let o;try{o=EC(e)}catch(r){console.log(ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=qd("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await h$({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))}Fn("MESH_TOKEN",o.token);let s=await de(r=>{qe(r,"mesh.enabled",!0);let i=cs(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 Wn=new OC().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Wn.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 u$({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Wn.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 p$({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});Wn.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 f$({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 b$=Wn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");b$.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 w$({url:e.url,configPath:e.config})});b$.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 y$(e,{configPath:t.config})});Wn.action(()=>{console.log(),console.log(Ws.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ws.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ws.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ws.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ws.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ws.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as IC}from"commander";import se from"chalk";var Bn=new IC().name("usage").description("token usage analysis and reporting");Bn.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}`))}});Bn.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}`))}});Bn.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?"))}});Bn.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()});Bn.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-MDS4XDAY.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 NC}from"commander";import We from"chalk";import{readFileSync as jC}from"fs";import{resolve as PC}from"path";ne();var tn=new NC().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");tn.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{ru(PC(process.cwd(),".env"))}catch{}let t=_C(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-ORELMK25.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 _C(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
554
  `)),{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}}}}tn.command("list").description("list configured boards").action(()=>{try{let e=T();if(!e.boards?.length){console.log(We.dim(`
555
555
  No boards configured.
556
556
  `));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)}});tn.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{qr(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(r=>r.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(r=>r.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(We.red(` ${o.message}`)),process.exit(1)}});tn.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,t)=>{try{qr(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=[];if(t.name&&(s.name=t.name,r.push(`name="${t.name}"`)),t.projects){let i=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(i.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:i},r.push(`projects=${i.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,r.push("label cleared")):(s.primaryToolLabel=t.label,r.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,r.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,r.push(`closed-days=${s.closedWindowDays}`)),r.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${r.join(", ")})`})}catch(o){console.log(We.red(` ${o.message}`)),process.exit(1)}});var Bd=tn.command("column").description("manage a board's columns (add / remove / edit / list)");Bd.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(jC("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)}});Bd.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,t,o)=>{try{qr(n=>{let r=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!r)throw new Error(`board "${e}" not found`);if(r.columns=r.columns||[],r.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let i={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");i.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");i.mapsToLabel=o.label}return o.accent&&(i.accent=o.accent),r.columns.push(i),`column "${t}" added to board "${e}"`})}catch(n){console.log(We.red(` ${n.message}`)),process.exit(1)}});Bd.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{qr(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(i=>i.id!==t),s.columns.length===r)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(We.red(` ${o.message}`)),process.exit(1)}});tn.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{qr(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(We.red(` ${t.message}`)),process.exit(1)}});function qr(e){let{summary:t,backupPath:o}=jt(n=>e(n));console.log(We.green(`
@@ -580,19 +580,19 @@ An edit that breaks these rules is refused and the note is deferred.
580
580
 
581
581
  ${t}
582
582
  `}function x$(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=Fa(a.reason||"no reason given");if(a.outcome!=="patched")return{id:i.id,outcome:a.outcome,reason:c,patched:[]};let l=DC(a.edits,o,n.paths,n.agentId);if("refused"in l)return{id:i.id,outcome:"deferred",reason:Fa(`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??[],Hd(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:Fa(`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:Fa(`${c} (edited ${f.join(", ")})`),patched:f}})}function DC(e,t,o,n){if(e.length===0)return{refused:"patched with no edits"};if(e.length>Fr.edits)return{refused:`more than ${Fr.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>Fr.find||r.replace.length>Fr.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*Fr.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=[...MC(i.content,a),...UC(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 MC(e,t){let o=ur(e,t),n=ur(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 LC=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,qC=/(?<![\w@.])@[A-Za-z0-9_]{3,}/g,FC=/^\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 UC(e,t){let o=t.toLowerCase(),n=[];for(let s of e.matchAll(LC))o.includes(s[0].toLowerCase())||n.push(`email ${s[0]}`);for(let s of e.matchAll(qC))o.includes(s[0].toLowerCase())||n.push(`handle ${s[0]}`);for(let s of e.matchAll(FC)){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 Fa(e){return e.length>Ec.reason?`${e.slice(0,Ec.reason-1)}\u2026`:e}import He from"chalk";import{resolve as WC}from"path";var BC=e=>e||WC(process.cwd(),".agentx/wiki");async function Bs(e){let{FactLedger:t}=await import("./ledger-P62U3FHT.js");return new t(BC(e))}function Js(e){return async(...t)=>{try{await e(...t)}catch(o){o?.name!=="LedgerCorruptError"&&console.error(He.red(` ${o?.message??o}`)),process.exitCode=1}}}function S$(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(Js(async n=>{let{isStaleFact:s}=await import("./ledger-P62U3FHT.js"),r=(await Bs(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(Js(async(n,s)=>{let r=(await Bs(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: ${kc.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(Js(async n=>{if(n.class&&!uu(n.class)){console.error(He.red(` --class must be one of ${kc.join(", ")}`)),process.exitCode=1;return}let r=(await Bs(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(Js(async n=>{let{listFactProposals:s}=await import("./fact-proposals-X2O4W7VN.js"),r=s(await Bs(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(`
583
- 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(Js(async(n,s)=>{let{approveFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),{write:i}=r(await Bs(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(Js(async(n,s)=>{let{rejectFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),i=r(await Bs(s.dir),n,s.by,s.reason);console.log(He.dim(` rejected: ${i.claim}`))}))}import Ve from"chalk";import{existsSync as A$,readFileSync as E$}from"fs";import{resolve as zd}from"path";var Gd=e=>e||zd(process.cwd(),".agentx/wiki");function JC(e){if(e)return e.replace(/\/+$/,"");if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL.replace(/\/+$/,"");try{let t=zd(process.cwd(),"agentx.json");if(A$(t)){let o=JSON.parse(E$(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 ho(e){console.error(Ve.red(` ${e}`)),process.exitCode=1}function Ua(e){return async(...t)=>{try{await e(...t)}catch(o){ho(o?.message??String(o))}}}function R$(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(Ua(async o=>{if(!o.from){ho("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){ho("--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){ho(l.error);return}s={ok:!0,...new a(Gd(o.dir)).add(l.note)}}else{let a=JC(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){ho(`could not reach the daemon at ${a}: ${l?.message??l}`);return}if(s=await c.json().catch(()=>({})),!c.ok){ho(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(Ua(async o=>{let{NoteStore:n}=await import("./notes-WJJEJ4CJ.js"),s=["waiting","open","patched","rejected","deferred","expired","all"];if(!s.includes(o.status)){ho(`--status must be one of ${s.join(", ")}`);return}let r=new n(Gd(o.dir)),i=r.load();if(i.unreadable){ho(`${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(Ua(async(o,n)=>{let{NoteStore:s}=await import("./notes-WJJEJ4CJ.js"),r=new s(Gd(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(Ua(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){ho("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-S56W3EGU.js"),{summary:l}=c(g=>n(g,r));console.log(Ve.green(` ${l}`))}let i=zd(process.cwd(),"agentx.json");if(!A$(i)){ho(`agentx.json not found at ${i}`);return}let a=s(JSON.parse(E$(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 on from"chalk";import{resolve as HC}from"path";var Yd=e=>e||HC(process.cwd(),".agentx/wiki");function T$(e){let t=e.command("ontology").description("the wiki's pillars, types, typed relations and page lenses (show, init, check)");t.command("init").description("write the default ontology to ontology.yaml in the wiki, to edit").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{writeDefaultOntology:n}=await import("./load-LQ2I2PQI.js");try{let s=n(Yd(o.dir));console.log(on.green(` wrote ${s}`))}catch(s){console.error(on.red(` ${s.message}`)),process.exitCode=1}}),t.command("check").description("report problems in ontology.yaml").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{loadOntology:n}=await import("./load-LQ2I2PQI.js"),{file:s,errors:r}=n(Yd(o.dir));if(!s){console.log(on.dim(" no ontology.yaml: the built-in defaults are in use"));return}if(r.length===0){console.log(on.green(` ${s}: no problems`));return}console.log(on.yellow(` ${s}: ${r.length} problem(s)`));for(let i of r)console.log(` - ${i}`);process.exitCode=1}),t.command("show").description("pages per pillar and type, as the wiki view groups them").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--json","print JSON").action(async o=>{let{loadOntology:n}=await import("./load-LQ2I2PQI.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{WikiHub:r}=await import("./hub-WRXWDBUZ.js"),i=Yd(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(on.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)} ${on.dim(u.map(w=>`${w.id} ${f.get(w.id)??0}`).join(" \xB7 "))}`)}l.length&&console.log(on.yellow(` ontology.yaml has ${l.length} problem(s): agentx wiki ontology check`))})}import tt from"chalk";import{resolve as GC}from"path";var Kd=e=>e||GC(process.cwd(),".agentx/wiki"),zC=()=>new Date().toISOString().slice(0,10);async function Xd(e){let{WikiHub:t}=await import("./hub-WRXWDBUZ.js"),{GraphCache:o}=await import("./graph-ZVKV3JBD.js"),{loadOntology:n}=await import("./load-LQ2I2PQI.js"),{loadRoster:s}=await import("./roster-BZGKG2ZA.js"),r=new t(e,()=>{}),{ontology:i}=n(e),a=new o().get(r,i,s(e,r.listAgents([]),i.agent_names));return{hub:r,g:a}}function C$(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 O$(e){let t=e.command("events").description("give each event page an importance level (minor, normal, major) and the pages it is about").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--about <titles...>","only events linked to or naming these pages (a pilot)").option("--max <n>","most events per run","200").option("--batch <n>","events per model call","20").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","haiku").option("--rules-only","use only the importance rules in ontology.yaml; no model call").option("--force","redo events whose level this job set earlier").option("--dry-run","show what would be written, write nothing").option("--json","print the run as JSON").action(async o=>{let{runEvents:n,summariseAbout:s}=await import("./event-levels-NBOMTB23.js"),{claudeCall:r}=await import("./wiki-enrich-JS6WC6ER.js"),i=C$(o.max,"--max"),a=C$(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 Xd(Kd(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:zC()}),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-NBOMTB23.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 Xd(Kd(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 Xd(Kd(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 YC}from"path";var KC=e=>e||YC(process.cwd(),".agentx/wiki");function I$(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-WRXWDBUZ.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{loadOntology:r}=await import("./load-LQ2I2PQI.js"),{loadRoster:i}=await import("./roster-BZGKG2ZA.js"),{loadRulesState:a,ruleWordsPattern:c,runRules:l,saveRulesState:g}=await import("./rules-5ZZQZLQA.js"),d=KC(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,Df(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(`
583
+ 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(Js(async(n,s)=>{let{approveFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),{write:i}=r(await Bs(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(Js(async(n,s)=>{let{rejectFactProposal:r}=await import("./fact-proposals-X2O4W7VN.js"),i=r(await Bs(s.dir),n,s.by,s.reason);console.log(He.dim(` rejected: ${i.claim}`))}))}import Ve from"chalk";import{existsSync as A$,readFileSync as E$}from"fs";import{resolve as zd}from"path";var Gd=e=>e||zd(process.cwd(),".agentx/wiki");function JC(e){if(e)return e.replace(/\/+$/,"");if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL.replace(/\/+$/,"");try{let t=zd(process.cwd(),"agentx.json");if(A$(t)){let o=JSON.parse(E$(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 ho(e){console.error(Ve.red(` ${e}`)),process.exitCode=1}function Ua(e){return async(...t)=>{try{await e(...t)}catch(o){ho(o?.message??String(o))}}}function R$(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(Ua(async o=>{if(!o.from){ho("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){ho("--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){ho(l.error);return}s={ok:!0,...new a(Gd(o.dir)).add(l.note)}}else{let a=JC(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){ho(`could not reach the daemon at ${a}: ${l?.message??l}`);return}if(s=await c.json().catch(()=>({})),!c.ok){ho(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(Ua(async o=>{let{NoteStore:n}=await import("./notes-WJJEJ4CJ.js"),s=["waiting","open","patched","rejected","deferred","expired","all"];if(!s.includes(o.status)){ho(`--status must be one of ${s.join(", ")}`);return}let r=new n(Gd(o.dir)),i=r.load();if(i.unreadable){ho(`${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(Ua(async(o,n)=>{let{NoteStore:s}=await import("./notes-WJJEJ4CJ.js"),r=new s(Gd(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(Ua(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){ho("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-YJI2JEMP.js"),{summary:l}=c(g=>n(g,r));console.log(Ve.green(` ${l}`))}let i=zd(process.cwd(),"agentx.json");if(!A$(i)){ho(`agentx.json not found at ${i}`);return}let a=s(JSON.parse(E$(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 on from"chalk";import{resolve as HC}from"path";var Yd=e=>e||HC(process.cwd(),".agentx/wiki");function T$(e){let t=e.command("ontology").description("the wiki's pillars, types, typed relations and page lenses (show, init, check)");t.command("init").description("write the default ontology to ontology.yaml in the wiki, to edit").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{writeDefaultOntology:n}=await import("./load-LQ2I2PQI.js");try{let s=n(Yd(o.dir));console.log(on.green(` wrote ${s}`))}catch(s){console.error(on.red(` ${s.message}`)),process.exitCode=1}}),t.command("check").description("report problems in ontology.yaml").option("--dir <path>","wiki directory (default .agentx/wiki)").action(async o=>{let{loadOntology:n}=await import("./load-LQ2I2PQI.js"),{file:s,errors:r}=n(Yd(o.dir));if(!s){console.log(on.dim(" no ontology.yaml: the built-in defaults are in use"));return}if(r.length===0){console.log(on.green(` ${s}: no problems`));return}console.log(on.yellow(` ${s}: ${r.length} problem(s)`));for(let i of r)console.log(` - ${i}`);process.exitCode=1}),t.command("show").description("pages per pillar and type, as the wiki view groups them").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--json","print JSON").action(async o=>{let{loadOntology:n}=await import("./load-LQ2I2PQI.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{WikiHub:r}=await import("./hub-QN4HRLGZ.js"),i=Yd(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(on.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)} ${on.dim(u.map(w=>`${w.id} ${f.get(w.id)??0}`).join(" \xB7 "))}`)}l.length&&console.log(on.yellow(` ontology.yaml has ${l.length} problem(s): agentx wiki ontology check`))})}import tt from"chalk";import{resolve as GC}from"path";var Kd=e=>e||GC(process.cwd(),".agentx/wiki"),zC=()=>new Date().toISOString().slice(0,10);async function Xd(e){let{WikiHub:t}=await import("./hub-QN4HRLGZ.js"),{GraphCache:o}=await import("./graph-ZVKV3JBD.js"),{loadOntology:n}=await import("./load-LQ2I2PQI.js"),{loadRoster:s}=await import("./roster-BZGKG2ZA.js"),r=new t(e,()=>{}),{ontology:i}=n(e),a=new o().get(r,i,s(e,r.listAgents([]),i.agent_names));return{hub:r,g:a}}function C$(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 O$(e){let t=e.command("events").description("give each event page an importance level (minor, normal, major) and the pages it is about").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--about <titles...>","only events linked to or naming these pages (a pilot)").option("--max <n>","most events per run","200").option("--batch <n>","events per model call","20").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","haiku").option("--rules-only","use only the importance rules in ontology.yaml; no model call").option("--force","redo events whose level this job set earlier").option("--dry-run","show what would be written, write nothing").option("--json","print the run as JSON").action(async o=>{let{runEvents:n,summariseAbout:s}=await import("./event-levels-NBOMTB23.js"),{claudeCall:r}=await import("./wiki-enrich-IN7UANOJ.js"),i=C$(o.max,"--max"),a=C$(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 Xd(Kd(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:zC()}),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-NBOMTB23.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 Xd(Kd(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 Xd(Kd(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 YC}from"path";var KC=e=>e||YC(process.cwd(),".agentx/wiki");function I$(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-QN4HRLGZ.js"),{GraphCache:s}=await import("./graph-ZVKV3JBD.js"),{loadOntology:r}=await import("./load-LQ2I2PQI.js"),{loadRoster:i}=await import("./roster-BZGKG2ZA.js"),{loadRulesState:a,ruleWordsPattern:c,runRules:l,saveRulesState:g}=await import("./rules-5ZZQZLQA.js"),d=KC(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,Df(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
584
  `).map(R=>` | ${R}`).join(`
585
- `)))}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 Wa from"chalk";import{resolve as XC}from"path";var VC=e=>e||XC(process.cwd(),".agentx/wiki");function N$(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-LMVIRMSR.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-GPCTV4AD.js");r=g().wiki.summaries}catch{}let i=new o(VC(t.dir),void 0,"graph"),a=t.agent||process.env.AGENTX_AGENT_ID;if(!t.all&&!a){console.log(Wa.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(Wa.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?Wa.yellow(`, ${d.failed} failed`):""}${d.removed?`, ${d.removed} removed`:""}`;console.log(` ${Wa.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 j$,dirname as P$}from"path";import{exec as ZC,execSync as Jn}from"child_process";import{promisify as eO}from"util";import{appendFileSync as tO,statSync as oO,writeFileSync as Ft,mkdirSync as eo,readFileSync as Ut,readdirSync as nO,renameSync as Ba,rmSync as Qd,existsSync as ot}from"fs";var F$=eO(ZC);function ke(e,t){return new $c(wt(e),void 0,t||"graph")}async function U$(e){let t=[];try{let{loadDaemonConfig:n}=await import("./config-GPCTV4AD.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 W$(){try{let{loadDaemonConfig:e}=await import("./config-GPCTV4AD.js"),t=Object.keys(e().agents||{});return t.length?new Set(t):null}catch{return null}}async function _$(){try{let{loadDaemonConfig:e}=await import("./config-GPCTV4AD.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 sO(){try{let{loadDaemonConfig:e}=await import("./config-GPCTV4AD.js");return Af(e().agents||{})}catch{return new Set}}function Hn(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 D$(){let{sharedQueryEnabled:e}=await import("./query-KMRMTYL6.js");return e()}async function B$(e){let{loadQuerySettings:t}=await import("./query-settings-M3HVXUMQ.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 wt(e){return e||F(process.cwd(),".agentx/wiki")}function Zd(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var z=new QC().name("wiki").description("wiki knowledge base management");S$(z);R$(z);T$(z);Mf(z);O$(z);I$(z);N$(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=ke(e.dir,t),n=o.summary(),r=o.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${Zd(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=ke(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(wt(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=Jd(e.model)}catch(R){console.log(m.red(` ${R.message}`)),process.exitCode=1;return}let n=ke(e.dir,t),s=await W$(),{agents:r,skipped:i}=Ef(n.listAgents().filter(R=>!s||s.has(R)),{only:e.agent,off:await sO()}),a=i.length&&e.notes!==!1?(await _$())?.absorbAgent:void 0;for(let R of i)console.log(` ${m.cyan(R)}: ${m.dim(Rf(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 _o({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(Ie=>Ie.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{tO($,`${JSON.stringify(R)}
585
+ `)))}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 Wa from"chalk";import{resolve as XC}from"path";var VC=e=>e||XC(process.cwd(),".agentx/wiki");function N$(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-4CT7SXMO.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-WBW2WCS2.js");r=g().wiki.summaries}catch{}let i=new o(VC(t.dir),void 0,"graph"),a=t.agent||process.env.AGENTX_AGENT_ID;if(!t.all&&!a){console.log(Wa.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(Wa.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?Wa.yellow(`, ${d.failed} failed`):""}${d.removed?`, ${d.removed} removed`:""}`;console.log(` ${Wa.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 j$,dirname as P$}from"path";import{exec as ZC,execSync as Jn}from"child_process";import{promisify as eO}from"util";import{appendFileSync as tO,statSync as oO,writeFileSync as Ft,mkdirSync as eo,readFileSync as Ut,readdirSync as nO,renameSync as Ba,rmSync as Qd,existsSync as ot}from"fs";var F$=eO(ZC);function ke(e,t){return new $c(wt(e),void 0,t||"graph")}async function U$(e){let t=[];try{let{loadDaemonConfig:n}=await import("./config-WBW2WCS2.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 W$(){try{let{loadDaemonConfig:e}=await import("./config-WBW2WCS2.js"),t=Object.keys(e().agents||{});return t.length?new Set(t):null}catch{return null}}async function _$(){try{let{loadDaemonConfig:e}=await import("./config-WBW2WCS2.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 sO(){try{let{loadDaemonConfig:e}=await import("./config-WBW2WCS2.js");return Af(e().agents||{})}catch{return new Set}}function Hn(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 D$(){let{sharedQueryEnabled:e}=await import("./query-AFQMYQTS.js");return e()}async function B$(e){let{loadQuerySettings:t}=await import("./query-settings-U32L6542.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 wt(e){return e||F(process.cwd(),".agentx/wiki")}function Zd(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var z=new QC().name("wiki").description("wiki knowledge base management");S$(z);R$(z);T$(z);Mf(z);O$(z);I$(z);N$(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=ke(e.dir,t),n=o.summary(),r=o.getSharedStore().listEntries().length;console.log(),console.log(m.bold(` Wiki Hub Status [${Zd(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=ke(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(wt(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=Jd(e.model)}catch(R){console.log(m.red(` ${R.message}`)),process.exitCode=1;return}let n=ke(e.dir,t),s=await W$(),{agents:r,skipped:i}=Ef(n.listAgents().filter(R=>!s||s.has(R)),{only:e.agent,off:await sO()}),a=i.length&&e.notes!==!1?(await _$())?.absorbAgent:void 0;for(let R of i)console.log(` ${m.cyan(R)}: ${m.dim(Rf(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 _o({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(Ie=>Ie.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{tO($,`${JSON.stringify(R)}
586
586
  `)}catch{}},x=new Date().toISOString(),k=e.notes===!1?null:await _$(),A=k?new Eu(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),Ie=Q.rebuildIndex(),Ye=Q.getWorldview()||n.getSharedStore().getWorldview()||"",M=_.map(le=>`--- ENTRY ${le.id} [${le.date} ${le.agentId} via ${le.source}] ---
587
587
  ${le.content}
588
588
  --- END ENTRY ---`).join(`
589
589
 
590
- `),ce="";if(e.facts!==!1){let{extractHints:le,resolveFacts:an,mergeRecords:Xn,renderFactsBlock:Vn,installPrompts:ti,defaultSources:Qn,recordsFromEntries:cn}=await import("./facts-ALJBF7IA.js");if(!f){let q=new Set;for(let Be of n.listAgents())for(let yt of n.getAgentWiki(Be).listArticles(Be))yt.meta.type==="person"&&q.add(yt.meta.title);f=[...q]}let ln=le(_.map(q=>({context:q.sourceContext,content:q.content,sender:typeof q.meta?.sender=="string"?q.meta.sender:void 0})),{known:f}),Zn=cn(_);if(ln.length>0||Zn.length>0){let q=Qn(),{records:Be,results:yt}=ln.length>0?await an(ln,{sources:q}):{records:[],results:[]},xe=Xn([...Zn,...Be]);ce=Vn(xe);let it=[...Zn.length>0?[`entries:${Zn.length}`]:[],...yt.filter(Le=>Le.records.length>0).map(Le=>`${Le.source}:${Le.records.length}`)];console.log(m.dim(` Facts: ${ln.length} entities \u2192 ${xe.length} resolved${it.length?` (${it.join(" ")})`:""}`));for(let Le of ti(yt,q))console.log(m.yellow(` ! ${Le.source} ${Le.kind} \u2014 would supply ${Le.provides.join(", ")}`)),console.log(m.dim(` ${Le.hint}`))}}let Pe=Ie.articles.filter(le=>le.path&&!le.path.includes("/_versions/")),ue=await Nf([..._,...V.map(le=>({id:Hd(le.id),content:le.change}))],Q,R,Pe);ue.length>0&&console.log(m.dim(` Existing: ${ue.map(le=>le.path).join(", ")}`));let N=jf(ue),be=v$(V),rt=_c(t,R,Ye,Ie.articles,M,_.length,ce,N,be);console.log(m.dim(` Mode: ${Zd(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-_c(t,R,Ye,[],M,_.length,ce,N,be).length,catalogArticles:Ie.articles.length,covering:N.length,facts:ce.length,worldview:Ye.length,notes:be.length},...V.length?{notes:V.length}:{}},bo=Date.now();Me.prepMs=bo-O;try{let le,an=!1;try{le=Jn(`cat '${De}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Po(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(q){if(le=q.stdout||"",!le)throw q;an=!0}let Xn=le;try{let q=JSON.parse(le);Object.assign(Me,rl(q)),q.is_error===!0&&(an=!0),Xn=q.result||q.content||"",Xn||(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 Vn=$$(Xn);if("error"in Vn){V.length>0&&console.log(m.yellow(` ${V.length} wiki note(s) stay waiting`)),console.log(m.red(` ${Vn.error}`)),console.log(m.dim(` First 500 chars: ${Xn.slice(0,500)}`));continue}let{articles:ti,gaps:Qn}=Vn,cn=new Set,ln=new Set,Zn=new Set(_.map(q=>q.id));for(let q of ti){let Be=new Date().toISOString().slice(0,10),yt=Array.isArray(q.sources)?q.sources:[],xe=V.length>0?yt.filter(jo=>Zn.has(jo)):yt;if(V.length>0&&xe.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=Pf(q,Pe);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 jo=ur(Le.content,String(q.content??""));if(jo.length>0){console.log(m.yellow(` ! refused ${q.path}: the rewrite drops ${jo.length} fact(s) the article has`)),console.log(m.dim(` ${jo.slice(0,8).join("; ")}${jo.length>8?"; \u2026":""}`));for(let Nv of xe)cn.add(Nv);Me.refused++;continue}}let mc=u(xe,_)??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??[],...xe])],graphPath:mc},q.content,R);let Ov=q.type?m.magenta(`[${q.type}]`)+" ":"",Iv=Array.isArray(q.related)&&q.related.length?` \u2192 ${q.related.slice(0,3).join(", ")}${q.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(Le?"~":"+")} ${Ov}${q.path}: ${q.title}${m.dim(Iv)}`);let Pg=(q.tags||[]).slice(0,4).join(", ");Pg&&console.log(m.dim(` tags: ${Pg}`)),mc?.length&&(console.log(m.dim(` graphPath: ${mc.join(" \u203A ")}`)),w++),h++,Me.articles++;for(let jo of xe)ln.add(jo)}if(V.length>0&&!an){let q=V.filter(xe=>{let it=A.get(xe.id);return it&&it.status!=="open"&&it.status!=="deferred"?(console.log(m.dim(` note ${xe.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 ${xe.id} already deferred by ${it.handled.by} during this run; left as it is`)),!1):!0}),Be=x$(q,k$(Vn.notes),Q,{agentId:R,paths:new Set(ue.map(xe=>xe.path))}),yt=0;for(let xe of Be){try{A.handle(xe.id,xe.outcome,xe.reason,R,W),yt++}catch(Le){console.log(m.yellow(` ! note ${xe.id}: could not record ${xe.outcome}: ${Le?.message??Le}`))}let it=xe.outcome==="patched"?m.green("~"):xe.outcome==="rejected"?m.red("x"):m.yellow("\u2026");console.log(` ${it} note ${xe.id} ${xe.outcome}: ${m.dim(xe.reason.slice(0,160))}`)}Me.notesPatched=Be.filter(xe=>xe.outcome==="patched").length,Me.notesRecorded=yt}else V.length>0&&console.log(m.yellow(` ${V.length} wiki note(s) stay waiting`));if(Me.failed=an,Me.heldCited=[...cn].filter(q=>ln.has(q)).length,an)console.log(m.yellow(` Run reported an error \u2014 ${_.length} entries stay queued`));else{let q=_.map(Be=>Be.id).filter(Be=>!cn.has(Be));cn.size>0&&console.log(m.yellow(` ${_.length-q.length} entries stay queued behind refused saves`)),n.markProcessed(R,q,ti.flatMap(Be=>Be.sources||[]).filter(Be=>!cn.has(Be)))}if(Qn.length>0){console.log(),console.log(m.yellow(` Gaps detected (${Qn.length} missing pieces):`));for(let q of Qn)console.log(m.yellow(` ? ${q}`));try{let{QuestionStore:q}=await import("./questions-ZATLU5AW.js"),Be=new q(wt(e.dir)).add(Qn.map(yt=>({kind:"article",agentId:R,path:"",subject:String(yt).slice(0,120),question:`No article yet for: ${String(yt).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()-bo,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-TF3OMPHG.js"),{extractJson:l}=await import("./extract-json-7775Q7KO.js"),g=ke(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 Pe=b.get(ce);Pe?Pe.push(M.article.content):b.set(ce,[M.article.content])}let $=M=>{if(!p)return!0;try{return oO(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 Pe=M.keys.length-x.length;Pe>0&&console.error(m.yellow(` ${Pe} 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)}
590
+ `),ce="";if(e.facts!==!1){let{extractHints:le,resolveFacts:an,mergeRecords:Xn,renderFactsBlock:Vn,installPrompts:ti,defaultSources:Qn,recordsFromEntries:cn}=await import("./facts-ALJBF7IA.js");if(!f){let q=new Set;for(let Be of n.listAgents())for(let yt of n.getAgentWiki(Be).listArticles(Be))yt.meta.type==="person"&&q.add(yt.meta.title);f=[...q]}let ln=le(_.map(q=>({context:q.sourceContext,content:q.content,sender:typeof q.meta?.sender=="string"?q.meta.sender:void 0})),{known:f}),Zn=cn(_);if(ln.length>0||Zn.length>0){let q=Qn(),{records:Be,results:yt}=ln.length>0?await an(ln,{sources:q}):{records:[],results:[]},xe=Xn([...Zn,...Be]);ce=Vn(xe);let it=[...Zn.length>0?[`entries:${Zn.length}`]:[],...yt.filter(Le=>Le.records.length>0).map(Le=>`${Le.source}:${Le.records.length}`)];console.log(m.dim(` Facts: ${ln.length} entities \u2192 ${xe.length} resolved${it.length?` (${it.join(" ")})`:""}`));for(let Le of ti(yt,q))console.log(m.yellow(` ! ${Le.source} ${Le.kind} \u2014 would supply ${Le.provides.join(", ")}`)),console.log(m.dim(` ${Le.hint}`))}}let Pe=Ie.articles.filter(le=>le.path&&!le.path.includes("/_versions/")),ue=await Nf([..._,...V.map(le=>({id:Hd(le.id),content:le.change}))],Q,R,Pe);ue.length>0&&console.log(m.dim(` Existing: ${ue.map(le=>le.path).join(", ")}`));let N=jf(ue),be=v$(V),rt=_c(t,R,Ye,Ie.articles,M,_.length,ce,N,be);console.log(m.dim(` Mode: ${Zd(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-_c(t,R,Ye,[],M,_.length,ce,N,be).length,catalogArticles:Ie.articles.length,covering:N.length,facts:ce.length,worldview:Ye.length,notes:be.length},...V.length?{notes:V.length}:{}},bo=Date.now();Me.prepMs=bo-O;try{let le,an=!1;try{le=Jn(`cat '${De}' | claude -p - --output-format json --max-turns 3 --model '${o}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Po(),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(q){if(le=q.stdout||"",!le)throw q;an=!0}let Xn=le;try{let q=JSON.parse(le);Object.assign(Me,rl(q)),q.is_error===!0&&(an=!0),Xn=q.result||q.content||"",Xn||(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 Vn=$$(Xn);if("error"in Vn){V.length>0&&console.log(m.yellow(` ${V.length} wiki note(s) stay waiting`)),console.log(m.red(` ${Vn.error}`)),console.log(m.dim(` First 500 chars: ${Xn.slice(0,500)}`));continue}let{articles:ti,gaps:Qn}=Vn,cn=new Set,ln=new Set,Zn=new Set(_.map(q=>q.id));for(let q of ti){let Be=new Date().toISOString().slice(0,10),yt=Array.isArray(q.sources)?q.sources:[],xe=V.length>0?yt.filter(jo=>Zn.has(jo)):yt;if(V.length>0&&xe.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=Pf(q,Pe);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 jo=ur(Le.content,String(q.content??""));if(jo.length>0){console.log(m.yellow(` ! refused ${q.path}: the rewrite drops ${jo.length} fact(s) the article has`)),console.log(m.dim(` ${jo.slice(0,8).join("; ")}${jo.length>8?"; \u2026":""}`));for(let Nv of xe)cn.add(Nv);Me.refused++;continue}}let mc=u(xe,_)??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??[],...xe])],graphPath:mc},q.content,R);let Ov=q.type?m.magenta(`[${q.type}]`)+" ":"",Iv=Array.isArray(q.related)&&q.related.length?` \u2192 ${q.related.slice(0,3).join(", ")}${q.related.length>3?", \u2026":""}`:"";console.log(` ${m.green(Le?"~":"+")} ${Ov}${q.path}: ${q.title}${m.dim(Iv)}`);let Pg=(q.tags||[]).slice(0,4).join(", ");Pg&&console.log(m.dim(` tags: ${Pg}`)),mc?.length&&(console.log(m.dim(` graphPath: ${mc.join(" \u203A ")}`)),w++),h++,Me.articles++;for(let jo of xe)ln.add(jo)}if(V.length>0&&!an){let q=V.filter(xe=>{let it=A.get(xe.id);return it&&it.status!=="open"&&it.status!=="deferred"?(console.log(m.dim(` note ${xe.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 ${xe.id} already deferred by ${it.handled.by} during this run; left as it is`)),!1):!0}),Be=x$(q,k$(Vn.notes),Q,{agentId:R,paths:new Set(ue.map(xe=>xe.path))}),yt=0;for(let xe of Be){try{A.handle(xe.id,xe.outcome,xe.reason,R,W),yt++}catch(Le){console.log(m.yellow(` ! note ${xe.id}: could not record ${xe.outcome}: ${Le?.message??Le}`))}let it=xe.outcome==="patched"?m.green("~"):xe.outcome==="rejected"?m.red("x"):m.yellow("\u2026");console.log(` ${it} note ${xe.id} ${xe.outcome}: ${m.dim(xe.reason.slice(0,160))}`)}Me.notesPatched=Be.filter(xe=>xe.outcome==="patched").length,Me.notesRecorded=yt}else V.length>0&&console.log(m.yellow(` ${V.length} wiki note(s) stay waiting`));if(Me.failed=an,Me.heldCited=[...cn].filter(q=>ln.has(q)).length,an)console.log(m.yellow(` Run reported an error \u2014 ${_.length} entries stay queued`));else{let q=_.map(Be=>Be.id).filter(Be=>!cn.has(Be));cn.size>0&&console.log(m.yellow(` ${_.length-q.length} entries stay queued behind refused saves`)),n.markProcessed(R,q,ti.flatMap(Be=>Be.sources||[]).filter(Be=>!cn.has(Be)))}if(Qn.length>0){console.log(),console.log(m.yellow(` Gaps detected (${Qn.length} missing pieces):`));for(let q of Qn)console.log(m.yellow(` ? ${q}`));try{let{QuestionStore:q}=await import("./questions-ZATLU5AW.js"),Be=new q(wt(e.dir)).add(Qn.map(yt=>({kind:"article",agentId:R,path:"",subject:String(yt).slice(0,120),question:`No article yet for: ${String(yt).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()-bo,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-YMRCIJCC.js"),{extractJson:l}=await import("./extract-json-7775Q7KO.js"),g=ke(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 Pe=b.get(ce);Pe?Pe.push(M.article.content):b.set(ce,[M.article.content])}let $=M=>{if(!p)return!0;try{return oO(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 Pe=M.keys.length-x.length;Pe>0&&console.error(m.yellow(` ${Pe} 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
591
  `),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),Pe=u?ce.filter(N=>N.timestamp>=u):ce.slice(0,1),ue=Pe[Pe.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=Jd(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 Pe=R.map((ue,N)=>({a:ue,i:N}));await Promise.all(Array.from({length:Math.min(3,Pe.length)},async()=>{for(let ue=Pe.shift();ue;ue=Pe.shift()){let{a:N,i:be}=ue,rt=N.sources.map(De=>h.get(De)).filter(De=>!!De),no=F(ce,`absorb-eval-${process.pid}-${be}.txt`);Ft(no,s(N,rt));try{let{stdout:De}=await F$(`cat '${no}' | claude -p - --output-format json --max-turns 1 --model '${M}' --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Po(),encoding:"utf-8",timeout:3e5,maxBuffer:4194304}),Me=De;try{Me=JSON.parse(De).result??De}catch{}let bo=r(l(Me));bo?_.push({path:N.path,verdict:bo}):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{Qd(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 Pe={};try{Pe=JSON.parse(Ut(ce,"utf-8")).entries??{}}catch{continue}for(let[ue,N]of Object.entries(Pe)){if(J.has(ue)||u&&String(N.at??"")<u)continue;let be=h.get(ue);be&&W.push(be)}}let V=w.map(M=>M.article.content).join(`
592
- `),Q=c(W,V),Ie=i(O,D,{seed:S,since:u||void 0},_,5,{entries:W.length,lost:Q}),Ye=a(Ie);e.out&&Ft(e.out,Ye),e.json?console.log(JSON.stringify({card:Ie,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(wt(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-TF3OMPHG.js"),o=F(wt(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(`
593
- `).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=rO(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-OR3GP2SU.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 im({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 Ja=z.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Ha(e){return e?F(e):F(process.cwd(),".agentx","wiki")}Ja.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(Ha(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}`))}});Ja.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(Ha(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(`
592
+ `),Q=c(W,V),Ie=i(O,D,{seed:S,since:u||void 0},_,5,{entries:W.length,lost:Q}),Ye=a(Ie);e.out&&Ft(e.out,Ye),e.json?console.log(JSON.stringify({card:Ie,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(wt(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-YMRCIJCC.js"),o=F(wt(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(`
593
+ `).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=rO(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-C5BXFQLG.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 im({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 Ja=z.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function Ha(e){return e?F(e):F(process.cwd(),".agentx","wiki")}Ja.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(Ha(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}`))}});Ja.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(Ha(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(`
594
594
  `).map(s=>` ${s}`).join(`
595
- `)),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>)`))}});Ja.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-B2QIPGIF.js"),n=o(Ha(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`))});Ja.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-B2QIPGIF.js"),n=o(Ha(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 rO(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-KMRMTYL6.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:r,join:i}=await import("path"),a=ke(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(`
595
+ `)),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>)`))}});Ja.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-6BZBQZ2E.js"),n=o(Ha(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`))});Ja.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-6BZBQZ2E.js"),n=o(Ha(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 rO(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-AFQMYQTS.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:r,join:i}=await import("path"),a=ke(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
596
  `)||"_(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:**
597
597
 
598
598
  ${x.answer}
@@ -609,14 +609,14 @@ Q: ${N.q}
609
609
  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(`
610
610
  `),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"`,be=Jn(N,{env:Po(),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let rt=JSON.parse(be);k=String(rt.result||rt.content||"")}catch{k=be}}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(`
611
611
  `)){let be=N.match(/^(\w+):\s*(.+)$/);be&&(I[be[1]]=be[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 Ie=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",be=F(S,`draft-${o().slice(0,8)}.md`);Ft(be,k);try{Jn(`${N} '${be}'`,{stdio:"inherit"});let no=Ut(be,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(no){let De={};for(let Me of no[1].split(`
612
- `)){let bo=Me.match(/^(\w+):\s*(.+)$/);bo&&(De[bo[1]]=bo[2].trim().replace(/^"(.*)"$/,"$1"))}Ie=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,Ie,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${V} saved.`));let ce=a.extractWikilinks(Ie),Pe=new Map;for(let N of a.listArticles(e.agent))Pe.set(N.meta.title.toLowerCase(),!0);let ue=ce.filter(N=>!Pe.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-KMRMTYL6.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=ke(e.dir);if(e.commit!==!1&&Hn(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,`
612
+ `)){let bo=Me.match(/^(\w+):\s*(.+)$/);bo&&(De[bo[1]]=bo[2].trim().replace(/^"(.*)"$/,"$1"))}Ie=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,Ie,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${V} saved.`));let ce=a.extractWikilinks(Ie),Pe=new Map;for(let N of a.listArticles(e.agent))Pe.set(N.meta.title.toLowerCase(),!0);let ue=ce.filter(N=>!Pe.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-AFQMYQTS.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=ke(e.dir);if(e.commit!==!1&&Hn(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
613
  `)),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=lO(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=Jn(W,{env:Po(),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ie=JSON.parse(V);I=String(Ie.result||Ie.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(`
614
614
  `).length,_=I.split(`
615
615
  `).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(`
616
- `)),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=ke(o.dir);if(Hn(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=Wr(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{Jn(`${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 iO(){let{loadDaemonConfig:e}=await import("./config-GPCTV4AD.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 aO(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=ke(n.dir);if(Hn(s,e))return;let r=Wr(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 iO(),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)&&aO(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=ke(o.dir).getAgentWiki(e),s=Wr(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=ke(n.dir);if(Hn(s,e))return;let r=s.getAgentWiki(e),i=Wr(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 lu))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-GPCTV4AD.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-S56W3EGU.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=ke(n.dir);if(Hn(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=Wr(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=cO(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=Jn(S,{env:Po(),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(`
616
+ `)),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=ke(o.dir);if(Hn(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=Wr(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{Jn(`${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 iO(){let{loadDaemonConfig:e}=await import("./config-WBW2WCS2.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 aO(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=ke(n.dir);if(Hn(s,e))return;let r=Wr(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 iO(),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)&&aO(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=ke(o.dir).getAgentWiki(e),s=Wr(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=ke(n.dir);if(Hn(s,e))return;let r=s.getAgentWiki(e),i=Wr(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 lu))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-WBW2WCS2.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-YJI2JEMP.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=ke(n.dir);if(Hn(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=Wr(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=cO(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=Jn(S,{env:Po(),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
617
  `).length,h=p.split(`
618
- `).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=_f(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 M$=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-LK72ZY6S.js"),o=ke(e.dir),n=wt(e.dir),s={},r={};try{let{loadDaemonConfig:d}=await import("./config-GPCTV4AD.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 F$(`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:Po(),timeout:18e4,maxBuffer:4194304});try{let b=JSON.parse(w);return{text:String(b.result||b.content||""),costUsd:rl(b).costUsd}}catch{return{text:w}}}finally{Qd(h,{force:!0})}},g=[];try{for(let d of i){if(Hn(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]])M$.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-G2MEPNGH.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={...M$.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 Ur=z.command("contributions").description("the daily merge of agents' wiki patches (list, merge, held, approve, reject)");Ur.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-LK72ZY6S.js"),s=wt(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()});Ur.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-LK72ZY6S.js"),o=t(ke(e.dir),wt(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()});Ur.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-LK72ZY6S.js"),o=t(wt(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(`
619
- agentx wiki contributions approve <id> \xB7 agentx wiki contributions reject <id>`)),console.log()});Ur.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-LK72ZY6S.js"),n=o(ke(t.dir),wt(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.`))});Ur.command("reject <id>").description("drop a held patch").option("--dir <path>","wiki directory").action(async(e,t)=>{let{rejectHeld:o}=await import("./contributions-LK72ZY6S.js"),n=o(wt(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 Wr(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 cO(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(`
618
+ `).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=_f(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 M$=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-HJPRWHSN.js"),o=ke(e.dir),n=wt(e.dir),s={},r={};try{let{loadDaemonConfig:d}=await import("./config-WBW2WCS2.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 F$(`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:Po(),timeout:18e4,maxBuffer:4194304});try{let b=JSON.parse(w);return{text:String(b.result||b.content||""),costUsd:rl(b).costUsd}}catch{return{text:w}}}finally{Qd(h,{force:!0})}},g=[];try{for(let d of i){if(Hn(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]])M$.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-GOYUMGWG.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={...M$.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 Ur=z.command("contributions").description("the daily merge of agents' wiki patches (list, merge, held, approve, reject)");Ur.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-HJPRWHSN.js"),s=wt(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()});Ur.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-HJPRWHSN.js"),o=t(ke(e.dir),wt(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()});Ur.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-HJPRWHSN.js"),o=t(wt(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(`
619
+ agentx wiki contributions approve <id> \xB7 agentx wiki contributions reject <id>`)),console.log()});Ur.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-HJPRWHSN.js"),n=o(ke(t.dir),wt(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.`))});Ur.command("reject <id>").description("drop a held patch").option("--dir <path>","wiki directory").action(async(e,t)=>{let{rejectHeld:o}=await import("./contributions-HJPRWHSN.js"),n=o(wt(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 Wr(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 cO(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(`
620
620
  `)}function lO(e,t,o,n,s){let r={"/correct":`The operator says the article contains an error:
621
621
 
622
622
  ${o}
@@ -671,17 +671,17 @@ Output (JSON array, one entry per input article, same order):
671
671
  [
672
672
  {"path": "path/to/article.md", "type": "project"},
673
673
  ...
674
- ]`}z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ke(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 U$(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(),Cf(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-FFDCUGCG.js"),c=ke(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(`
674
+ ]`}z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ke(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 U$(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(),Cf(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-G6YNXTEY.js"),c=ke(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
675
  ${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(`
676
- ${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-KMRMTYL6.js"),{noteSourceFor:n}=await import("./query-settings-M3HVXUMQ.js"),{QUERY_RUNS_FILE:s,queryFailed:r,recordQueryRun:i,timedQuery:a}=await import("./query-runs-VXS572PQ.js"),c=await B$(t);if(!c)return;let l=ke(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 D$()?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 D$()?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-KMRMTYL6.js"),{noteSourceFor:u}=await import("./query-settings-M3HVXUMQ.js"),{meteredModelCall:h}=await import("./model-call-HMVMUAXS.js"),w=await B$(e);if(!w)return;let b=ke(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)}
676
+ ${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-AFQMYQTS.js"),{noteSourceFor:n}=await import("./query-settings-U32L6542.js"),{QUERY_RUNS_FILE:s,queryFailed:r,recordQueryRun:i,timedQuery:a}=await import("./query-runs-VXS572PQ.js"),c=await B$(t);if(!c)return;let l=ke(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 D$()?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 D$()?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-AFQMYQTS.js"),{noteSourceFor:u}=await import("./query-settings-U32L6542.js"),{meteredModelCall:h}=await import("./model-call-HMVMUAXS.js"),w=await B$(e);if(!w)return;let b=ke(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
677
  `))}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)}
678
678
  `),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(`
679
- 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=ke(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=ke(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 _o({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=ke(e.dir),o=t.getSharedStore(),n=await U$(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 W$();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 $c(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:Zd(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} (${uO(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-FFDCUGCG.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=ke(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(wt(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-GPCTV4AD.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(`
679
+ 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=ke(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=ke(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 _o({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=ke(e.dir),o=t.getSharedStore(),n=await U$(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 W$();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 $c(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:Zd(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} (${uO(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-G6YNXTEY.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=ke(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(wt(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-WBW2WCS2.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
680
  `),J=R.length>10?`
681
681
  \u2026and ${R.length-10} more`:"",W=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
682
682
  ${_}${J}
683
683
 
684
- 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-FFDCUGCG.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ALJBF7IA.js"),{backfillArticle:f}=await import("./backfill-7TCF4SHG.js"),p=ke(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:Ie,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,be])=>[N,be.value]))}]:[],...Ie]);if(ce.length===0)continue;let{content:Pe,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,Pe,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(wt(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(wt(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(wt(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=ke(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-FFDCUGCG.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=ke(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((Ie,Ye)=>Ye.recall-Ie.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 uO(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"}tu();import{Command as mO}from"commander";import U from"chalk";import{resolve as Ga}from"path";import{existsSync as pO}from"fs";ne();var Hs=new mO().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Hs.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 _o({baseDir:Ga(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=li(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=fO(h,a,c),$=null;try{$=await hO(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{wO(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()});Hs.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=Ga(process.cwd(),t.graph.baseDir);if(!pO(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 _o({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()});Hs.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 _o({baseDir:Ga(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 fO(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(`
684
+ 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-G6YNXTEY.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ALJBF7IA.js"),{backfillArticle:f}=await import("./backfill-7TCF4SHG.js"),p=ke(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:Ie,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,be])=>[N,be.value]))}]:[],...Ie]);if(ce.length===0)continue;let{content:Pe,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,Pe,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(wt(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(wt(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(wt(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=ke(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-G6YNXTEY.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=ke(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((Ie,Ye)=>Ye.recall-Ie.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 uO(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"}tu();import{Command as mO}from"commander";import U from"chalk";import{resolve as Ga}from"path";import{existsSync as pO}from"fs";ne();var Hs=new mO().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Hs.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 _o({baseDir:Ga(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=li(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=fO(h,a,c),$=null;try{$=await hO(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{wO(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()});Hs.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=Ga(process.cwd(),t.graph.baseDir);if(!pO(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 _o({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()});Hs.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 _o({baseDir:Ga(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 fO(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
685
  `),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(`
686
686
  `)}async function hO(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 ci((c?.content||"").toString())}finally{clearTimeout(i)}}function wO(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function eg(){let e=T();if(!e.graph?.baseDir)return console.log(U.red(" graph.baseDir is not configured")),null;let t=Ga(process.cwd(),e.graph.baseDir);return{store:new _o({baseDir:t}),baseDir:t}}var tg=Hs.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");tg.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=eg();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(li(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]"))});tg.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=eg();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}: ${li(i[0].path,c)||i[0].path.join(" \u203A ")}`)),o.path&&console.log(U.dim(` should have been: ${o.path}`))});tg.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let t=eg();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 xO}from"commander";import ae from"chalk";import{Command as H$}from"commander";import Te from"chalk";import{existsSync as yO}from"fs";import{resolve as bO}from"path";import $O from"better-sqlite3";function kO(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(Te.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function vO(e){let t=bO(process.cwd(),e);return yO(t)||(console.log(Te.red(` No db at ${t}`)),process.exit(1)),new $O(t,{readonly:!0})}var G$=new H$().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(ar)).option("--max <n>","max clusters distilled per run",String(hi)).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(Te.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let t=vO(e.path),o=await am(t,{since:kO(e.since),agentId:e.agent,sessions:new cu(process.cwd()),minOccurrences:Number(e.minOccurrences)||ar,max:Number(e.max)||hi,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(Te.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(` ${Te.cyan(n.key)} ${Te.bold(`\xD7${n.count}`)} ${Te.dim(n.status)}`),n.sampleMessage&&console.log(Te.dim(` "${n.sampleMessage.slice(0,100)}"`));if(o.nearMisses.length){console.log(Te.dim(`
687
687
  near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of o.nearMisses.slice(0,5))console.log(Te.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of o.drafted)console.log(Te.green(` \u2713 draft written: ${n.id}`)+Te.dim(` (${n.count} occurrences)`));for(let n of o.skipped)console.log(Te.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of o.warnings)console.log(Te.yellow(` \u26A0 ${n}`));o.dryRun?console.log(Te.dim(`
@@ -752,7 +752,7 @@ ${e.body||""}`)}function n1(e){return e.startsWith("test/")||/\.test\.[cm]?[jt]s
752
752
 
753
753
  `))>=0;){let p=l.slice(0,f);l=l.slice(f+2),w1(p)}}}catch(i){console.error(ye.red(` disconnected: ${i.message||i}`)),process.exit(1)}});function w1(e){let t="message",o="";for(let r of e.split(`
754
754
  `))r.startsWith("event: ")?t=r.slice(7):r.startsWith("data: ")&&(o=r.slice(6));if(!o)return;let n={};try{n=JSON.parse(o)}catch{console.log(`${t}: ${o}`);return}let s=n.at?ye.dim(new Date(n.at).toLocaleTimeString()):"";switch(t){case"run":{let r=ye.cyan(n.phase?.padEnd(9)??"run"),i=ye.bold(n.workflowId??""),a=ye.dim((n.runId??"").slice(0,8)),c=n.nodeId?ye.yellow(n.nodeId):"",l=n.note?ye.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${r} ${i} ${a} ${c} ${l}`);break}case"task":{let r=ye.magenta(`task.${n.phase}`.padEnd(14)),i=ye.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ye.dim(`"${n.title}"`):"";console.log(`${s} ${r} ${i} ${ye.cyan(a)} ${c}`);break}case"signal":{let r=ye.green("signal".padEnd(9)),i=ye.bold(n.name),a=ye.dim(`(${n.scope})`),c=n.workflowId?ye.dim(n.workflowId):"";console.log(`${s} ${r} ${i} ${a} ${c}`);break}case"mesh":{let r=ye.blue("mesh".padEnd(9)),i=ye.bold(n.peer),a=n.healthy?ye.green("\u2713 healthy"):ye.red("\u2717 lost");console.log(`${s} ${r} ${i} ${a} ${ye.dim(n.delta??"")}`);break}case"channel":{let r=ye.yellow("channel".padEnd(9)),i=n.direction==="in"?ye.cyan("\u2190"):ye.magenta("\u2192"),a=ye.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ye.dim(n.textPreview):"";console.log(`${s} ${r} ${i} ${a} ${c}`);break}case"status":{console.log(ye.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${t} ${JSON.stringify(n)}`)}}ne();import{Command as Kk}from"commander";import yo from"chalk";function y1(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 b1(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 Xk(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 $1=new Kk().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}=Xk(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(b1(e,n)),signal:AbortSignal.timeout(1e4)}),c=await a.json().catch(()=>({}));if(!a.ok){console.error(yo.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(yo.green(` \u2713 Emitted ${c.event?.type??e} on ${c.event?.node??"this machine"}`)+yo.dim(` (event ${c.event?.id??"?"})`))}catch(a){console.error(yo.red(` daemon unreachable at ${s}: ${a?.message||a}`)),process.exitCode=1}}),Vk=new Kk().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($1).action(async e=>{let{baseUrl:t,token:o}=Xk(e),n={};o&&(n.Authorization=`Bearer ${o}`);let s;try{let a=await fetch(y1(t,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(yo.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(yo.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(yo.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(r.length===0){console.log(yo.dim(" no events"));return}for(let a of r)console.log(` ${pu(a)} ${yo.dim(a.id)}`);let i=s.next??r[r.length-1].id;console.log(yo.dim(`
755
- ${r.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${i}`))});import{Command as v1}from"commander";import zr from"chalk";import{spawn as x1}from"node:child_process";import{execFileSync as k1}from"node:child_process";function Qk(e=()=>k1("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 Zk=new v1().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(zr.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-Y63KZEDJ.js"),o=t({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Qk();if(n?.ok){let{fetchAgents:l}=await import("./client-Y63KZEDJ.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(zr.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:x1,log:b=>console.error(zr.dim(b))});return}n&&!n.ok&&(console.error(zr.yellow(n.reason)),console.error(zr.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-2LXSOVIN.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 S1}from"commander";import ge from"chalk";import{randomUUID as ov}from"crypto";import{createInterface as A1}from"node:readline/promises";import E1 from"ora";import sc from"chalk";function ev(e){console.error(),console.error(sc.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(sc.dim(` ${e.why}`)),console.error(),console.error(` Use ${sc.cyan(e.instead)} instead.`),e.note&&console.error(sc.dim(` ${e.note}`)),console.error()}var tv={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 nv=new S1().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)=>{ev({what:"agentx chat",...tv});let o=Lf({node:t.node,token:t.token,config:t.config}),n=(e??"").replace(/^@/,"").trim(),s=t.channel,r=t.chatId||`chat-cli:${ov().slice(0,12)}`,i=[];try{i=await qi(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-4TRWF5SI.js"),f=(await import("react")).default;await g(f.createElement(d,{conn:o,agentId:n,channel:s,chatId:r,agents:i})).waitUntilExit();return}T1(o.baseUrl,n,r,s);let a=A1({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(ge.dim(`
755
+ ${r.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${i}`))});import{Command as v1}from"commander";import zr from"chalk";import{spawn as x1}from"node:child_process";import{execFileSync as k1}from"node:child_process";function Qk(e=()=>k1("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 Zk=new v1().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(zr.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:t}=await import("./client-HZKF3XY6.js"),o=t({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:Qk();if(n?.ok){let{fetchAgents:l}=await import("./client-HZKF3XY6.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(zr.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:x1,log:b=>console.error(zr.dim(b))});return}n&&!n.ok&&(console.error(zr.yellow(n.reason)),console.error(zr.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-DYS5IYTQ.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 S1}from"commander";import ge from"chalk";import{randomUUID as ov}from"crypto";import{createInterface as A1}from"node:readline/promises";import E1 from"ora";import sc from"chalk";function ev(e){console.error(),console.error(sc.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(sc.dim(` ${e.why}`)),console.error(),console.error(` Use ${sc.cyan(e.instead)} instead.`),e.note&&console.error(sc.dim(` ${e.note}`)),console.error()}var tv={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 nv=new S1().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)=>{ev({what:"agentx chat",...tv});let o=Lf({node:t.node,token:t.token,config:t.config}),n=(e??"").replace(/^@/,"").trim(),s=t.channel,r=t.chatId||`chat-cli:${ov().slice(0,12)}`,i=[];try{i=await qi(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-ZZHEP2P7.js"),f=(await import("react")).default;await g(f.createElement(d,{conn:o,agentId:n,channel:s,chatId:r,agents:i})).waitUntilExit();return}T1(o.baseUrl,n,r,s);let a=A1({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(ge.dim(`
756
756
  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:${ov().slice(0,12)}`,console.log(ge.dim(` fresh chatId=${r} (warm process dropped)`));continue}if(g==="/agents"){try{let u=await qi(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 qi(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=E1({text:`@${n}\u2026`,color:"cyan"}).start(),f=Date.now(),p=R1(n);try{let u=await qf(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 R1(e){let t=!1,o=!0,n=!1,s=new Set,r=()=>{t||(process.stdout.write(`${ge.green(`@${e}`)}
757
757
  `),t=!0)};return{text(i){if(i){r(),n=!0;for(let a of i)o&&a!==`
758
758
  `&&(process.stdout.write(" "),o=!1),process.stdout.write(a),a===`
@@ -852,7 +852,7 @@ Restart the daemon to activate.
852
852
  dist/
853
853
  *.log
854
854
  .env
855
- `}import{Command as gI}from"commander";import st from"chalk";import{writeFileSync as uI,mkdirSync as mI,existsSync as dc,readFileSync as yv,appendFileSync as bv}from"fs";import{resolve as er,dirname as vv}from"path";import{homedir as Tg}from"os";var xv=new gI().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-5CHM6EPW.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=hI(o);break;case"bash":s=kI(o);break;case"fish":s=vI(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?er(String(e.output)):pI(n);mI(vv(r),{recursive:!0}),uI(r,s),console.log(st.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),fI(n,r,!!e.yes)});function pI(e){let t=Tg();switch(e){case"zsh":return er(t,".zsh","completions","_agentx");case"bash":return er(t,".bash_completion.d","agentx.bash");case"fish":return er(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function fI(e,t,o){if(e==="zsh"){let n=er(Tg(),".zshrc"),s=vv(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=dc(n)?yv(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&&dc(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),bv(n,g.join(`
855
+ `}import{Command as gI}from"commander";import st from"chalk";import{writeFileSync as uI,mkdirSync as mI,existsSync as dc,readFileSync as yv,appendFileSync as bv}from"fs";import{resolve as er,dirname as vv}from"path";import{homedir as Tg}from"os";var xv=new gI().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-MDS4XDAY.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=hI(o);break;case"bash":s=kI(o);break;case"fish":s=vI(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?er(String(e.output)):pI(n);mI(vv(r),{recursive:!0}),uI(r,s),console.log(st.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),fI(n,r,!!e.yes)});function pI(e){let t=Tg();switch(e){case"zsh":return er(t,".zsh","completions","_agentx");case"bash":return er(t,".bash_completion.d","agentx.bash");case"fish":return er(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function fI(e,t,o){if(e==="zsh"){let n=er(Tg(),".zshrc"),s=vv(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=dc(n)?yv(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&&dc(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),bv(n,g.join(`
856
856
  `)+`
857
857
  `),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=er(Tg(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((dc(n)?yv(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&&dc(n)){bv(n,`
858
858
  # agentx completion
@@ -868,4 +868,4 @@ ${xI({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
868
868
  ${o.url}`)}catch(t){console.error(or.red(` ${t.message}`)),process.exitCode=1}});ei.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",Og).action(async(e,t)=>{try{let o=await jg(t.models);if(!Ig(t.model,o)){console.log(Ng(t.model,o)),process.exitCode=1;return}let n=e==="-"?await EI():await AI(e,"utf8"),s=JSON.parse(n),{version:r}=await fi(),i=Rv({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(or.red(` ${o.message}`)),process.exitCode=1}});async function EI(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function Z4(){let e=await fi(),t=new RI().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=xf(n);Sf(s)&&vf("cli",s)});for(let o of[yw,Ih,Oh,Wn,hs,lo,Pt,of,So,oa,Eo,bn,Mn,To,en,c$,Zo,zi,Zk,Ko,iy,ay,hy,Nr,Ry,Ny,ny,_y,Dy,Zy,nb,sb,qt,Bn,rv,kr,Jo,xv,ei])t.addCommand(o);for(let o of Cv)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=Cv.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,TI(o,74," "),""].join(`
869
869
  `)}),t}var Cv=[z,Hs,Io,to,Sr,Ds,Qe,Oo,tn,Dn,Ys,Ks,zo,$t,Ts,fa,Ia,_n,Na,Yk,Vk,Ao,Gr,Dt,Ff,vn,Qr,Dl,sn,St,Es,Ml,Za,wo,No,gv,Qs,uv,nv];function TI(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(`
870
870
  `)}export{Z4 as buildProgram};
871
- //# sourceMappingURL=program-5CHM6EPW.js.map
871
+ //# sourceMappingURL=program-MDS4XDAY.js.map