agentix-cli 0.207.2 → 0.208.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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-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)}
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-OW4XJDFO.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-N2E73XNT.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-2BWTUD6Z.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}
@@ -538,7 +538,7 @@ People who asked not to be contacted. The sales agent never drafts a message to
538
538
  `).flatMap(s=>{if(!s.trim())return[];try{let r=JSON.parse(s);return Date.parse(r.at)>=n?[r]:[]}catch{return[]}})}var sk=e=>e.length>160?e.slice(0,159)+"\u2026":e;function ou(e){let t=[];for(let o of e){let n=`[${o.name}](${o.url})`,s=[...o.added.map(r=>`- ${n} added: "${sk(r)}"`),...o.removed.map(r=>`- ${n} removed: "${sk(r)}"`)];t.push(...s.slice(0,Zd)),s.length>Zd&&t.push(`- ${n}: ${s.length-Zd} more changed lines`)}return t}var dk=864e5,nu=()=>new Date().toISOString().slice(0,10);function Va(e){return uk(e.workspace??process.cwd())}function mO(e){let t=e.trim().match(/^(\d+)\s*([hd]?)$/i);if(!t)throw new Error(`"${e}" is not a duration like 24h or 2d`);return Number(t[1])*(t[2].toLowerCase()==="d"?dk:dk/24)}var Yn=new dO().name("sales").description("the sales team's lead list, opt-outs and competitor watch (run in the sales agent's folder)");Yn.command("leads").description("new and quiet leads from leads.md, leaving out everyone in opt-outs.md").option("--workspace <dir>","the sales agent's folder (default: this folder)").option("--days <n>","days without contact before a lead is quiet","7").option("--quiet-only","list only the quiet leads").action(e=>{let t=Va(e),o=Number(e.days);if(!Number.isInteger(o)||o<1)throw new Error("--days must be a whole number of days, 1 or more");let n=ek(t),s=tk(t),r=Q$(n,s,nu(),o),i=[];if(!e.quietOnly){let c=Z$(n,s,nu(),2);i.push("New leads (added today or yesterday):",...c.length?c.map(Qd):["- None."],"")}i.push(`Quiet leads (no contact for ${o} days or more):`,...r.length?r.map(Qd):["- None."]);let a=n.filter(c=>Vr(c,s)).length;a&&i.push("",`Summary: ${a} opted-out lead${a===1?"":"s"} left out. Never contact them.`),console.log(i.join(`
539
539
  `))});Yn.command("opt-out <name>").description("record that someone asked not to be contacted; they are left out of every list and draft").option("--company <company>","their company (unset: the person at every company)").option("--reason <text>","why, in a few words").option("--workspace <dir>","the sales agent's folder (default: this folder)").action((e,t)=>{let o=ok(Va(t),{name:e,company:t.company,reason:t.reason},nu()),n=t.company?`${e} (${t.company})`:e;console.log(o?` ${n} is opted out. No message will be drafted for them.`:` ${n} was already opted out.`)});Yn.command("watch").description("check the pages in competitors.md and print only what changed since the last check").option("--workspace <dir>","the sales agent's folder (default: this folder)").action(async e=>{let t=Va(e),o=await ak(t),n=o.changes.length?["Competitor changes:",...ou(o.changes)]:["No competitor changes."];for(let s of o.baselined)n.push(`- Now watching [${s.name}](${s.url}); changes show from the next check.`);for(let s of o.failed)n.push(`- Could not check [${s.competitor.name}](${s.competitor.url}): ${s.error}`);!o.changes.length&&!o.baselined.length&&!o.failed.length&&!o.unchanged&&n.push("Summary: competitors.md lists no pages to watch."),console.log(n.join(`
540
540
  `))});Yn.command("changes").description("competitor changes recorded by `sales watch`, for the brief").option("--since <duration>","how far back, like 24h or 3d","24h").option("--workspace <dir>","the sales agent's folder (default: this folder)").action(e=>{let t=ck(Va(e),new Date(Date.now()-mO(e.since)));console.log(t.length?["Competitor changes:",...ou(t)].join(`
