agentix-cli 0.207.1 → 0.207.2

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 (27) hide show
  1. package/dist/{agent-OVSBIXDF.js → agent-AG2FLW4B.js} +2 -2
  2. package/dist/{board-dashboard-P7F52WNX.js → board-dashboard-DWJPDDGM.js} +374 -357
  3. package/dist/board-dashboard-DWJPDDGM.js.map +1 -0
  4. package/dist/{chunk-T435JKGN.js → chunk-4M26YGFM.js} +23 -23
  5. package/dist/chunk-4M26YGFM.js.map +1 -0
  6. package/dist/{chunk-RP2YGJDW.js → chunk-D4QTZJ4G.js} +30 -30
  7. package/dist/chunk-D4QTZJ4G.js.map +1 -0
  8. package/dist/{chunk-HHFF7X4L.js → chunk-IANIJUL5.js} +2 -2
  9. package/dist/{chunk-BY7QINNM.js → chunk-IJXCGKAB.js} +3 -3
  10. package/dist/{chunk-FNB2IBG7.js → chunk-LNGTVK6V.js} +2 -2
  11. package/dist/{chunk-4GN2VGRB.js → chunk-S2LHJSB5.js} +2 -2
  12. package/dist/cli.js +1 -1
  13. package/dist/index.d.ts +4 -1
  14. package/dist/index.js +1 -1
  15. package/dist/{program-TTGZWU2T.js → program-RVODWQAM.js} +4 -4
  16. package/dist/{registry-ZZ27JGL5.js → registry-T2SZPIUE.js} +2 -2
  17. package/package.json +1 -1
  18. package/dist/board-dashboard-P7F52WNX.js.map +0 -1
  19. package/dist/chunk-RP2YGJDW.js.map +0 -1
  20. package/dist/chunk-T435JKGN.js.map +0 -1
  21. /package/dist/{agent-OVSBIXDF.js.map → agent-AG2FLW4B.js.map} +0 -0
  22. /package/dist/{chunk-HHFF7X4L.js.map → chunk-IANIJUL5.js.map} +0 -0
  23. /package/dist/{chunk-BY7QINNM.js.map → chunk-IJXCGKAB.js.map} +0 -0
  24. /package/dist/{chunk-FNB2IBG7.js.map → chunk-LNGTVK6V.js.map} +0 -0
  25. /package/dist/{chunk-4GN2VGRB.js.map → chunk-S2LHJSB5.js.map} +0 -0
  26. /package/dist/{program-TTGZWU2T.js.map → program-RVODWQAM.js.map} +0 -0
  27. /package/dist/{registry-ZZ27JGL5.js.map → registry-T2SZPIUE.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as zh,b as ta,g as Yh}from"./chunk-YQNZ26HG.js";import{b as Jh}from"./chunk-YNYYFDFA.js";import{$ as xh,A as lh,B as mh,C as ph,E as fh,G as hh,H as wh,I as El,J as yh,U as bh,V as $h,W as Rl,X as kh,_ as vh,aa as Sh,ba as Ah,ca as Th,da as Oh,ea as Ih,fa as Nh,g as Xf,ga as jh,h as Vf,ha as _h,ja as Cl,ka as Ph,l as Qf,la as Dh,m as Zf,na as Mh,o as Ts,p as Os,q as eh,qa as Lh,r as th,ra as qh,s as oh,sa as Fh,t as nh,u as sh,v as rh,x as lo,z as ch}from"./chunk-FNB2IBG7.js";import{n as Tl}from"./chunk-GVFLCK6T.js";import{a as Uh,b as Wh,d as Rr,e as Bh}from"./chunk-Y6WVNIIQ.js";import{a as Hh,b as Gh}from"./chunk-XVGSUY5K.js";import"./chunk-EFGAPAYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{d as dh,e as Al,h as uh,i as gh}from"./chunk-CTN4KYE6.js";import{a as Eh,c as Rh,d as Ch}from"./chunk-TADIDWYZ.js";import{b as Io}from"./chunk-7NQQIDDI.js";import{a as ih,c as ah}from"./chunk-M6TLZQTE.js";import"./chunk-2LJZHKTY.js";import{a as xl}from"./chunk-LNY6N73E.js";import"./chunk-2YDG5CSS.js";import{a as Vc,b as Im}from"./chunk-RKPAVWXF.js";import{a as Xm,b as ol}from"./chunk-GMP2IB4E.js";import{$ as bf,A as cl,Aa as Ar,B as Gp,Ba as Bf,C as ll,Ca as gt,D as zp,Da as Vi,E as Yp,Ea as Qi,F as Kp,Fa as Er,G as Xp,Ga as $l,H as Vp,Ha as Jf,I as Qp,Ia as Gf,J as dl,Ja as vl,K as Zp,Ka as Yf,L as Ji,La as Zi,M as ef,Ma as Cs,N as ul,Na as ea,O as tf,Oa as Sl,P as of,Pa as Kf,Q as nf,R as sf,S as rf,T as Hi,U as uf,V as pf,W as ff,X as hf,Y as wf,Z as yf,_ as ml,a as tp,aa as $f,b as op,ba as kf,ca as vf,da as xf,ea as Sf,fa as Af,ga as Ef,h as _i,ha as Rf,i as Ss,ia as Cf,j as ip,ja as Pf,k as kr,ka as Yi,l as Pi,la as Oo,m as cp,ma as zo,n as dp,na as As,o as Ap,oa as Ki,p as Ep,pa as Xi,q as Ui,qa as bl,r as al,ra as Df,s as jp,sa as Mf,t as Fp,ta as Lf,u as Up,ua as qf,v as Wp,va as Ff,w as Bp,wa as Uf,x as Bi,xa as Es,y as Jp,ya as Rs,z as Hp,za as Wf}from"./chunk-T435JKGN.js";import{Bb as jf,Cb as _f,Db as wl,Kb as yl,P as Pp,R as vr,S as Dp,V as Mp,W as Wi,Zb as Hf,_b as kl,ab as xr,db as pl,eb as Gi,fb as Tf,mb as Go,mc as co,nb as Of,ob as fl,oc as zf,pa as af,qa as cf,qb as hl,ra as lf,sa as gl,sb as If,tb as Nf,ub as Sr,v as lp,va as df,yb as zi}from"./chunk-4GN2VGRB.js";import"./chunk-GTJIKXDB.js";import{a as np,c as sl,e as sp,f as rp}from"./chunk-WXYO7JFL.js";import"./chunk-ZVP6GB4G.js";import{A as wp,B as yp,C as bp,D as $p,E as kp,F as vp,K as Li,L as xp,M as Sp,Q as Lp,R as qp,a as Kc,b as Am,e as Em,f as Rm,o as up,s as Di,t as Mi,u as gp,v as mp,w as pp,y as fp,z as hp}from"./chunk-5Q62AXJG.js";import"./chunk-IMLAPB7G.js";import{a as gf,b as mf}from"./chunk-EKJG63EJ.js";import"./chunk-LWVALEWQ.js";import"./chunk-JSCVOB4G.js";import"./chunk-JLBRNYKY.js";import{a as _p}from"./chunk-BYEL7KKR.js";import{a as Dt}from"./chunk-2GEO3AWE.js";import"./chunk-MRIVENBY.js";import"./chunk-GJOKXP5D.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{b as Pt}from"./chunk-UKUH662W.js";import{c as Rp}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import{c as il}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as Cp,e as qi,g as Fi}from"./chunk-LQE73AZR.js";import{a as Tp,b as Op,c as Ip,d as Np}from"./chunk-2D3RYIDU.js";import"./chunk-Q3A5P373.js";import{m as Vm,n as Qm,o as nl,p as ji,q as Zm,r as ep}from"./chunk-TWWHZNHZ.js";import{a as Xc,d as Cm,e as Ni}from"./chunk-QPABR72X.js";import"./chunk-A5GYG56I.js";import{a as rl,p as ap}from"./chunk-E2JKO262.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-6TTGRTDO.js";import{a as qm,b as Fm,c as Um,d as Wm,e as Zc,f as Bm,g as el,h as tl,l as Jm,m as Hm}from"./chunk-RX5O5637.js";import{a as $r,e as Nm,f as jm,g as Qc,i as _m,j as Pm,l as Dm,m as Mm,n as Lm}from"./chunk-DPN3EYW3.js";import{f as Gm,i as zm,l as Ym,m as Km}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{b as xs,e as Om}from"./chunk-IFUAP7UD.js";import{c as Tm}from"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{$ as vm,Ca as Sm,D as Jc,E as rm,S as Ho,Y as $m,aa as xm,g as Kg,r as Xg,s as Vg,t as Qg}from"./chunk-BY7QINNM.js";import{I as ys,J as Oi,K as Ii,L as bs,M as am,N as Bo,P as Jo,b as ws,fa as ym,r as Co,s as Hc,t as im,u as Gc,ua as bm,w as To,wa as km,x as Ti}from"./chunk-RP2YGJDW.js";import{b as $n}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-HHFF7X4L.js";import"./chunk-SFQUP3BP.js";import{a as $s}from"./chunk-GV7S5BAX.js";import{c as lm}from"./chunk-SZDACK6O.js";import{f as dm,g as um,h as zc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as mm,f as kn,k as ks}from"./chunk-VJVXEVZ7.js";import{a as nm,l as gm,o as wm}from"./chunk-C5VFABFI.js";import{a as yt,b as me,c as We,d as vs,e as pm}from"./chunk-TTAKAN5L.js";import{a as fm,b as Yc,h as hm}from"./chunk-3UOTLMXD.js";import"./chunk-VWTBHLMX.js";import{i as em,j as tm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as Bc,b as om}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as sm}from"./chunk-X5C5W3E4.js";import{e as cm}from"./chunk-GSX4NK2N.js";import"./chunk-HPRLRD4P.js";import{a as Wc}from"./chunk-KN5LZ3JS.js";import"./chunk-7GCB4HDJ.js";import{c as Zg}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-PAMMBHB2.js";import"./chunk-JTFCU5LH.js";import{g as Wo,i as Ci}from"./chunk-WD4HZAYI.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-XPKDQDBH.js";import{a as jc,b as ug,c as u0,d as wi,e as gg,f as Pg,g as k0,h as Dg,i as v0,m as hs,n as Lg,q as qg,u as Fg,y as io,z as br}from"./chunk-NXOBCFUJ.js";import{a as Eo,b as fs,e as Ng,f as yr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Si,b as Mg}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as Uo,j as Ug}from"./chunk-QUFIUXMQ.js";import{n as Uc,p as zg,v as Yg}from"./chunk-3AHYZLGE.js";import{d as Wg,e as bn,f as Bg,g as Ai,j as Jg,k as Hg,m as Gg,n as Fc,r as Ei,s as Ro,t as Ri}from"./chunk-XL7UWG36.js";import{a as ao}from"./chunk-MNG2AMKZ.js";import"./chunk-LY4G7PCW.js";import"./chunk-2HBEZV7L.js";import"./chunk-A7JSRDJL.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as ro,b as d0}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as kg,B as bg,C as $g,D as p0,Fb as vi,Gb as wr,Hb as O,Kb as xi,M as Pc,Ma as Rg,N as f0,Qa as w0,Rb as te,Za as Cg,_a as yn,aa as h0,ab as Mc,f as yi,fa as $i,g as mg,ga as ki,hb as Lc,ib as qc,j as _t,ja as vg,k as _c,kb as Tg,la as xg,lb as y0,m as pg,ma as ps,n as bi,na as Dc,p as g0,rb as Ig,ua as Sg,wa as Ag,x as hg,xa as Eg,y as wg,z as yg}from"./chunk-ZAPHYYGT.js";import"./chunk-KEUW6YLL.js";import{j as ut,r as wn}from"./chunk-UEEB3UTU.js";import{a as fg,e as m0}from"./chunk-VQRY4IDI.js";import{a as Og,c as b0}from"./chunk-YSCT6DPR.js";import{g as jg,k as _g,l as $0}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as x0}from"commander";var Kh=new x0().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 op({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 S0}from"commander";import{execFileSync as uo}from"node:child_process";import{cpSync as Xh,existsSync as Nl,mkdirSync as Ol,mkdtempSync as A0,readdirSync as E0,rmSync as Vh,writeFileSync as Qh}from"node:fs";import{dirname as Zh,join as mt}from"node:path";import{homedir as oa,release as R0,tmpdir as C0}from"node:os";import{setTimeout as T0}from"node:timers/promises";function na(){let e=gp(process.platform,process.arch,R0());if(e)throw new Error(e)}function sa(){let e=mt(oa(),"Library/LaunchAgents"),t=[];try{t=E0(e).filter(fp)}catch{}let o=t.flatMap(n=>{let s=mt(e,n);try{return[{file:s,plist:uo("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return hp(e,o)}function Cr(e){return`gui/${process.getuid()}/${e.label}`}async function Il(e){try{uo("launchctl",["bootout",Cr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{uo("launchctl",["print",Cr(e)],{stdio:"pipe"})}catch{return}await T0(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function ew(e){if(!Nl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{uo("launchctl",["print",Cr(e)],{stdio:"pipe"})}catch{t=!1}t||uo("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),uo("launchctl",["kickstart",Cr(e)],{stdio:"pipe"})}function O0(){let e=vp();if(e&&Nl(mt(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 Is=new S0("desktop").description("install and control the macOS desktop assistant");Is.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=>{na();let t=O(),o=mp(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=O0(),i=mt(oa(),"Applications"),{keep:a,remove:c}=sa();if(console.log(`Desktop assistant \u2192 ${mt(i,Di)}
1
+ import{a as zh,b as ta,g as Yh}from"./chunk-YQNZ26HG.js";import{b as Jh}from"./chunk-YNYYFDFA.js";import{$ as xh,A as lh,B as mh,C as ph,E as fh,G as hh,H as wh,I as El,J as yh,U as bh,V as $h,W as Rl,X as kh,_ as vh,aa as Sh,ba as Ah,ca as Th,da as Oh,ea as Ih,fa as Nh,g as Xf,ga as jh,h as Vf,ha as _h,ja as Cl,ka as Ph,l as Qf,la as Dh,m as Zf,na as Mh,o as Ts,p as Os,q as eh,qa as Lh,r as th,ra as qh,s as oh,sa as Fh,t as nh,u as sh,v as rh,x as lo,z as ch}from"./chunk-LNGTVK6V.js";import{n as Tl}from"./chunk-GVFLCK6T.js";import{a as Uh,b as Wh,d as Rr,e as Bh}from"./chunk-Y6WVNIIQ.js";import{a as Hh,b as Gh}from"./chunk-XVGSUY5K.js";import"./chunk-EFGAPAYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{d as dh,e as Al,h as uh,i as gh}from"./chunk-CTN4KYE6.js";import{a as Eh,c as Rh,d as Ch}from"./chunk-TADIDWYZ.js";import{b as Io}from"./chunk-7NQQIDDI.js";import{a as ih,c as ah}from"./chunk-M6TLZQTE.js";import"./chunk-2LJZHKTY.js";import{a as xl}from"./chunk-LNY6N73E.js";import"./chunk-2YDG5CSS.js";import{a as Vc,b as Im}from"./chunk-RKPAVWXF.js";import{a as Xm,b as ol}from"./chunk-GMP2IB4E.js";import{$ as bf,A as cl,Aa as Ar,B as Gp,Ba as Bf,C as ll,Ca as gt,D as zp,Da as Vi,E as Yp,Ea as Qi,F as Kp,Fa as Er,G as Xp,Ga as $l,H as Vp,Ha as Jf,I as Qp,Ia as Gf,J as dl,Ja as vl,K as Zp,Ka as Yf,L as Ji,La as Zi,M as ef,Ma as Cs,N as ul,Na as ea,O as tf,Oa as Sl,P as of,Pa as Kf,Q as nf,R as sf,S as rf,T as Hi,U as uf,V as pf,W as ff,X as hf,Y as wf,Z as yf,_ as ml,a as tp,aa as $f,b as op,ba as kf,ca as vf,da as xf,ea as Sf,fa as Af,ga as Ef,h as _i,ha as Rf,i as Ss,ia as Cf,j as ip,ja as Pf,k as kr,ka as Yi,l as Pi,la as Oo,m as cp,ma as zo,n as dp,na as As,o as Ap,oa as Ki,p as Ep,pa as Xi,q as Ui,qa as bl,r as al,ra as Df,s as jp,sa as Mf,t as Fp,ta as Lf,u as Up,ua as qf,v as Wp,va as Ff,w as Bp,wa as Uf,x as Bi,xa as Es,y as Jp,ya as Rs,z as Hp,za as Wf}from"./chunk-4M26YGFM.js";import{Bb as jf,Cb as _f,Db as wl,Kb as yl,P as Pp,R as vr,S as Dp,V as Mp,W as Wi,Zb as Hf,_b as kl,ab as xr,db as pl,eb as Gi,fb as Tf,mb as Go,mc as co,nb as Of,ob as fl,oc as zf,pa as af,qa as cf,qb as hl,ra as lf,sa as gl,sb as If,tb as Nf,ub as Sr,v as lp,va as df,yb as zi}from"./chunk-S2LHJSB5.js";import"./chunk-GTJIKXDB.js";import{a as np,c as sl,e as sp,f as rp}from"./chunk-WXYO7JFL.js";import"./chunk-ZVP6GB4G.js";import{A as wp,B as yp,C as bp,D as $p,E as kp,F as vp,K as Li,L as xp,M as Sp,Q as Lp,R as qp,a as Kc,b as Am,e as Em,f as Rm,o as up,s as Di,t as Mi,u as gp,v as mp,w as pp,y as fp,z as hp}from"./chunk-5Q62AXJG.js";import"./chunk-IMLAPB7G.js";import{a as gf,b as mf}from"./chunk-EKJG63EJ.js";import"./chunk-LWVALEWQ.js";import"./chunk-JSCVOB4G.js";import"./chunk-JLBRNYKY.js";import{a as _p}from"./chunk-BYEL7KKR.js";import{a as Dt}from"./chunk-2GEO3AWE.js";import"./chunk-MRIVENBY.js";import"./chunk-GJOKXP5D.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{b as Pt}from"./chunk-UKUH662W.js";import{c as Rp}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import{c as il}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as Cp,e as qi,g as Fi}from"./chunk-LQE73AZR.js";import{a as Tp,b as Op,c as Ip,d as Np}from"./chunk-2D3RYIDU.js";import"./chunk-Q3A5P373.js";import{m as Vm,n as Qm,o as nl,p as ji,q as Zm,r as ep}from"./chunk-TWWHZNHZ.js";import{a as Xc,d as Cm,e as Ni}from"./chunk-QPABR72X.js";import"./chunk-A5GYG56I.js";import{a as rl,p as ap}from"./chunk-E2JKO262.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-6TTGRTDO.js";import{a as qm,b as Fm,c as Um,d as Wm,e as Zc,f as Bm,g as el,h as tl,l as Jm,m as Hm}from"./chunk-RX5O5637.js";import{a as $r,e as Nm,f as jm,g as Qc,i as _m,j as Pm,l as Dm,m as Mm,n as Lm}from"./chunk-DPN3EYW3.js";import{f as Gm,i as zm,l as Ym,m as Km}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{b as xs,e as Om}from"./chunk-IFUAP7UD.js";import{c as Tm}from"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{$ as vm,Ca as Sm,D as Jc,E as rm,S as Ho,Y as $m,aa as xm,g as Kg,r as Xg,s as Vg,t as Qg}from"./chunk-IJXCGKAB.js";import{I as ys,J as Oi,K as Ii,L as bs,M as am,N as Bo,P as Jo,b as ws,fa as ym,r as Co,s as Hc,t as im,u as Gc,ua as bm,w as To,wa as km,x as Ti}from"./chunk-D4QTZJ4G.js";import{b as $n}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-IANIJUL5.js";import"./chunk-SFQUP3BP.js";import{a as $s}from"./chunk-GV7S5BAX.js";import{c as lm}from"./chunk-SZDACK6O.js";import{f as dm,g as um,h as zc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as mm,f as kn,k as ks}from"./chunk-VJVXEVZ7.js";import{a as nm,l as gm,o as wm}from"./chunk-C5VFABFI.js";import{a as yt,b as me,c as We,d as vs,e as pm}from"./chunk-TTAKAN5L.js";import{a as fm,b as Yc,h as hm}from"./chunk-3UOTLMXD.js";import"./chunk-VWTBHLMX.js";import{i as em,j as tm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as Bc,b as om}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as sm}from"./chunk-X5C5W3E4.js";import{e as cm}from"./chunk-GSX4NK2N.js";import"./chunk-HPRLRD4P.js";import{a as Wc}from"./chunk-KN5LZ3JS.js";import"./chunk-7GCB4HDJ.js";import{c as Zg}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-PAMMBHB2.js";import"./chunk-JTFCU5LH.js";import{g as Wo,i as Ci}from"./chunk-WD4HZAYI.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-XPKDQDBH.js";import{a as jc,b as ug,c as u0,d as wi,e as gg,f as Pg,g as k0,h as Dg,i as v0,m as hs,n as Lg,q as qg,u as Fg,y as io,z as br}from"./chunk-NXOBCFUJ.js";import{a as Eo,b as fs,e as Ng,f as yr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Si,b as Mg}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as Uo,j as Ug}from"./chunk-QUFIUXMQ.js";import{n as Uc,p as zg,v as Yg}from"./chunk-3AHYZLGE.js";import{d as Wg,e as bn,f as Bg,g as Ai,j as Jg,k as Hg,m as Gg,n as Fc,r as Ei,s as Ro,t as Ri}from"./chunk-XL7UWG36.js";import{a as ao}from"./chunk-MNG2AMKZ.js";import"./chunk-LY4G7PCW.js";import"./chunk-2HBEZV7L.js";import"./chunk-A7JSRDJL.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as ro,b as d0}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as kg,B as bg,C as $g,D as p0,Fb as vi,Gb as wr,Hb as O,Kb as xi,M as Pc,Ma as Rg,N as f0,Qa as w0,Rb as te,Za as Cg,_a as yn,aa as h0,ab as Mc,f as yi,fa as $i,g as mg,ga as ki,hb as Lc,ib as qc,j as _t,ja as vg,k as _c,kb as Tg,la as xg,lb as y0,m as pg,ma as ps,n as bi,na as Dc,p as g0,rb as Ig,ua as Sg,wa as Ag,x as hg,xa as Eg,y as wg,z as yg}from"./chunk-ZAPHYYGT.js";import"./chunk-KEUW6YLL.js";import{j as ut,r as wn}from"./chunk-UEEB3UTU.js";import{a as fg,e as m0}from"./chunk-VQRY4IDI.js";import{a as Og,c as b0}from"./chunk-YSCT6DPR.js";import{g as jg,k as _g,l as $0}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as x0}from"commander";var Kh=new x0().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 op({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 S0}from"commander";import{execFileSync as uo}from"node:child_process";import{cpSync as Xh,existsSync as Nl,mkdirSync as Ol,mkdtempSync as A0,readdirSync as E0,rmSync as Vh,writeFileSync as Qh}from"node:fs";import{dirname as Zh,join as mt}from"node:path";import{homedir as oa,release as R0,tmpdir as C0}from"node:os";import{setTimeout as T0}from"node:timers/promises";function na(){let e=gp(process.platform,process.arch,R0());if(e)throw new Error(e)}function sa(){let e=mt(oa(),"Library/LaunchAgents"),t=[];try{t=E0(e).filter(fp)}catch{}let o=t.flatMap(n=>{let s=mt(e,n);try{return[{file:s,plist:uo("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return hp(e,o)}function Cr(e){return`gui/${process.getuid()}/${e.label}`}async function Il(e){try{uo("launchctl",["bootout",Cr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{uo("launchctl",["print",Cr(e)],{stdio:"pipe"})}catch{return}await T0(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function ew(e){if(!Nl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{uo("launchctl",["print",Cr(e)],{stdio:"pipe"})}catch{t=!1}t||uo("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),uo("launchctl",["kickstart",Cr(e)],{stdio:"pipe"})}function O0(){let e=vp();if(e&&Nl(mt(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 Is=new S0("desktop").description("install and control the macOS desktop assistant");Is.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=>{na();let t=O(),o=mp(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=O0(),i=mt(oa(),"Applications"),{keep:a,remove:c}=sa();if(console.log(`Desktop assistant \u2192 ${mt(i,Di)}
2
2
  Computer-use helper \u2192 ${mt(i,Mi)}
3
3
  Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -572,7 +572,7 @@ ${oe.text}`));C.delivery.reached.of++,ie&&C.delivery.reached.n++;let j=D[0]??Q[0
572
572
  Plan ${q.dim(`[${r.state}] by ${r.createdBy}, ${Qn(r.createdAt)}`)}`),_k(s.steps(e)),console.log(`
573
573
  Log`);for(let i of s.events(e))console.log(q.dim(` ${Qn(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});Po.command("step <id> <step>").description("move a step of a request's plan on: --retry, --skip or --done").option("--retry","hand the step to its agent again, with a fresh count of nudges (approves a message whose card expired)").option("--skip","leave the step out; the plan goes on with the next one").option("--done","mark the step done yourself").option("--note <text>","why, or the evidence for --done").action((e,t,o)=>{let n=["retry","skip","done"].filter(c=>o[c]);if(n.length!==1){console.error(q.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=or();if(!s)return;let r=ec();if(!r){process.exitCode=1;return}let i=Number(t),a=ef(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(q.red(` ${a}`)),process.exitCode=1;return}console.log(q.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+q.dim(" (the daemon goes on within a minute)")),_k(r.steps(e))});function Pk(e,t,o,n){let s=Po.command(`${e} <id>`).description(t).option(o,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped");e==="done"&&s.option("--reason <text>",'close it by hand without a link, saying why ("checked by hand"); also closes a loop its check cannot verify'),s.action((r,i)=>{let a=or();if(!a)return;let c=e==="done"?i.evidence??(i.reason?`closed by owner: ${i.reason}`:void 0):i.reason??"dropped by the owner";if(!c){console.error(q.red(` ${n}`)),process.exitCode=1;return}let l=a.get(r);if(!l||l.state==="candidate"){console.error(q.red(` no request "${r}"`)),process.exitCode=1;return}if(!a.close(r,e==="done"?"done":"dropped",c,Date.now())){console.error(q.red(` ${r} is already closed (${uu[l.state]??l.state})`)),process.exitCode=1;return}console.log(q.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}Pk("done","close a request as finished, with a link to the evidence or the reason","--evidence <link>","a finished request needs --evidence <link> or --reason <text>");Pk("drop","drop a request you no longer want","--reason <text>","");Po.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").option("--headlines <on|off>","write a headline for a request its agent did not describe (one small model call each)").option("--catch <on|off>","read the reply of each of your turns for a promise or a question to you (one small model call each)").option("--catch-cap <n>","model calls a day the promise catch may make").option("--settle <on|off>","close a quiet request whose handed work all came back done, instead of bringing it back to you").option("--home-closes <on|off>","close a request once its issue or merge request home is merged or closed as completed").option("--plans <on|off>","follow requests of two or more steps as tracked plans").option("--stall-minutes <n>","minutes without progress before a plan step's agent is nudged").option("--max-nudges <n>","nudges per step before it counts as blocked and you are told").option("--approve-kinds <kind,...>",'step kinds you approve once when the plan is made; "none" to clear').option("--plans-off-for <agent,...>",'agents that may not open a plan; "none" to clear').option("--plan-for <work,...>",'kinds of work an agent must plan before it starts (default code); "none" to clear').option("--plan-over <minutes>","work estimated over this many minutes needs a plan (default 30); 0 turns it off").option("--checks <kind,...>",`checks agents may use to close a loop (${$i.join(", ")}); "none" to turn them all off`).option("--check-every <minutes>","how often each open loop's check runs").option("--auto-resend <on|off>","send a request stopped by a usage limit or a restart back to its agent once, on its own").option("--resend-after <minutes>","minutes after it stopped before it is resent (a limit also waits for its reset)").option("--resend-hold-hours <n>","hours your notice waits for the resend before you are told anyway").option("--flow-zone <zone>","the time zone whose day the flow rate counts by, for example Africa/Tunis").action(async e=>{let t={};try{let u=(h,y)=>{if(y===void 0)return;let $=Number(y);if(!($>0))throw new Error(`${h} must be a positive number`);return $},d=(h,y)=>h===void 0?void 0:h===y?[]:h.split(",").map($=>$.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");t.enabled=e.enabled==="on"}if(t.from=d(e.from,"none"),t.channels=d(e.channels,"all"),t.staleAfterHours=u("--stale-hours",e.staleHours),t.retentionDays=u("--retention-days",e.retentionDays),e.headlines!==void 0){if(e.headlines!=="on"&&e.headlines!=="off")throw new Error("--headlines takes on or off");t.headlines={enabled:e.headlines==="on"}}if(e.catch!==void 0||e.catchCap!==void 0){if(e.catch!==void 0&&e.catch!=="on"&&e.catch!=="off")throw new Error("--catch takes on or off");let h=u("--catch-cap",e.catchCap);if(h!==void 0&&!Number.isInteger(h))throw new Error("--catch-cap must be a whole number");t.catchPromises={...e.catch!==void 0?{enabled:e.catch==="on"}:{},...h!==void 0?{dailyCap:h}:{}}}if(e.settle!==void 0){if(e.settle!=="on"&&e.settle!=="off")throw new Error("--settle takes on or off");t.settleHandedBack=e.settle==="on"}if(e.homeCloses!==void 0){if(e.homeCloses!=="on"&&e.homeCloses!=="off")throw new Error("--home-closes takes on or off");t.homeCloses=e.homeCloses==="on"}let f={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");f.enabled=e.plans==="on"}if(f.stallMinutes=u("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let h=Number(e.maxNudges);if(!Number.isInteger(h)||h<0)throw new Error("--max-nudges must be a whole number, 0 or more");f.maxNudges=h}if(f.approveKinds=d(e.approveKinds,"none"),f.disabledAgents=d(e.plansOffFor,"none"),f.requireForWork=d(e.planFor,"none"),e.planOver!==void 0){let h=Number(e.planOver);if(!(h>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");f.requireOverMinutes=h}Object.values(f).some(h=>h!==void 0)&&(t.plans=f);let p={},g=d(e.checks,"none");if(g){let h=g.filter(y=>!$i.includes(y));if(h.length)throw new Error(`unknown check ${h.join(", ")}: use ${$i.join(", ")}`);p.enabled=g}p.checkEveryMinutes=u("--check-every",e.checkEvery),Object.values(p).some(h=>h!==void 0)&&(t.checkers=p);let w={};if(e.autoResend!==void 0){if(e.autoResend!=="on"&&e.autoResend!=="off")throw new Error("--auto-resend takes on or off");w.enabled=e.autoResend==="on"}if(e.resendAfter!==void 0){let h=Number(e.resendAfter);if(!(h>=0))throw new Error("--resend-after must be a number of minutes, 0 or more");w.afterMinutes=h}w.holdMaxHours=u("--resend-hold-hours",e.resendHoldHours),Object.values(w).some(h=>h!==void 0)&&(t.autoResend=w),e.flowZone!==void 0&&(t.flow={timeZone:e.flowZone})}catch(u){console.error(q.red(` ${u.message}`)),process.exitCode=1;return}if(Object.values(t).some(u=>u!==void 0)){let u=await Dp(t);if(!u.success){console.error(q.red(` ${u.error}`)),process.exitCode=1;return}console.log(q.green(" \u2713 saved")+(u.reloaded?q.dim(" (daemon reloaded)"):""))}let o=vr();console.log(` Requests ${o.enabled?"on":"off"}`),console.log(` Channels ${o.channels.length?o.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${o.from.length?o.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${o.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${o.retentionDays} day(s)`),console.log(` Headlines ${o.headlines?.enabled===!1?"off: titled with the start of your words":"on: written when the agent gave none"}`);let n=o.catchPromises;console.log(` Catch promises ${n?.enabled?`on: each of your turns' reply is read, up to ${n.dailyCap} call(s) a day`:"off"}`),console.log(` Handed work came back ${o.settleHandedBack===!1?"comes back to you when quiet":"closed when quiet, with its link or marked unproven"}`),console.log(` Home closed ${o.homeCloses===!1?"left open":"closes the request: merged, or closed as completed"}`);let s=o.plans??Ji;console.log(` Plans ${s.enabled?"on":"off"}`),console.log(` Nudge a quiet step after ${s.stallMinutes} minute(s), up to ${s.maxNudges} time(s)`),console.log(` You approve up front ${s.approveKinds.length?s.approveKinds.join(", "):"nothing"}`),console.log(` Plans off for ${s.disabledAgents.length?s.disabledAgents.join(", "):"no agent"}`);let r=s.requireOverMinutes??Ji.requireOverMinutes,i=s.requireForWork??Ji.requireForWork;console.log(` Plan before starting ${[i.length?`${i.join(", ")} work`:"",r>0?`work over ${r} minute(s)`:""].filter(Boolean).join("; ")||"never required"}`);let a=o.autoResend??Zp;console.log(` Resend once ${a.enabled?`on: after a usage limit resets or a restart, ${a.afterMinutes} minute(s) on; you are told after ${a.holdMaxHours} hour(s) or a second stop`:"off"}`),console.log(` Flow rate counts by ${(o.flow??nl).timeZone} days`);let c=o.checkers??ki;console.log(` Loop checks ${c.enabled.length?c.enabled.join(", "):"off"}, every ${c.checkEveryMinutes} minute(s)`);let l=Object.keys(c.repos);console.log(` Repos for git-ancestor ${l.length?l.join(", "):"none (requests.checkers.repos in agentx.json)"}`)});import{Command as XO}from"commander";import nr from"chalk";te();var Dk=new XO("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Rl.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(nr.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await me(r=>{n=kh(r,e,t==="on")});s.success||(console.error(nr.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(nr.green(`\u2713 ${n}`)),s.reloaded&&console.log(nr.dim(" daemon hot-reloaded"))}let o=O().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Rl)console.log(` ${n.padEnd(8)} ${o.includes(n)?nr.green("on"):nr.dim("off")}`)});import{Command as A1}from"commander";import sr from"chalk";import xe from"chalk";import Zr from"prompts";import{readFileSync as VO,writeFileSync as QO,existsSync as ZO}from"fs";import{resolve as Mk}from"path";var e1=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function t1(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function mu(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Lk(e=".env"){let t=Mk(e);if(!ZO(t))return[];let o=VO(t,"utf-8"),n=[];for(let s of o.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let r=s.match(e1);r?n.push({kind:"kv",key:r[1],value:t1(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function o1(e){return e.map(t=>t.kind==="kv"?`${t.key}=${mu(t.value)}`:t.raw).join(`
574
574
  `)+`
575
- `}function Zn(e,t,o=".env"){let n=Mk(o),s=Lk(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${mu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${mu(t)}`})),QO(n,o1(s))}function pu(e,t=".env"){return Lk(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var qk="https://t.me/BotFather";async function n1(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function s1(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Fk(e={}){console.log(),console.log(xe.bold(" Connect Telegram")),console.log(),console.log(xe.dim(` 1. Open ${qk}`)),console.log(xe.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(xe.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Zr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Io(qk);let{token:o}=await Zr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:v=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(v.trim())||"That doesn't look like a Telegram token"});o||(console.log(xe.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await n1(o.trim());n||(console.log(xe.red("\u2717 invalid or revoked")),process.exit(1)),console.log(xe.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(xe.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(xe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await Zr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),u||(console.log(xe.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||u;d[f]&&d[f].agentBinding!==u&&(f=(await Zr({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(xe.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Zn(p,o.trim()),process.env[p]=o.trim();let g=await me(v=>{We(v,"channels.telegram.enabled",!0),We(v,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:u});let S=vs(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),We(v,`agents.${u}.mentions`,S))},{configPath:e.configPath});if(g.success||(console.log(xe.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(xe.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(xe.dim(` Token stored in .env as ${p}`)),console.log(xe.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(xe.dim(" Daemon hot-reloaded.")):console.log(xe.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Zr({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(xe.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(xe.dim(" Waiting up to 90s..."));let h=await s1(o.trim(),9e4);if(!h){console.log(xe.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(xe.dim(" agentx config set notifications.destination.channel telegram")),console.log(xe.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(xe.dim(` agentx config set notifications.destination.accountId ${f}`));return}let y={channel:"telegram",chatId:String(h.chatId),accountId:f},$=[],x=await me(v=>{We(v,"notifications.destination",y),$=ga(v,y)},{configPath:e.configPath});if(!x.success){console.log(xe.red(` \u2717 failed to save destination: ${x.error}`));return}console.log(xe.green(" \u2713 Default --notify target set")),console.log(xe.dim(` Chat: ${h.chatTitle||h.chatId} (from ${h.from})`)),console.log(xe.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(xe.dim(` Schedules that now report here: ${$.join(", ")}`)),x.reloaded&&console.log(xe.dim(" Daemon hot-reloaded."))}import Me from"chalk";import fu from"prompts";import{existsSync as wu,mkdirSync as r1,readdirSync as i1,readFileSync as Uk}from"fs";import{resolve as hu}from"path";var a1=".agentx/whatsapp-sessions";function c1(){let e=hu(process.cwd(),".agentx/daemon.pid");if(!wu(e))return!1;try{let t=parseInt(Uk(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function l1(e){if(!wu(e))return!1;try{return i1(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function d1(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Me.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Me.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;r1(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(u=>{let f=setTimeout(()=>{t(Me.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}u(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(Me.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Me.green(" \u2713 Paired"));try{l.end(void 0)}catch{}u(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Me.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Wk(e={}){if(console.log(),console.log(Me.bold(" Connect WhatsApp")),console.log(),c1()){console.log(Me.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Me.dim(" agentx daemon stop")),console.log();let{cont:l}=await fu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Me.red(" Aborted")),process.exit(1))}let t=e.configPath||hu(process.cwd(),"agentx.json");wu(t)||(console.log(Me.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Uk(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||a1,s=hu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Me.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await fu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(Me.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(l1(s)&&a){let{keep:l}=await fu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(Me.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await d1(s,u=>console.log(u))||(console.log(Me.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await me(l=>{We(l,"channels.whatsapp.enabled",!0),We(l,"channels.whatsapp.sessionDir",n),We(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Me.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Me.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Me.dim(` Session: ${n}`)),console.log(Me.dim(" Start the daemon to begin receiving:")),console.log(Me.dim(" agentx daemon start")),console.log(Me.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Me.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Me.dim(" Add routes later with:")),console.log(Me.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Rt from"chalk";import u1 from"prompts";import{existsSync as g1,readFileSync as m1}from"fs";import{resolve as p1}from"path";async function f1(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function h1(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Do(e){console.log(Rt.red(` ${e}`)),process.exit(1)}async function es(e){return(await u1(e,{onCancel:()=>Do("Aborted")}))[e.name]}async function Bk(e={}){console.log(),console.log(Rt.bold(" Connect email")),console.log();let t=e.configPath||p1(process.cwd(),"agentx.json");g1(t)||Do(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(m1(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Do("No agents configured. Run: agentx agent add");let s=e.agent??await es({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(y=>({title:y,value:y}))});o.agents?.[s]||Do(`No agent "${s}" in ${t}`);let r=(e.address??await es({type:"text",name:"address",message:"Email address customers write to:",validate:y=>/^\S+@\S+\.\S+$/.test(y.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=xh(r),c=e.imapHost??a?.imapHost??await es({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await es({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await es({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await es({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Do("Ports must be numbers.");let f=e.passwordEnv||Ah(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&Do(`${e.passwordEnv} is not set in the environment.`),p||(a?.imapHost==="imap.gmail.com"&&(console.log(Rt.dim(` Gmail needs an app password, not your account password: ${vh}`)),console.log(Rt.dim(" (2-step verification must be on for that page to show.)"))),p=(await es({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||Do("Aborted");let g={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:f,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let y=await f1(g,p);y&&(console.log(Rt.red("\u2717")),Do(y)),console.log(Rt.green("\u2713"))}e.passwordEnv||(Zn(f,p),process.env[f]=p);let w=await me(y=>{We(y,"channels.email.enabled",!0),We(y,`channels.email.accounts.${i}`,Sh(g))},{configPath:e.configPath});w.success||Do(`Config save failed: ${w.error}`),console.log(),console.log(Rt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Rt.dim(` Password stored in .env as ${f}`)),console.log(Rt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let h=h1(o.agents[s]?.tier,g.allowFrom);h&&console.log(Rt.yellow(` ${h}`)),console.log(g.send==="auto"?Rt.yellow(" Replies are sent as soon as the agent writes them."):Rt.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Rt.dim(" Only mail that arrives from now on is answered.")),console.log(Rt.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as w1}from"crypto";import Ke from"chalk";import Jk from"prompts";var tc="agentx-mesh:",oc="//join/";function y1(e){return Buffer.from(e,"utf-8").toString("base64url")}function b1(e){return Buffer.from(e,"base64url").toString("utf-8")}function $1(e){return`${tc}${oc}${y1(JSON.stringify(e))}`}function k1(e){if(!e.startsWith(`${tc}${oc}`))throw new Error(`Not a mesh invite link \u2014 expected ${tc}${oc}\u2026`);let t=e.slice(tc.length+oc.length),o=JSON.parse(b1(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function v1(){return w1(32).toString("hex")}function x1(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function S1(e){return e?.node?.name||e?.node?.id||"node"}async function Hk(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ke.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=pu("MESH_TOKEN");i||(i=v1(),Zn("MESH_TOKEN",i),console.log(Ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||x1(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Jk({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(Ke.red(" Aborted")),process.exit(1)),a=d}let l=await me(d=>{We(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ke.red(` \u2717 ${l.error}`)),process.exit(1));let u=$1({url:a,token:i,name:S1(r),version:1});console.log(),console.log(Ke.bold(" Mesh invite")),console.log(),console.log(` ${Ke.cyan(u)}`),console.log(),console.log(Ke.dim(" Run on the other node:")),console.log(Ke.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ke.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Gk(e,t={}){let o;try{o=k1(e)}catch(r){console.log(Ke.red(` \u2717 ${r.message}`)),process.exit(1)}let n=pu("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Jk({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ke.red(" Aborted (keeping existing .env)")),process.exit(1))}Zn("MESH_TOKEN",o.token);let s=await me(r=>{We(r,"mesh.enabled",!0);let i=vs(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),We(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ke.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ke.green(" \u2713 Joined mesh")),console.log(Ke.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ke.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ke.dim(" Daemon hot-reloaded.")):console.log(Ke.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Ke.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ke.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ke.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ts=new A1().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ts.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 Fk({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ts.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 Wk({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});ts.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await Bk({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var zk=ts.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");zk.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 Hk({url:e.url,configPath:e.config})});zk.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Gk(e,{configPath:t.config})});ts.action(()=>{console.log(),console.log(sr.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${sr.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${sr.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${sr.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${sr.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(sr.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as E1}from"commander";import le from"chalk";var os=new E1().name("usage").description("token usage analysis and reporting");os.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(le.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(le.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${le.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${le.red(String(s.totalErrors))}`),console.log(),console.log(le.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),u=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${le.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${le.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${e.message}`))}});os.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=O(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:le.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(le.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(le.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-c)/6e4)),w=d.resetsAt>c?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",h=l.has(d.window)?le.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,w,h].filter(Boolean).join(", ")}`)}console.log();let u=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${u(i.maxPerHour)} in the last hour, ${i.last5h}${u(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(le.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${t.message}`))}});os.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(le.red(` Script not found: ${s}`)),console.log(le.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(le.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(le.red(" Analysis failed. Is Python 3 installed?"))}});os.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=g=>/^\d{4}-\d{2}-\d{2}$/.test(g)&&!Number.isNaN(Date.parse(g));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(le.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(le.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=g=>g===null?"-":`$${g.toFixed(g<10?3:2)}`,u=g=>`${(g/1e6).toFixed(1)}M`;console.log(),console.log(le.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(le.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(le.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(g=>[g,a.channels[g],c?.channels[g]]).sort((g,w)=>(w[1]?.cost||0)-(g[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[g,w,h]of p){let y=r(w),$=` ${g.padEnd(14)} ${String(w?.tasks||0).padStart(6)} ${u(w?.cacheRead||0).padStart(11)} ${u(w?.cacheCreate||0).padStart(11)} ${u(w?.output||0).padStart(8)} ${l(w?.cost||0).padStart(10)} ${l(y).padStart(9)}`;if(c){let x=r(h),v=y!==null&&x?`${((y-x)/x*100).toFixed(0)}%`:"-";$+=` ${l(x).padStart(9)} ${v.padStart(7)}`}console.log($)}console.log(),c&&console.log(le.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(le.dim(` Saved ${e.save}`)),console.log()});os.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y7D5W52I.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-TTGZWU2T.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let g=f?`${f} ${p.name()}`:p.name();c.push(g),l(p,g)}};l(i,"");let u=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:u},null,2));return}console.log(),console.log(le.bold(` Never used in the last ${e.days} days (${u.length}/${c.length})`)),console.log();for(let d of u)console.log(` ${le.dim("\xB7")} ${d}`);console.log(),console.log(le.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(le.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(le.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(le.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(le.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(le.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=le.dim(`${r.days}d`);console.log(` ${le.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(le.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as R1}from"commander";import He from"chalk";import{readFileSync as C1}from"fs";import{resolve as T1}from"path";te();var ln=new R1().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");ln.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{Ug(T1(process.cwd(),".env"))}catch{}let t=O1(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-P7F52WNX.js");o(t)}catch(t){console.log(He.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(He.dim(t.stack)),process.exit(1)}});function O1(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(He.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(He.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
575
+ `}function Zn(e,t,o=".env"){let n=Mk(o),s=Lk(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${mu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${mu(t)}`})),QO(n,o1(s))}function pu(e,t=".env"){return Lk(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var qk="https://t.me/BotFather";async function n1(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function s1(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Fk(e={}){console.log(),console.log(xe.bold(" Connect Telegram")),console.log(),console.log(xe.dim(` 1. Open ${qk}`)),console.log(xe.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(xe.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Zr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Io(qk);let{token:o}=await Zr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:v=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(v.trim())||"That doesn't look like a Telegram token"});o||(console.log(xe.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await n1(o.trim());n||(console.log(xe.red("\u2717 invalid or revoked")),process.exit(1)),console.log(xe.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(xe.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(xe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await Zr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),u||(console.log(xe.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||u;d[f]&&d[f].agentBinding!==u&&(f=(await Zr({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(xe.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Zn(p,o.trim()),process.env[p]=o.trim();let g=await me(v=>{We(v,"channels.telegram.enabled",!0),We(v,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:u});let S=vs(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),We(v,`agents.${u}.mentions`,S))},{configPath:e.configPath});if(g.success||(console.log(xe.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(xe.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(xe.dim(` Token stored in .env as ${p}`)),console.log(xe.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(xe.dim(" Daemon hot-reloaded.")):console.log(xe.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Zr({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(xe.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(xe.dim(" Waiting up to 90s..."));let h=await s1(o.trim(),9e4);if(!h){console.log(xe.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(xe.dim(" agentx config set notifications.destination.channel telegram")),console.log(xe.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(xe.dim(` agentx config set notifications.destination.accountId ${f}`));return}let y={channel:"telegram",chatId:String(h.chatId),accountId:f},$=[],x=await me(v=>{We(v,"notifications.destination",y),$=ga(v,y)},{configPath:e.configPath});if(!x.success){console.log(xe.red(` \u2717 failed to save destination: ${x.error}`));return}console.log(xe.green(" \u2713 Default --notify target set")),console.log(xe.dim(` Chat: ${h.chatTitle||h.chatId} (from ${h.from})`)),console.log(xe.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(xe.dim(` Schedules that now report here: ${$.join(", ")}`)),x.reloaded&&console.log(xe.dim(" Daemon hot-reloaded."))}import Me from"chalk";import fu from"prompts";import{existsSync as wu,mkdirSync as r1,readdirSync as i1,readFileSync as Uk}from"fs";import{resolve as hu}from"path";var a1=".agentx/whatsapp-sessions";function c1(){let e=hu(process.cwd(),".agentx/daemon.pid");if(!wu(e))return!1;try{let t=parseInt(Uk(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function l1(e){if(!wu(e))return!1;try{return i1(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function d1(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Me.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Me.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;r1(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(u=>{let f=setTimeout(()=>{t(Me.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}u(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(Me.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Me.green(" \u2713 Paired"));try{l.end(void 0)}catch{}u(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Me.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Wk(e={}){if(console.log(),console.log(Me.bold(" Connect WhatsApp")),console.log(),c1()){console.log(Me.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Me.dim(" agentx daemon stop")),console.log();let{cont:l}=await fu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Me.red(" Aborted")),process.exit(1))}let t=e.configPath||hu(process.cwd(),"agentx.json");wu(t)||(console.log(Me.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Uk(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||a1,s=hu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Me.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await fu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(Me.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(l1(s)&&a){let{keep:l}=await fu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(Me.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await d1(s,u=>console.log(u))||(console.log(Me.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await me(l=>{We(l,"channels.whatsapp.enabled",!0),We(l,"channels.whatsapp.sessionDir",n),We(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Me.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Me.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Me.dim(` Session: ${n}`)),console.log(Me.dim(" Start the daemon to begin receiving:")),console.log(Me.dim(" agentx daemon start")),console.log(Me.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Me.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Me.dim(" Add routes later with:")),console.log(Me.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Rt from"chalk";import u1 from"prompts";import{existsSync as g1,readFileSync as m1}from"fs";import{resolve as p1}from"path";async function f1(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function h1(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Do(e){console.log(Rt.red(` ${e}`)),process.exit(1)}async function es(e){return(await u1(e,{onCancel:()=>Do("Aborted")}))[e.name]}async function Bk(e={}){console.log(),console.log(Rt.bold(" Connect email")),console.log();let t=e.configPath||p1(process.cwd(),"agentx.json");g1(t)||Do(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(m1(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Do("No agents configured. Run: agentx agent add");let s=e.agent??await es({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(y=>({title:y,value:y}))});o.agents?.[s]||Do(`No agent "${s}" in ${t}`);let r=(e.address??await es({type:"text",name:"address",message:"Email address customers write to:",validate:y=>/^\S+@\S+\.\S+$/.test(y.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=xh(r),c=e.imapHost??a?.imapHost??await es({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await es({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await es({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await es({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Do("Ports must be numbers.");let f=e.passwordEnv||Ah(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&Do(`${e.passwordEnv} is not set in the environment.`),p||(a?.imapHost==="imap.gmail.com"&&(console.log(Rt.dim(` Gmail needs an app password, not your account password: ${vh}`)),console.log(Rt.dim(" (2-step verification must be on for that page to show.)"))),p=(await es({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||Do("Aborted");let g={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:f,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let y=await f1(g,p);y&&(console.log(Rt.red("\u2717")),Do(y)),console.log(Rt.green("\u2713"))}e.passwordEnv||(Zn(f,p),process.env[f]=p);let w=await me(y=>{We(y,"channels.email.enabled",!0),We(y,`channels.email.accounts.${i}`,Sh(g))},{configPath:e.configPath});w.success||Do(`Config save failed: ${w.error}`),console.log(),console.log(Rt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Rt.dim(` Password stored in .env as ${f}`)),console.log(Rt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let h=h1(o.agents[s]?.tier,g.allowFrom);h&&console.log(Rt.yellow(` ${h}`)),console.log(g.send==="auto"?Rt.yellow(" Replies are sent as soon as the agent writes them."):Rt.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Rt.dim(" Only mail that arrives from now on is answered.")),console.log(Rt.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as w1}from"crypto";import Ke from"chalk";import Jk from"prompts";var tc="agentx-mesh:",oc="//join/";function y1(e){return Buffer.from(e,"utf-8").toString("base64url")}function b1(e){return Buffer.from(e,"base64url").toString("utf-8")}function $1(e){return`${tc}${oc}${y1(JSON.stringify(e))}`}function k1(e){if(!e.startsWith(`${tc}${oc}`))throw new Error(`Not a mesh invite link \u2014 expected ${tc}${oc}\u2026`);let t=e.slice(tc.length+oc.length),o=JSON.parse(b1(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function v1(){return w1(32).toString("hex")}function x1(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function S1(e){return e?.node?.name||e?.node?.id||"node"}async function Hk(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ke.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=pu("MESH_TOKEN");i||(i=v1(),Zn("MESH_TOKEN",i),console.log(Ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||x1(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Jk({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(Ke.red(" Aborted")),process.exit(1)),a=d}let l=await me(d=>{We(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ke.red(` \u2717 ${l.error}`)),process.exit(1));let u=$1({url:a,token:i,name:S1(r),version:1});console.log(),console.log(Ke.bold(" Mesh invite")),console.log(),console.log(` ${Ke.cyan(u)}`),console.log(),console.log(Ke.dim(" Run on the other node:")),console.log(Ke.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ke.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Gk(e,t={}){let o;try{o=k1(e)}catch(r){console.log(Ke.red(` \u2717 ${r.message}`)),process.exit(1)}let n=pu("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Jk({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ke.red(" Aborted (keeping existing .env)")),process.exit(1))}Zn("MESH_TOKEN",o.token);let s=await me(r=>{We(r,"mesh.enabled",!0);let i=vs(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),We(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ke.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ke.green(" \u2713 Joined mesh")),console.log(Ke.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ke.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ke.dim(" Daemon hot-reloaded.")):console.log(Ke.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Ke.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ke.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ke.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ts=new A1().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ts.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 Fk({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ts.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 Wk({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});ts.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await Bk({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var zk=ts.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");zk.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 Hk({url:e.url,configPath:e.config})});zk.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Gk(e,{configPath:t.config})});ts.action(()=>{console.log(),console.log(sr.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${sr.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${sr.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${sr.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${sr.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(sr.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as E1}from"commander";import le from"chalk";var os=new E1().name("usage").description("token usage analysis and reporting");os.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(le.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(le.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${le.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${le.red(String(s.totalErrors))}`),console.log(),console.log(le.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),u=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${le.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${le.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${e.message}`))}});os.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=O(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:le.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(le.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(le.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-c)/6e4)),w=d.resetsAt>c?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",h=l.has(d.window)?le.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,w,h].filter(Boolean).join(", ")}`)}console.log();let u=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${u(i.maxPerHour)} in the last hour, ${i.last5h}${u(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(le.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${t.message}`))}});os.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(le.red(` Script not found: ${s}`)),console.log(le.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(le.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(le.red(" Analysis failed. Is Python 3 installed?"))}});os.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=g=>/^\d{4}-\d{2}-\d{2}$/.test(g)&&!Number.isNaN(Date.parse(g));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(le.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(le.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=g=>g===null?"-":`$${g.toFixed(g<10?3:2)}`,u=g=>`${(g/1e6).toFixed(1)}M`;console.log(),console.log(le.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(le.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(le.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(g=>[g,a.channels[g],c?.channels[g]]).sort((g,w)=>(w[1]?.cost||0)-(g[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[g,w,h]of p){let y=r(w),$=` ${g.padEnd(14)} ${String(w?.tasks||0).padStart(6)} ${u(w?.cacheRead||0).padStart(11)} ${u(w?.cacheCreate||0).padStart(11)} ${u(w?.output||0).padStart(8)} ${l(w?.cost||0).padStart(10)} ${l(y).padStart(9)}`;if(c){let x=r(h),v=y!==null&&x?`${((y-x)/x*100).toFixed(0)}%`:"-";$+=` ${l(x).padStart(9)} ${v.padStart(7)}`}console.log($)}console.log(),c&&console.log(le.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(le.dim(` Saved ${e.save}`)),console.log()});os.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y7D5W52I.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-RVODWQAM.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let g=f?`${f} ${p.name()}`:p.name();c.push(g),l(p,g)}};l(i,"");let u=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:u},null,2));return}console.log(),console.log(le.bold(` Never used in the last ${e.days} days (${u.length}/${c.length})`)),console.log();for(let d of u)console.log(` ${le.dim("\xB7")} ${d}`);console.log(),console.log(le.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(le.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(le.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(le.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(le.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(le.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=le.dim(`${r.days}d`);console.log(` ${le.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(le.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as R1}from"commander";import He from"chalk";import{readFileSync as C1}from"fs";import{resolve as T1}from"path";te();var ln=new R1().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");ln.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{Ug(T1(process.cwd(),".env"))}catch{}let t=O1(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-DWJPDDGM.js");o(t)}catch(t){console.log(He.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(He.dim(t.stack)),process.exit(1)}});function O1(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(He.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(He.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
576
576
  `)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}ln.command("list").description("list configured boards").action(()=>{try{let e=O();if(!e.boards?.length){console.log(He.dim(`
577
577
  No boards configured.
578
578
  `));return}console.log();for(let t of e.boards){console.log(` ${He.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(He.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(He.dim(` primary label: ${t.primaryToolLabel}`)),console.log(He.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(He.red(` ${e.message}`)),process.exit(1)}});ln.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{ei(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(r=>r.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(r=>r.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(He.red(` ${o.message}`)),process.exit(1)}});ln.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,t)=>{try{ei(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=[];if(t.name&&(s.name=t.name,r.push(`name="${t.name}"`)),t.projects){let i=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(i.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:i},r.push(`projects=${i.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,r.push("label cleared")):(s.primaryToolLabel=t.label,r.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,r.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,r.push(`closed-days=${s.closedWindowDays}`)),r.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${r.join(", ")})`})}catch(o){console.log(He.red(` ${o.message}`)),process.exit(1)}});var yu=ln.command("column").description("manage a board's columns (add / remove / edit / list)");yu.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(C1("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log(He.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let r=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${He.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${He.dim(r)}`)}}catch(t){console.log(He.red(` ${t.message}`)),process.exit(1)}});yu.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,t,o)=>{try{ei(n=>{let r=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!r)throw new Error(`board "${e}" not found`);if(r.columns=r.columns||[],r.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let i={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");i.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");i.mapsToLabel=o.label}return o.accent&&(i.accent=o.accent),r.columns.push(i),`column "${t}" added to board "${e}"`})}catch(n){console.log(He.red(` ${n.message}`)),process.exit(1)}});yu.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{ei(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(i=>i.id!==t),s.columns.length===r)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(He.red(` ${o.message}`)),process.exit(1)}});ln.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{ei(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(He.red(` ${t.message}`)),process.exit(1)}});function ei(e){let{summary:t,backupPath:o}=Dt(n=>e(n));console.log(He.green(`
@@ -874,7 +874,7 @@ Restart the daemon to activate.
874
874
  dist/
875
875
  *.log
876
876
  .env
877
- `}import{Command as uj}from"commander";import at from"chalk";import{writeFileSync as gj,mkdirSync as mj,existsSync as Tc,readFileSync as Kx,appendFileSync as Xx}from"fs";import{resolve as pr,dirname as Zx}from"path";import{homedir as sg}from"os";var e0=new uj().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-TTGZWU2T.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=hj(o);break;case"bash":s=kj(o);break;case"fish":s=vj(o);break;default:console.error(at.red(`unsupported shell: ${n}`)),console.error(at.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?pr(String(e.output)):pj(n);mj(Zx(r),{recursive:!0}),gj(r,s),console.log(at.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),fj(n,r,!!e.yes)});function pj(e){let t=sg();switch(e){case"zsh":return pr(t,".zsh","completions","_agentx");case"bash":return pr(t,".bash_completion.d","agentx.bash");case"fish":return pr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function fj(e,t,o){if(e==="zsh"){let n=pr(sg(),".zshrc"),s=Zx(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Tc(n)?Kx(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(at.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Tc(n)){let u=["","# agentx completion"];c&&u.push(r),l&&u.push(i),Xx(n,u.join(`
877
+ `}import{Command as uj}from"commander";import at from"chalk";import{writeFileSync as gj,mkdirSync as mj,existsSync as Tc,readFileSync as Kx,appendFileSync as Xx}from"fs";import{resolve as pr,dirname as Zx}from"path";import{homedir as sg}from"os";var e0=new uj().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-RVODWQAM.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=hj(o);break;case"bash":s=kj(o);break;case"fish":s=vj(o);break;default:console.error(at.red(`unsupported shell: ${n}`)),console.error(at.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?pr(String(e.output)):pj(n);mj(Zx(r),{recursive:!0}),gj(r,s),console.log(at.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),fj(n,r,!!e.yes)});function pj(e){let t=sg();switch(e){case"zsh":return pr(t,".zsh","completions","_agentx");case"bash":return pr(t,".bash_completion.d","agentx.bash");case"fish":return pr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function fj(e,t,o){if(e==="zsh"){let n=pr(sg(),".zshrc"),s=Zx(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Tc(n)?Kx(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(at.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Tc(n)){let u=["","# agentx completion"];c&&u.push(r),l&&u.push(i),Xx(n,u.join(`
878
878
  `)+`
879
879
  `),console.log(at.green("\u2713 Patched ~/.zshrc")),console.log(at.dim("Reload your shell: exec zsh"));return}console.log(at.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(at.cyan(` ${r}`)),l&&console.log(at.cyan(` ${i}`)),console.log(),console.log(at.dim("Then reload: exec zsh")),console.log(at.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=pr(sg(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Tc(n)?Kx(n,"utf-8"):"").includes(t)){console.log(at.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&Tc(n)){Xx(n,`
880
880
  # agentx completion
@@ -890,4 +890,4 @@ ${xj({...t,category:e.category})}`),u&&a.set(l.id,u)}let c=`https://github.com/$
890
890
  ${o.url}`)}catch(t){console.error(hr.red(` ${t.message}`)),process.exitCode=1}});fi.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",ig).action(async(e,t)=>{try{let o=await lg(t.models);if(!ag(t.model,o)){console.log(cg(t.model,o)),process.exitCode=1;return}let n=e==="-"?await Ej():await Aj(e,"utf8"),s=JSON.parse(n),{version:r}=await _i(),i=s0({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(hr.red(` ${o.message}`)),process.exitCode=1}});async function Ej(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function cz(){let e=await _i(),t=new Rj().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");t.hook("preAction",(o,n)=>{let s=Rh(n);Ch(s)&&Eh("cli",s)});for(let o of[Cy,Uw,Fw,ts,Is,go,Mt,ah,q$,U$,fo,ya,jo,Rn,Yn,bo,Po,Dk,cn,la,Ox,nn,Sb,Ab,_b,zr,Hb,Xb,kb,Zb,e$,w$,k$,v$,Wt,os,Dx,Dr,Qo,e0,fi])t.addCommand(o);for(let o of i0)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=i0.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Cj(o,74," "),""].join(`
891
891
  `)}),t}var i0=[X,ar,Lo,oo,Lr,Vs,tt,Mo,ln,zn,as,lr,tn,xt,Bs,Ia,Ga,Hn,za,Ya,Ax,Cx,No,ai,qt,Kh,Nn,mi,ad,gn,$t,Us,cd,yc,xo,Du,qo,Wx,gr,Bx,_x];function Cj(e,t,o){let n=[],s="";for(let r of e)s&&s.length+r.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+r;return s&&n.push(o+s),n.join(`
892
892
  `)}export{cz as buildProgram};
893
- //# sourceMappingURL=program-TTGZWU2T.js.map
893
+ //# sourceMappingURL=program-RVODWQAM.js.map
@@ -1,2 +1,2 @@
1
- import{Aa as m,Ba as n,Ca as o,Da as p,oa as a,pa as b,qa as c,ra as d,sa as e,ta as f,ua as g,va as h,wa as i,xa as j,ya as k,za as l}from"./chunk-BY7QINNM.js";import"./chunk-RP2YGJDW.js";import"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-GV7S5BAX.js";import"./chunk-SZDACK6O.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-VJVXEVZ7.js";import"./chunk-C5VFABFI.js";import"./chunk-TTAKAN5L.js";import"./chunk-3UOTLMXD.js";import"./chunk-VWTBHLMX.js";import"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GSX4NK2N.js";import"./chunk-HPRLRD4P.js";import"./chunk-KN5LZ3JS.js";import"./chunk-7GCB4HDJ.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-PAMMBHB2.js";import"./chunk-JTFCU5LH.js";import"./chunk-WD4HZAYI.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-XPKDQDBH.js";import"./chunk-NXOBCFUJ.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-QUFIUXMQ.js";import"./chunk-3AHYZLGE.js";import"./chunk-XL7UWG36.js";import"./chunk-MNG2AMKZ.js";import"./chunk-LY4G7PCW.js";import"./chunk-2HBEZV7L.js";import"./chunk-A7JSRDJL.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.js";import"./chunk-DCIYOPJF.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-ZAPHYYGT.js";import"./chunk-KEUW6YLL.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-YSCT6DPR.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{o as AgentRegistry,f as DEFAULT_SLOT_WAIT_MS,a as EDIT_TOOL_INSTRUCTION,j as TRACE_STEP_SUMMARY_BYTES,g as buildEntryMeta,h as buildEventDigest,i as buildWikiContext,k as clipForTrace,b as codingInstructions,n as emitTraceStepsFromStreamEvent,m as firstMissingRequiredTool,d as getGlobalRegistry,e as lastActivityLine,p as richReplyPrompt,c as setGlobalRegistry,l as tallyToolUses};
2
- //# sourceMappingURL=registry-ZZ27JGL5.js.map
1
+ import{Aa as m,Ba as n,Ca as o,Da as p,oa as a,pa as b,qa as c,ra as d,sa as e,ta as f,ua as g,va as h,wa as i,xa as j,ya as k,za as l}from"./chunk-IJXCGKAB.js";import"./chunk-D4QTZJ4G.js";import"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-GV7S5BAX.js";import"./chunk-SZDACK6O.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-VJVXEVZ7.js";import"./chunk-C5VFABFI.js";import"./chunk-TTAKAN5L.js";import"./chunk-3UOTLMXD.js";import"./chunk-VWTBHLMX.js";import"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GSX4NK2N.js";import"./chunk-HPRLRD4P.js";import"./chunk-KN5LZ3JS.js";import"./chunk-7GCB4HDJ.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-PAMMBHB2.js";import"./chunk-JTFCU5LH.js";import"./chunk-WD4HZAYI.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-XPKDQDBH.js";import"./chunk-NXOBCFUJ.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-QUFIUXMQ.js";import"./chunk-3AHYZLGE.js";import"./chunk-XL7UWG36.js";import"./chunk-MNG2AMKZ.js";import"./chunk-LY4G7PCW.js";import"./chunk-2HBEZV7L.js";import"./chunk-A7JSRDJL.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.js";import"./chunk-DCIYOPJF.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-ZAPHYYGT.js";import"./chunk-KEUW6YLL.js";import"./chunk-UEEB3UTU.js";import"./chunk-VQRY4IDI.js";import"./chunk-YSCT6DPR.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{o as AgentRegistry,f as DEFAULT_SLOT_WAIT_MS,a as EDIT_TOOL_INSTRUCTION,j as TRACE_STEP_SUMMARY_BYTES,g as buildEntryMeta,h as buildEventDigest,i as buildWikiContext,k as clipForTrace,b as codingInstructions,n as emitTraceStepsFromStreamEvent,m as firstMissingRequiredTool,d as getGlobalRegistry,e as lastActivityLine,p as richReplyPrompt,c as setGlobalRegistry,l as tallyToolUses};
2
+ //# sourceMappingURL=registry-T2SZPIUE.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentix-cli",
3
- "version": "0.207.1",
3
+ "version": "0.207.2",
4
4
  "description": "AI staff for a small company: they find sales, answer clients, write your posts and watch the money, on a machine you own. You approve what matters. Runs a team of AI agents across Telegram, WhatsApp, GitLab, GitHub, crons, webhooks and mesh tasks, on Claude Code, Codex, OpenCode or any LLM API. Web wizard for operators, CLI for engineers.",
5
5
  "license": "MIT",
6
6
  "author": {