agentix-cli 0.100.0 → 0.101.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 (103) hide show
  1. package/apps/mac-voice/Sources/AgentXVoice/SettingsWindow.swift +1 -1
  2. package/dist/{App-XLQDP26J.js → App-EYUDDF6K.js} +2 -2
  3. package/dist/{ChatApp-DRDUXZ66.js → ChatApp-F5LZLBI3.js} +2 -2
  4. package/dist/{agent-QHM3J2XS.js → agent-XF3BWMOB.js} +2 -2
  5. package/dist/{board-dashboard-R6ZTCTSI.js → board-dashboard-TVSOWW32.js} +4 -4
  6. package/dist/{chunk-DRUEPGLP.js → chunk-5UO6BBDG.js} +2 -2
  7. package/dist/{chunk-S2GPUSBU.js → chunk-AYNZAOJN.js} +2 -2
  8. package/dist/chunk-ECM2QEXF.js +54 -0
  9. package/dist/chunk-ECM2QEXF.js.map +1 -0
  10. package/dist/{chunk-J64VIHL5.js → chunk-EEZI2K7S.js} +2 -2
  11. package/dist/{chunk-BERHVF3T.js → chunk-EXPIKLUN.js} +2 -2
  12. package/dist/{chunk-Z4FY64BS.js → chunk-GSFB46YC.js} +2 -2
  13. package/dist/{chunk-OFVMUBIP.js → chunk-HMDM5MCR.js} +2 -2
  14. package/dist/{chunk-SJMOZY7Y.js → chunk-HQJW3BC5.js} +2 -2
  15. package/dist/{chunk-B32A6OOY.js → chunk-MWLX3QCD.js} +47 -47
  16. package/dist/chunk-MWLX3QCD.js.map +1 -0
  17. package/dist/{chunk-VBFXUZTY.js → chunk-N57ES35J.js} +2 -2
  18. package/dist/{chunk-GJ5EJVMZ.js → chunk-PYCTWI2I.js} +2 -2
  19. package/dist/{chunk-IQJ7UZVV.js → chunk-QRD3ZG27.js} +2 -2
  20. package/dist/{chunk-DXJRMPGH.js → chunk-RWSCQMLD.js} +2 -2
  21. package/dist/{chunk-YYCFI4VP.js → chunk-S337S2M7.js} +2 -2
  22. package/dist/{chunk-6BZMRVKJ.js → chunk-SRPQLIAL.js} +177 -177
  23. package/dist/chunk-SRPQLIAL.js.map +1 -0
  24. package/dist/{chunk-BHKWXFJD.js → chunk-TXFIMVVF.js} +5 -5
  25. package/dist/{chunk-LXJGLNVG.js → chunk-V6W3FFW7.js} +2 -2
  26. package/dist/{chunk-4BCAH7XI.js → chunk-XO55WKCX.js} +2 -2
  27. package/dist/{chunk-J4JVKVEK.js → chunk-Y6POV2X5.js} +2 -2
  28. package/dist/{chunk-BTLW2RML.js → chunk-YOCQ2MWL.js} +2 -2
  29. package/dist/{chunk-JZJ7AZJD.js → chunk-ZJXDBVBT.js} +2 -2
  30. package/dist/cli.js +1 -1
  31. package/dist/{client-BLUCLNIS.js → client-526OCGWD.js} +2 -2
  32. package/dist/config-HCJ5NZW5.js +2 -0
  33. package/dist/config-mutator-PGR2OGWC.js +2 -0
  34. package/dist/{doctor-XGQW5SMD.js → doctor-AC5ONEO2.js} +2 -2
  35. package/dist/index.d.ts +9 -9
  36. package/dist/index.js +1 -1
  37. package/dist/{program-CH5QSA7K.js → program-MPLZJQA5.js} +16 -16
  38. package/dist/program-MPLZJQA5.js.map +1 -0
  39. package/dist/{promote-K5LP5Q6Z.js → promote-CNKIINYK.js} +2 -2
  40. package/dist/{query-LHXSINM2.js → query-A2N2LIR7.js} +2 -2
  41. package/dist/{registry-OQUO6NCW.js → registry-REKWHOHS.js} +2 -2
  42. package/dist/{request-planner-TW5OCKTF.js → request-planner-MS5BS6HY.js} +2 -2
  43. package/dist/{review-candidates-EFELFOSY.js → review-candidates-2F4QK6QQ.js} +2 -2
  44. package/dist/{routing-TSRZLD7B.js → routing-SU5Q4IPM.js} +2 -2
  45. package/dist/schedule-tool-24KHZY2Z.js +2 -0
  46. package/dist/scheduler-ALDZOUKJ.js +2 -0
  47. package/dist/{seat-NIPWHLKC.js → seat-PZBFMYQL.js} +2 -2
  48. package/dist/{select-UAKDLN76.js → select-D3XOFXA5.js} +2 -2
  49. package/dist/{set-enabled-74DLXMSM.js → set-enabled-DNDRQ3CZ.js} +2 -2
  50. package/dist/{tool-TEGHFORD.js → tool-FB6SPVIS.js} +2 -2
  51. package/dist/{tool-CEBL57UW.js → tool-RRGOHJW6.js} +2 -2
  52. package/dist/wiki-3DH2QYTX.js +2 -0
  53. package/package.json +1 -1
  54. package/dist/chunk-6BZMRVKJ.js.map +0 -1
  55. package/dist/chunk-B32A6OOY.js.map +0 -1
  56. package/dist/chunk-JREA25GJ.js +0 -54
  57. package/dist/chunk-JREA25GJ.js.map +0 -1
  58. package/dist/config-ZUMI4IY4.js +0 -2
  59. package/dist/config-mutator-S3CD2IWQ.js +0 -2
  60. package/dist/program-CH5QSA7K.js.map +0 -1
  61. package/dist/schedule-tool-JUHRVU5D.js +0 -2
  62. package/dist/scheduler-EHJPTULN.js +0 -2
  63. package/dist/wiki-WOK4SCB7.js +0 -2
  64. /package/dist/{App-XLQDP26J.js.map → App-EYUDDF6K.js.map} +0 -0
  65. /package/dist/{ChatApp-DRDUXZ66.js.map → ChatApp-F5LZLBI3.js.map} +0 -0
  66. /package/dist/{agent-QHM3J2XS.js.map → agent-XF3BWMOB.js.map} +0 -0
  67. /package/dist/{board-dashboard-R6ZTCTSI.js.map → board-dashboard-TVSOWW32.js.map} +0 -0
  68. /package/dist/{chunk-DRUEPGLP.js.map → chunk-5UO6BBDG.js.map} +0 -0
  69. /package/dist/{chunk-S2GPUSBU.js.map → chunk-AYNZAOJN.js.map} +0 -0
  70. /package/dist/{chunk-J64VIHL5.js.map → chunk-EEZI2K7S.js.map} +0 -0
  71. /package/dist/{chunk-BERHVF3T.js.map → chunk-EXPIKLUN.js.map} +0 -0
  72. /package/dist/{chunk-Z4FY64BS.js.map → chunk-GSFB46YC.js.map} +0 -0
  73. /package/dist/{chunk-OFVMUBIP.js.map → chunk-HMDM5MCR.js.map} +0 -0
  74. /package/dist/{chunk-SJMOZY7Y.js.map → chunk-HQJW3BC5.js.map} +0 -0
  75. /package/dist/{chunk-VBFXUZTY.js.map → chunk-N57ES35J.js.map} +0 -0
  76. /package/dist/{chunk-GJ5EJVMZ.js.map → chunk-PYCTWI2I.js.map} +0 -0
  77. /package/dist/{chunk-IQJ7UZVV.js.map → chunk-QRD3ZG27.js.map} +0 -0
  78. /package/dist/{chunk-DXJRMPGH.js.map → chunk-RWSCQMLD.js.map} +0 -0
  79. /package/dist/{chunk-YYCFI4VP.js.map → chunk-S337S2M7.js.map} +0 -0
  80. /package/dist/{chunk-BHKWXFJD.js.map → chunk-TXFIMVVF.js.map} +0 -0
  81. /package/dist/{chunk-LXJGLNVG.js.map → chunk-V6W3FFW7.js.map} +0 -0
  82. /package/dist/{chunk-4BCAH7XI.js.map → chunk-XO55WKCX.js.map} +0 -0
  83. /package/dist/{chunk-J4JVKVEK.js.map → chunk-Y6POV2X5.js.map} +0 -0
  84. /package/dist/{chunk-BTLW2RML.js.map → chunk-YOCQ2MWL.js.map} +0 -0
  85. /package/dist/{chunk-JZJ7AZJD.js.map → chunk-ZJXDBVBT.js.map} +0 -0
  86. /package/dist/{client-BLUCLNIS.js.map → client-526OCGWD.js.map} +0 -0
  87. /package/dist/{config-ZUMI4IY4.js.map → config-HCJ5NZW5.js.map} +0 -0
  88. /package/dist/{config-mutator-S3CD2IWQ.js.map → config-mutator-PGR2OGWC.js.map} +0 -0
  89. /package/dist/{doctor-XGQW5SMD.js.map → doctor-AC5ONEO2.js.map} +0 -0
  90. /package/dist/{promote-K5LP5Q6Z.js.map → promote-CNKIINYK.js.map} +0 -0
  91. /package/dist/{query-LHXSINM2.js.map → query-A2N2LIR7.js.map} +0 -0
  92. /package/dist/{registry-OQUO6NCW.js.map → registry-REKWHOHS.js.map} +0 -0
  93. /package/dist/{request-planner-TW5OCKTF.js.map → request-planner-MS5BS6HY.js.map} +0 -0
  94. /package/dist/{review-candidates-EFELFOSY.js.map → review-candidates-2F4QK6QQ.js.map} +0 -0
  95. /package/dist/{routing-TSRZLD7B.js.map → routing-SU5Q4IPM.js.map} +0 -0
  96. /package/dist/{schedule-tool-JUHRVU5D.js.map → schedule-tool-24KHZY2Z.js.map} +0 -0
  97. /package/dist/{scheduler-EHJPTULN.js.map → scheduler-ALDZOUKJ.js.map} +0 -0
  98. /package/dist/{seat-NIPWHLKC.js.map → seat-PZBFMYQL.js.map} +0 -0
  99. /package/dist/{select-UAKDLN76.js.map → select-D3XOFXA5.js.map} +0 -0
  100. /package/dist/{set-enabled-74DLXMSM.js.map → set-enabled-DNDRQ3CZ.js.map} +0 -0
  101. /package/dist/{tool-TEGHFORD.js.map → tool-FB6SPVIS.js.map} +0 -0
  102. /package/dist/{tool-CEBL57UW.js.map → tool-RRGOHJW6.js.map} +0 -0
  103. /package/dist/{wiki-WOK4SCB7.js.map → wiki-3DH2QYTX.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as od,b as Ns,g as td}from"./chunk-GJ5EJVMZ.js";import{A as ed,a as so,b as Ll,f as Pt,g as Fl,h as Wl,i as Bl,j as Jl,l as Hl,m as Gl,r as zl,s as Vl,t as tr,u as Yl,x as nr,y as Zl}from"./chunk-VBFXUZTY.js";import{a as Xl,c as Kl,d as Ql}from"./chunk-UVMCAZL7.js";import"./chunk-N7HKIMMR.js";import{a as ql,c as Ul}from"./chunk-SJMOZY7Y.js";import{a as Ui,b as mc}from"./chunk-RKPAVWXF.js";import{$ as Il,A as dl,B as gl,C as ml,D as pl,E as ul,F as fl,G as vl,H as As,I as Yi,J as Nt,K as Ts,L as js,M as Xi,N as xl,O as Sl,P as El,Q as Al,R as Tl,S as jl,T as Rt,U as _t,V as Ol,W as Cl,X as Le,Y as Os,Z as On,_ as Ki,a as bc,aa as _l,b as kc,ba as er,ca as Pl,da as Cs,ea as Dt,fa as Is,ga as or,h as fs,ha as Ml,i as Ec,j as An,k as hs,l as jc,m as Oc,n as Fc,o as Wc,p as vs,q as Wi,r as Vc,s as ol,t as tl,u as il,v as rl,w as al,x as cl,y as ll,z as Ji}from"./chunk-6BZMRVKJ.js";import{$a as Dl,A as xs,C as el,Ia as Nl,Ja as Qi,Ka as Rl,La as Zi,R as Tn,U as Hi,V as Ss,W as hl,Za as ko,ba as Fo,ca as yl,da as Gi,fa as zi,ha as wl,ia as $l,ja as jn,na as Es,qa as bl,ra as kl,sa as Vi,w as Bi,x as Qc,z as Zc}from"./chunk-B32A6OOY.js";import"./chunk-GTJIKXDB.js";import{a as vc,d as xc,e as Sc}from"./chunk-JZJ7AZJD.js";import"./chunk-DG5I6PPM.js";import"./chunk-ZVP6GB4G.js";import{a as ys,b as ws,c as Cc,d as Ic,e as Nc,g as Rc,h as _c,j as Dc,k as Pc,l as Mc,m as Lc,p as $s,s as qc,t as Uc}from"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import{a as nl,b as sl}from"./chunk-EKJG63EJ.js";import{a as Ac,p as Tc}from"./chunk-YYCFI4VP.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as no}from"./chunk-ACFQBLPX.js";import{c as Bc,e as bs,g as ks}from"./chunk-LQE73AZR.js";import{a as Jc,b as Hc,c as Gc,d as zc}from"./chunk-2D3RYIDU.js";import"./chunk-3Z5P2CWS.js";import{a as Yc,e as Xc,g as Kc}from"./chunk-E5OV6RTG.js";import"./chunk-PPUN7YHA.js";import{I as Uo,O as ac,Z as lc,g as Ha,r as Ga,y as Mi,z as Xa}from"./chunk-BHKWXFJD.js";import{b as At,g as jt,h as ps,i as us,j as Ot,k as Ka,l as it,m as Sn,u as cc}from"./chunk-BERHVF3T.js";import{e as nc,f as qi,k as sc}from"./chunk-GLQLCBJS.js";import{b as Tt}from"./chunk-DP7RTNDM.js";import"./chunk-OFVMUBIP.js";import"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import{b as En}from"./chunk-LLNPKE7H.js";import{a as dc,b as gc}from"./chunk-SHEUCITK.js";import{a as Fi,e as pc,f as uc,h as fc,i as hc,k as yc,l as wc,m as $c}from"./chunk-LXJGLNVG.js";import{c as Za}from"./chunk-SZDACK6O.js";import{f as ec,g as oc,h as Li}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as Va,k as tc}from"./chunk-J4JVKVEK.js";import{a as ic,b as re,c as Ie,d as It,e as rc}from"./chunk-DRUEPGLP.js";import"./chunk-VWTBHLMX.js";import{a as Di}from"./chunk-J64VIHL5.js";import"./chunk-S2GPUSBU.js";import"./chunk-KA2UIZXG.js";import{a as Pi,b as za}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Ya}from"./chunk-X5C5W3E4.js";import{a as Ct}from"./chunk-GV7S5BAX.js";import{e as Qa}from"./chunk-GSX4NK2N.js";import"./chunk-Z4FY64BS.js";import"./chunk-MYVHVJWZ.js";import{h as Ja}from"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-BTLW2RML.js";import{g as qo,i as ms}from"./chunk-4BCAH7XI.js";import"./chunk-WPNRDEHW.js";import{b as Et,d as Ba}from"./chunk-2GIDVZ4H.js";import{a as Ni,b as Ea,c as Lp,d as ls,e as Aa,f as Ma,g as Bp,h as La,i as Jp,m as St,n as Ua,o as Fa,s as Wa,v as bo,w as xn}from"./chunk-DXJRMPGH.js";import{a as jo,b as xt,e as _a,f as vn}from"./chunk-72SZI2UW.js";import{a as qa,b as Hp}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-5MUJZODV.js";import{a as To,b as Mp}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{K as Ri,M as _i,T as Fp,ca as Na,da as Ra,ea as T,fa as gs,h as Ta,ha as te,i as ja,j as Oa,l as Ca,m as qp,w as Ia,x as Up}from"./chunk-JREA25GJ.js";import{a as Lo,i as ds}from"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as Da,k as Pa,l as Wp}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Gp}from"commander";var nd=new Gp().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 kc({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});te();import{Command as zp}from"commander";import{execFileSync as ao}from"node:child_process";import{cpSync as sd,existsSync as rr,mkdirSync as sr,mkdtempSync as Vp,readdirSync as Yp,rmSync as id,writeFileSync as rd}from"node:fs";import{dirname as ad,join as qe}from"node:path";import{homedir as Rs,release as Xp,tmpdir as Kp}from"node:os";import{setTimeout as Qp}from"node:timers/promises";function _s(){let e=Cc(process.platform,process.arch,Xp());if(e)throw new Error(e)}function Ds(){let e=qe(Rs(),"Library/LaunchAgents"),o=[];try{o=Yp(e).filter(Rc)}catch{}let t=o.flatMap(n=>{let s=qe(e,n);try{return[{file:s,plist:ao("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return _c(e,t)}function Cn(e){return`gui/${process.getuid()}/${e.label}`}async function ir(e){try{ao("launchctl",["bootout",Cn(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{ao("launchctl",["print",Cn(e)],{stdio:"pipe"})}catch{return}await Qp(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function cd(e){if(!rr(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{ao("launchctl",["print",Cn(e)],{stdio:"pipe"})}catch{o=!1}o||ao("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ao("launchctl",["kickstart",Cn(e)],{stdio:"pipe"})}function Zp(){let e=Lc();if(e&&rr(qe(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 Mt=new zp("desktop").description("install and control the macOS desktop assistant");Mt.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=>{_s();let o=T(),t=Ic(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=Zp(),r=qe(Rs(),"Applications"),{keep:a,remove:c}=Ds();if(console.log(`Desktop assistant \u2192 ${qe(r,ys)}
1
+ import{a as od,b as Ns,g as td}from"./chunk-PYCTWI2I.js";import{A as ed,a as so,b as Ll,f as Pt,g as Fl,h as Wl,i as Bl,j as Jl,l as Hl,m as Gl,r as zl,s as Vl,t as tr,u as Yl,x as nr,y as Zl}from"./chunk-N57ES35J.js";import{a as Xl,c as Kl,d as Ql}from"./chunk-UVMCAZL7.js";import"./chunk-N7HKIMMR.js";import{a as ql,c as Ul}from"./chunk-HQJW3BC5.js";import{a as Ui,b as mc}from"./chunk-RKPAVWXF.js";import{$ as Il,A as dl,B as gl,C as ml,D as pl,E as ul,F as fl,G as vl,H as As,I as Yi,J as Nt,K as Ts,L as js,M as Xi,N as xl,O as Sl,P as El,Q as Al,R as Tl,S as jl,T as Rt,U as _t,V as Ol,W as Cl,X as Le,Y as Os,Z as On,_ as Ki,a as bc,aa as _l,b as kc,ba as er,ca as Pl,da as Cs,ea as Dt,fa as Is,ga as or,h as fs,ha as Ml,i as Ec,j as An,k as hs,l as jc,m as Oc,n as Fc,o as Wc,p as vs,q as Wi,r as Vc,s as ol,t as tl,u as il,v as rl,w as al,x as cl,y as ll,z as Ji}from"./chunk-SRPQLIAL.js";import{$a as Dl,A as xs,C as el,Ia as Nl,Ja as Qi,Ka as Rl,La as Zi,R as Tn,U as Hi,V as Ss,W as hl,Za as ko,ba as Fo,ca as yl,da as Gi,fa as zi,ha as wl,ia as $l,ja as jn,na as Es,qa as bl,ra as kl,sa as Vi,w as Bi,x as Qc,z as Zc}from"./chunk-MWLX3QCD.js";import"./chunk-GTJIKXDB.js";import{a as vc,d as xc,e as Sc}from"./chunk-ZJXDBVBT.js";import"./chunk-DG5I6PPM.js";import"./chunk-ZVP6GB4G.js";import{a as ys,b as ws,c as Cc,d as Ic,e as Nc,g as Rc,h as _c,j as Dc,k as Pc,l as Mc,m as Lc,p as $s,s as qc,t as Uc}from"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import{a as nl,b as sl}from"./chunk-EKJG63EJ.js";import{a as Ac,p as Tc}from"./chunk-S337S2M7.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as no}from"./chunk-ACFQBLPX.js";import{c as Bc,e as bs,g as ks}from"./chunk-LQE73AZR.js";import{a as Jc,b as Hc,c as Gc,d as zc}from"./chunk-2D3RYIDU.js";import"./chunk-3Z5P2CWS.js";import{a as Yc,e as Xc,g as Kc}from"./chunk-E5OV6RTG.js";import"./chunk-PPUN7YHA.js";import{I as Uo,O as ac,Z as lc,g as Ha,r as Ga,y as Mi,z as Xa}from"./chunk-TXFIMVVF.js";import{b as At,g as jt,h as ps,i as us,j as Ot,k as Ka,l as it,m as Sn,u as cc}from"./chunk-EXPIKLUN.js";import{e as nc,f as qi,k as sc}from"./chunk-GLQLCBJS.js";import{b as Tt}from"./chunk-DP7RTNDM.js";import"./chunk-HMDM5MCR.js";import"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import{b as En}from"./chunk-LLNPKE7H.js";import{a as dc,b as gc}from"./chunk-SHEUCITK.js";import{a as Fi,e as pc,f as uc,h as fc,i as hc,k as yc,l as wc,m as $c}from"./chunk-V6W3FFW7.js";import{c as Za}from"./chunk-SZDACK6O.js";import{f as ec,g as oc,h as Li}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as Va,k as tc}from"./chunk-Y6POV2X5.js";import{a as ic,b as re,c as Ie,d as It,e as rc}from"./chunk-5UO6BBDG.js";import"./chunk-VWTBHLMX.js";import{a as Di}from"./chunk-EEZI2K7S.js";import"./chunk-AYNZAOJN.js";import"./chunk-KA2UIZXG.js";import{a as Pi,b as za}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Ya}from"./chunk-X5C5W3E4.js";import{a as Ct}from"./chunk-GV7S5BAX.js";import{e as Qa}from"./chunk-GSX4NK2N.js";import"./chunk-GSFB46YC.js";import"./chunk-MYVHVJWZ.js";import{h as Ja}from"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-YOCQ2MWL.js";import{g as qo,i as ms}from"./chunk-XO55WKCX.js";import"./chunk-WPNRDEHW.js";import{b as Et,d as Ba}from"./chunk-2GIDVZ4H.js";import{a as Ni,b as Ea,c as Lp,d as ls,e as Aa,f as Ma,g as Bp,h as La,i as Jp,m as St,n as Ua,o as Fa,s as Wa,v as bo,w as xn}from"./chunk-RWSCQMLD.js";import{a as jo,b as xt,e as _a,f as vn}from"./chunk-72SZI2UW.js";import{a as qa,b as Hp}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-5MUJZODV.js";import{a as To,b as Mp}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{J as Ri,L as _i,S as Fp,ba as Na,ca as Ra,da as T,ea as gs,ga as te,h as Ta,i as ja,j as Oa,k as Ca,l as qp,v as Ia,w as Up}from"./chunk-ECM2QEXF.js";import{a as Lo,i as ds}from"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as Da,k as Pa,l as Wp}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Gp}from"commander";var nd=new Gp().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 kc({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});te();import{Command as zp}from"commander";import{execFileSync as ao}from"node:child_process";import{cpSync as sd,existsSync as rr,mkdirSync as sr,mkdtempSync as Vp,readdirSync as Yp,rmSync as id,writeFileSync as rd}from"node:fs";import{dirname as ad,join as qe}from"node:path";import{homedir as Rs,release as Xp,tmpdir as Kp}from"node:os";import{setTimeout as Qp}from"node:timers/promises";function _s(){let e=Cc(process.platform,process.arch,Xp());if(e)throw new Error(e)}function Ds(){let e=qe(Rs(),"Library/LaunchAgents"),o=[];try{o=Yp(e).filter(Rc)}catch{}let t=o.flatMap(n=>{let s=qe(e,n);try{return[{file:s,plist:ao("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return _c(e,t)}function Cn(e){return`gui/${process.getuid()}/${e.label}`}async function ir(e){try{ao("launchctl",["bootout",Cn(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{ao("launchctl",["print",Cn(e)],{stdio:"pipe"})}catch{return}await Qp(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function cd(e){if(!rr(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{ao("launchctl",["print",Cn(e)],{stdio:"pipe"})}catch{o=!1}o||ao("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ao("launchctl",["kickstart",Cn(e)],{stdio:"pipe"})}function Zp(){let e=Lc();if(e&&rr(qe(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 Mt=new zp("desktop").description("install and control the macOS desktop assistant");Mt.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=>{_s();let o=T(),t=Ic(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=Zp(),r=qe(Rs(),"Applications"),{keep:a,remove:c}=Ds();if(console.log(`Desktop assistant \u2192 ${qe(r,ys)}
2
2
  Computer-use helper \u2192 ${qe(r,ws)}
3
3
  Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -27,7 +27,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
27
27
  `))});function Lu(e){let o=Math.round(Bc/6e4),t=[` Pairing code: ${Te.bold.cyan(bs(e.code))}`,Te.dim(` Open the app from the phone's home screen and type this code. It works once, for ${o} minutes.`)," Or scan the QR code with the phone's camera and open the link.",` Device ${Te.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,Te.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://")||t.push(Te.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),t}function mr(){let e;try{e=JSON.parse(Cd("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 o=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!o)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${o}`}var qu=new Set(["/app","/api/app","/member","/api/member"]);function pr(e,o){let t=[e,...Object.values(e?.Foreground??{})],n=[];for(let s of t)for(let[i,r]of Object.entries(s?.Web??{}))for(let[a,c]of Object.entries(r?.Handlers??{})){let l=String(c?.Proxy??"").match(/^(?:https?:\/\/)?(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/),g=a.replace(/\/+$/,"")||"/";l&&Number(l[1])===o&&!qu.has(g)&&n.push(`${i}${a}`)}return n}function ur(){try{return JSON.parse(Cd("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Pn(){try{return T().dashboard.port||4202}catch{return 4202}}te();import{Command as xo}from"commander";import h from"chalk";import Me from"prompts";import{readFileSync as Bo,writeFileSync as Ft,existsSync as we,mkdirSync as vo,cpSync as fr,readdirSync as yr}from"fs";import{resolve as G,join as Wo,dirname as Uu}from"path";import{fileURLToPath as Fu}from"url";function me(){let e=G(process.cwd(),"agentx.json");if(!we(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Bo(e,"utf-8"))}function Je(e){return re(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var lt=new xo().name("agent").description("manage agents \u2014 add, list, remove");lt.command("list").alias("ls").description("list configured agents").action(()=>{let e=me();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});lt.command("add").description("add a new agent interactively").action(async()=>{let e=me(),o=await Me([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:G(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(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:Wo(o.workspace,o.id);vo(G(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-42ARC42I.js"),i=s(o.id,n,"19900",(...l)=>{console.log(h.dim(` ${l.join(" ")}`))}),r=G(process.cwd(),"src/wiki/SKILL.md"),a=G(Uu(Fu(import.meta.url)),"../wiki/SKILL.md"),c=we(r)?r:a;we(c)&&(vo(G(t,".claude/skills/wiki"),{recursive:!0}),fr(c,G(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await Je(e),console.log(h.green(`
28
28
  Agent "${o.id}" added`)),console.log(h.dim(` Workspace: ${t}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});lt.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=me();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await Je(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});lt.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,o)=>{let t=me(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await Je(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Mn=new xo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Mn.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=me().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
29
29
  ${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
30
- `));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Mn.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,o)=>{let t=me();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-ZUMI4IY4.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Me({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Me({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Me({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"}]});u.scheme==="tokenEnv"?a=((await Me({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(l=((await Me({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await Me({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let f of String(u.metadata).split(",")){let[p,...y]=f.split("=");p&&(g[p.trim()]=y.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.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(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Je(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Mn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=me(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Je(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Mn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=me().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){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){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});lt.addCommand(Mn);var Fs=new xo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Fs.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=me();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Fs.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=me(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Me({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 Me([{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:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.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 Je(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Me([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{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 i=[],r=s.addRoute;for(;r;){let a=await Me([{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:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await Je(e),vo(G(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Me([{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 i=[],r=s.addRoute;for(;r;){let a=await Me([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await Je(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Wt=new xo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Wt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=me();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});Wt.command("add").description("add a cron job").action(async()=>{let e=me(),o=Object.keys(e.agents||{}),t=await Me([{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:o.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}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await Je(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Wt.command("enable <id>").description("enable a cron job").action(async e=>{let o=me();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Je(o),console.log(h.green(` Cron "${e}" enabled`))});Wt.command("disable <id>").description("disable a cron job").action(async e=>{let o=me();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Je(o),console.log(h.green(` Cron "${e}" disabled`))});var io=new xo().name("mesh").description("manage mesh peers \u2014 add, list, remove");io.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=me();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});io.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=me(),o=await Me([{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(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.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:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Je(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});io.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=me();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Je(o),console.log(h.green(` Peer "${e}" removed`)))});io.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 o=me();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Je(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});io.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,o)=>{let t=o.node||"";if(!t)try{t=T().dashboard?.daemonUrl||""}catch{}t=(t||"http://localhost:18800").replace(/\/+$/,"");let n=o.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${t}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...o.by?{by:o.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(h.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+h.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(h.red(` Could not reach the daemon at ${t}: ${i?.message||i}`)),process.exit(1)}});var Id=e=>{let o=e||"";if(!o)try{o=T().dashboard?.daemonUrl||""}catch{}return(o||"http://localhost:18800").replace(/\/+$/,"")};async function Ws(e,o,t={}){let n=Id(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let i=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${o}`,{method:"POST",headers:s,body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` ${r.error||`HTTP ${i.status}`}`)),process.exit(1));let a=r.grant;console.log(h.green(` \u2713 ${a?.name??e}: ${a?.state}${r.stopped?`, ${r.stopped} running turn(s) stopped`:""}`))}catch(i){console.log(h.red(` Could not reach the daemon at ${n}: ${i?.message||i}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var dt=io.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");dt.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:o}=await import("./token-store-YBSU2DTV.js"),{PairCodeStore:t,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:i}=await import("./grants-Y667GZAU.js"),r=T(),a=i({tokens:new o,codes:new t,guests:new s,hasAgent:l=>!!r.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(h.red(` ${a.error}`)),process.exit(1));let c=(e.url||Id()).replace(/\/+$/,"");console.log(),console.log(` Grant ${h.bold(a.grant.name)} for ${h.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(h.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(` ${h.cyan(c)}`),console.log(` ${h.bold(n(a.code))}`),console.log(),console.log(` They run: ${h.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()});dt.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:o}=await import("./store-7W2AP5H4.js"),t=new o().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(h.dim(`
30
+ `));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?h.green(`${g}:${d}=set`):h.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(h.dim(`sessionDir:${d}`));let l=Object.entries(i.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${h.dim(l)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Mn.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,o)=>{let t=me();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-HCJ5NZW5.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await Me({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await Me({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),l=String(o.sessionDir||"").trim();if(!a&&!c&&!l&&n){let u=await Me({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"}]});u.scheme==="tokenEnv"?a=((await Me({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(l=((await Me({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[f,...p]=u.split("=");f&&(g[f.trim()]=p.join("=").trim())}else if(n){let u=await Me({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let f of String(u.metadata).split(",")){let[p,...y]=f.split("=");p&&(g[p.trim()]=y.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.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(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:d,metadata:g,enabled:!0}),await Je(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Mn.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=me(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(l=>l.kind===i&&(!r||l.label===r)||l.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await Je(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Mn.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=me().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){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){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});lt.addCommand(Mn);var Fs=new xo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");Fs.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=me();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[s,i]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(s)} -> agent: ${i.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let s of t.routes||[]){let i=s.contact?`contact ${s.contact}`:`group "${s.group}"`;console.log(` ${i} -> agent: ${s.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let s of n.routes||[])console.log(` ${s.project} -> agent: ${s.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});Fs.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=me(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await Me({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 Me([{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:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.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 Je(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await Me([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{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 i=[],r=s.addRoute;for(;r;){let a=await Me([{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:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await Je(e),vo(G(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await Me([{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 i=[],r=s.addRoute;for(;r;){let a=await Me([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await Je(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Wt=new xo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Wt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=me();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});Wt.command("add").description("add a cron job").action(async()=>{let e=me(),o=Object.keys(e.agents||{}),t=await Me([{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:o.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}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await Je(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Wt.command("enable <id>").description("enable a cron job").action(async e=>{let o=me();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}if(o.crons[e].approval?.action==="create"){console.log(h.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}o.crons[e].enabled=!0,await Je(o),console.log(h.green(` Cron "${e}" enabled`))});Wt.command("disable <id>").description("disable a cron job").action(async e=>{let o=me();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await Je(o),console.log(h.green(` Cron "${e}" disabled`))});var io=new xo().name("mesh").description("manage mesh peers \u2014 add, list, remove");io.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=me();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});io.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=me(),o=await Me([{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(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.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:o.url,name:o.name,...o.token?{token:o.token}:{}}),await Je(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});io.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=me();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await Je(o),console.log(h.green(` Peer "${e}" removed`)))});io.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 o=me();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await Je(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});io.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,o)=>{let t=o.node||"";if(!t)try{t=T().dashboard?.daemonUrl||""}catch{}t=(t||"http://localhost:18800").replace(/\/+$/,"");let n=o.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let i=await fetch(`${t}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...o.by?{by:o.by}:{}}),signal:AbortSignal.timeout(1e4)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` Announcement refused (${i.status}): ${r.error||"unknown error"}`)),process.exit(1)),console.log(h.green(` \u2713 Announced from ${r.event?.node??"this machine"}`)+h.dim(` (event ${r.event?.id??"?"})`))}catch(i){console.log(h.red(` Could not reach the daemon at ${t}: ${i?.message||i}`)),process.exit(1)}});var Id=e=>{let o=e||"";if(!o)try{o=T().dashboard?.daemonUrl||""}catch{}return(o||"http://localhost:18800").replace(/\/+$/,"")};async function Ws(e,o,t={}){let n=Id(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let i=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${o}`,{method:"POST",headers:s,body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)}),r=await i.json().catch(()=>({}));i.ok||(console.log(h.red(` ${r.error||`HTTP ${i.status}`}`)),process.exit(1));let a=r.grant;console.log(h.green(` \u2713 ${a?.name??e}: ${a?.state}${r.stopped?`, ${r.stopped} running turn(s) stopped`:""}`))}catch(i){console.log(h.red(` Could not reach the daemon at ${n}: ${i?.message||i}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var dt=io.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");dt.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:o}=await import("./token-store-YBSU2DTV.js"),{PairCodeStore:t,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:i}=await import("./grants-Y667GZAU.js"),r=T(),a=i({tokens:new o,codes:new t,guests:new s,hasAgent:l=>!!r.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(h.red(` ${a.error}`)),process.exit(1));let c=(e.url||Id()).replace(/\/+$/,"");console.log(),console.log(` Grant ${h.bold(a.grant.name)} for ${h.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(h.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(` ${h.cyan(c)}`),console.log(` ${h.bold(n(a.code))}`),console.log(),console.log(` They run: ${h.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()});dt.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:o}=await import("./store-7W2AP5H4.js"),t=new o().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t.length){console.log(h.dim(`
31
31
  No guest grants. Open one: agentx mesh guests invite --name \u2026 --guest \u2026 --agent \u2026
32
32
  `));return}console.log();for(let n of t){let s=n.state==="active"?h.green("active"):n.state==="pending"?h.yellow(n.guestNode?"waiting for your approval":"not joined yet"):n.state==="paused"?h.yellow("paused"):h.red(`ended${n.endedReason?`: ${n.endedReason}`:""}`);console.log(` ${h.cyan(n.id)} ${h.bold(n.name)} ${n.guest} \u2192 ${n.agentId} ${n.level} ${s}`),console.log(h.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()});dt.command("show <id>").description("one grant, what it opens and what the guest did").action(async e=>{let{GuestStore:o}=await import("./store-7W2AP5H4.js"),t=new o,n=t.get(e);n||(console.log(h.red(` No grant "${e}". See \`agentx mesh guests\`.`)),process.exit(1)),console.log(),console.log(` ${h.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"}
33
33
  skills: ${n.skills.join(", ")||"none"}
@@ -38,7 +38,7 @@ The AgentX daemon and a speech transcription backend must also be available. Run
38
38
  Not a guest anywhere. Join with: agentx mesh join <url> --code \u2026 --name \u2026
39
39
  `));return}console.log();for(let n of t){let s=await o(n),i=s.ok?s.grant.state==="active"?h.green("active"):h.yellow(String(s.grant.state)):s.status===403?h.yellow(s.error):h.red(s.error);console.log(` ${h.cyan(n.name)} ${h.dim(n.url)} ${n.agentId} until ${n.expiresAt.slice(0,10)} ${i}`)}console.log()});io.command("ask <host> <message...>").description("ask the host's agent something, inside the grant").action(async(e,o)=>{let{GuestHostStore:t,askHost:n}=await import("./hosts-NFNCYKGY.js"),s=new t().get(e);s||(console.log(h.red(` No host "${e}". See \`agentx mesh hosts\`.`)),process.exit(1));let i=await n(s,o.join(" "));i.error&&(console.log(h.red(` ${i.error}`)),process.exit(1)),console.log(`
40
40
  ${i.content}
41
- `)});io.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:o}=await import("./hosts-NFNCYKGY.js");new o().remove(e)||(console.log(h.red(` No host "${e}".`)),process.exit(1)),console.log(h.green(` \u2713 Left ${e}`))});var gt=new xo().name("skill").description("manage skills \u2014 add to agent(s), list");gt.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,o)=>{let t=me(),n=G(e);if(!we(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=we(Wo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Me({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=G(a.workspace,".claude/skills",s);vo(c,{recursive:!0}),we(Wo(n,"SKILL.md"))?fr(n,c,{recursive:!0}):n.endsWith(".md")&&fr(n,Wo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});gt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=me();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=G(t.workspace,".claude/skills"),s=we(n)?yr(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});gt.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,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[G(n,"src",e,"SKILL.md"),G(n,"skills",e,"SKILL.md")],i=s.find(k=>we(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=Bo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=T()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,y=0;for(let[k,b]of d){let $=b.workspace;if(!$||!we($)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+($||"undefined")+")")}`),y++;continue}let E=G($,".claude/skills",e),S=G(E,"SKILL.md");if(!we(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),y++;continue}o.dryRun||(vo(E,{recursive:!0}),Ft(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let v=Bo(S,"utf-8");if(t("sha256").update(v).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let R=(v.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Ft(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${y} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});gt.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:o}=await import("./loader-YFVSSYSL.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=me().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(G(f.workspace))}else if(e.allWorkspaces){let u=me();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(G(f.workspace))}else i.push(G(e.cwd));let r=G(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${p} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let y of f.reasons)console.log(` ${h.dim("\xB7")} ${y}`)}console.log(),console.log(` ${h.green(`${u.PASS} PASS`)} ${h.yellow(`${u.REVIEW} REVIEW`)} ${h.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});gt.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,o)=>{let t=me(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-UAKDLN76.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.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(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
41
+ `)});io.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:o}=await import("./hosts-NFNCYKGY.js");new o().remove(e)||(console.log(h.red(` No host "${e}".`)),process.exit(1)),console.log(h.green(` \u2713 Left ${e}`))});var gt=new xo().name("skill").description("manage skills \u2014 add to agent(s), list");gt.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,o)=>{let t=me(),n=G(e);if(!we(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=we(Wo(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await Me({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=G(a.workspace,".claude/skills",s);vo(c,{recursive:!0}),we(Wo(n,"SKILL.md"))?fr(n,c,{recursive:!0}):n.endsWith(".md")&&fr(n,Wo(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});gt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=me();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=G(t.workspace,".claude/skills"),s=we(n)?yr(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});gt.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,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[G(n,"src",e,"SKILL.md"),G(n,"skills",e,"SKILL.md")],i=s.find(k=>we(k));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(h.dim(` ${k}`));return}let r=Bo(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=T()}catch(k){console.log(h.red(` Can't load agentx.json: ${k.message}`));return}let g=Object.entries(l.agents||{}),d=o.agent?g.filter(([k])=>k===o.agent):g;if(d.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,f=0,p=0,y=0;for(let[k,b]of d){let $=b.workspace;if(!$||!we($)){console.log(` ${h.yellow("\u2717")} ${k.padEnd(22)} ${h.dim("(workspace missing: "+($||"undefined")+")")}`),y++;continue}let E=G($,".claude/skills",e),S=G(E,"SKILL.md");if(!we(S)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${k.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),y++;continue}o.dryRun||(vo(E,{recursive:!0}),Ft(S,r)),console.log(` ${h.green("+")} ${k.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let v=Bo(S,"utf-8");if(t("sha256").update(v).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${k.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),p++;continue}let R=(v.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Ft(S,r),console.log(` ${h.yellow("\u21BB")} ${k.padEnd(22)} ${h.dim(`v${R} \u2192 v${c}`)}`),f++}console.log();let w=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${w} seed ${u}, ${w} update ${f}, ${p} already current, ${y} skipped.`)),o.dryRun&&(u>0||f>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});gt.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:o}=await import("./loader-YFVSSYSL.js"),{auditAll:t}=await import("./audit-CMJ2TZ3K.js"),{loadReferences:n}=await import("./loader-KKMG24O5.js"),{loadRecipes:s}=await import("./recipes-423CIPZ3.js"),i=[];if(e.workspace){let f=me().agents?.[e.workspace];f||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(G(f.workspace))}else if(e.allWorkspaces){let u=me();for(let f of Object.values(u.agents||{}))f?.workspace&&i.push(G(f.workspace))}else i.push(G(e.cwd));let r=G(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[l,g]=await Promise.all([n(r),s(r)]),d=t({skills:c,references:l,recipes:g});if(e.json)console.log(JSON.stringify(d.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let f of d)u[f.verdict]++;console.log();for(let f of d){let p=f.verdict==="PASS"?h.green("PASS "):f.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${p} ${h.bold(f.name)}${f.skill?.path?h.dim(` (${f.skill.path})`):""}`);for(let y of f.reasons)console.log(` ${h.dim("\xB7")} ${y}`)}console.log(),console.log(` ${h.green(`${u.PASS} PASS`)} ${h.yellow(`${u.REVIEW} REVIEW`)} ${h.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(d.some(u=>u.verdict==="FAILING")?1:0)});gt.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,o)=>{let t=me(),n=Object.entries(t.agents||{}),[s,i]=o.agent?n.find(([g])=>g===o.agent)??[]:n[0]??[];i||(console.log(h.red(` no such agent${o.agent?` "${o.agent}"`:""}`)),process.exit(1));let{loadLocalSkills:r}=await import("./loader-YFVSSYSL.js"),{pickSkillForTask:a}=await import("./select-D3XOFXA5.js"),c=await r(i.workspace);if(c.length===0){console.log(h.yellow(` ${s} has no skills`));return}let l=await a(c,e,{agent:s,minRelevant:Number(o.min)||.6});if(o.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(` ${h.green("\u2192")} ${h.bold(l.skill.frontmatter.name)} ${h.dim(`\xB7 ${l.reason}`)}`),console.log(` ${h.dim(l.skill.frontmatter.description.slice(0,140))}`)):console.log(` ${h.yellow("\xB7")} no skill for this ${h.dim(`\u2014 ${l.reason}`)}`),l.shortlist.length>1){console.log(h.dim(`
42
42
  shortlist (lexical -> judged)`));for(let g of l.shortlist.slice(0,6)){let d=g.p===void 0?" - ":g.p.toFixed(2);console.log(h.dim(` ${g.lexical.toFixed(2)} -> ${d} ${g.name}`))}}l.judged||console.log(h.dim(`
43
43
  (lexical only \u2014 set decisions.seats.skill-select.mode to judge)`)),console.log()});var Ln=new xo().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Ln.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,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=G(o.cwd),n=G(t,"references/example"),s=G(t,"references/recipes/example.yaml");we(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=G(t,".agentx/references",e),r=G(t,".agentx/references/recipes");vo(i,{recursive:!0}),vo(r,{recursive:!0});let a=yr(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let u=Wo(i,d);if(we(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),l++;continue}let p=Bo(Wo(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Ft(u,p),console.log(h.green(` + ${u}`)),c++}let g=Wo(r,`${e}.yaml`);if(we(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),l++;else if(we(s)){let d=Bo(s,"utf-8").replaceAll("example.",`${e}.`);Ft(g,d),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Ln.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,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-YFVSSYSL.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-7YFQNYLC.js"),i=G(o.cwd),r=o.from?String(o.from).split(",").map(y=>y.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([y,w])=>[y,w.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let g=s(c,e),d=G(o.referencesCwd||o.cwd),u=G(d,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${u}/`));for(let[y,w]of Object.entries(g))console.log(h.cyan(`
44
44
  --- ${y} ---`)),console.log(w.split(`
@@ -47,7 +47,7 @@ ${i.content}
47
47
  `).length>30&&console.log(h.dim(` \u2026 (${w.split(`
48
48
  `).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${u}/`)),console.log();return}vo(u,{recursive:!0});let f=0,p=0;for(let[y,w]of Object.entries(g)){let k=Wo(u,y);if(we(k)&&!o.force){console.log(h.dim(` skip ${k} (exists; --force to overwrite)`)),p++;continue}Ft(k,w),console.log(h.green(` + ${k}`)),f++}console.log(),console.log(h.dim(` ${f} written, ${p} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Ln.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:o}=await import("./loader-KKMG24O5.js"),t=await o(G(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var wr=new xo().name("hook").description("manage hooks \u2014 add to agent workspace");wr.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=me().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=G(t.workspace,".claude/settings.json"),s=we(n)?JSON.parse(Bo(n,"utf-8")):{},i=await Me([{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(!i.event||!i.value)return;s.hooks=s.hooks||{},s.hooks[i.event]=s.hooks[i.event]||[];let a={hooks:[{type:i.type,...i.type==="command"?{command:i.value}:{url:i.value}}]};i.matcher&&(a.matcher=i.matcher),s.hooks[i.event].push(a),vo(G(t.workspace,".claude"),{recursive:!0}),Ft(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var $r=new xo().name("migrate").description("import configuration from OpenClaw or other tools");$r.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,o)=>{let t=[e,G(process.env.HOME||"",".openclaw/openclaw.json"),G(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of t)if(f&&we(f)){n=f;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(Bo(n,"utf-8")),i=we(G(process.cwd(),"agentx.json"))?me():{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:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);r.find(f=>f.id==="main"||f.default)&&(c.default="main");let l=0;for(let f of r){if(f.workspace?.startsWith("/data"))continue;let p=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),y=f.groupChat?.mentionPatterns||[];if(y.some(w=>w===p)||y.push(p),i.agents[p]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:y,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!o.dryRun){vo(G(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-42ARC42I.js");w(p,i.agents[p])}}console.log(` ${h.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},d=0;for(let[f,p]of Object.entries(g)){if(!p.botToken)continue;let w=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[f]={token:p.botToken,agentBinding:w},i.channels.telegram.enabled=!0,d++}console.log(` ${h.green(d)} Telegram accounts imported`);let u=G(n,"../cron/jobs.json");if(we(u)){let f=JSON.parse(Bo(u,"utf-8")),p=0;for(let y of f.jobs||[]){let w=y.name||y.id,k=y.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[w]={enabled:y.enabled||!1,schedule:y.schedule?.expr||"0 9 * * *",timezone:y.schedule?.tz||"UTC",agent:k,prompt:y.payload?.message||"",timeout:y.payload?.timeoutSeconds||600,onError:["log"]},p++}console.log(` ${h.green(p)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
49
49
  Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await Je(i),console.log(h.green(`
50
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Jo=new xo().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 o=T(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=gs(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=we(G(r,".claude")),c=we(G(r,"CLAUDE.md")),l=we(G(r,".claude/settings.json")),g=we(G(r,".claude/skills"))?yr(G(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Jo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=T(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Wu(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function hr(e){return e===void 0?h.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,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-S3CD2IWQ.js"),{expandEnvVars:r}=await import("./config-ZUMI4IY4.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(hr(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,o,t)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-S3CD2IWQ.js"),r=Wu(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${hr(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${hr(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.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,o)=>{let{applyConfigMutation:t,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-S3CD2IWQ.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.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 o=!1,t=0,n;try{let d=T(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});ds();import{Command as Bu}from"commander";import Ho from"chalk";import{resolve as Go}from"path";import{existsSync as Ju}from"fs";var Oo=new Bu().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function mt(e){let o=Go(e,".agentx/db.sqlite");Ju(o)||(console.log(Ho.red(` No SQLite at ${o}`)),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 t=Lo({path:o});return t||(console.log(Ho.red(` Could not open ${o}`)),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)),t}function pt(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Ho.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}Oo.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=mt(Go(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
50
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Jo=new xo().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 o=T(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=gs(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=we(G(r,".claude")),c=we(G(r,"CLAUDE.md")),l=we(G(r,".claude/settings.json")),g=we(G(r,".claude/skills"))?yr(G(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,d=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",l?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${d.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Jo.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=T(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Wu(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function hr(e){return e===void 0?h.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,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-PGR2OGWC.js"),{expandEnvVars:r}=await import("./config-HCJ5NZW5.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),l=o.raw?c:r(c),g=i(l,e);o.json?console.log(JSON.stringify(g)):console.log(hr(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,o,t)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-PGR2OGWC.js"),r=Wu(o,!!t.string),a=await n(l=>{s(l,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${hr(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${hr(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.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,o)=>{let{applyConfigMutation:t,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-PGR2OGWC.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.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 o=!1,t=0,n;try{let d=T(e.config);o=!!d.business?.enabled,t=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});ds();import{Command as Bu}from"commander";import Ho from"chalk";import{resolve as Go}from"path";import{existsSync as Ju}from"fs";var Oo=new Bu().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function mt(e){let o=Go(e,".agentx/db.sqlite");Ju(o)||(console.log(Ho.red(` No SQLite at ${o}`)),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 t=Lo({path:o});return t||(console.log(Ho.red(` Could not open ${o}`)),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)),t}function pt(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Ho.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}Oo.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=mt(Go(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
51
51
  SELECT agent_id, channel, status, duration_ms,
52
52
  input_tokens, output_tokens,
53
53
  substr(message_preview, 1, 60) AS message,
@@ -428,11 +428,11 @@ return aid ?? null`}function Vh(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
428
428
  `));for(let[a,c]of Object.entries(t.agents)){let l=c.voice?.provider??t.voice.provider,g=y=>y?Gi(y):J.dim("system default"),d=Object.entries(zi(a,c.voice?.system,c.voice?.gender,t.voice,o)).filter(([,y])=>(y?.id??null)!==(i.get(a)?.id??null)).map(([y,w])=>`${J.dim(`${y}:`)} ${g(w)}`).join(J.dim(" \xB7 ")),u=l==="elevenlabs"?`elevenlabs ${c.voice?.elevenlabsVoiceId??J.dim("(default voice)")}`:`system ${g(i.get(a))}${d?J.dim(" \xB7 ")+d:""}`,f=r.filter(y=>y.agents.includes(a)).map(y=>Vi(y.voice)),p=f.length?J.yellow(` \u2014 stands in for ${f.join(", ")} (not installed)`):"";console.log(` ${a.padEnd(24)} ${u}${c.voice?.gender?J.dim(` (${c.voice.gender})`):""}${p}`)}}console.log()});Co.command("set <agent> [voice]").description(`pick an agent's voice: a system voice name, a Siri voice as siri:<name>, "${Fo}" for the OS default, or an ElevenLabs id with --provider elevenlabs`).option("--provider <provider>","system or elevenlabs").option("--lang <lang>","use this voice for lines in one language only: en, fr, ar").option("--gender <gender>","female, male or neutral; an assigned voice matches it").option("-c, --config <path>","agentx.json to change").action((e,o,t)=>{try{let n=Xt(t.config),{raw:s,summary:i}=Ey(JSON.parse(Xg(n,"utf8")),e,o,t,Tn());Kg(n,JSON.stringify(s,null,2)+`
429
429
  `),console.log(J.green(` ${e}: ${i}`)),console.log(J.dim(" A running daemon picks this up on its next line."))}catch(n){console.log(J.red(` ${n.message}`)),process.exit(1)}});function Gn(e,o){let t=xl(o,T(e));if(t.length)throw new Error(t.map(s=>s.message).join(`
430
430
  `));let n=JSON.parse(Xg(e,"utf8"));Sl(n,o),Kg(e,JSON.stringify(n,null,2)+`
431
- `)}Co.command("palette [agent] [palette]").description(`the voice orb's colours: list the palettes, or pick one for an agent (${Oa.join(", ")}; "default" follows the agent's colour)`).option("-c, --config <path>","agentx.json to read or change").action((e,o,t)=>{try{let n=Xt(t.config);if(e&&o){let i=o==="default"?null:o;Gn(n,{agents:{[e]:{palette:i}}}),console.log(J.green(` ${e}: ${i?`palette ${i}`:"palette follows its colour"}`)),console.log(J.dim(" AgentX Voice picks this up the next time its menu opens."));return}let s=T(n);if(e&&!s.agents[e])throw new Error(`No agent "${e}" in agentx.json`);console.log(J.bold(`
431
+ `)}Co.command("palette [agent] [palette]").description(`the voice orb's colours: list the palettes, or pick one for an agent (${Oa.join(", ")}; "default" follows the agent's colour, or voice.palette when it has none)`).option("-c, --config <path>","agentx.json to read or change").action((e,o,t)=>{try{let n=Xt(t.config);if(e&&o){let i=o==="default"?null:o;Gn(n,{agents:{[e]:{palette:i}}}),console.log(J.green(` ${e}: ${i?`palette ${i}`:"palette follows its colour"}`)),console.log(J.dim(" AgentX Voice picks this up the next time its menu opens."));return}let s=T(n);if(e&&!s.agents[e])throw new Error(`No agent "${e}" in agentx.json`);console.log(J.bold(`
432
432
  Orb palettes
433
433
  `));for(let i of Ta)console.log(` ${i.id.padEnd(10)} ${J.dim(i.colors.join(" "))}`);console.log(J.bold(`
434
434
  Agents
435
- `));for(let[i,r]of Object.entries(s.agents)){if(e&&i!==e)continue;let a=Nt(i,r).color,c=Ca(r.presence?.palette,a);console.log(` ${i.padEnd(24)} ${c.id.padEnd(10)} ${J.dim(c.set?"chosen":`nearest its colour ${a}`)}`)}console.log()}catch(n){console.log(J.red(` ${n.message}`)),process.exit(1)}});Co.command("look [look]").description(`what shows the assistant's state in AgentX Voice: ${ja.join(" or ")}`).option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=Xt(o.config);e!==void 0&&Gn(t,{general:{look:e}});let n=T(t).voice.look;console.log(` Shown as: ${n==="character"?"the character, above the bottom edge of the screen":"the orb, in the pill"}`),e!==void 0&&console.log(J.dim(" AgentX Voice picks this up within a few seconds."))}catch(t){console.log(J.red(` ${t.message}`)),process.exit(1)}});Co.command("start [form]").description("how the pill is when AgentX Voice starts: full, or reduced to its orb").option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=Xt(o.config);if(e!==void 0&&e!=="full"&&e!=="reduced")throw new Error("The pill starts full or reduced");e!==void 0&&Gn(t,{general:{startReduced:e==="reduced"}});let n=T(t).voice;console.log(` Starts as: ${n.startReduced?"the orb alone, reduced":"the full pill"}`),n.startReduced&&n.look==="character"&&console.log(J.dim(" No effect while the character is shown: the pill has no orb to reduce to.")),e!==void 0&&console.log(J.dim(" AgentX Voice picks this up the next time it starts."))}catch(t){console.log(J.red(` ${t.message}`)),process.exit(1)}});Co.command("stroll [state]").description("whether the character takes a slow stroll when it has nothing to do: on or off").option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=Xt(o.config);if(e!==void 0&&e!=="on"&&e!=="off")throw new Error("The stroll is on or off");e!==void 0&&Gn(t,{general:{stroll:e==="on"}});let n=T(t).voice;console.log(` When idle: ${n.stroll?"the character takes a slow stroll now and then":"the character stays where it rests"}`),n.stroll&&n.look!=="character"&&console.log(J.dim(" No effect while the orb is shown.")),e!==void 0&&console.log(J.dim(" AgentX Voice picks this up within a few seconds."))}catch(t){console.log(J.red(` ${t.message}`)),process.exit(1)}});Co.command("card").description("the answer shown in the pill: how long it stays open and how tall it grows").option("--timeout <seconds>",`seconds it stays open once spoken, ${Xi.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${Xi.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let o=Xt(e.config),t={};e.timeout!==void 0&&(t.timeout=Number(e.timeout)),e.maxHeight!==void 0&&(t.maxHeight=Number(e.maxHeight)),Object.keys(t).length&&Gn(o,{general:{card:t}});let n=T(o).voice.card,s=n.timeout===0?"until closed":`${n.timeout} s after it is spoken`;console.log(` Answer card: open ${s}, at most ${n.maxHeight} pt tall`),Object.keys(t).length&&console.log(J.dim(" AgentX Voice picks this up within a few seconds."))}catch(o){console.log(J.red(` ${o.message}`)),process.exit(1)}});import{Command as Ay}from"commander";import N from"chalk";var Qo=new Ay().name("attach").description("wear an agentx agent identity in this Claude Code session"),ti=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${rt()}`;function ni(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function si(e,o,t){let n=await fetch(`${e}${o}`,{method:t?"POST":"GET",headers:{"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0}),s=await n.text(),i=null;try{i=s?JSON.parse(s):null}catch{}if(!n.ok)throw new Error(i?.error||s||`HTTP ${n.status}`);return i}function ii(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${N.cyan("agentx daemon start")}`:o}function Zg(e){return e==="auto"?N.yellow:e==="manual"?N.gray:N.green}function Ty(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):N.gray("(not bound)"),n=e.pending?N.yellow(`${e.pending} pending`):N.gray("empty"),s=o?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold(t)} ${Zg(e.mode)(e.mode)} ${n} ${N.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}function jy(e){let o=e.filter(n=>n.agentIds.length>0),t=e.filter(n=>n.watch&&n.agentIds.length===0);return{bound:o,watching:t,idle:e.length-o.length-t.length}}function Oy(e,o=!1){let t=e.watch?.subscriptions.map(s=>s.kinds.join("|")).join(", ")||"default",n=o?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold("watching")} ${N.gray(t)} ${N.gray(e.sessionId)}${n}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}Qo.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Mi.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ti).action(async(e,o)=>{let t=ni(o.session);t||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")} (list them with ${N.cyan("agentx attach list")}).`),process.exit(1)),Xa(o.mode)||(console.error(N.red(`Invalid mode "${o.mode}". Expected one of: ${Mi.join(", ")}`)),process.exit(1)),Nn()||(console.error(N.yellow("Attach hooks are not installed yet.")),console.error(`Run ${N.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await si(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${N.green("\u2713")} This session is now wearing ${N.bold(e)} (${Zg(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(N.yellow(` ${s} message(s) already queued for it.`)),console.log(N.gray(o.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":o.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(N.red(`Bind failed: ${ii(n)}`)),process.exit(1)}});function Qg(e){let o=(e??"").split(",").map(t=>t.trim()).filter(Boolean);return o.length?o:void 0}function Cy(e){let o=Qg(e.kinds),t=Qg(e.agents);if(!o&&!t&&!e.match)return;let n={kinds:o??["*"]};return t&&(n.agents=t),e.match&&(n.match=e.match),[n]}Qo.command("watch").description("watch this session: no identity, no messages, a short event digest on each prompt").option("--kinds <list>","event kinds or types to include, comma separated (default: failures, completions, approvals waiting, peers down)").option("--agents <list>","only events for these agents, comma separated").option("--match <text>","only events whose summary contains this text").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ti).action(async e=>{let o=ni(e.session);o||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")}.`),process.exit(1)),Nn()||(console.error(N.yellow("Attach hooks are not installed yet.")),console.error(`Run ${N.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{await si(e.url,"/attach/watch",{sessionId:o,cwd:process.cwd(),subscriptions:Cy(e)}),console.log(`${N.green("\u2713")} This session is now ${N.bold("watching")}. It answers for no agent.`),console.log(N.gray(" Each time you send a prompt, it gets a short list of new events.")),console.log(N.gray(` Stop with ${N.cyan("agentx attach detach")}.`))}catch(t){console.error(N.red(`Watch failed: ${ii(t)}`)),process.exit(1)}});Qo.command("detach").description("stop wearing an identity or watching in this session (queued work falls back to spawned agents)").option("--agent <id>","release only this identity (default: all)").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ti).action(async e=>{let o=ni(e.session);o||(console.error(N.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await si(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${N.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(N.red(`Detach failed: ${ii(t)}`)),process.exit(1)}});Qo.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",ti).option("--json","raw JSON output").action(async e=>{let o=ni();try{let n=(await si(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:Nn(),sessions:n},null,2));return}console.log(),console.log(Nn()?`${N.green("\u2713")} Attach hooks installed ${N.gray(In())}`:`${N.yellow("!")} Attach hooks not installed \u2014 run ${N.cyan("agentx attach install")}`),console.log();let{bound:s,watching:i,idle:r}=jy(n);if(console.log(N.bold(" Identities")),s.length===0)console.log(N.gray(" No session is wearing an identity right now."));else for(let a of s)Ty(a,a.sessionId===o);if(i.length>0){console.log(),console.log(N.bold(" Watchers"));for(let a of i)Oy(a,a.sessionId===o)}r>0&&console.log(N.gray(`
435
+ `));for(let[i,r]of Object.entries(s.agents)){if(e&&i!==e)continue;let a=Nt(i,r).color,c=Ca(r.presence,s.voice.palette);console.log(` ${i.padEnd(24)} ${c.id.padEnd(10)} ${J.dim(c.set?"chosen":r.presence?.color?`nearest its colour ${a}`:"the default, voice.palette")}`)}console.log()}catch(n){console.log(J.red(` ${n.message}`)),process.exit(1)}});Co.command("look [look]").description(`what shows the assistant's state in AgentX Voice: ${ja.join(" or ")}`).option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=Xt(o.config);e!==void 0&&Gn(t,{general:{look:e}});let n=T(t).voice.look;console.log(` Shown as: ${n==="character"?"the character, above the bottom edge of the screen":"the orb, in the pill"}`),e!==void 0&&console.log(J.dim(" AgentX Voice picks this up within a few seconds."))}catch(t){console.log(J.red(` ${t.message}`)),process.exit(1)}});Co.command("start [form]").description("how the pill is when AgentX Voice starts: full, or reduced to its orb").option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=Xt(o.config);if(e!==void 0&&e!=="full"&&e!=="reduced")throw new Error("The pill starts full or reduced");e!==void 0&&Gn(t,{general:{startReduced:e==="reduced"}});let n=T(t).voice;console.log(` Starts as: ${n.startReduced?"the orb alone, reduced":"the full pill"}`),n.startReduced&&n.look==="character"&&console.log(J.dim(" No effect while the character is shown: the pill has no orb to reduce to.")),e!==void 0&&console.log(J.dim(" AgentX Voice picks this up the next time it starts."))}catch(t){console.log(J.red(` ${t.message}`)),process.exit(1)}});Co.command("stroll [state]").description("whether the character takes a slow stroll when it has nothing to do: on or off").option("-c, --config <path>","agentx.json to read or change").action((e,o)=>{try{let t=Xt(o.config);if(e!==void 0&&e!=="on"&&e!=="off")throw new Error("The stroll is on or off");e!==void 0&&Gn(t,{general:{stroll:e==="on"}});let n=T(t).voice;console.log(` When idle: ${n.stroll?"the character takes a slow stroll now and then":"the character stays where it rests"}`),n.stroll&&n.look!=="character"&&console.log(J.dim(" No effect while the orb is shown.")),e!==void 0&&console.log(J.dim(" AgentX Voice picks this up within a few seconds."))}catch(t){console.log(J.red(` ${t.message}`)),process.exit(1)}});Co.command("card").description("the answer shown in the pill: how long it stays open and how tall it grows").option("--timeout <seconds>",`seconds it stays open once spoken, ${Xi.timeout.join("\u2013")}; 0 keeps it open until closed`).option("--max-height <points>",`tallest it grows before it scrolls, ${Xi.maxHeight.join("\u2013")}`).option("-c, --config <path>","agentx.json to read or change").action(e=>{try{let o=Xt(e.config),t={};e.timeout!==void 0&&(t.timeout=Number(e.timeout)),e.maxHeight!==void 0&&(t.maxHeight=Number(e.maxHeight)),Object.keys(t).length&&Gn(o,{general:{card:t}});let n=T(o).voice.card,s=n.timeout===0?"until closed":`${n.timeout} s after it is spoken`;console.log(` Answer card: open ${s}, at most ${n.maxHeight} pt tall`),Object.keys(t).length&&console.log(J.dim(" AgentX Voice picks this up within a few seconds."))}catch(o){console.log(J.red(` ${o.message}`)),process.exit(1)}});import{Command as Ay}from"commander";import N from"chalk";var Qo=new Ay().name("attach").description("wear an agentx agent identity in this Claude Code session"),ti=process.env.AGENTX_DAEMON_URL||`http://127.0.0.1:${rt()}`;function ni(e){return e||process.env.CLAUDE_CODE_SESSION_ID||void 0}async function si(e,o,t){let n=await fetch(`${e}${o}`,{method:t?"POST":"GET",headers:{"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0}),s=await n.text(),i=null;try{i=s?JSON.parse(s):null}catch{}if(!n.ok)throw new Error(i?.error||s||`HTTP ${n.status}`);return i}function ii(e){let o=e?.message??String(e);return/ECONNREFUSED|fetch failed/i.test(o)?`daemon not reachable \u2014 start it with ${N.cyan("agentx daemon start")}`:o}function Zg(e){return e==="auto"?N.yellow:e==="manual"?N.gray:N.green}function Ty(e,o=!1){let t=e.agentIds.length?e.agentIds.join(", "):N.gray("(not bound)"),n=e.pending?N.yellow(`${e.pending} pending`):N.gray("empty"),s=o?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold(t)} ${Zg(e.mode)(e.mode)} ${n} ${N.gray(e.sessionId)}${s}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}function jy(e){let o=e.filter(n=>n.agentIds.length>0),t=e.filter(n=>n.watch&&n.agentIds.length===0);return{bound:o,watching:t,idle:e.length-o.length-t.length}}function Oy(e,o=!1){let t=e.watch?.subscriptions.map(s=>s.kinds.join("|")).join(", ")||"default",n=o?N.cyan(" \u2190 this session"):"";console.log(` ${N.bold("watching")} ${N.gray(t)} ${N.gray(e.sessionId)}${n}`),e.cwd&&console.log(` ${N.gray(e.cwd)}`)}Qo.command("as <agent>",{isDefault:!0}).description("bind this Claude Code session to an agent identity").option("-m, --mode <mode>",`delivery mode: ${Mi.join(" | ")}`,"notify").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ti).action(async(e,o)=>{let t=ni(o.session);t||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")} (list them with ${N.cyan("agentx attach list")}).`),process.exit(1)),Xa(o.mode)||(console.error(N.red(`Invalid mode "${o.mode}". Expected one of: ${Mi.join(", ")}`)),process.exit(1)),Nn()||(console.error(N.yellow("Attach hooks are not installed yet.")),console.error(`Run ${N.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{let n=await si(o.url,"/attach/bind",{sessionId:t,agentId:e,mode:o.mode,cwd:process.cwd()});console.log(`${N.green("\u2713")} This session is now wearing ${N.bold(e)} (${Zg(o.mode)(o.mode)}).`);let s=Number(n?.pending??0);s>0&&console.log(N.yellow(` ${s} message(s) already queued for it.`)),console.log(N.gray(o.mode==="auto"?" Queued messages will be answered automatically at the end of each turn.":o.mode==="notify"?" You'll be told when messages arrive; run /inbox to answer them.":" Nothing will interrupt you; run /inbox to check for messages."))}catch(n){console.error(N.red(`Bind failed: ${ii(n)}`)),process.exit(1)}});function Qg(e){let o=(e??"").split(",").map(t=>t.trim()).filter(Boolean);return o.length?o:void 0}function Cy(e){let o=Qg(e.kinds),t=Qg(e.agents);if(!o&&!t&&!e.match)return;let n={kinds:o??["*"]};return t&&(n.agents=t),e.match&&(n.match=e.match),[n]}Qo.command("watch").description("watch this session: no identity, no messages, a short event digest on each prompt").option("--kinds <list>","event kinds or types to include, comma separated (default: failures, completions, approvals waiting, peers down)").option("--agents <list>","only events for these agents, comma separated").option("--match <text>","only events whose summary contains this text").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ti).action(async e=>{let o=ni(e.session);o||(console.error(N.red("Could not determine the Claude Code session id.")),console.error(`Run this inside a Claude Code session, or pass ${N.cyan("--session <id>")}.`),process.exit(1)),Nn()||(console.error(N.yellow("Attach hooks are not installed yet.")),console.error(`Run ${N.cyan("agentx attach install")} once, then try again.`),process.exit(1));try{await si(e.url,"/attach/watch",{sessionId:o,cwd:process.cwd(),subscriptions:Cy(e)}),console.log(`${N.green("\u2713")} This session is now ${N.bold("watching")}. It answers for no agent.`),console.log(N.gray(" Each time you send a prompt, it gets a short list of new events.")),console.log(N.gray(` Stop with ${N.cyan("agentx attach detach")}.`))}catch(t){console.error(N.red(`Watch failed: ${ii(t)}`)),process.exit(1)}});Qo.command("detach").description("stop wearing an identity or watching in this session (queued work falls back to spawned agents)").option("--agent <id>","release only this identity (default: all)").option("--session <id>","Claude Code session id (defaults to $CLAUDE_CODE_SESSION_ID)").option("--url <url>","daemon base url",ti).action(async e=>{let o=ni(e.session);o||(console.error(N.red("Could not determine the Claude Code session id. Pass --session <id>.")),process.exit(1));try{await si(e.url,"/attach/detach",{sessionId:o,agentId:e.agent}),console.log(`${N.green("\u2713")} Detached. New messages will spawn agents the normal way.`)}catch(t){console.error(N.red(`Detach failed: ${ii(t)}`)),process.exit(1)}});Qo.command("list").alias("status").description("show every attached session on this machine").option("--url <url>","daemon base url",ti).option("--json","raw JSON output").action(async e=>{let o=ni();try{let n=(await si(e.url,"/attach/sessions"))?.sessions??[];if(e.json){console.log(JSON.stringify({hooksInstalled:Nn(),sessions:n},null,2));return}console.log(),console.log(Nn()?`${N.green("\u2713")} Attach hooks installed ${N.gray(In())}`:`${N.yellow("!")} Attach hooks not installed \u2014 run ${N.cyan("agentx attach install")}`),console.log();let{bound:s,watching:i,idle:r}=jy(n);if(console.log(N.bold(" Identities")),s.length===0)console.log(N.gray(" No session is wearing an identity right now."));else for(let a of s)Ty(a,a.sessionId===o);if(i.length>0){console.log(),console.log(N.bold(" Watchers"));for(let a of i)Oy(a,a.sessionId===o)}r>0&&console.log(N.gray(`
436
436
  ${r} registered session(s) with no binding.`)),console.log()}catch(t){console.error(N.red(`Could not read attach state: ${ii(t)}`)),process.exit(1)}});Qo.command("install").description("wire the attach hooks into ~/.claude/settings.json (one time, all sessions)").option("--port <n>","daemon port the hooks should call (default: node.bind in agentx.json)").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--no-guard","skip the PreToolUse guard hook (not recommended)").action(e=>{try{let o=String(e.port||rt()),t=md(o,{path:e.path,withGuard:e.guard});console.log(t.changed?`${N.green("\u2713")} Installed attach hooks in ${N.gray(t.path)}`:`${N.green("\u2713")} Attach hooks already up to date in ${N.gray(t.path)}`),console.log(N.gray(` Events: ${t.events.join(", ")} \u2192 127.0.0.1:${o}`)),t.guardInstalled?(console.log(N.gray(" PreToolUse guard installed at user scope.")),console.log(N.gray(` (An attached session runs under your permissions, not the agent's workspace
437
437
  settings \u2014 without this an attached production identity would be less
438
438
  guarded than a spawned one.)`))):console.log(N.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${N.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(N.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Qo.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=pd({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(o.path)} (${o.events.join(", ")})`:`${N.gray("Nothing to remove.")}`),e.removeGuard||console.log(N.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(N.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});te();import{Command as Iy}from"commander";import be from"chalk";var ri=new Iy().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function om(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=T(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function tm(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function em(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s`:o<3600?`${Math.round(o/60)}m`:o<86400?`${Math.round(o/3600)}h`:`${Math.round(o/86400)}d`}function Ny(e){return e==="busy"?be.magenta:e==="warm-hot"?be.green:e==="warm-cold"?be.cyan:e==="idle"?be.yellow:e==="dead"?be.red:be.dim}ri.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=om(e),n;try{n=await fetch(`${o}/api/processes`,{headers:tm(t)})}catch(r){console.log(be.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(be.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(be.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(be.dim(" (no processes)"));return}for(let r of i){let a=Ny(r.state)(r.state.padEnd(9)),c=em(r.spawnedAt),l=r.lastTurnAt?em(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?be.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?be.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):be.dim("sess=\u2014"),u=r.pendingTaskId?be.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${be.bold(r.key.agentId)}${be.dim(":"+r.key.channel+":"+r.key.chatId)} ${be.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${be.red("dead:")} ${r.deadReason}`)}});ri.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=om(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:tm(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(be.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(be.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(be.red(` ${a}`)),process.exit(1)}console.log(be.green(` killed ${e}:${o}:${t}`))});import{Command as Ry}from"commander";import Fe from"chalk";import{existsSync as Ur,rmSync as _y}from"fs";import{resolve as Fr}from"path";var Kt=new Ry().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Kt.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,o,t)=>{o.length===0&&(console.log(Fe.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await ec(e,o,{verbose:n}),r=Date.now()-s;console.log(Fe.green(` \u2713 indexed ${i.docs} doc(s) for ${Fe.bold(e)} in ${r}ms`)),console.log(Fe.dim(` \u2192 ${i.path}`))});Kt.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Fr(e.cwd,".agentx","rag");if(!Ur(o)){console.log(Fe.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Ur(Fr(o,s,"index.json")));if(n.length===0){console.log(Fe.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Li(s);console.log(` ${Fe.bold(s)} ${i.docs} doc(s) ${Fe.dim(i.path)}`)}});Kt.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,o,t)=>{let n=parseInt(t.k,10)||5,s=oc(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Li(e);i.exists?console.log(Fe.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Fe.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Fe.bold(i.title)} ${Fe.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Fe.dim(i.path)}`),console.log(` ${Fe.dim(i.snippet.slice(0,200))}`)});Kt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Fr(process.cwd(),".agentx","rag",e);if(!Ur(o)){console.log(Fe.dim(` no index for ${e} \u2014 nothing to clear`));return}_y(o,{recursive:!0,force:!0}),console.log(Fe.green(` \u2713 cleared index for ${e}`))});te();import{Command as Dy}from"commander";import Z from"chalk";import Qt from"prompts";var yt=new Dy().name("backlog").description("manage the local backlog used by business workSource=backlog");function zn(e){let o=T(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new Nl(n)}}function Py(e){return e?Z.cyan(`${e.type}:${e.project}#${e.iid}`):Z.dim("manual")}function My(e){return{todo:Z.gray("todo"),doing:Z.yellow("doing"),blocked:Z.red("blocked"),done:Z.green("done")}[e]}yt.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:o}=zn(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(Z.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?Z.magenta(`@${n.assignee}`):Z.dim("unassigned");console.log(` ${My(n.status).padEnd(7)} ${Py(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(Z.dim(` ${n.source.url}`))}console.log(),console.log(Z.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});yt.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=zn(t.config);n.store.findById(e)||(console.error(Z.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(Z.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Rl([o],i.source,n.config),a=await Zi(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(Z.dim(" sync:"),...c));console.log(a.ok?Z.dim(` synced -> ${a.url??i.source.type}`):Z.yellow(` sync failed: ${a.error}`))}});yt.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,o)=>{let t=zn(o.config);t.store.findById(e)||(console.error(Z.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(Z.green(` done: ${s.title}`)),s.source){let i=await Zi(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(Z.dim(" sync:"),...r));console.log(i.ok?Z.dim(` synced -> ${i.url??s.source.type}`):Z.yellow(` sync failed: ${i.error}`))}});yt.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=zn(o.config);t.remove(e)||(console.error(Z.red(` item ${e} not found`)),process.exit(1)),console.log(Z.green(` removed ${e}`))});yt.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 o=zn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(Z.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=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Qt({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!t&&(console.error(Z.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(Z.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?qy(o.config):Uy(o.config);w.length?(i=(await Qt({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Qt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Qt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Qt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(Z.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Fy(o.config,i,a):await Wy(o.config,i,a);if(!c.length){console.log(Z.yellow(" no open issues matched"));return}console.log(Z.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(o.store.list().map(w=>w.id)),d=c.map(w=>{let k=Qi({type:s,project:l,iid:w.iid,url:w.url}),b=g.has(k),$=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${$}${b?Z.dim(" (already imported)"):""}`,value:w,disabled:b}}),f=(await Qt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(Z.dim(" nothing selected"));return}let p=f.map(w=>{let k={type:s,host:s==="gitlab"?Ly(o.config):void 0,project:l,iid:w.iid,url:w.url};return{id:Qi(k),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),y=o.store.addMany(p);console.log(Z.green(` imported ${y.length} item${y.length===1?"":"s"}`));for(let w of y)console.log(Z.dim(` ${w.id} \u2014 ${w.title}`))});function Ly(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function qy(e){let o=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&o.add(n.project);let t=e.business?.workSource;if(t?.type==="gitlab")for(let n of t.projects??[])o.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&o.add(n.id);return[...o].sort()}function Uy(e){let o=new Set;for(let t of e.channels.github?.routes??[])t.repo&&t.repo!=="*"&&o.add(t.repo);return[...o].sort()}async function Fy(e,o,t){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});t&&s.set("search",t);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(o)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.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 Wy(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(nm)}i=`https://api.github.com/repos/${o}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(nm):[]}function nm(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(o=>typeof o=="string"?o:o.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as By}from"commander";import W from"chalk";import{existsSync as Jy,readFileSync as Hy}from"fs";import{resolve as Gy}from"path";import zy from"prompts";te();function sm(e){let o=e||Gy(process.cwd(),"agentx.json");return Jy(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Hy(o,"utf-8"))}async function Vy(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await zy([{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||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Io=new By().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Io.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${Fi})`,Fi).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,o)=>{if(!e){Io.help();return}o.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let t=Ui(e);t||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=sm(o.config),s=Ra(n);n.agents?.[o.agent]||(console.log(W.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Vy(o.notify,s),r=o.id||mc(t.matched,o.agent),a=uc({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:pc(o.onError),enabled:!o.disabled}),c=a.onError,l=await re(d=>Ie(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(W.dim(` Agent: ${o.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});Io.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let t=sm(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=hc(fc(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])Io.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await $c(t,o);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});Io.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await re(t=>{if(!It(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);rc(t,`crons.${e}`)});o.success||(console.log(W.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",yc,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",wc,"reject an agent's pending create/delete request (drops the request)"]])Io.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});Io.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Ui(o);t||(console.log(W.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(W.green(` "${o}"`)),console.log(W.dim(` \u2192 ${t.cron}`)),console.log(W.dim(` \u2192 ${t.human}`))});import{Command as Yy}from"commander";import ke from"chalk";import No from"chalk";function im(e=Date.now()){return{id:"sample",title:"New meeting date for Sam",context:"He wrote: \u201CNo problem, pick the time that suits you and tell me.\u201D",ask:"Which date should I offer him?",recommend:"Thursday 14:00: your calendar is free and it is before his weekend",choices:["Thursday 14:00","Sunday 11:00","Monday 16:00"],draft:"Thanks Sam. Could we meet on {choice}? If that doesn't suit you, tell me what does.",say:"Sam is waiting for a new meeting date. Pick one.",if_silent:"keep",expires:new Date(e+2*864e5).toISOString(),raised_by:"assistant",created_at:new Date(e-12*6e4).toISOString(),status:"pending",origin:{kind:"reminder",id:"sample",title:"Reply to Sam about the meeting"}}}var rm=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function am(e){e.command("popup").description("show a card on this Mac now and record your answer (macOS)").argument("[key]","card key from `agentx approvals list`, e.g. card:2026-01-05-new-meeting-date-ab12").option("--sample","show a sample card; nothing is recorded").option("--pick <n>","start with option n picked (previews)").option("--theme <system|light|dark>","override approvals.popup.theme").option("--capture <file.png>","save a picture of the card window").option("--timeout <seconds>","override approvals.popup.timeoutSeconds").action(async(o,t)=>{if(process.platform!=="darwin"){console.error(No.red(" the popup needs macOS")),process.exitCode=1;return}let n=o?.startsWith("card:")?o.slice(5):o,s=t.sample?im():n?Xc(process.cwd(),n):null;if(!s||s.status!=="pending"){console.error(No.red(o?` no card waiting for "${o}"`:" give a card key, or --sample")),process.exitCode=1;return}let i={...Pt().popup};(t.theme==="system"||t.theme==="light"||t.theme==="dark")&&(i.theme=t.theme),t.timeout&&(i.timeoutSeconds=Number(t.timeout));let r=await el(s,i,{from:t.sample?"Assistant":void 0,capture:t.capture,pick:Number(t.pick)||void 0});if(t.capture&&console.log(No.dim(` picture saved to ${t.capture}`)),t.sample){console.log(` answer (not recorded): ${JSON.stringify(r)}`);return}if(r.action==="dismiss"){console.log(No.dim(` not answered${r.why?` (${r.why})`:""}; the card is still waiting`));return}let a=await xs({root:process.cwd()},`card:${s.id}`,r.action,{by:"operator (popup)",...r.action==="yes"?{choice:r.choice,text:r.text}:{}});if(!a.ok){console.error(No.red(` ${a.error}`)),process.exitCode=1;return}console.log(No.green(` \u2713 ${a.message}`))}),e.command("checkin").description("run a check-in now: waiting cards come back, open reminders get cards (daemon, macOS)").option("--daily","the daily pass: every open reminder, not only those due soon").action(async o=>{let t={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(t.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${rm()}/approvals/checkin`,{method:"POST",headers:t,body:JSON.stringify({daily:!!o.daily})}),s=await n.json().catch(()=>({}));if(!n.ok){console.error(No.red(` ${s.error??n.status}`)),process.exitCode=1;return}console.log(No.green(` \u2713 ${s.started} pass started; agents are writing cards. Watch: agentx approvals list`))}catch(n){console.error(No.red(` couldn't reach the daemon at ${rm()}: ${n?.message??n}`)),process.exitCode=1}})}var Ro=new Yy("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, WhatsApp replies)"),Xy={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki",whatsapp:"whatsapp",request:"request"};function cm(){return{root:process.cwd()}}function Wr(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Ky(e){console.log(` ${ke.cyan(e.key)} ${ke.dim(`[${Xy[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?ke.dim(` (later: until ${Wr(e.snoozed_until)})`):""}`),console.log(` ${ke.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${ke.green("Recommends:")} ${e.recommend}`),e.choices?.forEach((o,t)=>console.log(` ${ke.magenta(`${t+1}.`)} ${o}`)),e.expires&&console.log(ke.yellow(` Expires ${Wr(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(ke.dim(` ${e.detail}`)),e.source&&console.log(ke.dim(` ${e.source}`)),console.log(ke.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Ro.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let o=Zc(cm(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log(ke.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log(ke.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)Ky(t),console.log();console.log(ke.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function Br(e,o,t){let n=Pt(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error(ke.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await xs(cm(),e,o,{force:t.force,note:t.note,laterHours:s,choice:t.choice,text:t.text});if(!i.ok){console.error(ke.red(` ${i.error}`)),process.exitCode=1;return}console.log(ke.green(` \u2713 ${i.message}`))}Ro.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").option("--choice <n>","cards with choices: which one, by number or label").option("--text <message>","cards with a suggested message: the message as you want it sent").action((e,o)=>Br(e,"yes",o));Ro.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,o)=>Br(e,"no",o));Ro.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,o)=>Br(e,"later",o));Ro.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${Yc.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").option("--choice <label>","a ready-made answer; repeat for up to 5",(e,o=[])=>[...o,e]).option("--draft <message>","a suggested message; {choice} is replaced by the pick").option("--say <line>","the short line the Mac popup speaks (default: the title)").option("--context <text>","a few lines of background, shown above the question").action(e=>{let o=Pt(),t=Kc(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source,choices:e.choice,draft:e.draft,say:e.say,context:e.context},{settings:o});if(!t.ok){console.error(ke.red(` ${t.error}`)),process.exitCode=1;return}console.log(ke.green(` \u2713 card:${t.card.id} raised; expires ${Wr(t.card.expires)}, then: ${t.card.if_silent}`))});am(Ro);Ro.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').option("--popup <on|off>","Mac popup for new cards (macOS)").option("--popup-speak <on|off>","the popup speaks a short line").option("--popup-voice <name>",'voice for the spoken line; "default" for the system voice').option("--popup-sound <name>",'system sound, like Glass; "none" for silence').option("--popup-timeout <seconds>","how long the popup waits for you").option("--popup-style <card|dialog>","the web card, or plain macOS dialogs").option("--popup-theme <system|light|dark>","the card's colours").option("--checkin <on|off>","check-ins: waiting cards and open reminders, a few times a day (macOS)").option("--checkin-times <HH:MM,...>","local times of the normal passes").option("--checkin-daily <HH:MM>","local time of the daily pass").option("--checkin-lists <list,...>","your Reminders lists to look at").option("--checkin-agent <id>",'agent that writes cards for reminders no agent owns; "none" to clear').action(async e=>{let o={},t=(l,g)=>{if(g===void 0)return;let d=Number(g);if(!(d>0))throw new Error(`${l} must be a positive number`);return d},n=(l,g)=>{if(g!==void 0){if(g==="on")return!0;if(g==="off")return!1;throw new Error(`${l} takes on or off`)}};try{o.defaultExpiryDays=t("--expiry-days",e.expiryDays),o.maxExpiryDays=t("--max-expiry-days",e.maxExpiryDays),o.laterHours=t("--later-hours",e.laterHours),o.notifyAgent=n("--notify-agent",e.notifyAgent),o.digestEnabled=n("--digest",e.digest),o.popupEnabled=n("--popup",e.popup),o.popupSpeak=n("--popup-speak",e.popupSpeak),e.popupVoice!==void 0&&(o.popupVoice=e.popupVoice==="default"?null:e.popupVoice),e.popupSound!==void 0&&(o.popupSound=e.popupSound==="none"?"":e.popupSound),o.popupTimeoutSeconds=t("--popup-timeout",e.popupTimeout),e.popupStyle!==void 0&&(o.popupStyle=e.popupStyle),e.popupTheme!==void 0&&(o.popupTheme=e.popupTheme),o.checkinEnabled=n("--checkin",e.checkin);let l=g=>g?.split(",").map(d=>d.trim()).filter(Boolean);if(o.checkinTimes=l(e.checkinTimes),e.checkinDaily!==void 0&&(o.checkinDailyAt=e.checkinDaily),o.checkinLists=l(e.checkinLists),e.checkinAgent!==void 0&&(o.checkinAgent=e.checkinAgent==="none"?null:e.checkinAgent),e.digestTime!==void 0&&(o.digestTime=e.digestTime),e.digestTimezone!==void 0&&(o.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")o.destination=null;else{let g=Fl(e.digestTo);if(!g)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=g}}catch(l){console.error(ke.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(o).some(l=>l!==void 0)){let l=await Wl(o);if(!l.success){console.error(ke.red(` ${l.error}`)),process.exitCode=1;return}console.log(ke.green(" \u2713 saved")+(l.reloaded?ke.dim(" (daemon reloaded)"):""))}let i=Pt(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`);let a=i.popup;console.log(` Mac popup ${a.enabled?`on: ${a.style}, sound ${a.sound||"none"}, ${a.speak?`speaks${a.voice?` (${a.voice})`:""}`:"silent"}, waits ${a.timeoutSeconds}s`:"off"}`);let c=i.checkin;console.log(` Check-ins ${c.enabled?`on: daily ${c.dailyAt}, then ${c.times.join(", ")}; lists ${c.lists.join(", ")}; agent ${c.agent??"none"}`:"off"}`)});import{Command as Qy}from"commander";import z from"chalk";te();ds();Fp();var oo=new Qy("people").description("the humans who talk to your agents: one person per human, whatever channel they use"),Zy=["owner","member","guest"];function ai(){let e=90;try{e=T().members.logRetentionDays}catch{}return new cc(process.cwd(),Date.now,e)}var lm=(e,o=[])=>[...o,e];function mm(e){let o=[];try{o=Object.keys(T().agents)}catch{return}let t=e.filter(n=>!o.includes(n));t.length&&(console.log(z.yellow(` ! not an agent on this machine: ${t.join(", ")}. Agents here: ${o.join(", ")||"none"}.`)),console.log(z.yellow(" Keep it only if it runs on another node; a mistyped id reaches nothing.")))}var pm="An owner reaches every agent and cannot be limited. Change the role first if that is what you want.",ew="An owner is never limited. Change the role first if that is what you want.",Jr=["tools","skills"];function ow(e){let o=e.toLowerCase().replace(/^(tool|skill)$/,"$1s");return Jr.includes(o)?o:null}async function Zt(e){let o="",t=await re(n=>{n.people=Array.isArray(n.people)?n.people:[],o=e(n.people)});t.success||(console.error(z.red(`\u2717 ${(t.error??"").replace(/^Mutator threw: /,"")}`)),process.exit(1)),console.log(z.green(`\u2713 ${o}`)),t.reloaded&&console.log(z.dim(" daemon hot-reloaded"))}function Vn(e,o){let t=e.find(n=>n?.id===o);if(!t)throw new Error(`No person "${o}". See \`agentx people list\`.`);return t.identities=Array.isArray(t.identities)?t.identities:[],t}function um(e,o){let t=_i(e),n=_i(o);return!!t&&!!n&&t.channel===n.channel&&t.value===n.value}function fm(e){let o=Jr.filter(t=>e.deny?.[t]?.length).map(t=>` \xB7 no ${t}: ${e.deny[t].join(", ")}`).join("");console.log(` ${z.bold(e.id)} ${e.name} ${z.dim(`\xB7 ${e.role}`)}${e.agents?.length?z.dim(` \xB7 agents: ${e.agents.join(", ")}`):""}${z.dim(o)}`),console.log(z.dim(e.identities.length?` ${e.identities.join(", ")}`:" no identities yet: agentx people link "+e.id+" <channel:id>"))}oo.command("list",{isDefault:!0}).alias("ls").description("everyone, with their channel identities").option("--json","machine-readable output").action(e=>{let o=T().people;if(e.json){console.log(JSON.stringify(o,null,2));return}console.log(),o.length===0&&(console.log(z.dim(` no people listed. What you do on this machine (voice, app, dashboard) is recorded as "${Ri}"; senders on other channels are unknown.`)),console.log(z.dim(" add yourself: agentx people add <id> --name <name> --role owner --identity <channel:id>")));for(let t of o)fm(t);console.log()});oo.command("add <id>").description("add a person").requiredOption("--name <name>","their name").option("--role <role>",`${Zy.join(" | ")}`,"member").option("--identity <channel:id>","a login, a Telegram id or a WhatsApp number (repeatable)",lm,[]).option("--agent <id>","an agent this person may reach; repeat for several. None: every agent",lm,[]).action(async(e,o)=>{await Zt(t=>{if(t.some(n=>n?.id===e))throw new Error(`"${e}" is already listed. Add an identity with \`agentx people link ${e} <channel:id>\`.`);if(o.role==="owner"&&o.agent.length)throw new Error(pm);return t.push({id:e,name:o.name,role:o.role,identities:o.identity,agents:o.agent}),`added ${e} (${o.role})${o.agent.length?`, may reach ${o.agent.join(", ")}`:""}`}),mm(o.agent)});oo.command("allow <id> <agents...>").description('limit a person to these agents (ids, space-separated). "all" lifts the limit').action(async(e,o)=>{let t=o.length===1&&o[0].toLowerCase()==="all";await Zt(n=>{let s=Vn(n,e);if(!t&&s.role==="owner")throw new Error(pm);return s.agents=t?[]:[...new Set(o)],t?`${e} may reach every agent`:`${e} may reach ${s.agents.join(", ")} and no other agent`}),t||mm(o)});oo.command("deny <id> <level> <names...>").description(`stop a person's turns using these tools or skills. Level: tools | skills. Names match without case; * is a wildcard. "none" lifts the limit`).action(async(e,o,t)=>{let n=ow(o);n||(console.error(z.red(`\u2717 level must be one of: ${Jr.join(", ")}`)),process.exit(1));let s=t.length===1&&t[0].toLowerCase()==="none";await Zt(i=>{let r=Vn(i,e);if(!s&&r.role==="owner")throw new Error(ew);return r.deny={...r.deny??{},[n]:s?[]:[...new Set(t)]},s?`${e} may use every ${n.slice(0,-1)}`:`${e} may not use these ${n}: ${r.deny[n].join(", ")}`})});oo.command("link <id> <identity>").description("add a channel identity to a person, written channel:id (gitlab:sara, whatsapp:21620123456)").action(async(e,o)=>{await Zt(t=>{let n=Vn(t,e);return n.identities.some(s=>um(s,o))?`${e} already has ${o}`:(n.identities.push(o),`${o} is now ${e}`)})});oo.command("unlink <id> <identity>").description("take a channel identity away from a person").action(async(e,o)=>{await Zt(t=>{let n=Vn(t,e),s=n.identities.length;if(n.identities=n.identities.filter(i=>!um(i,o)),n.identities.length===s)throw new Error(`"${e}" has no identity ${o}.`);return`${o} is no longer ${e}`})});oo.command("remove <id>").alias("rm").description("remove a person. Their past runs keep the id; new messages from them are unknown; every machine of theirs stops at once").action(async e=>{await Zt(t=>(Vn(t,e),t.splice(t.findIndex(n=>n?.id===e),1),`removed ${e}`));let o=Vl({tokens:new no,members:ai()},e);o.length&&console.log(z.green(`\u2713 ended ${o.length} machine(s) of ${e}: ${o.map(t=>t.name).join(", ")}`)),console.log(z.dim(" If you shared this computer with them on the private network, remove that share too."))});oo.command("invite <id>").description("a one-time code that pairs one of this person's machines with their own work page (/member)").option("--url <origin>","address the person opens, e.g. https://my-mac.tailnet-name.ts.net (default: this computer's Tailscale name)").action((e,o)=>{try{let t=Pn(),n=pr(ur(),t);if(n.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the member page: ${n.join(", ")}`," Anyone you share this computer with could open it. Serve only the member paths instead:"," tailscale serve reset (removes every served path; add the phone app's /app lines back if you use it)",` tailscale serve --bg --set-path /member http://127.0.0.1:${t}/member`,` tailscale serve --bg --set-path /api/member http://127.0.0.1:${t}/api/member`].join(`
@@ -448,7 +448,7 @@ return aid ?? null`}function Vh(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
448
448
  Latest runs (${s.length})`),s.length===0&&console.log(z.dim(" nothing recorded yet"));for(let r of s){let a=r.status==="ok"?z.green("ok"):r.status==="in-flight"?z.yellow("running"):z.red(r.status);console.log(` ${z.dim(dm(r.startedAt))} ${(r.channel??"?").padEnd(9)} ${r.agentId} ${a} ${gm(r.messagePreview)}`)}console.log()});ds();Up();import{Command as tw}from"commander";import{existsSync as nw}from"fs";import ye from"chalk";var en=new tw("requests").description("what you asked agents for that is not finished, oldest first"),hm={in_progress:"in progress",waiting_owner:"waiting on you",waiting_other:"waiting on another agent",needs_attention:"needs attention",done:"done",declined:"declined",dropped:"dropped"};function Hr(){if(!nw(ic()))return console.error(ye.red(" no agentx.json here: run this from the install folder, the one that holds agentx.json")),process.exitCode=1,null;let e=Lo();return e?new Ia(e):(process.exitCode=1,null)}var ci=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function ym(e){let o=e.state==="needs_attention"?ye.red:e.state==="waiting_owner"?ye.yellow:ye.dim;console.log(` ${ye.cyan(e.id)} ${o(`[${hm[e.state]??e.state}]`)} ${ye.dim(`${ci(e.createdAt)} \xB7 ${e.channel} \xB7 ${e.agentId}`)}`),console.log(` ${e.text.replace(/\s+/g," ").trim().slice(0,240)}`),e.state==="waiting_owner"&&e.question&&console.log(ye.yellow(` Question: ${e.question}`)),e.state==="needs_attention"&&e.attentionReason&&console.log(ye.red(` ${e.attentionReason}`)),e.evidence&&console.log(ye.green(` Evidence: ${e.evidence}`)),e.closeReason&&console.log(ye.dim(` Reason: ${e.closeReason}`))}en.command("list",{isDefault:!0}).alias("ls").description("open requests, oldest first").option("--json","machine-readable output").action(e=>{let o=Hr();if(!o)return;let t=o.listOpen();if(e.json){console.log(JSON.stringify(t,null,2));return}if(Bi().enabled||console.log(ye.dim(" requests are off: turn them on with `agentx requests settings --enabled on`")),t.length===0){console.log(ye.dim(" no open requests"));return}for(let n of t)ym(n);console.log(ye.dim(`
449
449
  ${t.length} open. Close one: agentx requests done <id> --evidence <link> \xB7 agentx requests drop <id>`))});en.command("show <id>").description("one request and the runs, delegations and cards linked to it").action(e=>{let o=Hr();if(!o)return;let t=o.get(e);if(!t||t.state==="candidate"){console.error(ye.red(` no request "${e}"`)),process.exitCode=1;return}ym(t),console.log(ye.dim(` Last activity ${ci(t.updatedAt)}${t.closedAt?` \xB7 closed ${ci(t.closedAt)}`:""}`));for(let n of o.links(e))console.log(ye.dim(` ${n.kind} ${n.ref} (${ci(n.at)})`))});function wm(e,o,t,n){en.command(`${e} <id>`).description(o).option(t,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped").action((s,i)=>{let r=Hr();if(!r)return;let a=e==="done"?i.evidence:i.reason??"dropped by the owner";if(!a){console.error(ye.red(` ${n}`)),process.exitCode=1;return}let c=r.get(s);if(!c||c.state==="candidate"){console.error(ye.red(` no request "${s}"`)),process.exitCode=1;return}if(!r.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(ye.red(` ${s} is already closed (${hm[c.state]??c.state})`)),process.exitCode=1;return}console.log(ye.green(` \u2713 ${s} ${e==="done"?"closed as done":"dropped"}`))})}wm("done","close a request as finished, with a link to the evidence","--evidence <link>","a finished request needs --evidence <link>");wm("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").action(async e=>{let o={};try{let n=(i,r)=>{if(r===void 0)return;let a=Number(r);if(!(a>0))throw new Error(`${i} must be a positive number`);return a},s=(i,r)=>i===void 0?void 0:i===r?[]:i.split(",").map(a=>a.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");o.enabled=e.enabled==="on"}o.from=s(e.from,"none"),o.channels=s(e.channels,"all"),o.staleAfterHours=n("--stale-hours",e.staleHours),o.retentionDays=n("--retention-days",e.retentionDays)}catch(n){console.error(ye.red(` ${n.message}`)),process.exitCode=1;return}if(Object.values(o).some(n=>n!==void 0)){let n=await Qc(o);if(!n.success){console.error(ye.red(` ${n.error}`)),process.exitCode=1;return}console.log(ye.green(" \u2713 saved")+(n.reloaded?ye.dim(" (daemon reloaded)"):""))}let t=Bi();console.log(` Requests ${t.enabled?"on":"off"}`),console.log(` Channels ${t.channels.length?t.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${t.from.length?t.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${t.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${t.retentionDays} day(s)`)});import{Command as sw}from"commander";import on from"chalk";te();var $m=new sw("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",tr.join(" or ")).argument("[state]","on or off").action(async(e,o)=>{if(e!==void 0){o!=="on"&&o!=="off"&&(console.error(on.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await re(i=>{n=Yl(i,e,o==="on")});s.success||(console.error(on.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(on.green(`\u2713 ${n}`)),s.reloaded&&console.log(on.dim(" daemon hot-reloaded"))}let t=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of tr)console.log(` ${n.padEnd(8)} ${t.includes(n)?on.green("on"):on.dim("off")}`)});import{Command as Tw}from"commander";import tn from"chalk";import ce from"chalk";import Xn from"prompts";import{readFileSync as iw,writeFileSync as rw,existsSync as aw}from"fs";import{resolve as bm}from"path";var cw=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function lw(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Gr(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function km(e=".env"){let o=bm(e);if(!aw(o))return[];let t=iw(o,"utf-8"),n=[];for(let s of t.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 i=s.match(cw);i?n.push({kind:"kv",key:i[1],value:lw(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function dw(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Gr(o.value)}`:o.raw).join(`
450
450
  `)+`
451
- `}function Yn(e,o,t=".env"){let n=bm(t),s=km(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Gr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Gr(o)}`})),rw(n,dw(s))}function zr(e,o=".env"){return km(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var vm="https://t.me/BotFather";async function gw(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function mw(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.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 xm(e={}){console.log(),console.log(ce.bold(" Connect Telegram")),console.log(),console.log(ce.dim(` 1. Open ${vm}`)),console.log(ce.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ce.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await Xn({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&&ct(vm);let{token:t}=await Xn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await gw(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ce.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ce.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(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Xn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ce.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Xn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ce.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Yn(f,t.trim()),process.env[f]=t.trim();let p=await re(b=>{Ie(b,"channels.telegram.enabled",!0),Ie(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=It(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ce.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ce.dim(` Token stored in .env as ${f}`)),console.log(ce.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Xn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(ce.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ce.dim(" Waiting up to 90s..."));let w=await mw(t.trim(),9e4);if(!w){console.log(ce.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ce.dim(" agentx config set notifications.destination.channel telegram")),console.log(ce.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ce.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await re(b=>{Ie(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ce.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ce.green(" \u2713 Default --notify target set")),console.log(ce.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ce.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ce.dim(" Daemon hot-reloaded."))}import ve from"chalk";import Vr from"prompts";import{existsSync as Xr,mkdirSync as pw,readdirSync as uw,readFileSync as Sm}from"fs";import{resolve as Yr}from"path";var fw=".agentx/whatsapp-sessions";function hw(){let e=Yr(process.cwd(),".agentx/daemon.pid");if(!Xr(e))return!1;try{let o=parseInt(Sm(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function yw(e){if(!Xr(e))return!1;try{return uw(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function ww(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ve.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ve.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;pw(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ve.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ve.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ve.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ve.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Em(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),hw()){console.log(ve.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ve.dim(" agentx daemon stop")),console.log();let{cont:l}=await Vr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||Yr(process.cwd(),"agentx.json");Xr(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Sm(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||fw,s=Yr(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Vr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ve.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(yw(s)&&a){let{keep:l}=await Vr({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(ve.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await ww(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{Ie(l,"channels.whatsapp.enabled",!0),Ie(l,"channels.whatsapp.sessionDir",n),Ie(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ve.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ve.dim(` Session: ${n}`)),console.log(ve.dim(" Start the daemon to begin receiving:")),console.log(ve.dim(" agentx daemon start")),console.log(ve.dim(" Add routes later with:")),console.log(ve.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as $w}from"crypto";import je from"chalk";import Am from"prompts";var li="agentx-mesh:",di="//join/";function bw(e){return Buffer.from(e,"utf-8").toString("base64url")}function kw(e){return Buffer.from(e,"base64url").toString("utf-8")}function vw(e){return`${li}${di}${bw(JSON.stringify(e))}`}function xw(e){if(!e.startsWith(`${li}${di}`))throw new Error(`Not a mesh invite link \u2014 expected ${li}${di}\u2026`);let o=e.slice(li.length+di.length),t=JSON.parse(kw(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Sw(){return $w(32).toString("hex")}function Ew(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Aw(e){return e?.node?.name||e?.node?.id||"node"}async function Tm(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=zr("MESH_TOKEN");r||(r=Sw(),Yn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Ew(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Am({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:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(je.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=vw({url:a,token:r,name:Aw(i),version:1});console.log(),console.log(je.bold(" Mesh invite")),console.log(),console.log(` ${je.cyan(g)}`),console.log(),console.log(je.dim(" Run on the other node:")),console.log(je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function jm(e,o={}){let t;try{t=xw(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=zr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Am({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(je.red(" Aborted (keeping existing .env)")),process.exit(1))}Yn("MESH_TOKEN",t.token);let s=await re(i=>{Ie(i,"mesh.enabled",!0);let r=It(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ie(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(je.green(" \u2713 Joined mesh")),console.log(je.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(je.dim(" Daemon hot-reloaded.")):console.log(je.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(je.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(je.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(je.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var nn=new Tw().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");nn.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 xm({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});nn.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 Em({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Om=nn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Om.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 Tm({url:e.url,configPath:e.config})});Om.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await jm(e,{configPath:o.config})});nn.action(()=>{console.log(),console.log(tn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${tn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${tn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${tn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${tn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(tn.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as jw}from"commander";import oe from"chalk";var sn=new jw().name("usage").description("token usage analysis and reporting");sn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(oe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(oe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${oe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${oe.red(String(s.totalErrors))}`),console.log(),console.log(oe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${oe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${oe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${e.message}`))}});sn.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 o=T(),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}`,i=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)throw new Error(`Daemon answered ${i.status}. It may be older than this command; restart it.`);let r=await i.json();if(e.json){console.log(JSON.stringify(r,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=r.lifted.map(u=>a(u.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:oe.dim(" No hold to lift.")),console.log();return}let c=r.now,l=new Set(r.holds.map(d=>d.window));console.log(oe.bold(" Claude plan (as Claude Code last reported it)")),console.log(),r.provider.length===0&&console.log(oe.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of r.provider){let u=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?oe.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${u.padEnd(12)} ${[f,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${r.lastHour}${g(r.maxPerHour)} in the last hour, ${r.last5h}${g(r.maxPer5h)} in the last 5 hours`),l.size&&console.log(oe.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(o){o.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${o.message}`))}});sn.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:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(oe.red(` Script not found: ${s}`)),console.log(oe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(oe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(oe.red(" Analysis failed. Is Python 3 installed?"))}});sn.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:o}=await import("./surface-usage-CH3SHO77.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-CH5QSA7K.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");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(oe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${oe.dim("\xB7")} ${d}`);console.log(),console.log(oe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(oe.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(oe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(oe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(oe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(oe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=oe.dim(`${i.days}d`);console.log(` ${oe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(oe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Ow}from"commander";import xe from"chalk";import{readFileSync as Cw}from"fs";import{resolve as Iw}from"path";te();var Zo=new Ow().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Zo.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Ba(Iw(process.cwd(),".env"))}catch{}let o=Nw(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-R6ZTCTSI.js");t(o)}catch(o){console.log(xe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(xe.dim(o.stack)),process.exit(1)}});function Nw(e,o){try{let t=T();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(xe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(xe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
451
+ `}function Yn(e,o,t=".env"){let n=bm(t),s=km(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Gr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Gr(o)}`})),rw(n,dw(s))}function zr(e,o=".env"){return km(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var vm="https://t.me/BotFather";async function gw(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function mw(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.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 xm(e={}){console.log(),console.log(ce.bold(" Connect Telegram")),console.log(),console.log(ce.dim(` 1. Open ${vm}`)),console.log(ce.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ce.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await Xn({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&&ct(vm);let{token:t}=await Xn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await gw(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ce.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ce.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(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Xn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ce.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Xn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ce.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Yn(f,t.trim()),process.env[f]=t.trim();let p=await re(b=>{Ie(b,"channels.telegram.enabled",!0),Ie(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=It(b,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(b,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ce.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ce.dim(` Token stored in .env as ${f}`)),console.log(ce.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Xn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(ce.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ce.dim(" Waiting up to 90s..."));let w=await mw(t.trim(),9e4);if(!w){console.log(ce.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ce.dim(" agentx config set notifications.destination.channel telegram")),console.log(ce.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ce.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await re(b=>{Ie(b,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ce.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ce.green(" \u2713 Default --notify target set")),console.log(ce.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ce.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ce.dim(" Daemon hot-reloaded."))}import ve from"chalk";import Vr from"prompts";import{existsSync as Xr,mkdirSync as pw,readdirSync as uw,readFileSync as Sm}from"fs";import{resolve as Yr}from"path";var fw=".agentx/whatsapp-sessions";function hw(){let e=Yr(process.cwd(),".agentx/daemon.pid");if(!Xr(e))return!1;try{let o=parseInt(Sm(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function yw(e){if(!Xr(e))return!1;try{return uw(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function ww(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ve.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ve.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;pw(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ve.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ve.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ve.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ve.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Em(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),hw()){console.log(ve.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ve.dim(" agentx daemon stop")),console.log();let{cont:l}=await Vr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||Yr(process.cwd(),"agentx.json");Xr(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Sm(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||fw,s=Yr(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Vr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ve.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(yw(s)&&a){let{keep:l}=await Vr({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(ve.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await ww(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{Ie(l,"channels.whatsapp.enabled",!0),Ie(l,"channels.whatsapp.sessionDir",n),Ie(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ve.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ve.dim(` Session: ${n}`)),console.log(ve.dim(" Start the daemon to begin receiving:")),console.log(ve.dim(" agentx daemon start")),console.log(ve.dim(" Add routes later with:")),console.log(ve.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as $w}from"crypto";import je from"chalk";import Am from"prompts";var li="agentx-mesh:",di="//join/";function bw(e){return Buffer.from(e,"utf-8").toString("base64url")}function kw(e){return Buffer.from(e,"base64url").toString("utf-8")}function vw(e){return`${li}${di}${bw(JSON.stringify(e))}`}function xw(e){if(!e.startsWith(`${li}${di}`))throw new Error(`Not a mesh invite link \u2014 expected ${li}${di}\u2026`);let o=e.slice(li.length+di.length),t=JSON.parse(kw(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Sw(){return $w(32).toString("hex")}function Ew(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Aw(e){return e?.node?.name||e?.node?.id||"node"}async function Tm(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=zr("MESH_TOKEN");r||(r=Sw(),Yn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Ew(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Am({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:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(je.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=vw({url:a,token:r,name:Aw(i),version:1});console.log(),console.log(je.bold(" Mesh invite")),console.log(),console.log(` ${je.cyan(g)}`),console.log(),console.log(je.dim(" Run on the other node:")),console.log(je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function jm(e,o={}){let t;try{t=xw(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=zr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Am({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(je.red(" Aborted (keeping existing .env)")),process.exit(1))}Yn("MESH_TOKEN",t.token);let s=await re(i=>{Ie(i,"mesh.enabled",!0);let r=It(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ie(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(je.green(" \u2713 Joined mesh")),console.log(je.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(je.dim(" Daemon hot-reloaded.")):console.log(je.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(je.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(je.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(je.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var nn=new Tw().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");nn.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 xm({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});nn.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 Em({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Om=nn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Om.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 Tm({url:e.url,configPath:e.config})});Om.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await jm(e,{configPath:o.config})});nn.action(()=>{console.log(),console.log(tn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${tn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${tn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${tn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${tn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(tn.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as jw}from"commander";import oe from"chalk";var sn=new jw().name("usage").description("token usage analysis and reporting");sn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(oe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(oe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${oe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${oe.red(String(s.totalErrors))}`),console.log(),console.log(oe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${oe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${oe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${e.message}`))}});sn.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 o=T(),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}`,i=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)throw new Error(`Daemon answered ${i.status}. It may be older than this command; restart it.`);let r=await i.json();if(e.json){console.log(JSON.stringify(r,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=r.lifted.map(u=>a(u.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:oe.dim(" No hold to lift.")),console.log();return}let c=r.now,l=new Set(r.holds.map(d=>d.window));console.log(oe.bold(" Claude plan (as Claude Code last reported it)")),console.log(),r.provider.length===0&&console.log(oe.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of r.provider){let u=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?oe.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${u.padEnd(12)} ${[f,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${r.lastHour}${g(r.maxPerHour)} in the last hour, ${r.last5h}${g(r.maxPer5h)} in the last 5 hours`),l.size&&console.log(oe.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(o){o.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${o.message}`))}});sn.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:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(oe.red(` Script not found: ${s}`)),console.log(oe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(oe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(oe.red(" Analysis failed. Is Python 3 installed?"))}});sn.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:o}=await import("./surface-usage-CH3SHO77.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-MPLZJQA5.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");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(oe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${oe.dim("\xB7")} ${d}`);console.log(),console.log(oe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(oe.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(oe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(oe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(oe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(oe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=oe.dim(`${i.days}d`);console.log(` ${oe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(oe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Ow}from"commander";import xe from"chalk";import{readFileSync as Cw}from"fs";import{resolve as Iw}from"path";te();var Zo=new Ow().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Zo.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Ba(Iw(process.cwd(),".env"))}catch{}let o=Nw(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-TVSOWW32.js");t(o)}catch(o){console.log(xe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(xe.dim(o.stack)),process.exit(1)}});function Nw(e,o){try{let t=T();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(xe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(xe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
452
452
  `)),{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:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Zo.command("list").description("list configured boards").action(()=>{try{let e=T();if(!e.boards?.length){console.log(xe.dim(`
453
453
  No boards configured.
454
454
  `));return}console.log();for(let o of e.boards){console.log(` ${xe.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(xe.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(xe.dim(` primary label: ${o.primaryToolLabel}`)),console.log(xe.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(xe.red(` ${e.message}`)),process.exit(1)}});Zo.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,o)=>{try{Kn(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});Zo.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,o)=>{try{Kn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});var Kr=Zo.command("column").description("manage a board's columns (add / remove / edit / list)");Kr.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(Cw("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(xe.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${xe.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${xe.dim(i)}`)}}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});Kr.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,o,t)=>{try{Kn(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(xe.red(` ${n.message}`)),process.exit(1)}});Kr.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{Kn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});Zo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Kn(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});function Kn(e){let{summary:o,backupPath:t}=so(n=>e(n));console.log(xe.green(`
@@ -459,9 +459,9 @@ return aid ?? null`}function Vh(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
459
459
  ${x.content}
460
460
  --- END ENTRY ---`).join(`
461
461
 
462
- `),$="";if(e.facts!==!1){let{extractHints:x,resolveFacts:R,mergeRecords:I,renderFactsBlock:C,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-ROUMKS7I.js");if(!a){let H=new Set;for(let Ce of t.listAgents())for(let Se of t.getAgentWiki(Ce).listArticles(Ce))Se.meta.type==="person"&&H.add(Se.meta.title);a=[...H]}let V=x(p.map(H=>({context:H.sourceContext,content:H.content,sender:typeof H.meta?.sender=="string"?H.meta.sender:void 0})),{known:a}),fe=L(p);if(V.length>0||fe.length>0){let H=B(),{records:Ce,results:Se}=V.length>0?await R(V,{sources:H}):{records:[],results:[]},M=I([...fe,...Ce]);$=C(M);let Qe=[...fe.length>0?[`entries:${fe.length}`]:[],...Se.filter(Ee=>Ee.records.length>0).map(Ee=>`${Ee.source}:${Ee.records.length}`)];console.log(m.dim(` Facts: ${V.length} entities \u2192 ${M.length} resolved${Qe.length?` (${Qe.join(" ")})`:""}`));for(let Ee of P(Se,H))console.log(m.yellow(` ! ${Ee.source} ${Ee.kind} \u2014 would supply ${Ee.provides.join(", ")}`)),console.log(m.dim(` ${Ee.hint}`))}}let E=Ac(o,u,k,w.articles,b,p.length,$);console.log(m.dim(` Mode: ${Zr(o)}`));let S=q(y.baseDir,"_tmp");_o(S,{recursive:!0});let v=q(S,"absorb-prompt.txt");$t(v,E),console.log(m.dim(" Compiling with Claude..."));try{let x;try{x=wt(`cat '${v}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Et({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(x=M.stdout||"",!x)throw M}let R=x;try{let M=JSON.parse(x);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let I,C=[],P=R.indexOf("{"),B=R.indexOf("["),L=P>=0&&(B<0||P<B)?P:B;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let V=R[L],fe=V==="{"?"}":"]",H=0,Ce=-1;for(let M=L;M<R.length;M++)if(R[M]===V)H++;else if(R[M]===fe&&(H--,H===0)){Ce=M+1;break}if(Ce===-1){console.log(m.red(" Unbalanced JSON"));continue}let Se=R.slice(L,Ce);try{let M=JSON.parse(Se);Array.isArray(M)?I=M:(I=M.articles||[],C=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${Se.slice(0,300)}`));continue}for(let M of I){let Qe=new Date().toISOString().slice(0,10),Ee=l(M.sources||[],p);y.writeArticle(M.path,{title:M.title,type:M.type,related:Array.isArray(M.related)?M.related:void 0,tags:M.tags||[],owner:u,access:"public",created:Qe,lastUpdated:Qe,sources:M.sources||[],graphPath:Ee},M.content,u);let st=M.type?m.magenta(`[${M.type}]`)+" ":"",_=Array.isArray(M.related)&&M.related.length?` \u2192 ${M.related.slice(0,3).join(", ")}${M.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${st}${M.path}: ${M.title}${m.dim(_)}`);let $e=(M.tags||[]).slice(0,4).join(", ");$e&&console.log(m.dim(` tags: ${$e}`)),Ee?.length&&(console.log(m.dim(` graphPath: ${Ee.join(" \u203A ")}`)),d++),g++}if(C.length>0){console.log(),console.log(m.yellow(` Gaps detected (${C.length} missing pieces):`));for(let M of C)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Qe=new M(bt(e.dir)).add(C.map(Ee=>({kind:"article",agentId:u,path:"",subject:String(Ee).slice(0,120),question:`No article yet for: ${String(Ee).slice(0,160)}`})));Qe.added>0&&console.log(m.dim(` queued ${Qe.added} for follow-up (agentx wiki questions)`))}catch{}}y.rebuildIndex()}catch(x){console.log(m.red(` Absorb failed: ${x.message?.slice(0,200)}`)),x.stderr&&console.log(m.dim(String(x.stderr).slice(0,300))),x.stdout&&console.log(m.dim("stdout: "+String(x.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ne.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 o=Lw(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.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 i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-EFELFOSY.js"),{default:c}=await import("better-sqlite3"),l=q(process.cwd(),".agentx/db.sqlite");if(!to(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()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.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-PBPF45GN.js"),{default:g}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!to(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(o??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let y=p[0];y&&console.log(m.dim(` most recurrent (${y.occurrences} sessions, ${y.failure.runs} runs): ${y.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await Tc({extraCandidates:i,wikiDir:e.dir?q(e.dir):void 0,memoryRoot:e.memoryDir?q(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,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(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.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(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.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 r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var mi=ne.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function pi(e){return e?q(e):q(process.cwd(),".agentx","wiki")}mi.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:o}=await import("./proposals-O4B5LD5T.js"),t=o(pi(e.dir),e.all?void 0:"pending");if(t.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of t){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,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(` ${r}`))}});mi.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,o)=>{let{readProposal:t}=await import("./proposals-O4B5LD5T.js"),n=t(pi(o.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(`
462
+ `),$="";if(e.facts!==!1){let{extractHints:x,resolveFacts:R,mergeRecords:I,renderFactsBlock:C,installPrompts:P,defaultSources:B,recordsFromEntries:L}=await import("./facts-ROUMKS7I.js");if(!a){let H=new Set;for(let Ce of t.listAgents())for(let Se of t.getAgentWiki(Ce).listArticles(Ce))Se.meta.type==="person"&&H.add(Se.meta.title);a=[...H]}let V=x(p.map(H=>({context:H.sourceContext,content:H.content,sender:typeof H.meta?.sender=="string"?H.meta.sender:void 0})),{known:a}),fe=L(p);if(V.length>0||fe.length>0){let H=B(),{records:Ce,results:Se}=V.length>0?await R(V,{sources:H}):{records:[],results:[]},M=I([...fe,...Ce]);$=C(M);let Qe=[...fe.length>0?[`entries:${fe.length}`]:[],...Se.filter(Ee=>Ee.records.length>0).map(Ee=>`${Ee.source}:${Ee.records.length}`)];console.log(m.dim(` Facts: ${V.length} entities \u2192 ${M.length} resolved${Qe.length?` (${Qe.join(" ")})`:""}`));for(let Ee of P(Se,H))console.log(m.yellow(` ! ${Ee.source} ${Ee.kind} \u2014 would supply ${Ee.provides.join(", ")}`)),console.log(m.dim(` ${Ee.hint}`))}}let E=Ac(o,u,k,w.articles,b,p.length,$);console.log(m.dim(` Mode: ${Zr(o)}`));let S=q(y.baseDir,"_tmp");_o(S,{recursive:!0});let v=q(S,"absorb-prompt.txt");$t(v,E),console.log(m.dim(" Compiling with Claude..."));try{let x;try{x=wt(`cat '${v}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{env:Et({...process.env}),encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(M){if(x=M.stdout||"",!x)throw M}let R=x;try{let M=JSON.parse(x);R=M.result||M.content||"",R||(console.log(m.dim(` Claude envelope keys: ${Object.keys(M).join(", ")}`)),console.log(m.dim(` is_error: ${M.is_error}, stop_reason: ${M.stop_reason}`)))}catch{}let I,C=[],P=R.indexOf("{"),B=R.indexOf("["),L=P>=0&&(B<0||P<B)?P:B;if(L===-1){console.log(m.red(" No JSON found in response")),console.log(m.dim(R.slice(0,500)));continue}let V=R[L],fe=V==="{"?"}":"]",H=0,Ce=-1;for(let M=L;M<R.length;M++)if(R[M]===V)H++;else if(R[M]===fe&&(H--,H===0)){Ce=M+1;break}if(Ce===-1){console.log(m.red(" Unbalanced JSON"));continue}let Se=R.slice(L,Ce);try{let M=JSON.parse(Se);Array.isArray(M)?I=M:(I=M.articles||[],C=M.gaps||[])}catch(M){console.log(m.red(` JSON parse error: ${M.message}`)),console.log(m.dim(` First 300 chars: ${Se.slice(0,300)}`));continue}for(let M of I){let Qe=new Date().toISOString().slice(0,10),Ee=l(M.sources||[],p);y.writeArticle(M.path,{title:M.title,type:M.type,related:Array.isArray(M.related)?M.related:void 0,tags:M.tags||[],owner:u,access:"public",created:Qe,lastUpdated:Qe,sources:M.sources||[],graphPath:Ee},M.content,u);let st=M.type?m.magenta(`[${M.type}]`)+" ":"",_=Array.isArray(M.related)&&M.related.length?` \u2192 ${M.related.slice(0,3).join(", ")}${M.related.length>3?", \u2026":""}`:"";console.log(` ${m.green("+")} ${st}${M.path}: ${M.title}${m.dim(_)}`);let $e=(M.tags||[]).slice(0,4).join(", ");$e&&console.log(m.dim(` tags: ${$e}`)),Ee?.length&&(console.log(m.dim(` graphPath: ${Ee.join(" \u203A ")}`)),d++),g++}if(C.length>0){console.log(),console.log(m.yellow(` Gaps detected (${C.length} missing pieces):`));for(let M of C)console.log(m.yellow(` ? ${M}`));try{let{QuestionStore:M}=await import("./questions-ZATLU5AW.js"),Qe=new M(bt(e.dir)).add(C.map(Ee=>({kind:"article",agentId:u,path:"",subject:String(Ee).slice(0,120),question:`No article yet for: ${String(Ee).slice(0,160)}`})));Qe.added>0&&console.log(m.dim(` queued ${Qe.added} for follow-up (agentx wiki questions)`))}catch{}}y.rebuildIndex()}catch(x){console.log(m.red(` Absorb failed: ${x.message?.slice(0,200)}`)),x.stderr&&console.log(m.dim(String(x.stderr).slice(0,300))),x.stdout&&console.log(m.dim("stdout: "+String(x.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(m.dim(" Dry run \u2014 no changes made"));else if(g>0&&(console.log(m.green(` ${g} articles compiled across ${n.length} agent(s)`)),i)){let u=g>0?Math.round(d/g*100):0;console.log(m.dim(` ${d}/${g} carry graphPath (${u}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});ne.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 o=Lw(e.since),t=String(e.types).split(",").map(a=>a.trim()).filter(Boolean),n=["user","feedback","project","reference"],s=t.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 i=[];if(e.reviews){let{reviewsToCandidates:a}=await import("./review-candidates-2F4QK6QQ.js"),{default:c}=await import("better-sqlite3"),l=q(process.cwd(),".agentx/db.sqlite");if(!to(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()-(o??6048e5));i=a(d,{kinds:String(e.reviewKinds).split(",").map(p=>p.trim()).filter(Boolean)});let u=i.filter(p=>(p.occurrences??1)>1).length;console.log(m.dim(` ${d.length} review(s) in window \u2192 ${i.length} candidate finding(s), ${u} seen in more than one session`));let f=i[0];f&&(f.occurrences??1)>1&&console.log(m.dim(` most recurrent (${f.occurrences} sessions): ${f.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-PBPF45GN.js"),{default:g}=await import("better-sqlite3"),d=q(process.cwd(),".agentx/db.sqlite");if(!to(d))console.log(m.yellow(` --failures: no ${d}`));else{let u=new g(d,{readonly:!0});try{let f=c(u,{since:Date.now()-(o??6048e5)}),p=l(f,{minSessions:a});console.log(m.dim(` ${f.length} failed run(s) in window \u2192 ${p.length} failure(s) seen in ${a}+ sessions`));let y=p[0];y&&console.log(m.dim(` most recurrent (${y.occurrences} sessions, ${y.failure.runs} runs): ${y.memory.description.slice(0,84)}`)),i=[...i,...p]}finally{u.close()}}}let r=await Tc({extraCandidates:i,wikiDir:e.dir?q(e.dir):void 0,memoryRoot:e.memoryDir?q(e.memoryDir):void 0,sinceMs:o,agentFilter:e.agent,types:t,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(r.candidates.length===0){console.log(m.dim(" Nothing unpromoted in window")),console.log();return}console.log(` ${r.candidates.length} candidate(s) in ${r.clusters.length} cluster(s):`);for(let a of r.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(),r.dryRun){console.log(m.dim(" Dry run \u2014 pass --commit to judge and propose")),console.log();return}for(let a of r.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 r.skipped)console.log(` ${m.yellow("-")} ${a.stamp} ${m.dim(`\u2014 ${a.reason}`)}`);if(r.gaps.length){console.log(),console.log(m.yellow(` Gaps (${r.gaps.length}):`));for(let a of r.gaps)console.log(m.yellow(` ? ${a}`))}for(let a of r.warnings)console.log(m.dim(` ! ${a}`));for(let a of r.errors)console.log(m.red(` x ${a}`));console.log(),console.log(r.errors.length?m.red(` ${r.proposed.length} proposed, ${r.errors.length} error(s)`):m.green(` ${r.proposed.length} proposed, ${r.skipped.length} skipped`)),r.proposed.length&&console.log(m.dim(" Nothing is in the wiki yet. Review with: agentx wiki proposals list")),console.log(),r.errors.length&&process.exit(1)});var mi=ne.command("proposals").description("review lessons proposed for the shared wiki (list, show, approve, reject)");function pi(e){return e?q(e):q(process.cwd(),".agentx","wiki")}mi.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:o}=await import("./proposals-O4B5LD5T.js"),t=o(pi(e.dir),e.all?void 0:"pending");if(t.length===0){console.log(m.dim(e.all?" no proposals":" nothing pending"));return}for(let n of t){let s=n.evidence,i=s.sources.some(l=>l.kind==="failure")?" \xB7 from a recurring failure":"",r=`${s.agents.join(", ")}${s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:""} \xB7 ${s.sources.length} source(s)${i}`,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(` ${r}`))}});mi.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,o)=>{let{readProposal:t}=await import("./proposals-O4B5LD5T.js"),n=t(pi(o.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(`
463
463
  `).map(s=>` ${s}`).join(`
464
- `)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),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>)`))}});mi.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,o)=>{let{approveProposal:t}=await import("./promote-K5LP5Q6Z.js"),n=t(pi(o.dir),e,{force:o.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`))});mi.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,o)=>{let{rejectProposal:t}=await import("./promote-K5LP5Q6Z.js"),n=t(pi(o.dir),e,{reason:o.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function Lw(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ne.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",q(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:o}=await import("./query-LHXSINM2.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Oe(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=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let u=[],f=t(d).sort().reverse();for(let w of f){let k=r(d,w),b=[];try{b=t(k).filter($=>$.endsWith(".json")).sort().reverse()}catch{continue}for(let $ of b){if(u.length>=g)break;try{let E=JSON.parse(n(r(k,$),"utf-8")),S=E.message||E.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:E.id||$.replace(".json",""),message:S.trim(),ts:E.at||E.timestamp||w})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.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 p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.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<u.length;w++){let k=u[w];process.stdout.write(m.dim(` [${w+1}/${u.length}] querying... `));let $=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
464
+ `)),console.log(),console.log(m.bold(" Evidence"));for(let s of n.evidence.sources){let i=s.author?`${s.author}${s.taskId?` \xB7 task ${s.taskId}`:""}`:s.agentId,r=s.occurrences&&s.occurrences>1?` \xB7 seen in ${s.occurrences} sessions`:"";console.log(` - ${m.cyan(s.kind)} ${s.type}/${s.name} ${m.dim(`(${i}, ${s.updatedAt.slice(0,10)}${r})`)}`),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>)`))}});mi.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,o)=>{let{approveProposal:t}=await import("./promote-CNKIINYK.js"),n=t(pi(o.dir),e,{force:o.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`))});mi.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,o)=>{let{rejectProposal:t}=await import("./promote-CNKIINYK.js"),n=t(pi(o.dir),e,{reason:o.reason});if(!n.ok){console.error(m.red(` ${n.error}`)),process.exitCode=1;return}console.log(m.green(` \u2713 ${e} rejected`))});function Lw(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());o||(console.log(m.red(` Invalid --since "${e}". Use "30m", "24h", or "7d".`)),process.exit(1));let t=Number(o[1]),n=o[2];return t*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}ne.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",q(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:o}=await import("./query-A2N2LIR7.js"),{readdirSync:t,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=Oe(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=i(e.history,c);if(!s(d)){console.log(m.yellow(` no task-history at ${d}`));return}let u=[],f=t(d).sort().reverse();for(let w of f){let k=r(d,w),b=[];try{b=t(k).filter($=>$.endsWith(".json")).sort().reverse()}catch{continue}for(let $ of b){if(u.length>=g)break;try{let E=JSON.parse(n(r(k,$),"utf-8")),S=E.message||E.task?.message;typeof S=="string"&&S.trim().length>10&&u.push({id:E.id||$.replace(".json",""),message:S.trim(),ts:E.at||E.timestamp||w})}catch{}}if(u.length>=g)break}if(u.length===0){console.log(m.yellow(` no task messages found under ${d}`));return}console.log(),console.log(m.bold(` A/B harness \u2014 ${u.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 p=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${u.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<u.length;w++){let k=u[w];process.stdout.write(m.dim(` [${w+1}/${u.length}] querying... `));let $=l.findRelevant(k.message,c,3).map(S=>`- **${S.meta.title}** [${S.meta.type||"?"}] (${S.path})`).join(`
465
465
  `)||"_(none returned)_",E;try{let S=await o(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(S.status!=="ok")E=`_(status: ${S.status}${S.error?" \u2014 "+S.error:""})_`;else{let v=S.citations.map(x=>`\`${x.title}\` [${x.type||"?"}]`).join(", ");E=`**Answer:**
466
466
 
467
467
  ${S.answer}
@@ -478,7 +478,7 @@ Q: ${_.q}
478
478
  A: ${_.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",b||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${d}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
479
479
  `),E=q(a.baseDir,"_tmp");_o(E,{recursive:!0});let S=q(E,`interview-${t().slice(0,8)}.txt`);$t(S,$),console.log(),console.log(m.dim(` Synthesizing draft with ${e.model}...`));let v="";try{let _=`cat '${S}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,$e=wt(_,{env:Et({...process.env}),encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let ro=JSON.parse($e);v=String(ro.result||ro.content||"")}catch{v=$e}}catch(_){console.log(m.red(` synthesis failed: ${_.message?.slice(0,200)}`)),c?.close();return}v=v.trim();let x=v.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);x&&(v=x[1].trim());let R=v.indexOf("---");R>0&&(v=v.slice(R));let I=v.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!I){console.log(m.red(" LLM output is not a valid frontmatter+body article:")),console.log(v.slice(0,600)),c?.close();return}let C={};for(let _ of I[1].split(`
480
480
  `)){let $e=_.match(/^(\w+):\s*(.+)$/);$e&&(C[$e[1]]=$e[2].trim().replace(/^"(.*)"$/,"$1"))}let P=I[2],B=C.title||g,L=B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),fe=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${L}.md`;console.log(),console.log(m.bold(" === Draft preview ===")),console.log(m.dim(` Path: ${fe}`)),console.log(),console.log(v),console.log();let H=await l(` ${m.green("save")} / ${m.yellow("edit (opens $EDITOR)")} / ${m.red("scrap")} ? `);if(c?.close(),H==="scrap"||H==="/abort"){console.log(m.dim(" Discarded."));return}if(!e.commit){console.log(m.dim(" --no-commit: not writing.")),console.log(m.dim(` Draft kept at ${S} (prompt only; no article file)`));return}let Ce=P,Se={title:B,type:C.type||d,related:C.related?C.related.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:C.tags?C.tags.replace(/^\[|\]$/g,"").split(",").map(_=>_.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:C.access||"public",created:C.created||new Date().toISOString().slice(0,10),lastUpdated:C.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(H==="edit"){let _=process.env.EDITOR||"vi",$e=q(E,`draft-${t().slice(0,8)}.md`);$t($e,v);try{wt(`${_} '${$e}'`,{stdio:"inherit"});let Ci=Qn($e,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(Ci){let Mo={};for(let kn of Ci[1].split(`
481
- `)){let Ii=kn.match(/^(\w+):\s*(.+)$/);Ii&&(Mo[Ii[1]]=Ii[2].trim().replace(/^"(.*)"$/,"$1"))}Ce=Ci[2],Se={...Se,title:Mo.title||Se.title,type:Mo.type||Se.type,access:Mo.access||Se.access,related:Mo.related?Mo.related.replace(/^\[|\]$/g,"").split(",").map(kn=>kn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.related,tags:Mo.tags?Mo.tags.replace(/^\[|\]$/g,"").split(",").map(kn=>kn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.tags}}}catch(ro){console.log(m.red(` editor failed: ${ro.message}`));return}}if(!a.writeArticle(fe,Se,Ce,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${fe} saved.`));let Qe=a.extractWikilinks(Ce),Ee=new Map;for(let _ of a.listArticles(e.agent))Ee.set(_.meta.title.toLowerCase(),!0);let st=Qe.filter(_=>!Ee.has(_.toLowerCase()));if(st.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of st.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ne.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 o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-LHXSINM2.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Oe(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let p=Qn(e.script,"utf-8").split(/\n\s*\n/).map(y=>y.trim()).filter(Boolean);r=[];for(let y of p){let w=y.split(/\r?\n/).filter($=>$.trim());if(w.length<2)continue;let k=w[0].replace(/^Q:\s*/i,"").trim(),b=w.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.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 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],u=0;for(let f=0;f<l;f++){let p,y;if(r){let V=r[f];if(!V)break;p=V.q,y=V.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;y=""}process.stdout.write(m.dim(" querying... "));let w;try{w=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(V){console.log(m.red(`failed: ${V.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 V=w.citations.map(fe=>`${fe.title} [${fe.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
481
+ `)){let Ii=kn.match(/^(\w+):\s*(.+)$/);Ii&&(Mo[Ii[1]]=Ii[2].trim().replace(/^"(.*)"$/,"$1"))}Ce=Ci[2],Se={...Se,title:Mo.title||Se.title,type:Mo.type||Se.type,access:Mo.access||Se.access,related:Mo.related?Mo.related.replace(/^\[|\]$/g,"").split(",").map(kn=>kn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.related,tags:Mo.tags?Mo.tags.replace(/^\[|\]$/g,"").split(",").map(kn=>kn.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):Se.tags}}}catch(ro){console.log(m.red(` editor failed: ${ro.message}`));return}}if(!a.writeArticle(fe,Se,Ce,e.agent)){console.log(m.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(m.green(` \u2713 ${fe} saved.`));let Qe=a.extractWikilinks(Ce),Ee=new Map;for(let _ of a.listArticles(e.agent))Ee.set(_.meta.title.toLowerCase(),!0);let st=Qe.filter(_=>!Ee.has(_.toLowerCase()));if(st.length){console.log(),console.log(m.bold(" Gaps referenced but not yet covered:"));for(let _ of st.slice(0,8))console.log(m.dim(` - ${_}`));console.log(m.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});ne.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 o=await import("node:readline/promises"),{randomUUID:t}=await import("node:crypto"),{agenticQuery:n}=await import("./query-A2N2LIR7.js");if(!e.agent){console.log(m.red(" --agent <id> is required."));return}let s=Oe(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(f){console.log(m.red(` can't open wiki for agent "${e.agent}": ${f.message}`));return}let r=null;if(e.script){let p=Qn(e.script,"utf-8").split(/\n\s*\n/).map(y=>y.trim()).filter(Boolean);r=[];for(let y of p){let w=y.split(/\r?\n/).filter($=>$.trim());if(w.length<2)continue;let k=w[0].replace(/^Q:\s*/i,"").trim(),b=w.slice(1).join(" ").trim();k&&b&&r.push({q:k,verdict:b})}}let a=r?null:o.createInterface({input:process.stdin,output:process.stdout}),c=async f=>a?(await a.question(f)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.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 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(m.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],u=0;for(let f=0;f<l;f++){let p,y;if(r){let V=r[f];if(!V)break;p=V.q,y=V.verdict,console.log(m.cyan(` [${f+1}] Q: `)+p)}else{if(p=await c(m.cyan(` [${f+1}] Q: `)),!p||p==="/done"||p==="/abort")break;y=""}process.stdout.write(m.dim(" querying... "));let w;try{w=await n(p,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(V){console.log(m.red(`failed: ${V.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 V=w.citations.map(fe=>`${fe.title} [${fe.type||"?"}]`).join(" \xB7 ");console.log(),console.log(m.dim(" A: ")+w.answer.replace(/\n/g,`
482
482
  `)),console.log(m.dim(" citations: "+V))}r||(y=await c(m.cyan(" verdict > "))),console.log(m.dim(" verdict: ")+y);let k={q:p,answer:w.answer,citations:w.citations,verdict:y},b=y.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!b){console.log(m.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let $=b[1].toLowerCase(),E=(b[2]||"").trim();if(d.push(k),$==="/ok"||$==="/skip")continue;if(!E){console.log(m.yellow(` ${$} without note \u2014 skipping.`));continue}let S=w.citations[0];if(!S){console.log(m.yellow(" no cited article to patch."));continue}let v=i.readArticle(S.path);if(!v){console.log(m.red(` can't read ${S.path} to patch.`));continue}console.log(m.dim(` patching ${S.title} (${S.path})...`));let x=Uw(v.content,$,E,v.meta.title,v.meta.type),R=q(i.baseDir,"_tmp");_o(R,{recursive:!0});let I=q(R,`quiz-patch-${t().slice(0,8)}.txt`);$t(I,x);let C="";try{let V=`cat '${I}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,fe=wt(V,{env:Et({...process.env}),encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ce=JSON.parse(fe);C=String(Ce.result||Ce.content||"")}catch{C=fe}let H=C.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);H&&(C=H[1].trim()),C=C.trim()}catch(V){console.log(m.red(` patch failed: ${V.message?.slice(0,120)}`));continue}if(!C||C.length<20){console.log(m.yellow(" patch returned nothing usable."));continue}let P=v.content.split(`
483
483
  `).length,B=C.split(`
484
484
  `).length;if(console.log(m.dim(` diff: ${P} \u2192 ${B} lines (${B-P>=0?"+":""}${B-P})`)),!g){console.log(m.dim(" (--no-commit: patch not written)")),k.patched=S.path+" (dry)";continue}if(!i.writeArticle(S.path,{...v.meta,lastUpdated:new Date().toISOString().slice(0,10)},C,e.agent)){console.log(m.red(" write failed (permission?)"));continue}u++,k.patched=S.path,console.log(m.green(` \u2713 patched ${S.path}`))}if(a&&a.close(),u>0&&g&&i.rebuildIndex(),console.log(),console.log(m.bold(` Session done: ${d.length} rounds, ${u} patches applied.`)),e.out){let f=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${u} patches_`,""];for(let p=0;p<d.length;p++){let y=d[p];f.push(`## ${p+1}. Q: ${y.q}`,"",`**A:** ${y.answer}`,"",`**Citations:** ${y.citations.map(w=>`\`${w.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${y.verdict}\``+(y.patched?` \u2192 patched \`${y.patched}\``:""),"")}$t(e.out,f.join(`
@@ -539,14 +539,14 @@ Output (JSON array, one entry per input article, same order):
539
539
  [
540
540
  {"path": "path/to/article.md", "type": "project"},
541
541
  ...
542
- ]`}ne.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Oe(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()});ne.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 o=e.dir||q(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-ZUMI4IY4.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${m.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(m.dim(` Wiki: ${o}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),ed(o,t,e.agent,n,e.mode)});ne.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:o,articleQualityState:t,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-NIPWHLKC.js"),c=Oe(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let w of l){let k=c.getAgentWiki(w);for(let b of k.listArticles(w)){if(u.length>=g)break e;let $=k.readArticle(b.path);if(!$||e.type&&$.meta.type!==e.type)continue;let E={...o($.meta.type),...e.fields?i($.meta.type):{}},S=await a(s,t({path:b.path,title:$.meta.title,type:$.meta.type,tags:$.meta.tags,body:$.content}),E,{links:[{kind:"article",id:b.path}],features:{agent:w,type:$.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let v=n(S.answers),x=e.fields?r($.meta.type,S.answers):null;v.completeness>=d&&!(x&&!x.fit)||u.push({agent:w,type:$.meta.type??"?",score:v.completeness.toFixed(2),standsAlone:v.standsAlone.toFixed(2),gap:v.biggestGap,...x?{missing:x.missingCritical.join(",")||"-",cov:`${Math.round(x.coverage*100)}%`}:{},title:$.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((w,k)=>parseFloat(w.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(w=>Math.max(w.length,...u.map(k=>String(k[w]).length))),y=w=>w.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(y(f)));for(let w of u)console.log(y(f.map(k=>w[k])));if(e.fields){let w=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
542
+ ]`}ne.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=Oe(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()});ne.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 o=e.dir||q(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-HCJ5NZW5.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(m.bold(" AgentX Wiki Server")),console.log(),console.log(` ${m.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${m.cyan(e.agent)}`):console.log(` Mode: ${m.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${m.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(m.dim(` Wiki: ${o}`)),console.log(m.dim(" Press Ctrl+C to stop")),console.log(),ed(o,t,e.agent,n,e.mode)});ne.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:o,articleQualityState:t,gradeArticle:n,ARTICLE_QUALITY_SEAT:s}=await import("./article-quality-JFJMZWFQ.js"),{fieldQuestions:i,reportFields:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-PZBFMYQL.js"),c=Oe(e.dir,e.mode),l=e.agent?[e.agent]:c.listAgents(),g=parseInt(e.limit),d=parseFloat(e.min),u=[];e:for(let w of l){let k=c.getAgentWiki(w);for(let b of k.listArticles(w)){if(u.length>=g)break e;let $=k.readArticle(b.path);if(!$||e.type&&$.meta.type!==e.type)continue;let E={...o($.meta.type),...e.fields?i($.meta.type):{}},S=await a(s,t({path:b.path,title:$.meta.title,type:$.meta.type,tags:$.meta.tags,body:$.content}),E,{links:[{kind:"article",id:b.path}],features:{agent:w,type:$.meta.type??"?"}});if(!S){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-quality.mode"));return}let v=n(S.answers),x=e.fields?r($.meta.type,S.answers):null;v.completeness>=d&&!(x&&!x.fit)||u.push({agent:w,type:$.meta.type??"?",score:v.completeness.toFixed(2),standsAlone:v.standsAlone.toFixed(2),gap:v.biggestGap,...x?{missing:x.missingCritical.join(",")||"-",cov:`${Math.round(x.coverage*100)}%`}:{},title:$.meta.title.slice(0,44)})}}if(e.json){console.log(JSON.stringify(u,null,2));return}if(u.length===0){console.log(m.green(" no articles below the threshold"));return}u.sort((w,k)=>parseFloat(w.score)-parseFloat(k.score));let f=e.fields?["score","cov","missing","type","gap","agent","title"]:["score","standsAlone","type","gap","agent","title"],p=f.map(w=>Math.max(w.length,...u.map(k=>String(k[w]).length))),y=w=>w.map((k,b)=>String(k).padEnd(p[b])).join(" ");console.log(),console.log(m.bold(y(f)));for(let w of u)console.log(y(f.map(k=>w[k])));if(e.fields){let w=u.filter(k=>k.missing!=="-").length;console.log(m.dim(`
543
543
  ${u.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(`
544
- ${u.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."))});ne.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-LHXSINM2.js"),n=Oe(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=q(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});ne.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,o)=>{let t=Oe(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));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()});ne.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 o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=q(process.cwd(),".agentx/graph");if(!to(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new qo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,u]of Object.entries(i.entries))r.set(d,u.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of t){let u=o.getAgentWiki(d),f=u.listArticles(d),p=o.getSharedStore().listEntries(),y=new Map(p.map($=>[$.id,$])),w=0,k=0,b=0;for(let $ of f){if(a++,$.meta.graphPath?.length||!$.meta.sources?.length)continue;w++,c++;let E=new Map;for(let v of $.meta.sources){let x=y.get(v);if(!x)continue;let R=String(x.meta?.sender??""),I=s.fingerprint({text:x.content,channel:x.source,sender:R}),C=r.get(I);if(!C?.length)continue;let P=C.join("/"),B=E.get(P);B?B.n++:E.set(P,{path:C,n:1})}if(E.size===0)continue;k++,l++;let S;for(let v of E.values())(!S||v.n>S.n)&&(S=v);S&&(e.dryRun||(u.writeArticle($.path,{...$.meta,graphPath:S.path},$.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ne.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=Oe(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-ZUMI4IY4.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let u of l)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});ne.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 o=e.dir||q(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Di(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,y=0,w=new Set;for(let b of d.articles){for(let $ of b.tags||[])p.add($);y+=b.tags?.length||0;for(let $ of b.sources||[])w.add($)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Zr(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(y/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:w.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["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 r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.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()});ne.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,o)=>{let t=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");to(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=q(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),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=to(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Bw(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ne.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:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-NIPWHLKC.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Oe(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let v of d){let x=l.getAgentWiki(v);for(let R of x.listArticles(v)){if(f>=u)break e;let I=x.readArticle(R.path);if(!I||e.type&&I.meta.type!==e.type)continue;f++;let C=await a(r,n({title:I.meta.title,type:I.meta.type,body:I.content}),o(I.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:v,type:I.meta.type??"?"}});if(!C){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(I.meta.type,C.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:v,path:R.path,subject:I.meta.title,field:B.field,tier:B.tier,question:`${I.meta.title} (${I.meta.type??"?"}) \u2014 ${B.label}?`}),p.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:v,article:I.meta.title.slice(0,40)}))}}let y={added:0,skipped:0};if(e.ask&&g.length>0&&(y=new c(bt(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let w=["tier","need","how","uncertain","agent","article"],k=v=>String(v).replace(/\u001b\[[0-9;]*m/g,""),b=w.map(v=>Math.max(v.length,...p.map(x=>k(x[v]).length))),$=(v,x)=>String(v)+" ".repeat(Math.max(0,b[x]-k(v).length));console.log(),console.log(m.bold(w.map((v,x)=>$(v,x)).join(" ")));for(let v of p)console.log(w.map((x,R)=>$(v[x],R)).join(" "));let E=p.filter(v=>v.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${E} can be closed by a lookup; ${p.length-E} need a person.`));let S=p[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${y.added} question(s) for a person (${y.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&y.added>0){let{TIER_RANK:v}=await import("./article-fields-PITN4NHA.js"),x=v[e.notifyTier]??v.pillar,R=g.filter(I=>(v[I.tier??"furniture"]??9)<=x);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:I}=await import("./config-ZUMI4IY4.js"),C=I(),P=C?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(H=>`\u2022 ${H.question}`).join(`
544
+ ${u.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."))});ne.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-A2N2LIR7.js"),n=Oe(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),g=q(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(m.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(m.bold(` Q: ${e}`)),console.log(m.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(m.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(m.dim(" Citations:"));for(let c of a.citations){let l=c.type?m.magenta(` [${c.type}]`):"";console.log(m.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(m.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(m.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(g=>g.path===l.path));console.log(m.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});ne.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,o)=>{let t=Oe(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=await t.getAgentWiki(i).findRelevantReranked(e,void 0,10);if(a.length>0){console.log(m.bold(` ${m.cyan(i)}:`));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()});ne.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 o=Oe(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=q(process.cwd(),".agentx/graph");if(!to(n)){console.log(m.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new qo({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,u]of Object.entries(i.entries))r.set(d,u.path);if(r.size===0){console.log(m.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(m.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,g=0;for(let d of t){let u=o.getAgentWiki(d),f=u.listArticles(d),p=o.getSharedStore().listEntries(),y=new Map(p.map($=>[$.id,$])),w=0,k=0,b=0;for(let $ of f){if(a++,$.meta.graphPath?.length||!$.meta.sources?.length)continue;w++,c++;let E=new Map;for(let v of $.meta.sources){let x=y.get(v);if(!x)continue;let R=String(x.meta?.sender??""),I=s.fingerprint({text:x.content,channel:x.source,sender:R}),C=r.get(I);if(!C?.length)continue;let P=C.join("/"),B=E.get(P);B?B.n++:E.set(P,{path:C,n:1})}if(E.size===0)continue;k++,l++;let S;for(let v of E.values())(!S||v.n>S.n)&&(S=v);S&&(e.dryRun||(u.writeArticle($.path,{...$.meta,graphPath:S.path},$.content,d),b++,g++))}console.log(` ${m.cyan(d)}: ${m.bold(f.length)} articles \xB7 ${w} eligible \xB7 ${k} matched \xB7 ${m.green(b)} written`)}console.log(),console.log(m.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(m.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ne.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.64.0.11:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=Oe(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-HCJ5NZW5.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(m.red(" No --peer specified and no daemon config found")),console.log(m.dim(" Usage: agentx wiki sync --peer http://100.64.0.11:19900"));return}if(n.length===0){console.log(m.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(m.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(m.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],g=c.nodeId||"unknown";console.log(m.dim(` Node: ${g} \u2014 ${l.length} entries`));let d=0;for(let u of l)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),d++);d>0?console.log(m.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(m.dim(" Already up to date")),i+=d;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let f=await u.json();for(let p of f.agents||[])p.totalEntries>0&&console.log(m.dim(` ${p.agentId}: ${p.totalEntries} entries, ${p.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(m.red(" Connection refused")):console.log(m.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(m.green(` ${i} entries synced.`)):i>0?console.log(m.dim(` ${i} entries would be synced (dry run)`)):console.log(m.dim(" All peers up to date")),console.log()});ne.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 o=e.dir||q(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let l=new Di(o,void 0,c),d=l.getAgentWiki(t).rebuildIndex(),u=l.getAgentEntries(t),f=l.getUnabsorbedEntries(t),p=new Set,y=0,w=new Set;for(let b of d.articles){for(let $ of b.tags||[])p.add($);y+=b.tags?.length||0;for(let $ of b.sources||[])w.add($)}let k=new Set(d.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:Zr(c),articles:d.articles.length,entries:u.length,unabsorbed:f.length,uniqueTags:p.size,avgTags:d.articles.length>0?(y/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:w.size,articleList:d.articles}});console.log(),console.log(m.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["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 r){let g=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,l)=>{let g=Math.max(...s.map(u=>u[c])),d=s.filter(u=>u[c]===g).map(u=>u.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()});ne.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,o)=>{let t=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");to(t)||(console.log(m.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?q(process.cwd(),e):q(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=q(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),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=to(s)?g(s).size:0;console.log(),console.log(m.green(` \u2713 wrote ${s} (${Bw(d)})`)),console.log(m.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ne.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:o,reportFields:t,articleFieldsState:n,nextActions:s,TIER_MEANING:i,ARTICLE_FIELDS_SEAT:r}=await import("./article-fields-PITN4NHA.js"),{askSeat:a}=await import("./seat-PZBFMYQL.js"),{QuestionStore:c}=await import("./questions-ZATLU5AW.js"),l=Oe(e.dir,e.mode),g=[],d=e.agent?[e.agent]:l.listAgents(),u=parseInt(e.limit),f=0,p=[];e:for(let v of d){let x=l.getAgentWiki(v);for(let R of x.listArticles(v)){if(f>=u)break e;let I=x.readArticle(R.path);if(!I||e.type&&I.meta.type!==e.type)continue;f++;let C=await a(r,n({title:I.meta.title,type:I.meta.type,body:I.content}),o(I.meta.type),{links:[{kind:"article",id:R.path}],features:{agent:v,type:I.meta.type??"?"}});if(!C){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let P=t(I.meta.type,C.answers);for(let B of s(P,{maxTier:e.maxTier,includeUnclear:!!e.unclear}))e.auto&&B.needsHuman||(e.ask&&B.needsHuman&&g.push({kind:"field",agentId:v,path:R.path,subject:I.meta.title,field:B.field,tier:B.tier,question:`${I.meta.title} (${I.meta.type??"?"}) \u2014 ${B.label}?`}),p.push({tier:B.tier,need:B.field,how:B.needsHuman?m.yellow("ask"):B.sources.join("/"),uncertain:B.uncertain?"?":"",agent:v,article:I.meta.title.slice(0,40)}))}}let y={added:0,skipped:0};if(e.ask&&g.length>0&&(y=new c(bt(e.dir)).add(g)),e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(m.green(` ${f} article(s) checked \u2014 nothing missing at or above ${e.maxTier}`));return}let w=["tier","need","how","uncertain","agent","article"],k=v=>String(v).replace(/\u001b\[[0-9;]*m/g,""),b=w.map(v=>Math.max(v.length,...p.map(x=>k(x[v]).length))),$=(v,x)=>String(v)+" ".repeat(Math.max(0,b[x]-k(v).length));console.log(),console.log(m.bold(w.map((v,x)=>$(v,x)).join(" ")));for(let v of p)console.log(w.map((x,R)=>$(v[x],R)).join(" "));let E=p.filter(v=>v.how!==m.yellow("ask")).length;console.log(),console.log(m.dim(` ${p.length} gap(s) across ${f} article(s).`)),console.log(m.dim(` ${E} can be closed by a lookup; ${p.length-E} need a person.`));let S=p[0]?.tier;if(S&&console.log(m.dim(` Start at ${S} \u2014 ${i[S]}.`)),e.ask&&(console.log(m.cyan(` Queued ${y.added} question(s) for a person (${y.skipped} already asked).`)),console.log(m.dim(' agentx wiki questions \xB7 agentx wiki answer <id> "<value>"'))),e.ask&&e.notify&&y.added>0){let{TIER_RANK:v}=await import("./article-fields-PITN4NHA.js"),x=v[e.notifyTier]??v.pillar,R=g.filter(I=>(v[I.tier??"furniture"]??9)<=x);if(R.length===0)console.log(m.dim(` Nothing at or above ${e.notifyTier} \u2014 not interrupting anyone.`));else{let{loadDaemonConfig:I}=await import("./config-HCJ5NZW5.js"),C=I(),P=C?.notifications?.destination;if(!P?.channel||!P?.chatId)console.log(m.yellow(" --notify: no notifications.destination configured \u2014 questions are queued but nobody was told."));else{let B=R.slice(0,10).map(H=>`\u2022 ${H.question}`).join(`
545
545
  `),L=R.length>10?`
546
546
  \u2026and ${R.length-10} more`:"",V=`${R.length} wiki gap(s) need you (${e.notifyTier}+):
547
547
  ${B}${L}
548
548
 
549
- agentx wiki questions`,fe=C?.daemon?.port??C?.port??18800;try{let H=await fetch(`http://127.0.0.1:${fe}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:V})});console.log(H.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${H.status}) \u2014 questions are still queued.`))}catch(H){console.log(m.yellow(` Push failed (${String(H?.message??H).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ne.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:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-NIPWHLKC.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ROUMKS7I.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Oe(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),y=parseInt(e.limit),w=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(C=>[C.name.toLowerCase().trim(),C])),$=0,E=0,S=[],v=!1;e:for(let C of p){let P=f.getAgentWiki(C);for(let B of P.listArticles(C)){if($>=y)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;$++;let V=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:C,op:"backfill"}});if(!V){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let H=t(L.meta.type,V.answers).missing.filter(_=>i.includes(_));if(H.length===0)continue;let{records:Ce,results:Se}=await a([{name:L.meta.title,type:"person"}],{sources:w}),M=b.get(L.meta.title.toLowerCase().trim());if(!v){for(let _ of l(Se,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));v=!0}let Qe=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,$e])=>[_,$e.value]))}]:[],...Ce]);if(Qe.length===0)continue;let{content:Ee,edits:st}=u(L.content,Qe[0],H);if(st.length!==0){for(let _ of st)S.push({agent:C,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,Ee,C)?E++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${$} person article(s) considered \u2014 nothing to backfill`));return}let x=["agent","article","field","action","got"],R=x.map(C=>Math.max(C.length,...S.map(P=>String(P[C]).length))),I=C=>C.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(I(x)));for(let C of S)console.log(I(x.map(P=>C[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${E} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${$} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ne.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:o}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(bt(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,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${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`))});ne.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,o,t)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(bt(t.dir)),a=r.list().find(y=>(y.id===e||y.id.startsWith(e))&&y.status!=="open"&&y.kind==="contradiction");if(a&&!r.list("open").some(y=>y.id===e||y.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(t.dismiss){try{let y=r.resolve(e,"dismissed");console.log(y?m.dim(` dismissed: ${y.question}`):m.red(` no question matching "${e}"`))}catch(y){console.log(m.red(` ${y?.message??y}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(y=>y.id===e||y.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:y}=await import("./ledger-CH7R756S.js"),w=new y(bt(t.dir));try{let k=w.get(c.factId);if(k){let b=w.write({subject:k.subject,attribute:k.attribute,value:o,source:"owner said",verifiedBy:"operator",volatility:k.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${k.id} ${k.subject} \xB7 ${k.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(k){k?.name!=="LedgerCorruptError"&&console.log(m.red(` ${k?.message??k}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",o),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",o)}catch(y){console.log(m.red(` ${y?.message??y}`)),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(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=Oe(t.dir,t.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${o} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});ne.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:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-NIPWHLKC.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Oe(e.dir,"graph").getSharedStore(),p=f.listEntries(),y=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:w,backlog:k}=r(p,y),b=a(w,L=>L.absorbed,parseInt(e.n)),$={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},E=[],S=0,v=Date.now();if(e.load){let{readFileSync:L}=await import("fs");E.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${E.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let V=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!V){S++;continue}let fe=V.answers;E.push({entry:L,verdict:s(V.answers,$),citeWorthy:fe.citeWorthy?.noul})}if(E.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(E)),console.log(m.dim(` saved ${E.length} outcome(s) to ${e.save}`))}let x=c(E,{minType:$.minTypeConfidence,minWorth:$.minWorth,minDurability:$.minDurability}),R=l(E,"seat","seat"),I=d(R,{minN:50}),C=((Date.now()-v)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:x,calibration:I,failures:S,elapsed:C},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${x.n} (${x.positives} kept by absorb, ${x.negatives} passed over)`),console.log(` recall ${P(x.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(x.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(x.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${x.lostPositives>0?m.yellow(`lost ${x.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in I)||!I.insufficient)&&console.log(` ECE ${I.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),x.lostPositives>0){let L=x.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=x.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${C}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:V,points:fe}=g(E,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${fe.length} policies, recall floor ${P(L)})`)),V)console.log(` best: ${V.requireTyped?`typed & type>=${V.minType}`:"type gate OFF"} worth>=${V.minWorth} durability>=${V.minDurability}`),console.log(` recall ${P(V.recall)} \xB7 filtered ${P(V.filtered)} \xB7 precision ${P(V.precision)} \xB7 lost ${V.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let H=fe.slice().sort((Ce,Se)=>Se.recall-Ce.recall)[0];H&&console.log(m.dim(` Best recall available: ${P(H.recall)} at ${H.requireTyped?`type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} dur>=${H.minDurability}, filtering ${P(H.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ne.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,o)=>{let t=q(process.cwd(),e);to(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");to(n)&&!o.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=q(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{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 Bw(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"}Hp();import{Command as Jw}from"commander";import D from"chalk";import{resolve as ui}from"path";import{existsSync as Hw}from"fs";te();var cn=new Jw().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");cn.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 o=T();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(D.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new qo({baseDir:ui(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let y=r[p],w=ms(y.path,c)||y.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(y.msgHash.slice(0,8))} ${D.dim(w)} ... `);let k=Gw(y,a,c),b=null;try{b=await zw(n,t,k,o.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let $=String(b.decision).toLowerCase().trim(),E=(b.reason||"").toString().slice(0,180);if($==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{Vw(i,y,a,c,t),i.updateClassificationStatus(y.msgHash,{status:"approved",reviewer:t,reviewReason:E}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else $==="reject"?(console.log(D.red("REJECT")+" "+D.dim(E)),e.dryRun||i.updateClassificationStatus(y.msgHash,{status:"rejected",reviewer:t,reviewReason:E}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(E||$)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});cn.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 o=T();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=ui(process.cwd(),o.graph.baseDir);if(!Hw(t)){console.log(D.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new qo({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});cn.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 o=T();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new qo({baseDir:ui(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(x=>x.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let x=await fetch(`${t}/graph/schema`,{headers:s});if(!x.ok)throw new Error(`schema HTTP ${x.status}`);l=(await x.json()).schema;let I=await fetch(`${t}/graph/nodes`,{headers:s});if(!I.ok)throw new Error(`nodes HTTP ${I.status}`);g=(await I.json()).nodes||[];let C=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!C.ok)throw new Error(`classifications HTTP ${C.status}`);d=(await C.json()).classifications||[]}catch(x){console.log(D.red(` fetch failed: ${x.message}`));return}let u=r.levels.map(x=>x.id).join(","),f=l?.levels?.map(x=>x.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let y=p?r:l,w=new Map;y.levels.forEach((x,R)=>w.set(x.id,R));let k=[...g].sort((x,R)=>(w.get(x.level)??99)-(w.get(R.level)??99)),b=0,$=0,E=0;for(let x of k){if(c.has(x.id)){$++;continue}if(e.dryRun){b++,c.add(x.id);continue}try{i.addNode({...x,createdBy:x.createdBy?`${x.createdBy} (sync)`:`sync:${t}`}),c.add(x.id),b++}catch(R){E++,console.log(D.yellow(` skip node ${x.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${$} already-present \xB7 ${E} failed`));let S=0,v=0;for(let x of d)if(!(!x.msgHash||!Array.isArray(x.path))){if(i.getFingerprint(x.msgHash)){v++;continue}if(e.dryRun){S++;continue}i.setFingerprint(x.msgHash,{path:x.path,leaf:x.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${v} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${t}`)),console.log()});function Gw(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
549
+ agentx wiki questions`,fe=C?.daemon?.port??C?.port??18800;try{let H=await fetch(`http://127.0.0.1:${fe}/channel/send`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({channel:P.channel,chatId:P.chatId,accountId:P.accountId,text:V})});console.log(H.ok?m.cyan(` Pushed ${R.length} question(s) to ${P.channel}.`):m.yellow(` Push failed (${H.status}) \u2014 questions are still queued.`))}catch(H){console.log(m.yellow(` Push failed (${String(H?.message??H).slice(0,80)}) \u2014 questions are still queued.`))}}}}});ne.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:o,reportFields:t,articleFieldsState:n,ARTICLE_FIELDS_SEAT:s,BACKFILL_ORDER:i}=await import("./article-fields-PITN4NHA.js"),{askSeat:r}=await import("./seat-PZBFMYQL.js"),{resolveFacts:a,mergeRecords:c,installPrompts:l,defaultSources:g,recordsFromEntries:d}=await import("./facts-ROUMKS7I.js"),{backfillArticle:u}=await import("./backfill-7TCF4SHG.js"),f=Oe(e.dir,e.mode),p=e.agent?[e.agent]:f.listAgents(),y=parseInt(e.limit),w=g(),k=c(d(f.getSharedStore().listEntries())),b=new Map(k.map(C=>[C.name.toLowerCase().trim(),C])),$=0,E=0,S=[],v=!1;e:for(let C of p){let P=f.getAgentWiki(C);for(let B of P.listArticles(C)){if($>=y)break e;if(B.meta.type!=="person")continue;let L=P.readArticle(B.path);if(!L)continue;$++;let V=await r(s,n({title:L.meta.title,type:L.meta.type,body:L.content}),o(L.meta.type),{links:[{kind:"article",id:B.path}],features:{agent:C,op:"backfill"}});if(!V){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.article-fields.mode"));return}let H=t(L.meta.type,V.answers).missing.filter(_=>i.includes(_));if(H.length===0)continue;let{records:Ce,results:Se}=await a([{name:L.meta.title,type:"person"}],{sources:w}),M=b.get(L.meta.title.toLowerCase().trim());if(!v){for(let _ of l(Se,w))console.log(m.yellow(` ! ${_.source} ${_.kind} \u2014 would supply ${_.provides.join(", ")}`)),console.log(m.dim(` ${_.hint}`));v=!0}let Qe=c([...M?[{name:M.name,source:"entries",fields:Object.fromEntries(Object.entries(M.fields).map(([_,$e])=>[_,$e.value]))}]:[],...Ce]);if(Qe.length===0)continue;let{content:Ee,edits:st}=u(L.content,Qe[0],H);if(st.length!==0){for(let _ of st)S.push({agent:C,article:L.meta.title.slice(0,32),field:_.field,action:_.replaced?"replace":"add",got:`${_.value.split(";").length} value(s)`});e.apply&&(P.writeArticle(B.path,L.meta,Ee,C)?E++:console.log(m.red(` could not write ${B.path}`)))}}}if(e.json){console.log(JSON.stringify(S,null,2));return}if(S.length===0){console.log(m.green(` ${$} person article(s) considered \u2014 nothing to backfill`));return}let x=["agent","article","field","action","got"],R=x.map(C=>Math.max(C.length,...S.map(P=>String(P[C]).length))),I=C=>C.map((P,B)=>String(P).padEnd(R[B])).join(" ");console.log(),console.log(m.bold(I(x)));for(let C of S)console.log(I(x.map(P=>C[P])));console.log(),e.apply?(console.log(m.green(` ${S.length} field(s) written across ${E} article(s).`)),console.log(m.dim(" Prior versions are in _versions/ if any of this is wrong."))):(console.log(m.dim(` ${S.length} field(s) would be written across ${$} article(s) considered.`)),console.log(m.dim(" Re-run with --apply to write them.")))});ne.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:o}=await import("./questions-ZATLU5AW.js"),{TIER_RANK:t}=await import("./article-fields-PITN4NHA.js"),n=new o(bt(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,i)=>(t[s.tier??"furniture"]??9)-(t[i.tier??"furniture"]??9)),console.log();for(let s of n){let i=s.tier?m.dim(`[${s.tier}]`):"";console.log(` ${m.cyan(s.id)} ${i} ${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`))});ne.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,o,t)=>{let{QuestionStore:n}=await import("./questions-ZATLU5AW.js"),{patchIdentityField:s}=await import("./backfill-7TCF4SHG.js"),{IDENTITY_SLOTS:i}=await import("./article-fields-PITN4NHA.js"),r=new n(bt(t.dir)),a=r.list().find(y=>(y.id===e||y.id.startsWith(e))&&y.status!=="open"&&y.kind==="contradiction");if(a&&!r.list("open").some(y=>y.id===e||y.id.startsWith(e))){console.log(m.dim(` already ${a.status}: ${a.question}`));return}if(t.dismiss){try{let y=r.resolve(e,"dismissed");console.log(y?m.dim(` dismissed: ${y.question}`):m.red(` no question matching "${e}"`))}catch(y){console.log(m.red(` ${y?.message??y}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1}return}if(!o){console.log(m.red(" give a value, or pass --dismiss"));return}let c=r.list("open").find(y=>y.id===e||y.id.startsWith(e));if(c?.kind==="contradiction"&&c.factId){let{FactLedger:y}=await import("./ledger-CH7R756S.js"),w=new y(bt(t.dir));try{let k=w.get(c.factId);if(k){let b=w.write({subject:k.subject,attribute:k.attribute,value:o,source:"owner said",verifiedBy:"operator",volatility:k.volatility},{confirmedBy:"operator"});console.log(m.green(` ${b.status}: ${k.id} ${k.subject} \xB7 ${k.attribute}: ${b.fact.value}`))}else console.log(m.yellow(` fact ${c.factId} is gone; answer recorded only.`))}catch(k){k?.name!=="LedgerCorruptError"&&console.log(m.red(` ${k?.message??k}`)),console.log(m.yellow(" the question stays open.")),process.exitCode=1;return}r.resolve(c.id,"answered",o),console.log(m.green(` answered: ${c.question}`));return}let l;try{l=r.resolve(e,"answered",o)}catch(y){console.log(m.red(` ${y?.message??y}`)),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(!i[l.field]){console.log(m.dim(` recorded against ${l.path}. "${l.field}" has no fixed slot, so nothing was rewritten.`));return}let d=Oe(t.dir,t.mode).getAgentWiki(l.agentId),u=d.readArticle(l.path);if(!u){console.log(m.yellow(` article gone: ${l.path}`));return}let f=s(u.content,l.field,`${o} (answered by operator)`);if(!f){console.log(m.dim(" already present \u2014 nothing to write."));return}let p=d.writeArticle(l.path,u.meta,f.content,l.agentId);console.log(p?m.green(` wrote ${l.field} into ${l.path} (prior version kept)`):m.red(` could not write ${l.path}`))});ne.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:o,entryTriageQuestions:t,triageState:n,triage:s}=await import("./entry-triage-LZWMMLLN.js"),{askSeat:i}=await import("./seat-PZBFMYQL.js"),{labelEntries:r,sample:a,scoreBacktest:c,toGradedRows:l,sweepPolicies:g}=await import("./triage-backtest-DLKYJSEB.js"),{calibrationReport:d}=await import("./calibration-MCCVYGZQ.js"),f=Oe(e.dir,"graph").getSharedStore(),p=f.listEntries(),y=new Set(f.getUnabsorbedEntries().map(L=>L.id)),{labeled:w,backlog:k}=r(p,y),b=a(w,L=>L.absorbed,parseInt(e.n)),$={minWorth:e.minWorth?parseFloat(e.minWorth):void 0,minDurability:e.minDurability?parseFloat(e.minDurability):void 0,minTypeConfidence:e.minType?parseFloat(e.minType):void 0},E=[],S=0,v=Date.now();if(e.load){let{readFileSync:L}=await import("fs");E.push(...JSON.parse(L(e.load,"utf-8"))),console.log(m.dim(` re-sweeping ${E.length} saved outcome(s) \u2014 no calls made`))}else console.log(m.dim(` ${w.length} labelled (${k} in backlog) \u2014 grading ${b.length}`));for(let L of e.load?[]:b){let V=await i(o,n(L),t,{features:{source:L.source??"",absorbed:L.absorbed}});if(!V){S++;continue}let fe=V.answers;E.push({entry:L,verdict:s(V.answers,$),citeWorthy:fe.citeWorthy?.noul})}if(E.length===0){console.log(m.yellow(" seat is off or unavailable \u2014 set decisions.seats.entry-triage.mode"));return}if(e.save){let{writeFileSync:L}=await import("fs");L(e.save,JSON.stringify(E)),console.log(m.dim(` saved ${E.length} outcome(s) to ${e.save}`))}let x=c(E,{minType:$.minTypeConfidence,minWorth:$.minWorth,minDurability:$.minDurability}),R=l(E,"seat","seat"),I=d(R,{minN:50}),C=((Date.now()-v)/1e3).toFixed(1);if(e.json){console.log(JSON.stringify({report:x,calibration:I,failures:S,elapsed:C},null,2));return}let P=L=>`${(L*100).toFixed(1)}%`;if(console.log(),console.log(m.bold(" entry-triage vs absorb's own verdicts")),console.log(` graded ${x.n} (${x.positives} kept by absorb, ${x.negatives} passed over)`),console.log(` recall ${P(x.recall)} ${m.dim("of what absorb kept, the gate would keep")}`),console.log(` precision ${P(x.precision)} ${m.dim("of what the gate keeps, absorb agreed")}`),console.log(` filtered ${P(x.filtered)} ${m.dim("never reaches the writing model")}`),console.log(` ${x.lostPositives>0?m.yellow(`lost ${x.lostPositives} article(s) absorb would have written`):m.green("lost 0 \u2014 nothing absorb kept was dropped")}`),(!("insufficient"in I)||!I.insufficient)&&console.log(` ECE ${I.ece?.toFixed(3)??"n/a"} ${m.dim("on P(worth keeping)")}`),x.lostPositives>0){let L=x.droppedBy;console.log(m.dim(` dropped by: type ${L.type} \xB7 worth ${L.worth} \xB7 durability ${L.durability} (a positive can fail several)`))}let B=x.positiveMeans;if(console.log(m.dim(` positives avg: worth ${B.worth.toFixed(2)} \xB7 durability ${B.durability.toFixed(2)} \xB7 typeConf ${B.typeConfidence.toFixed(2)}`)),console.log(m.dim(` ${C}s, ${S} seat failure(s)`)),console.log(),console.log(m.dim(" Recall is the number that decides this: a dropped positive is")),console.log(m.dim(" knowledge destroyed silently. Filtered is only the prize.")),e.sweep){let L=parseFloat(e.minRecall),{best:V,points:fe}=g(E,{minRecall:L});if(console.log(),console.log(m.bold(` threshold sweep (${fe.length} policies, recall floor ${P(L)})`)),V)console.log(` best: ${V.requireTyped?`typed & type>=${V.minType}`:"type gate OFF"} worth>=${V.minWorth} durability>=${V.minDurability}`),console.log(` recall ${P(V.recall)} \xB7 filtered ${P(V.filtered)} \xB7 precision ${P(V.precision)} \xB7 lost ${V.lostPositives}`),console.log(m.dim(" Filtering here is the real saving; anything above it costs articles."));else{console.log(m.red(` No policy reaches ${P(L)} recall \u2014 not even keeping everything typed.`));let H=fe.slice().sort((Ce,Se)=>Se.recall-Ce.recall)[0];H&&console.log(m.dim(` Best recall available: ${P(H.recall)} at ${H.requireTyped?`type>=${H.minType}`:"type gate OFF"} worth>=${H.minWorth} dur>=${H.minDurability}, filtering ${P(H.filtered)}`)),console.log(m.yellow(" The gate is not safe to run in active mode on this evidence."))}}});ne.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,o)=>{let t=q(process.cwd(),e);to(t)||(console.log(m.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?q(process.cwd(),o.dir):q(process.cwd(),".agentx/wiki");to(n)&&!o.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=q(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(m.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{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 Bw(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"}Hp();import{Command as Jw}from"commander";import D from"chalk";import{resolve as ui}from"path";import{existsSync as Hw}from"fs";te();var cn=new Jw().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");cn.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 o=T();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(D.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(D.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new qo({baseDir:ui(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(D.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(D.bold(` Graph review \u2014 ${r.length} pending`)),console.log(D.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,g=0,d=0,u=0;for(let p=0;p<r.length;p++){let y=r[p],w=ms(y.path,c)||y.path.join(" \u203A ");process.stdout.write(` [${p+1}/${r.length}] ${D.cyan(y.msgHash.slice(0,8))} ${D.dim(w)} ... `);let k=Gw(y,a,c),b=null;try{b=await zw(n,t,k,o.dashboard?.token)}catch(S){u++,console.log(D.red(`ERR ${S.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(D.red("ERR no decision"));continue}let $=String(b.decision).toLowerCase().trim(),E=(b.reason||"").toString().slice(0,180);if($==="approve")if(console.log(D.green("APPROVE")+" "+D.dim(E)),e.dryRun)l++;else try{Vw(i,y,a,c,t),i.updateClassificationStatus(y.msgHash,{status:"approved",reviewer:t,reviewReason:E}),l++}catch(S){console.log(D.yellow(` (commit failed, staying pending: ${S.message?.slice(0,100)})`)),u++}else $==="reject"?(console.log(D.red("REJECT")+" "+D.dim(E)),e.dryRun||i.updateClassificationStatus(y.msgHash,{status:"rejected",reviewer:t,reviewReason:E}),g++):(console.log(D.yellow("SKIP")+" "+D.dim(E||$)),d++)}console.log();let f=e.dryRun?"would":"did";console.log(D.dim(` Summary: ${f} approve ${l}, ${f} reject ${g}, ${d} skipped, ${u} errors.`)),e.dryRun&&(l>0||g>0)&&console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});cn.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 o=T();if(!o.graph){console.log(D.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=ui(process.cwd(),o.graph.baseDir);if(!Hw(t)){console.log(D.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-W7RRFM24.js"),s=new qo({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(D.dim(" "),...a)});console.log(),console.log(D.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(D.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});cn.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 o=T();if(!o.graph?.enabled){console.log(D.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new qo({baseDir:ui(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(x=>x.id));console.log(),console.log(D.bold(` graph pull \u2190 ${t}`));let l,g,d;try{let x=await fetch(`${t}/graph/schema`,{headers:s});if(!x.ok)throw new Error(`schema HTTP ${x.status}`);l=(await x.json()).schema;let I=await fetch(`${t}/graph/nodes`,{headers:s});if(!I.ok)throw new Error(`nodes HTTP ${I.status}`);g=(await I.json()).nodes||[];let C=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!C.ok)throw new Error(`classifications HTTP ${C.status}`);d=(await C.json()).classifications||[]}catch(x){console.log(D.red(` fetch failed: ${x.message}`));return}let u=r.levels.map(x=>x.id).join(","),f=l?.levels?.map(x=>x.id).join(","),p=u===f;p?console.log(D.dim(` schema matches (${r.levels.length} levels)`)):(console.log(D.yellow(" \u26A0 schema levels differ:")),console.log(D.dim(` local: ${u}`)),console.log(D.dim(` peer: ${f}`)),a.length===0&&!e.dryRun?(console.log(D.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(D.yellow(" keeping local schema; node import may fail if levels disagree")));let y=p?r:l,w=new Map;y.levels.forEach((x,R)=>w.set(x.id,R));let k=[...g].sort((x,R)=>(w.get(x.level)??99)-(w.get(R.level)??99)),b=0,$=0,E=0;for(let x of k){if(c.has(x.id)){$++;continue}if(e.dryRun){b++,c.add(x.id);continue}try{i.addNode({...x,createdBy:x.createdBy?`${x.createdBy} (sync)`:`sync:${t}`}),c.add(x.id),b++}catch(R){E++,console.log(D.yellow(` skip node ${x.id}: ${R.message?.slice(0,100)}`))}}console.log(D.dim(` nodes: +${b} added \xB7 ${$} already-present \xB7 ${E} failed`));let S=0,v=0;for(let x of d)if(!(!x.msgHash||!Array.isArray(x.path))){if(i.getFingerprint(x.msgHash)){v++;continue}if(e.dryRun){S++;continue}i.setFingerprint(x.msgHash,{path:x.path,leaf:x.leaf||{}}),S++}console.log(D.dim(` fingerprints: +${S} cached \xB7 ${v} already-present`)),console.log(),e.dryRun?console.log(D.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(D.green(` \u2713 pulled from ${t}`)),console.log()});function Gw(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
550
550
  `),i=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) ---",i,"","--- 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(`
551
551
  `)}async function zw(e,o,t,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=new AbortController,r=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:o,message:t,context:{channel:"a2a",sender:"graph-review"}}),signal:i.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 qa((c?.content||"").toString())}finally{clearTimeout(r)}}function Vw(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function ea(){let e=T();if(!e.graph?.baseDir)return console.log(D.red(" graph.baseDir is not configured")),null;let o=ui(process.cwd(),e.graph.baseDir);return{store:new qo({baseDir:o}),baseDir:o}}var oa=cn.command("label").description("human verdicts on classifications \u2014 the labels calibration needs");oa.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 o=ea();if(!o)return;let{ReviewStore:t,buildQueue:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,new Set(i.keys()),{n:parseInt(e.n),strategy:e.strategy});if(e.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(D.green(" nothing left unreviewed"));return}let a=o.store.loadNodes().nodes;console.log();for(let c of r){let l=typeof c.confidence=="number"?c.confidence.toFixed(2):D.dim("cache");console.log(` ${D.cyan(c.msgHash.slice(0,8))} ${l.padStart(5)} ${D.bold(ms(c.path,a)||c.path.join(" \u203A "))}`),c.preview&&console.log(D.dim(` ${String(c.preview).replace(/\s+/g," ").slice(0,96)}`))}console.log(),console.log(D.dim(` ${r.length} to check (${e.strategy}).`)),console.log(D.dim(" agentx graph label mark <hash> correct|wrong|unsure [--path a/b/c]"))});oa.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,o,t)=>{if(!["correct","wrong","unsure"].includes(o)){console.log(D.red(" verdict must be correct | wrong | unsure"));return}let n=ea();if(!n)return;let{ReviewStore:s}=await import("./review-store-PW3OBGZQ.js"),r=n.store.listAllClassifications().filter(l=>l.msgHash===e||l.msgHash.startsWith(e));if(r.length===0){console.log(D.red(` no classification matching "${e}"`));return}if(r.length>1){console.log(D.red(` "${e}" matches ${r.length} rows \u2014 use more characters`));return}new s(n.baseDir).record({msgHash:r[0].msgHash,verdict:o,correctPath:t.path?String(t.path).split("/").filter(Boolean):void 0,note:t.note,reviewer:t.by});let c=n.store.loadNodes().nodes;console.log(D.green(` ${o}: ${ms(r[0].path,c)||r[0].path.join(" \u203A ")}`)),t.path&&console.log(D.dim(` should have been: ${t.path}`))});oa.command("stats").description("how many labels so far, and what they say").option("--json").action(async e=>{let o=ea();if(!o)return;let{ReviewStore:t,labelStats:n}=await import("./review-store-PW3OBGZQ.js"),s=o.store.listAllClassifications(),i=new t(o.baseDir).load(),r=n(s,i);if(e.json){console.log(JSON.stringify(r,null,2));return}let a=c=>`${(c*100).toFixed(1)}%`;if(console.log(),console.log(` classifications ${r.classifications}`),console.log(` reviewed ${r.reviewed} (${r.correct} correct \xB7 ${r.wrong} wrong \xB7 ${r.unsure} unsure)`),r.correct+r.wrong>0&&console.log(` accuracy ${a(r.accuracy)}`),console.log(` calibratable ${r.calibratable} ${D.dim("reviewed rows that carry a confidence")}`),r.byBin.length>0){console.log(),console.log(D.bold(" reliability \u2014 confidence vs how often it was right"));for(let c of r.byBin){let l=Math.abs(parseFloat(c.bin.split("-")[0])+.05-c.accuracy),g=c.n>=5&&l>.15?D.yellow(" \u2190 miscalibrated"):"";console.log(` ${c.bin} n=${String(c.n).padStart(3)} right ${a(c.accuracy).padStart(6)}${g}`)}}console.log(),r.calibratable<100?console.log(D.dim(` ${100-r.calibratable} more labelled rows before a calibration report means anything.`)):console.log(D.green(" enough labels for a calibration report \u2014 a seat here can now be graded."))});import{Command as e$}from"commander";import K from"chalk";import{Command as Mm}from"commander";import pe from"chalk";import{existsSync as Yw}from"fs";import{resolve as Xw}from"path";import Kw from"better-sqlite3";function Qw(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(pe.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Zw(e){let o=Xw(process.cwd(),e);return Yw(o)||(console.log(pe.red(` No db at ${o}`)),process.exit(1)),new Kw(o,{readonly:!0})}var Lm=new Mm().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(An)).option("--max <n>","max clusters distilled per run",String(hs)).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(pe.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=Zw(e.path),t=await jc(o,{since:Qw(e.since),agentId:e.agent,sessions:new Ga(process.cwd()),minOccurrences:Number(e.minOccurrences)||An,max:Number(e.max)||hs,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(pe.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${pe.cyan(n.key)} ${pe.bold(`\xD7${n.count}`)} ${pe.dim(n.status)}`),n.sampleMessage&&console.log(pe.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(pe.dim(`
552
552
  near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(pe.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(pe.green(` \u2713 draft written: ${n.id}`)+pe.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(pe.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(pe.yellow(` \u26A0 ${n}`));t.dryRun?console.log(pe.dim(`
@@ -582,7 +582,7 @@ agentx wiki questions`,fe=C?.daemon?.port??C?.port??18800;try{let H=await fetch(
582
582
 
583
583
  `))>=0;){let f=l.slice(0,u);l=l.slice(u+2),S$(f)}}}catch(r){console.error(ie.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function S$(e){let o="message",t="";for(let i of e.split(`
584
584
  `))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?ie.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=ie.cyan(n.phase?.padEnd(9)??"run"),r=ie.bold(n.workflowId??""),a=ie.dim((n.runId??"").slice(0,8)),c=n.nodeId?ie.yellow(n.nodeId):"",l=n.note?ie.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=ie.magenta(`task.${n.phase}`.padEnd(14)),r=ie.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?ie.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${ie.cyan(a)} ${c}`);break}case"signal":{let i=ie.green("signal".padEnd(9)),r=ie.bold(n.name),a=ie.dim(`(${n.scope})`),c=n.workflowId?ie.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=ie.blue("mesh".padEnd(9)),r=ie.bold(n.peer),a=n.healthy?ie.green("\u2713 healthy"):ie.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${ie.dim(n.delta??"")}`);break}case"channel":{let i=ie.yellow("channel".padEnd(9)),r=n.direction==="in"?ie.cyan("\u2190"):ie.magenta("\u2192"),a=ie.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?ie.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(ie.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}te();import{Command as E$}from"commander";import fn from"chalk";function A$(e,o){let t=e.replace(/\/+$/,""),n=new URLSearchParams;if(o.since&&n.set("since",o.since),o.limit&&n.set("limit",o.limit),o.agent){let s=n.toString();return`${t}/agents/${encodeURIComponent(o.agent)}/events${s?`?${s}`:""}`}return o.kind&&n.set("kind",o.kind),o.limit||n.set("limit","50"),`${t}/events/recent?${n}`}var op=new E$().name("events").description("recent events on this node, or those matching one agent's subscriptions").option("-c, --config <path>","daemon config file").option("-a, --agent <id>","only events matching this agent's subscriptions").option("-s, --since <id|iso>","only events after this event id or ISO time").option("-k, --kind <kind>","only this event kind (without --agent)").option("-n, --limit <n>","most events to show (with --agent: default 20, max 50)").option("--json","machine-readable output").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let a=T(e.config);o||(o=a.dashboard?.daemonUrl||""),t||(t=a.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n={};t&&(n.Authorization=`Bearer ${t}`);let s;try{let a=await fetch(A$(o,e),{headers:n,signal:AbortSignal.timeout(1e4)});if(s=await a.json().catch(()=>({})),!a.ok){console.error(fn.red(` ${s.error||`HTTP ${a.status}`}`)),process.exitCode=1;return}}catch(a){console.error(fn.red(` daemon unreachable at ${o}: ${a?.message||a}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(s,null,2));return}let i=s.events??[];if(e.agent&&!s.subscriptions){console.log(fn.dim(` ${e.agent} has no subscriptions (agents.${e.agent}.subscriptions in agentx.json)`));return}if(i.length===0){console.log(fn.dim(" no events"));return}for(let a of i)console.log(` ${Ya(a)} ${fn.dim(a.id)}`);let r=s.next??i[i.length-1].id;console.log(fn.dim(`
585
- ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as j$}from"commander";import os from"chalk";import{spawn as O$}from"node:child_process";import{execFileSync as T$}from"node:child_process";function tp(e=()=>T$("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=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 t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var np=new j$().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(os.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-BLUCLNIS.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:tp();if(n?.ok){let{fetchAgents:l}=await import("./client-BLUCLNIS.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(k=>k.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(k=>[k.id,{name:`AgentX ${k.name||k.id}`}])),p={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${d}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(os.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:y}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:w}=await import("./opencode-launch-ECMEY2QZ.js");await w({agentId:d,env:p,cwd:process.cwd(),pool:y,spawnImpl:O$,log:k=>console.error(os.dim(k))});return}n&&!n.ok&&(console.error(os.yellow(n.reason)),console.error(os.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-XLQDP26J.js"),{render:i}=await import("ink"),r=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await i(r.createElement(s,{conn:t,pollMs:a})).waitUntilExit()});import{Command as C$}from"commander";import Q from"chalk";import{randomUUID as rp}from"crypto";import{createInterface as I$}from"node:readline/promises";import N$ from"ora";import ki from"chalk";function sp(e){console.error(),console.error(ki.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(ki.dim(` ${e.why}`)),console.error(),console.error(` Use ${ki.cyan(e.instead)} instead.`),e.note&&console.error(ki.dim(` ${e.note}`)),console.error()}var ip={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 ap=new C$().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,o)=>{sp({what:"agentx chat",...ip});let t=od({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${rp().slice(0,12)}`,r=[];try{r=await Ns(t)}catch(g){console.error(Q.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(Q.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(Q.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(Q.red(` unknown agent: @${n}`)),console.error(Q.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(Q.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-DRDUXZ66.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}_$(t.baseUrl,n,i,s);let a=I$({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(Q.dim(`
585
+ ${i.length} event(s). Newer ones: agentx events${e.agent?` --agent ${e.agent}`:""} --since ${r}`))});import{Command as j$}from"commander";import os from"chalk";import{spawn as O$}from"node:child_process";import{execFileSync as T$}from"node:child_process";function tp(e=()=>T$("opencode",["--version"],{encoding:"utf8",timeout:5e3}).trim()){let o;try{o=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 t=o.match(/^(?:opencode\s+)?v?(\d+)\.\d+\.\d+(?:\s|$)/i);return t?Number(t[1])<2?{ok:!1,reason:`OpenCode ${o} is too old; AgentX TUI requires OpenCode v2 or newer.`}:{ok:!0,version:o}:{ok:!1,reason:`Could not recognize the OpenCode version: ${o||"empty output"}`}}var np=new j$().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(os.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-526OCGWD.js"),t=o({node:e.node,token:e.token,config:e.config}),n=e.legacy?null:tp();if(n?.ok){let{fetchAgents:l}=await import("./client-526OCGWD.js"),g=await l(t);if(!g.length)throw new Error(`No AgentX agents returned by ${t.baseUrl}`);let d=e.agent||g[0].id;if(!g.some(k=>k.id===d))throw new Error(`Unknown AgentX agent: ${d}`);let u={};try{u=JSON.parse(process.env.OPENCODE_CONFIG_CONTENT||"{}")}catch{}let f=Object.fromEntries(g.map(k=>[k.id,{name:`AgentX ${k.name||k.id}`}])),p={...process.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({...u,model:`agentx/${d}`,providers:{...u.providers,agentx:{name:"AgentX",package:"@opencode/ai/providers/openai-compatible",settings:{baseURL:`${t.baseUrl}/v1`},models:f}}})};console.error(os.dim(`Opening ${n.version} with AgentX model ${d}.`));let{openCodeProcessPool:y}=await import("./opencode-process-ENS4MXHM.js"),{launchOpenCode:w}=await import("./opencode-launch-ECMEY2QZ.js");await w({agentId:d,env:p,cwd:process.cwd(),pool:y,spawnImpl:O$,log:k=>console.error(os.dim(k))});return}n&&!n.ok&&(console.error(os.yellow(n.reason)),console.error(os.dim("Using the built-in AgentX TUI. Install OpenCode v2: https://opencode.ai/v2/docs")));let{App:s}=await import("./App-EYUDDF6K.js"),{render:i}=await import("ink"),r=(await import("react")).default,a=Math.max(500,Number(e.poll)||3e3);await i(r.createElement(s,{conn:t,pollMs:a})).waitUntilExit()});import{Command as C$}from"commander";import Q from"chalk";import{randomUUID as rp}from"crypto";import{createInterface as I$}from"node:readline/promises";import N$ from"ora";import ki from"chalk";function sp(e){console.error(),console.error(ki.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(ki.dim(` ${e.why}`)),console.error(),console.error(` Use ${ki.cyan(e.instead)} instead.`),e.note&&console.error(ki.dim(` ${e.note}`)),console.error()}var ip={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 ap=new C$().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,o)=>{sp({what:"agentx chat",...ip});let t=od({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${rp().slice(0,12)}`,r=[];try{r=await Ns(t)}catch(g){console.error(Q.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(Q.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(Q.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(Q.red(` unknown agent: @${n}`)),console.error(Q.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(Q.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-F5LZLBI3.js"),u=(await import("react")).default;await g(u.createElement(d,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}_$(t.baseUrl,n,i,s);let a=I$({input:process.stdin,output:process.stdout}),c=!1,l=!1;for(a.on("close",()=>{if(c){l=!0;return}console.log(Q.dim(`
586
586
  bye`)),process.exit(0)});;){let g;try{g=(await a.question(Q.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(Q.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${rp().slice(0,12)}`,console.log(Q.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let p=await Ns(t);for(let y of p){let w=y.id===n?Q.green("\u25CF"):Q.dim("\u25CB");console.log(` ${w} @${y.id} ${Q.dim(y.tier)} ${y.model??""}`)}}catch(p){console.error(Q.red(` failed to list agents: ${p?.message||p}`))}continue}if(g.startsWith("/agent ")){let p=g.slice(7).replace(/^@/,"").trim();if(!p){console.log(Q.red(" usage: /agent <id>"));continue}try{if(!(await Ns(t)).find(w=>w.id===p)){console.log(Q.red(` unknown agent: @${p}`));continue}n=p,console.log(Q.dim(` now talking to @${n}`))}catch(y){console.error(Q.red(` failed to switch agent: ${y?.message||y}`))}continue}if(g.startsWith("/")){console.log(Q.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(Q.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let d=N$({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),f=R$(n);try{let p=await td(t,n,g,{channel:s,chatId:i,onText:w=>{d.stop(),f.text(w)},onThinking:()=>{},onTool:w=>{d.stop(),f.tool(w)}});d.stop();let y=Math.round((Date.now()-u)/100)/10;p.error?f.finishError(p.error):f.finish(y,p.usage)}catch(p){d.stop(),f.finishError(p?.message||String(p))}finally{c=!1}if(l){console.log(Q.dim(" bye"));return}}});function R$(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${Q.green(`@${e}`)}
587
587
  `),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
588
588
  `&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
@@ -675,7 +675,7 @@ Restart the daemon to activate.
675
675
  dist/
676
676
  *.log
677
677
  .env
678
- `}import{Command as xb}from"commander";import Pe from"chalk";import{writeFileSync as Sb,mkdirSync as Eb,existsSync as Ti,readFileSync as Ep,appendFileSync as Ap}from"fs";import{resolve as wn,dirname as Op}from"path";import{homedir as $a}from"os";var Cp=new xb().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:o}=await import("./program-CH5QSA7K.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=jb(t);break;case"bash":s=Rb(t);break;case"fish":s=_b(t);break;default:console.error(Pe.red(`unsupported shell: ${n}`)),console.error(Pe.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?wn(String(e.output)):Ab(n);Eb(Op(i),{recursive:!0}),Sb(i,s),console.log(Pe.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Tb(n,i,!!e.yes)});function Ab(e){let o=$a();switch(e){case"zsh":return wn(o,".zsh","completions","_agentx");case"bash":return wn(o,".bash_completion.d","agentx.bash");case"fish":return wn(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Tb(e,o,t){if(e==="zsh"){let n=wn($a(),".zshrc"),s=Op(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ti(n)?Ep(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Pe.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ti(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Ap(n,g.join(`
678
+ `}import{Command as xb}from"commander";import Pe from"chalk";import{writeFileSync as Sb,mkdirSync as Eb,existsSync as Ti,readFileSync as Ep,appendFileSync as Ap}from"fs";import{resolve as wn,dirname as Op}from"path";import{homedir as $a}from"os";var Cp=new xb().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:o}=await import("./program-MPLZJQA5.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=jb(t);break;case"bash":s=Rb(t);break;case"fish":s=_b(t);break;default:console.error(Pe.red(`unsupported shell: ${n}`)),console.error(Pe.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?wn(String(e.output)):Ab(n);Eb(Op(i),{recursive:!0}),Sb(i,s),console.log(Pe.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Tb(n,i,!!e.yes)});function Ab(e){let o=$a();switch(e){case"zsh":return wn(o,".zsh","completions","_agentx");case"bash":return wn(o,".bash_completion.d","agentx.bash");case"fish":return wn(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Tb(e,o,t){if(e==="zsh"){let n=wn($a(),".zshrc"),s=Op(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ti(n)?Ep(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Pe.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ti(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Ap(n,g.join(`
679
679
  `)+`
680
680
  `),console.log(Pe.green("\u2713 Patched ~/.zshrc")),console.log(Pe.dim("Reload your shell: exec zsh"));return}console.log(Pe.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Pe.cyan(` ${i}`)),l&&console.log(Pe.cyan(` ${r}`)),console.log(),console.log(Pe.dim("Then reload: exec zsh")),console.log(Pe.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=wn($a(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Ti(n)?Ep(n,"utf-8"):"").includes(o)){console.log(Pe.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Ti(n)){Ap(n,`
681
681
  # agentx completion
@@ -691,4 +691,4 @@ ${Db({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
691
691
  ${t.url}`)}catch(o){console.error(bn.red(` ${o.message}`)),process.exitCode=1}});cs.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",ka).action(async(e,o)=>{try{let t=await Sa(o.models);if(!va(o.model,t)){console.log(xa(o.model,t)),process.exitCode=1;return}let n=e==="-"?await Lb():await Mb(e,"utf8"),s=JSON.parse(n),{version:i}=await fs(),r=_p({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error(bn.red(` ${t.message}`)),process.exitCode=1}});async function Lb(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function lI(){let e=await fs(),o=new qb().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");o.hook("preAction",(t,n)=>{let s=Kl(n);Ql(s)&&Xl("cli",s)});for(let t of[jd,Td,nn,Mt,Ut,co,Ul,lt,Fs,Io,Ro,en,$m,Qo,Us,np,Yo,Qd,ag,Jn,wg,vg,Xd,Eg,Ag,Bg,zg,Vg,Co,sn,cp,Dn,Jo,Cp,cs])o.addCommand(t);for(let t of Pp)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Pp.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Ub(t,74," "),""].join(`
692
692
  `)}),o}var Pp=[ne,cn,tt,$o,Ln,Kt,Xe,Do,Zo,yt,mn,pn,zo,Ge,Jt,ri,ep,op,Oo,io,nd,gt,rs,wr,ot,oo,Wt,$r,bi,Ao,Po,wp,bp,ap];function Ub(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
693
693
  `)}export{lI as buildProgram};
694
- //# sourceMappingURL=program-CH5QSA7K.js.map
694
+ //# sourceMappingURL=program-MPLZJQA5.js.map