541
- `):"No competitor changes.")});Yn.command("check <file>").description("list the lines of an answer that state a fact without a source link (- reads standard input)").action(async e=>{let t;if(e==="-"){let n=[];for await(let s of process.stdin)n.push(s);t=Buffer.concat(n).toString("utf-8")}else{let n=uk(e);if(!uO(n))throw new Error(`No file at ${n}`);t=gO(n,"utf-8")}let o=wm(t);if(!o.length){console.log(lk.green(" Every fact has a source."));return}console.log(lk.yellow(` ${o.length} line${o.length===1?"":"s"} without a source:`));for(let n of o)console.log(` line ${n.line}: ${n.text}`);process.exitCode=1});import{Command as pO}from"commander";import Te from"chalk";import{resolve as fO}from"path";import _o from"chalk";function gk(e=Date.now()){return{id:"sample",title:"New meeting date for Sam",context:"He wrote: \u201CNo problem, pick the time that suits you and tell me.\u201D",ask:"Which date should I offer him?",recommend:"Thursday 14:00: your calendar is free and it is before his weekend",choices:["Thursday 14:00","Sunday 11:00","Monday 16:00"],draft:"Thanks Sam. Could we meet on {choice}? If that doesn't suit you, tell me what does.",say:"Sam is waiting for a new meeting date. Pick one.",if_silent:"keep",expires:new Date(e+2*864e5).toISOString(),raised_by:"assistant",created_at:new Date(e-12*6e4).toISOString(),status:"pending",origin:{kind:"reminder",id:"sample",title:"Reply to Sam about the meeting"}}}var mk=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function pk(e){e.command("popup").description("show a card on this Mac now and record your answer (macOS)").argument("[key]","card key from `agentx approvals list`, e.g. card:2026-01-05-new-meeting-date-ab12").option("--sample","show a sample card; nothing is recorded").option("--pick <n>","start with option n picked (previews)").option("--theme <system|light|dark>","override approvals.popup.theme").option("--capture <file.png>","save a picture of the card window").option("--timeout <seconds>","override approvals.popup.timeoutSeconds").action(async(t,o)=>{if(process.platform!=="darwin"){console.error(_o.red(" the popup needs macOS")),process.exitCode=1;return}let n=t?.startsWith("card:")?t.slice(5):t,s=o.sample?gk():n?Ei(process.cwd(),n):null;if(!s||s.status!=="pending"){console.error(_o.red(t?` no card waiting for "${t}"`:" give a card key, or --sample")),process.exitCode=1;return}let r={...lo().popup};(o.theme==="system"||o.theme==="light"||o.theme==="dark")&&(r.theme=o.theme),o.timeout&&(r.timeoutSeconds=Number(o.timeout));let i=await df(s,r,{from:o.sample?"Assistant":void 0,capture:o.capture,pick:Number(o.pick)||void 0});if(o.capture&&console.log(_o.dim(` picture saved to ${o.capture}`)),o.sample){console.log(` answer (not recorded): ${JSON.stringify(i)}`);return}if(i.action==="dismiss"){console.log(_o.dim(` not answered${i.why?` (${i.why})`:""}; the card is still waiting`));return}let a=await Wi({root:process.cwd()},`card:${s.id}`,i.action,{by:"operator (popup)",...i.action==="yes"?{choice:i.choice,text:i.text}:{}});if(!a.ok){console.error(_o.red(` ${a.error}`)),process.exitCode=1;return}console.log(_o.green(` \u2713 ${a.message}`))}),e.command("checkin").description("run a check-in now: waiting cards come back, open reminders get cards (daemon, macOS)").option("--daily","the daily pass: every open reminder, not only those due soon").action(async t=>{let o={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(o.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${mk()}/approvals/checkin`,{method:"POST",headers:o,body:JSON.stringify({daily:!!t.daily})}),s=await n.json().catch(()=>({}));if(!n.ok){console.error(_o.red(` ${s.error??n.status}`)),process.exitCode=1;return}console.log(_o.green(` \u2713 ${s.started} pass started; agents are writing cards. Watch: agentx approvals list`))}catch(n){console.error(_o.red(` couldn't reach the daemon at ${mk()}: ${n?.message??n}`)),process.exitCode=1}})}var bo=new pO("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, wiki facts and questions, WhatsApp and email replies, posts)").hook("preAction",(e,t)=>{let o=t.getOptionValue("capture");typeof o=="string"&&t.setOptionValue("capture",fO(o));let n=Ss();n!==process.cwd()&&process.chdir(n)}),hO={card:"card",schedule:"schedule",agent:"new agent",memory:"memory",wiki:"wiki",fact:"wiki fact",question:"wiki question",whatsapp:"whatsapp",email:"email",content:"post",request:"request"};function su(){return{root:process.cwd()}}function Qr(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function wO(e,t=Date.now()){let o=t-Date.parse(e);if(!Number.isFinite(o)||o<0)return"";let n=Math.floor(o/36e5);return n<1?`${Math.max(1,Math.round(o/6e4))} min`:n<48?`${n} h`:`${Math.floor(n/24)} d`}function yO(e){let t=wO(e.created_at);console.log(` ${Te.cyan(e.key)} ${Te.dim(`[${hO[e.kind]}] from ${e.raised_by}${t?`, waiting ${t}`:""}`)}${e.snoozed_until?Te.dim(` (later: until ${Qr(e.snoozed_until)})`):""}`),console.log(` ${Te.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${Te.green("Recommends:")} ${e.recommend}`),e.choices?.forEach((o,n)=>console.log(` ${Te.magenta(`${n+1}.`)} ${o}`)),e.expires&&console.log(Te.yellow(` Expires ${Qr(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(Te.dim(` ${e.detail}`)),e.source&&console.log(Te.dim(` ${e.source}`)),console.log(Te.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}bo.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let t=Mp(su(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(t,null,2));return}for(let n of t.errors)console.log(Te.red(` couldn't read ${n.kind}: ${n.error}`));let o=()=>{for(let n of t.backlog)console.log(Te.dim(` Also: ${n.title}. See them with: ${n.more}`))};if(t.items.length===0){console.log(Te.dim(` nothing waiting${t.snoozed?` (${t.snoozed} put off; --all shows them)`:""}`)),o();return}console.log();for(let n of t.items)yO(n),console.log();console.log(Te.dim(` ${t.items.length} waiting${t.snoozed?`, ${t.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`)),o()});async function ru(e,t,o){let n=lo(),s=o.hours?Number(o.hours):n.laterHours;if(t==="later"&&!(s>0)){console.error(Te.red(" --hours must be a positive number")),process.exitCode=1;return}let r=To();if(r&&e.startsWith("agent:")){console.error(Te.red(` Only the owner decides on a new agent; agent "${r}" asked.`)),process.exitCode=1;return}let i=await Wi(su(),e,t,{force:o.force,note:o.note,laterHours:s,choice:o.choice,text:o.text});if(!i.ok){console.error(Te.red(` ${i.error}`)),process.exitCode=1;return}console.log(Te.green(` \u2713 ${i.message}`))}bo.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, publishes the post, sends the email reply, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").option("--choice <n>","cards with choices: which one, by number or label").option("--text <message>","cards with a suggested message, posts and email replies: the text as you want it sent or published").action((e,t)=>ru(e,"yes",t));bo.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,t)=>ru(e,"no",t));bo.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,t)=>ru(e,"later",t));bo.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${Gg.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").option("--choice <label>","a ready-made answer; repeat for up to 5",(e,t=[])=>[...t,e]).option("--draft <message>","a suggested message; {choice} is replaced by the pick").option("--say <line>","the short line the Mac popup speaks (default: the title)").option("--context <text>","a few lines of background, shown above the question").action(async e=>{let t=lo(),o={raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source,choices:e.choice,draft:e.draft,say:e.say,context:e.context},n=t.forwardTo?await bO(o):Ri(process.cwd(),o,{settings:t});if(!n.ok){console.error(Te.red(` ${n.error}`)),process.exitCode=1;return}let s=t.forwardTo?` on ${t.forwardTo}`:"";console.log(Te.green(` \u2713 card:${n.card.id} raised${s}; expires ${Qr(n.card.expires)}, then: ${n.card.if_silent}`))});async function bO(e){let t=(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,""),o={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(o.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${t}/approvals`,{method:"POST",headers:o,body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)}),s=await n.json().catch(()=>({}));return n.ok?{ok:!0,card:s.card}:{ok:!1,error:s.error??`HTTP ${n.status}`}}catch(n){return{ok:!1,error:`couldn't reach the daemon at ${t} (it forwards cards when approvals.forwardTo is set): ${n?.message??n}`}}}pk(bo);bo.command("mirror-report").description("the Reminders mirror's count: cards raised, Reminders created, cards missed, one line per day").option("--start <time>","when the first day starts (ISO time); default: 24 hours ago times --days").option("--days <n>","how many 24-hour days","1").option("--json","machine-readable output").action(e=>{let t=Number(e.days);if(!Number.isInteger(t)||t<1){console.error(Te.red(" --days must be a whole number, 1 or more")),process.exitCode=1;return}let o=Date.now(),n=24*36e5,s=e.start!==void 0?Date.parse(e.start):o-t*n;if(!Number.isFinite(s)){console.error(Te.red(" --start takes an ISO time, for example 2030-03-01T08:00:00Z")),process.exitCode=1;return}let r=su().root,i=Ro(r),a=Array.from({length:t},(c,l)=>s+l*n).filter(c=>c<o).map(c=>Lp(r,i,c,Math.min(c+n,o),o));if(e.json){console.log(JSON.stringify(a,null,2));return}a.forEach((c,l)=>{console.log(` day ${l} (${Qr(c.from)} to ${Qr(c.to)}): ${qp(c)}`);for(let u of c.missed)console.log(Te.yellow(` missed ${u.id} "${u.title}": ${u.reason}`))})});bo.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--forward-to <peer>",`send this machine's cards to that mesh peer's inbox and popup; "none" to keep them here`).option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').option("--popup <on|off>","Mac popup for new cards (macOS)").option("--popup-speak <on|off>","the popup speaks a short line").option("--popup-voice <name>",'voice for the spoken line; "default" for the system voice').option("--popup-sound <name>",'system sound, like Glass; "none" for silence').option("--popup-timeout <seconds>","how long the popup waits for you").option("--popup-style <card|dialog>","the web card, or plain macOS dialogs").option("--popup-theme <system|light|dark>","the card's colours").option("--checkin <on|off>","check-ins: waiting cards and open reminders, a few times a day (macOS)").option("--checkin-times <HH:MM,...>","local times of the normal passes").option("--checkin-daily <HH:MM>","local time of the daily pass").option("--checkin-lists <list,...>","your Reminders lists to look at").option("--checkin-agent <id>",'agent that writes cards for reminders no agent owns; "none" to clear').action(async e=>{let t={},o=(l,u)=>{if(u===void 0)return;let d=Number(u);if(!(d>0))throw new Error(`${l} must be a positive number`);return d},n=(l,u)=>{if(u!==void 0){if(u==="on")return!0;if(u==="off")return!1;throw new Error(`${l} takes on or off`)}};try{t.defaultExpiryDays=o("--expiry-days",e.expiryDays),t.maxExpiryDays=o("--max-expiry-days",e.maxExpiryDays),t.laterHours=o("--later-hours",e.laterHours),t.notifyAgent=n("--notify-agent",e.notifyAgent),e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo==="none"?null:e.forwardTo),t.digestEnabled=n("--digest",e.digest),t.popupEnabled=n("--popup",e.popup),t.popupSpeak=n("--popup-speak",e.popupSpeak),e.popupVoice!==void 0&&(t.popupVoice=e.popupVoice==="default"?null:e.popupVoice),e.popupSound!==void 0&&(t.popupSound=e.popupSound==="none"?"":e.popupSound),t.popupTimeoutSeconds=o("--popup-timeout",e.popupTimeout),e.popupStyle!==void 0&&(t.popupStyle=e.popupStyle),e.popupTheme!==void 0&&(t.popupTheme=e.popupTheme),t.checkinEnabled=n("--checkin",e.checkin);let l=u=>u?.split(",").map(d=>d.trim()).filter(Boolean);if(t.checkinTimes=l(e.checkinTimes),e.checkinDaily!==void 0&&(t.checkinDailyAt=e.checkinDaily),t.checkinLists=l(e.checkinLists),e.checkinAgent!==void 0&&(t.checkinAgent=e.checkinAgent==="none"?null:e.checkinAgent),e.digestTime!==void 0&&(t.digestTime=e.digestTime),e.digestTimezone!==void 0&&(t.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")t.destination=null;else{let u=ch(e.digestTo);if(!u)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");t.destination=u}}catch(l){console.error(Te.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(t).some(l=>l!==void 0)){let l=await lh(t);if(!l.success){console.error(Te.red(` ${l.error}`)),process.exitCode=1;return}console.log(Te.green(" \u2713 saved")+(l.reloaded?Te.dim(" (daemon reloaded)"):""))}let r=lo(),i=r.digest.destination;console.log(` Cards expire after ${r.defaultExpiryDays} day(s) unless they say (at most ${r.maxExpiryDays})`),console.log(` "Later" hides an item ${r.laterHours} hour(s)`),console.log(` Tell the agent ${r.notifyAgent?"on":"off"}`),console.log(` Cards go to ${r.forwardTo?`${r.forwardTo} (mesh peer)`:"this machine"}`),console.log(` Daily digest ${r.digest.enabled?`on, at ${r.digest.time}${r.digest.timezone?` (${r.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${i?`${i.channel} ${i.chatId}`:"notifications.destination"}`);let a=r.popup;console.log(` Mac popup ${a.enabled?`on: ${a.style}, sound ${a.sound||"none"}, ${a.speak?`speaks${a.voice?` (${a.voice})`:""}`:"silent"}, waits ${a.timeoutSeconds}s`:"off"}`);let c=r.checkin;console.log(` Check-ins ${c.enabled?`on: daily ${c.dailyAt}, then ${c.times.join(", ")}; lists ${c.lists.join(", ")}; agent ${c.agent??"none"}`:"off"}`)});import{Command as $O}from"commander";import K from"chalk";te();wn();Lc();var $t=new $O("people").description("the humans who talk to your agents: one person per human, whatever channel they use");$t.addCommand(Fy());var iu=Cg,fk="-".repeat(64);function Qa(){let e=90;try{e=O().members.logRetentionDays}catch{}return new km(process.cwd(),Date.now,e)}var hk=(e,t=[])=>[...t,e];function bk(e){let t=[];try{t=Object.keys(O().agents)}catch{return}let o=e.filter(n=>!t.includes(n));o.length&&(console.log(K.yellow(` ! not an agent on this machine: ${o.join(", ")}. Agents here: ${t.join(", ")||"none"}.`)),console.log(K.yellow(" Keep it only if it runs on another node; a mistyped id reaches nothing.")))}var $k="An owner reaches every agent and cannot be limited. Change the role first if that is what you want.",kO="An owner is never limited. Change the role first if that is what you want.",au=["tools","skills"];function vO(e){let t=e.toLowerCase().replace(/^(tool|skill)$/,"$1s");return au.includes(t)?t:null}async function Kn(e){let t="",o=await me(n=>{n.people=Array.isArray(n.people)?n.people:[],t=e(n.people)});o.success||(console.error(K.red(`\u2717 ${(o.error??"").replace(/^Mutator threw: /,"")}`)),process.exit(1)),console.log(K.green(`\u2713 ${t}`)),o.reloaded&&console.log(K.dim(" daemon hot-reloaded"))}function tr(e,t){let o=e.find(n=>n?.id===t);if(!o)throw new Error(`No person "${t}". See \`agentx people list\`.`);return o.identities=Array.isArray(o.identities)?o.identities:[],o}function kk(e,t){let o=Mc(e),n=Mc(t);return!!o&&!!n&&o.channel===n.channel&&o.value===n.value}function vk(e){let t=au.filter(o=>e.deny?.[o]?.length).map(o=>` \xB7 no ${o}: ${e.deny[o].join(", ")}`).join("");console.log(` ${K.bold(e.id)} ${e.name}${e.say?K.dim(` (said "${e.say}")`):""} ${K.dim(`\xB7 ${e.role}`)}${e.agents?.length?K.dim(` \xB7 agents: ${e.agents.join(", ")}`):""}${K.dim(t)}`),console.log(K.dim(e.identities.length?` ${e.identities.join(", ")}`:" no identities yet: agentx people link "+e.id+" <channel:id>"))}$t.command("list",{isDefault:!0}).alias("ls").description("everyone, with their channel identities").option("--json","machine-readable output").action(e=>{let t=O().people;if(e.json){console.log(JSON.stringify(t,null,2));return}console.log(),t.length===0&&(console.log(K.dim(` no people listed. What you do on this machine (voice, app, dashboard) is recorded as "${yn}"; senders on other channels are unknown.`)),console.log(K.dim(" add yourself: agentx people add <id> --name <name> --role owner --identity <channel:id>")));for(let o of t)vk(o);console.log()});$t.command("add <id>").description("add a person").requiredOption("--name <name>","their name").option("--role <role>",`${iu.join(" | ")}. A client is someone you do work for; their page is "Your project"`,"member").option("--identity <channel:id>","a login, a Telegram id or a WhatsApp number (repeatable)",hk,[]).option("--agent <id>","an agent this person may reach; repeat for several. None: every agent",hk,[]).action(async(e,t)=>{await Kn(o=>{if(o.some(n=>n?.id===e))throw new Error(`"${e}" is already listed. Add an identity with \`agentx people link ${e} <channel:id>\`.`);if(!iu.includes(t.role))throw new Error(`--role must be one of: ${iu.join(", ")}`);if(t.role==="owner"&&t.agent.length)throw new Error($k);return o.push({id:e,name:t.name,role:t.role,identities:t.identity,agents:t.agent}),`added ${e} (${t.role})${t.agent.length?`, may reach ${t.agent.join(", ")}`:""}`}),bk(t.agent)});$t.command("allow <id> <agents...>").description('limit a person to these agents (ids, space-separated). "all" lifts the limit').action(async(e,t)=>{let o=t.length===1&&t[0].toLowerCase()==="all";await Kn(n=>{let s=tr(n,e);if(!o&&s.role==="owner")throw new Error($k);return s.agents=o?[]:[...new Set(t)],o?`${e} may reach every agent`:`${e} may reach ${s.agents.join(", ")} and no other agent`}),o||bk(t)});$t.command("deny <id> <level> <names...>").description(`stop a person's turns using these tools or skills. Level: tools | skills. Names match without case; * is a wildcard. "none" lifts the limit`).action(async(e,t,o)=>{let n=vO(t);n||(console.error(K.red(`\u2717 level must be one of: ${au.join(", ")}`)),process.exit(1));let s=o.length===1&&o[0].toLowerCase()==="none";await Kn(r=>{let i=tr(r,e);if(!s&&i.role==="owner")throw new Error(kO);return i.deny={...i.deny??{},[n]:s?[]:[...new Set(o)]},s?`${e} may use every ${n.slice(0,-1)}`:`${e} may not use these ${n}: ${i.deny[n].join(", ")}`})});$t.command("link <id> <identity>").description("add a channel identity to a person, written channel:id (gitlab:sara, whatsapp:21620123456)").action(async(e,t)=>{await Kn(o=>{let n=tr(o,e);return n.identities.some(s=>kk(s,t))?`${e} already has ${t}`:(n.identities.push(t),`${t} is now ${e}`)})});$t.command("unlink <id> <identity>").description("take a channel identity away from a person").action(async(e,t)=>{await Kn(o=>{let n=tr(o,e),s=n.identities.length;if(n.identities=n.identities.filter(r=>!kk(r,t)),n.identities.length===s)throw new Error(`"${e}" has no identity ${t}.`);return`${t} is no longer ${e}`})});$t.command("say <id> [spoken...]").description(`how the person's name is said aloud, e.g. "A-neess Ma-roo-shee"; the written name stays. "none" clears it`).action(async(e,t=[])=>{let o=t.join(" ").trim();if(!o){let n=O().people.find(s=>s.id===e);n||(console.error(K.red(`\u2717 No person "${e}". See \`agentx people list\`.`)),process.exit(1)),console.log(n.say?` ${n.name} is said "${n.say}"`:` ${n.name} is said as written`);return}await Kn(n=>{let s=tr(n,e);if(o.toLowerCase()==="none")return delete s.say,`${s.name} is said as written`;if(o.length>120)throw new Error("The spoken form is at most 120 characters");return s.say=o,`${s.name} is now said "${o}"; written, it stays ${s.name}`})});$t.command("remove <id>").alias("rm").description("remove a person. Their past runs keep the id; new messages from them are unknown; every machine of theirs stops at once").action(async e=>{await Kn(o=>(tr(o,e),o.splice(o.findIndex(n=>n?.id===e),1),`removed ${e}`));let t=$h({tokens:new Pt,members:Qa()},e);t.length&&console.log(K.green(`\u2713 ended ${t.length} machine(s) of ${e}: ${t.map(o=>o.name).join(", ")}`)),console.log(K.dim(" If you shared this computer with them on the private network, remove that share too."))});$t.command("invite <id>").description("a one-time code that pairs one of this person's machines with their own page (/member): My work for a teammate, Your project for a client. Ends with a message to forward to them as it is").option("--url <origin>","address the person opens, e.g. https://my-mac.tailnet-name.ts.net (default: this computer's Tailscale name)").action((e,t)=>{try{let o=Mr(),n=od(nd(),o);if(n.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the member page: ${n.join(", ")}`," Anyone you share this computer with could open it. Serve only the member paths instead:"," tailscale serve reset (removes every served path; add the phone app's /app lines back if you use it)",` tailscale serve --bg --set-path /member http://127.0.0.1:${o}/member`,` tailscale serve --bg --set-path /api/member http://127.0.0.1:${o}/api/member`].join(`
541
+ `):"No competitor changes.")});Yn.command("check <file>").description("list the lines of an answer that state a fact without a source link (- reads standard input)").action(async e=>{let t;if(e==="-"){let n=[];for await(let s of process.stdin)n.push(s);t=Buffer.concat(n).toString("utf-8")}else{let n=uk(e);if(!uO(n))throw new Error(`No file at ${n}`);t=gO(n,"utf-8")}let o=wm(t);if(!o.length){console.log(lk.green(" Every fact has a source."));return}console.log(lk.yellow(` ${o.length} line${o.length===1?"":"s"} without a source:`));for(let n of o)console.log(` line ${n.line}: ${n.text}`);process.exitCode=1});import{Command as pO}from"commander";import Te from"chalk";import{resolve as fO}from"path";import _o from"chalk";function gk(e=Date.now()){return{id:"sample",title:"New meeting date for Sam",context:"He wrote: \u201CNo problem, pick the time that suits you and tell me.\u201D",ask:"Which date should I offer him?",recommend:"Thursday 14:00: your calendar is free and it is before his weekend",choices:["Thursday 14:00","Sunday 11:00","Monday 16:00"],draft:"Thanks Sam. Could we meet on {choice}? If that doesn't suit you, tell me what does.",say:"Sam is waiting for a new meeting date. Pick one.",if_silent:"keep",expires:new Date(e+2*864e5).toISOString(),raised_by:"assistant",created_at:new Date(e-12*6e4).toISOString(),status:"pending",origin:{kind:"reminder",id:"sample",title:"Reply to Sam about the meeting"}}}var mk=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function pk(e){e.command("popup").description("show a card on this Mac now and record your answer (macOS)").argument("[key]","card key from `agentx approvals list`, e.g. card:2026-01-05-new-meeting-date-ab12").option("--sample","show a sample card; nothing is recorded").option("--pick <n>","start with option n picked (previews)").option("--theme <system|light|dark>","override approvals.popup.theme").option("--capture <file.png>","save a picture of the card window").option("--timeout <seconds>","override approvals.popup.timeoutSeconds").action(async(t,o)=>{if(process.platform!=="darwin"){console.error(_o.red(" the popup needs macOS")),process.exitCode=1;return}let n=t?.startsWith("card:")?t.slice(5):t,s=o.sample?gk():n?Ei(process.cwd(),n):null;if(!s||s.status!=="pending"){console.error(_o.red(t?` no card waiting for "${t}"`:" give a card key, or --sample")),process.exitCode=1;return}let r={...lo().popup};(o.theme==="system"||o.theme==="light"||o.theme==="dark")&&(r.theme=o.theme),o.timeout&&(r.timeoutSeconds=Number(o.timeout));let i=await df(s,r,{from:o.sample?"Assistant":void 0,capture:o.capture,pick:Number(o.pick)||void 0});if(o.capture&&console.log(_o.dim(` picture saved to ${o.capture}`)),o.sample){console.log(` answer (not recorded): ${JSON.stringify(i)}`);return}if(i.action==="dismiss"){console.log(_o.dim(` not answered${i.why?` (${i.why})`:""}; the card is still waiting`));return}let a=await Wi({root:process.cwd()},`card:${s.id}`,i.action,{by:"operator (popup)",...i.action==="yes"?{choice:i.choice,text:i.text}:{}});if(!a.ok){console.error(_o.red(` ${a.error}`)),process.exitCode=1;return}console.log(_o.green(` \u2713 ${a.message}`))}),e.command("checkin").description("run a check-in now: waiting cards come back, open reminders get cards (daemon, macOS)").option("--daily","the daily pass: every open reminder, not only those due soon").action(async t=>{let o={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(o.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${mk()}/approvals/checkin`,{method:"POST",headers:o,body:JSON.stringify({daily:!!t.daily})}),s=await n.json().catch(()=>({}));if(!n.ok){console.error(_o.red(` ${s.error??n.status}`)),process.exitCode=1;return}console.log(_o.green(` \u2713 ${s.started} pass started; agents are writing cards. Watch: agentx approvals list`))}catch(n){console.error(_o.red(` couldn't reach the daemon at ${mk()}: ${n?.message??n}`)),process.exitCode=1}})}var bo=new pO("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals, wiki facts and questions, WhatsApp and email replies, posts)").hook("preAction",(e,t)=>{let o=t.getOptionValue("capture");typeof o=="string"&&t.setOptionValue("capture",fO(o));let n=Ss();n!==process.cwd()&&process.chdir(n)}),hO={card:"card",schedule:"schedule",agent:"new agent",memory:"memory",wiki:"wiki",fact:"wiki fact",question:"wiki question",whatsapp:"whatsapp",email:"email",content:"post",request:"request"};function su(){return{root:process.cwd()}}function Qr(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function wO(e,t=Date.now()){let o=t-Date.parse(e);if(!Number.isFinite(o)||o<0)return"";let n=Math.floor(o/36e5);return n<1?`${Math.max(1,Math.round(o/6e4))} min`:n<48?`${n} h`:`${Math.floor(n/24)} d`}function yO(e){let t=wO(e.created_at);console.log(` ${Te.cyan(e.key)} ${Te.dim(`[${hO[e.kind]}] from ${e.raised_by}${t?`, waiting ${t}`:""}`)}${e.snoozed_until?Te.dim(` (later: until ${Qr(e.snoozed_until)})`):""}`),console.log(` ${Te.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${Te.green("Recommends:")} ${e.recommend}`),e.choices?.forEach((o,n)=>console.log(` ${Te.magenta(`${n+1}.`)} ${o}`)),e.expires&&console.log(Te.yellow(` Expires ${Qr(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(Te.dim(` ${e.detail}`)),e.source&&console.log(Te.dim(` ${e.source}`)),console.log(Te.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}bo.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let t=Mp(su(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(t,null,2));return}for(let n of t.errors)console.log(Te.red(` couldn't read ${n.kind}: ${n.error}`));let o=()=>{for(let n of t.backlog)console.log(Te.dim(` Also: ${n.title}. See them with: ${n.more}`))};if(t.items.length===0){console.log(Te.dim(` nothing waiting${t.snoozed?` (${t.snoozed} put off; --all shows them)`:""}`)),o();return}console.log();for(let n of t.items)yO(n),console.log();console.log(Te.dim(` ${t.items.length} waiting${t.snoozed?`, ${t.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`)),o()});async function ru(e,t,o){let n=lo(),s=o.hours?Number(o.hours):n.laterHours;if(t==="later"&&!(s>0)){console.error(Te.red(" --hours must be a positive number")),process.exitCode=1;return}let r=To();if(r&&e.startsWith("agent:")){console.error(Te.red(` Only the owner decides on a new agent; agent "${r}" asked.`)),process.exitCode=1;return}let i=await Wi(su(),e,t,{force:o.force,note:o.note,laterHours:s,choice:o.choice,text:o.text,by:r});if(!i.ok){console.error(Te.red(` ${i.error}`)),process.exitCode=1;return}console.log(Te.green(` \u2713 ${i.message}`))}bo.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, publishes the post, sends the email reply, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").option("--choice <n>","cards with choices: which one, by number or label").option("--text <message>","cards with a suggested message, posts and email replies: the text as you want it sent or published").action((e,t)=>ru(e,"yes",t));bo.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,t)=>ru(e,"no",t));bo.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,t)=>ru(e,"later",t));bo.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${Gg.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").option("--choice <label>","a ready-made answer; repeat for up to 5",(e,t=[])=>[...t,e]).option("--draft <message>","a suggested message; {choice} is replaced by the pick").option("--say <line>","the short line the Mac popup speaks (default: the title)").option("--context <text>","a few lines of background, shown above the question").action(async e=>{let t=lo(),o={raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source,choices:e.choice,draft:e.draft,say:e.say,context:e.context},n=t.forwardTo?await bO(o):Ri(process.cwd(),o,{settings:t});if(!n.ok){console.error(Te.red(` ${n.error}`)),process.exitCode=1;return}let s=t.forwardTo?` on ${t.forwardTo}`:"";console.log(Te.green(` \u2713 card:${n.card.id} raised${s}; expires ${Qr(n.card.expires)}, then: ${n.card.if_silent}`))});async function bO(e){let t=(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,""),o={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(o.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let n=await fetch(`${t}/approvals`,{method:"POST",headers:o,body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)}),s=await n.json().catch(()=>({}));return n.ok?{ok:!0,card:s.card}:{ok:!1,error:s.error??`HTTP ${n.status}`}}catch(n){return{ok:!1,error:`couldn't reach the daemon at ${t} (it forwards cards when approvals.forwardTo is set): ${n?.message??n}`}}}pk(bo);bo.command("mirror-report").description("the Reminders mirror's count: cards raised, Reminders created, cards missed, one line per day").option("--start <time>","when the first day starts (ISO time); default: 24 hours ago times --days").option("--days <n>","how many 24-hour days","1").option("--json","machine-readable output").action(e=>{let t=Number(e.days);if(!Number.isInteger(t)||t<1){console.error(Te.red(" --days must be a whole number, 1 or more")),process.exitCode=1;return}let o=Date.now(),n=24*36e5,s=e.start!==void 0?Date.parse(e.start):o-t*n;if(!Number.isFinite(s)){console.error(Te.red(" --start takes an ISO time, for example 2030-03-01T08:00:00Z")),process.exitCode=1;return}let r=su().root,i=Ro(r),a=Array.from({length:t},(c,l)=>s+l*n).filter(c=>c<o).map(c=>Lp(r,i,c,Math.min(c+n,o),o));if(e.json){console.log(JSON.stringify(a,null,2));return}a.forEach((c,l)=>{console.log(` day ${l} (${Qr(c.from)} to ${Qr(c.to)}): ${qp(c)}`);for(let u of c.missed)console.log(Te.yellow(` missed ${u.id} "${u.title}": ${u.reason}`))})});bo.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--forward-to <peer>",`send this machine's cards to that mesh peer's inbox and popup; "none" to keep them here`).option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').option("--popup <on|off>","Mac popup for new cards (macOS)").option("--popup-speak <on|off>","the popup speaks a short line").option("--popup-voice <name>",'voice for the spoken line; "default" for the system voice').option("--popup-sound <name>",'system sound, like Glass; "none" for silence').option("--popup-timeout <seconds>","how long the popup waits for you").option("--popup-style <card|dialog>","the web card, or plain macOS dialogs").option("--popup-theme <system|light|dark>","the card's colours").option("--checkin <on|off>","check-ins: waiting cards and open reminders, a few times a day (macOS)").option("--checkin-times <HH:MM,...>","local times of the normal passes").option("--checkin-daily <HH:MM>","local time of the daily pass").option("--checkin-lists <list,...>","your Reminders lists to look at").option("--checkin-agent <id>",'agent that writes cards for reminders no agent owns; "none" to clear').action(async e=>{let t={},o=(l,u)=>{if(u===void 0)return;let d=Number(u);if(!(d>0))throw new Error(`${l} must be a positive number`);return d},n=(l,u)=>{if(u!==void 0){if(u==="on")return!0;if(u==="off")return!1;throw new Error(`${l} takes on or off`)}};try{t.defaultExpiryDays=o("--expiry-days",e.expiryDays),t.maxExpiryDays=o("--max-expiry-days",e.maxExpiryDays),t.laterHours=o("--later-hours",e.laterHours),t.notifyAgent=n("--notify-agent",e.notifyAgent),e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo==="none"?null:e.forwardTo),t.digestEnabled=n("--digest",e.digest),t.popupEnabled=n("--popup",e.popup),t.popupSpeak=n("--popup-speak",e.popupSpeak),e.popupVoice!==void 0&&(t.popupVoice=e.popupVoice==="default"?null:e.popupVoice),e.popupSound!==void 0&&(t.popupSound=e.popupSound==="none"?"":e.popupSound),t.popupTimeoutSeconds=o("--popup-timeout",e.popupTimeout),e.popupStyle!==void 0&&(t.popupStyle=e.popupStyle),e.popupTheme!==void 0&&(t.popupTheme=e.popupTheme),t.checkinEnabled=n("--checkin",e.checkin);let l=u=>u?.split(",").map(d=>d.trim()).filter(Boolean);if(t.checkinTimes=l(e.checkinTimes),e.checkinDaily!==void 0&&(t.checkinDailyAt=e.checkinDaily),t.checkinLists=l(e.checkinLists),e.checkinAgent!==void 0&&(t.checkinAgent=e.checkinAgent==="none"?null:e.checkinAgent),e.digestTime!==void 0&&(t.digestTime=e.digestTime),e.digestTimezone!==void 0&&(t.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")t.destination=null;else{let u=ch(e.digestTo);if(!u)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");t.destination=u}}catch(l){console.error(Te.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(t).some(l=>l!==void 0)){let l=await lh(t);if(!l.success){console.error(Te.red(` ${l.error}`)),process.exitCode=1;return}console.log(Te.green(" \u2713 saved")+(l.reloaded?Te.dim(" (daemon reloaded)"):""))}let r=lo(),i=r.digest.destination;console.log(` Cards expire after ${r.defaultExpiryDays} day(s) unless they say (at most ${r.maxExpiryDays})`),console.log(` "Later" hides an item ${r.laterHours} hour(s)`),console.log(` Tell the agent ${r.notifyAgent?"on":"off"}`),console.log(` Cards go to ${r.forwardTo?`${r.forwardTo} (mesh peer)`:"this machine"}`),console.log(` Daily digest ${r.digest.enabled?`on, at ${r.digest.time}${r.digest.timezone?` (${r.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${i?`${i.channel} ${i.chatId}`:"notifications.destination"}`);let a=r.popup;console.log(` Mac popup ${a.enabled?`on: ${a.style}, sound ${a.sound||"none"}, ${a.speak?`speaks${a.voice?` (${a.voice})`:""}`:"silent"}, waits ${a.timeoutSeconds}s`:"off"}`);let c=r.checkin;console.log(` Check-ins ${c.enabled?`on: daily ${c.dailyAt}, then ${c.times.join(", ")}; lists ${c.lists.join(", ")}; agent ${c.agent??"none"}`:"off"}`)});import{Command as $O}from"commander";import K from"chalk";te();wn();Lc();var $t=new $O("people").description("the humans who talk to your agents: one person per human, whatever channel they use");$t.addCommand(Fy());var iu=Cg,fk="-".repeat(64);function Qa(){let e=90;try{e=O().members.logRetentionDays}catch{}return new km(process.cwd(),Date.now,e)}var hk=(e,t=[])=>[...t,e];function bk(e){let t=[];try{t=Object.keys(O().agents)}catch{return}let o=e.filter(n=>!t.includes(n));o.length&&(console.log(K.yellow(` ! not an agent on this machine: ${o.join(", ")}. Agents here: ${t.join(", ")||"none"}.`)),console.log(K.yellow(" Keep it only if it runs on another node; a mistyped id reaches nothing.")))}var $k="An owner reaches every agent and cannot be limited. Change the role first if that is what you want.",kO="An owner is never limited. Change the role first if that is what you want.",au=["tools","skills"];function vO(e){let t=e.toLowerCase().replace(/^(tool|skill)$/,"$1s");return au.includes(t)?t:null}async function Kn(e){let t="",o=await me(n=>{n.people=Array.isArray(n.people)?n.people:[],t=e(n.people)});o.success||(console.error(K.red(`\u2717 ${(o.error??"").replace(/^Mutator threw: /,"")}`)),process.exit(1)),console.log(K.green(`\u2713 ${t}`)),o.reloaded&&console.log(K.dim(" daemon hot-reloaded"))}function tr(e,t){let o=e.find(n=>n?.id===t);if(!o)throw new Error(`No person "${t}". See \`agentx people list\`.`);return o.identities=Array.isArray(o.identities)?o.identities:[],o}function kk(e,t){let o=Mc(e),n=Mc(t);return!!o&&!!n&&o.channel===n.channel&&o.value===n.value}function vk(e){let t=au.filter(o=>e.deny?.[o]?.length).map(o=>` \xB7 no ${o}: ${e.deny[o].join(", ")}`).join("");console.log(` ${K.bold(e.id)} ${e.name}${e.say?K.dim(` (said "${e.say}")`):""} ${K.dim(`\xB7 ${e.role}`)}${e.agents?.length?K.dim(` \xB7 agents: ${e.agents.join(", ")}`):""}${K.dim(t)}`),console.log(K.dim(e.identities.length?` ${e.identities.join(", ")}`:" no identities yet: agentx people link "+e.id+" <channel:id>"))}$t.command("list",{isDefault:!0}).alias("ls").description("everyone, with their channel identities").option("--json","machine-readable output").action(e=>{let t=O().people;if(e.json){console.log(JSON.stringify(t,null,2));return}console.log(),t.length===0&&(console.log(K.dim(` no people listed. What you do on this machine (voice, app, dashboard) is recorded as "${yn}"; senders on other channels are unknown.`)),console.log(K.dim(" add yourself: agentx people add <id> --name <name> --role owner --identity <channel:id>")));for(let o of t)vk(o);console.log()});$t.command("add <id>").description("add a person").requiredOption("--name <name>","their name").option("--role <role>",`${iu.join(" | ")}. A client is someone you do work for; their page is "Your project"`,"member").option("--identity <channel:id>","a login, a Telegram id or a WhatsApp number (repeatable)",hk,[]).option("--agent <id>","an agent this person may reach; repeat for several. None: every agent",hk,[]).action(async(e,t)=>{await Kn(o=>{if(o.some(n=>n?.id===e))throw new Error(`"${e}" is already listed. Add an identity with \`agentx people link ${e} <channel:id>\`.`);if(!iu.includes(t.role))throw new Error(`--role must be one of: ${iu.join(", ")}`);if(t.role==="owner"&&t.agent.length)throw new Error($k);return o.push({id:e,name:t.name,role:t.role,identities:t.identity,agents:t.agent}),`added ${e} (${t.role})${t.agent.length?`, may reach ${t.agent.join(", ")}`:""}`}),bk(t.agent)});$t.command("allow <id> <agents...>").description('limit a person to these agents (ids, space-separated). "all" lifts the limit').action(async(e,t)=>{let o=t.length===1&&t[0].toLowerCase()==="all";await Kn(n=>{let s=tr(n,e);if(!o&&s.role==="owner")throw new Error($k);return s.agents=o?[]:[...new Set(t)],o?`${e} may reach every agent`:`${e} may reach ${s.agents.join(", ")} and no other agent`}),o||bk(t)});$t.command("deny <id> <level> <names...>").description(`stop a person's turns using these tools or skills. Level: tools | skills. Names match without case; * is a wildcard. "none" lifts the limit`).action(async(e,t,o)=>{let n=vO(t);n||(console.error(K.red(`\u2717 level must be one of: ${au.join(", ")}`)),process.exit(1));let s=o.length===1&&o[0].toLowerCase()==="none";await Kn(r=>{let i=tr(r,e);if(!s&&i.role==="owner")throw new Error(kO);return i.deny={...i.deny??{},[n]:s?[]:[...new Set(o)]},s?`${e} may use every ${n.slice(0,-1)}`:`${e} may not use these ${n}: ${i.deny[n].join(", ")}`})});$t.command("link <id> <identity>").description("add a channel identity to a person, written channel:id (gitlab:sara, whatsapp:21620123456)").action(async(e,t)=>{await Kn(o=>{let n=tr(o,e);return n.identities.some(s=>kk(s,t))?`${e} already has ${t}`:(n.identities.push(t),`${t} is now ${e}`)})});$t.command("unlink <id> <identity>").description("take a channel identity away from a person").action(async(e,t)=>{await Kn(o=>{let n=tr(o,e),s=n.identities.length;if(n.identities=n.identities.filter(r=>!kk(r,t)),n.identities.length===s)throw new Error(`"${e}" has no identity ${t}.`);return`${t} is no longer ${e}`})});$t.command("say <id> [spoken...]").description(`how the person's name is said aloud, e.g. "A-neess Ma-roo-shee"; the written name stays. "none" clears it`).action(async(e,t=[])=>{let o=t.join(" ").trim();if(!o){let n=O().people.find(s=>s.id===e);n||(console.error(K.red(`\u2717 No person "${e}". See \`agentx people list\`.`)),process.exit(1)),console.log(n.say?` ${n.name} is said "${n.say}"`:` ${n.name} is said as written`);return}await Kn(n=>{let s=tr(n,e);if(o.toLowerCase()==="none")return delete s.say,`${s.name} is said as written`;if(o.length>120)throw new Error("The spoken form is at most 120 characters");return s.say=o,`${s.name} is now said "${o}"; written, it stays ${s.name}`})});$t.command("remove <id>").alias("rm").description("remove a person. Their past runs keep the id; new messages from them are unknown; every machine of theirs stops at once").action(async e=>{await Kn(o=>(tr(o,e),o.splice(o.findIndex(n=>n?.id===e),1),`removed ${e}`));let t=$h({tokens:new Pt,members:Qa()},e);t.length&&console.log(K.green(`\u2713 ended ${t.length} machine(s) of ${e}: ${t.map(o=>o.name).join(", ")}`)),console.log(K.dim(" If you shared this computer with them on the private network, remove that share too."))});$t.command("invite <id>").description("a one-time code that pairs one of this person's machines with their own page (/member): My work for a teammate, Your project for a client. Ends with a message to forward to them as it is").option("--url <origin>","address the person opens, e.g. https://my-mac.tailnet-name.ts.net (default: this computer's Tailscale name)").action((e,t)=>{try{let o=Mr(),n=od(nd(),o);if(n.length>0)throw new Error([`tailscale serve publishes the whole dashboard, not only the member page: ${n.join(", ")}`," Anyone you share this computer with could open it. Serve only the member paths instead:"," tailscale serve reset (removes every served path; add the phone app's /app lines back if you use it)",` tailscale serve --bg --set-path /member http://127.0.0.1:${o}/member`,` tailscale serve --bg --set-path /api/member http://127.0.0.1:${o}/api/member`].join(`
542
542
  `));let s=(t.url?String(t.url):td()).replace(/\/+$/,"");if(!/^https?:\/\/[^/]+$/.test(s))throw new Error(`--url must be an origin like https://host.example.ts.net, got: ${s}`);let r=O().people,i=hh({tokens:new Pt,codes:new Fi,members:Qa(),people:()=>r},e);if(!i.ok)throw new Error(i.error);console.log(),console.log(` Invite for ${K.bold(i.person.name)} (${i.person.id}, ${i.person.role}). Their page is ${K.bold(El(i.person.role))}.`),console.log(),console.log(" 1. Share this computer with them on your private network, if you have not yet:"),console.log(K.dim(" Tailscale admin console \u2192 Machines \u2192 this computer \u2192 Share \u2192 send them the link.")),console.log(K.dim(' Limit what shared users can reach to port 443 in your access rules (see the docs page "Invite a teammate").')),console.log(` 2. Send them the message below, or this address and code. The code works once, for ${wh} minutes:`),console.log(),console.log(` ${K.cyan(`${s}/member`)}`),console.log(` ${K.bold(qi(i.code))}`),console.log(),console.log(` 3. When they pair, a card "New machine for ${i.person.name}" asks you to approve that machine. Then ${El(i.person.role)} opens for them.`),console.log(K.dim(` Their key stops after ${fh} days; invite again then. Machine id: ${i.tokenId}`)),console.log(),console.log(` ${K.bold("Message to forward")} ${K.dim("(copy everything between the two lines; the rest of this output is for you)")}`),console.log(K.dim(fk)),console.log(yh({person:i.person,origin:s,code:i.code})),console.log(K.dim(fk)),console.log()}catch(o){console.log(K.red(` ${o.message}`)),process.exit(1)}});$t.command("devices [id]").description("the machines paired to people's own pages (My work, Your project): state, where from, first and last use").option("--json","machine-readable output").action((e,t)=>{let o=Qa().devices(e);if(t.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(K.dim(`
543
543
  No machines${e?` for ${e}`:""}. Run \`agentx people invite <id>\`.
544
544
  `));return}console.log();for(let n of o){let s=n.state==="active"?K.green("active"):n.state==="pending"?K.yellow("waiting for your approval"):K.red(`removed${n.removedReason?`: ${n.removedReason}`:""}`);console.log(` ${K.cyan(n.tokenId)} ${K.bold(n.personId)} ${n.name} ${s}`),console.log(K.dim(` paired: ${n.createdAt} from ${n.address??"?"}${n.network?` as ${n.network}`:""}${n.lastSeenAt?` last used: ${n.lastSeenAt} from ${n.lastAddress??"?"}`:""}`))}console.log()});$t.command("revoke-device <tokenId>").description("end one machine's access at once").action(e=>{let t=bh({tokens:new Pt,members:Qa()},e);t||(console.log(K.red(` No machine with id ${e}. See \`agentx people devices\`.`)),process.exit(1)),console.log(K.green(`
@@ -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-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.
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-AJVTYLTY.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-6KGRVAK6.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-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(`
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-AJVTYLTY.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-RVODWQAM.js.map
893
+ //# sourceMappingURL=program-AJVTYLTY.js.map