agentix-cli 0.220.0 → 0.221.1
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.
- package/dist/{agent-UDKXN4QV.js → agent-DXKDG4DQ.js} +2 -2
- package/dist/{board-dashboard-CZXKVKK7.js → board-dashboard-QV7OD4SO.js} +4 -4
- package/dist/{board-dashboard-CZXKVKK7.js.map → board-dashboard-QV7OD4SO.js.map} +1 -1
- package/dist/chunk-3323WFVK.js +13 -0
- package/dist/chunk-3323WFVK.js.map +1 -0
- package/dist/{chunk-RHNOMUYZ.js → chunk-575LJSX2.js} +3 -3
- package/dist/{chunk-XQH4LCZR.js → chunk-74MHOALB.js} +2 -2
- package/dist/{chunk-5XN2OMBS.js → chunk-AAPHOKWS.js} +2 -2
- package/dist/{chunk-3XS7M5LM.js → chunk-AAQOXNLE.js} +260 -260
- package/dist/chunk-AAQOXNLE.js.map +1 -0
- package/dist/chunk-EFXZACH4.js +2 -0
- package/dist/chunk-EFXZACH4.js.map +1 -0
- package/dist/chunk-FG2FPOML.js +2 -0
- package/dist/chunk-FG2FPOML.js.map +1 -0
- package/dist/{chunk-5RCWAXVK.js → chunk-FRYEUVYD.js} +21 -21
- package/dist/chunk-FRYEUVYD.js.map +1 -0
- package/dist/{chunk-SYIDD7CI.js → chunk-KQ3LPQ2Z.js} +2 -2
- package/dist/{chunk-M6TZ7IIJ.js → chunk-LO5A3VKY.js} +2 -2
- package/dist/{chunk-PSUOF7O5.js → chunk-O4EQAPBB.js} +2 -2
- package/dist/{chunk-E3SA7KIZ.js → chunk-RMB6G7X2.js} +2 -2
- package/dist/{chunk-5CUOKXOD.js → chunk-VYNM7HYU.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{doctor-PLN3QJE4.js → doctor-AW53DQDU.js} +2 -2
- package/dist/{follow-up-tool-LS4OUMLZ.js → follow-up-tool-N5U7U5WN.js} +2 -2
- package/dist/{grants-ZA35QVTX.js → grants-AIUWETYP.js} +2 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/{org-tool-NVCSDX4I.js → org-tool-VNDHR7WM.js} +2 -2
- package/dist/{program-BRFPOZLO.js → program-Q4DXWAQU.js} +8 -8
- package/dist/{program-BRFPOZLO.js.map → program-Q4DXWAQU.js.map} +1 -1
- package/dist/registry-Q3H6QR6Q.js +2 -0
- package/dist/runner-KWSARUS4.js +2 -0
- package/dist/{sprint-tool-B2LNMNPB.js → sprint-tool-5NJYOFIZ.js} +2 -2
- package/dist/step-proof-GLY7XVPD.js +2 -0
- package/dist/{tool-OVW6DDOO.js → tool-2DOU5XCQ.js} +2 -2
- package/dist/tool-AR4BLSYC.js +1 -1
- package/dist/{tool-EG6PL6NM.js → tool-ZSNE7YWS.js} +2 -2
- package/dist/{workspace-setup-CQ5FMT2B.js → workspace-setup-W32C7WXN.js} +2 -2
- package/dist/workspace-setup-W32C7WXN.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-3XS7M5LM.js.map +0 -1
- package/dist/chunk-5RCWAXVK.js.map +0 -1
- package/dist/chunk-BXK5S2KK.js +0 -13
- package/dist/chunk-BXK5S2KK.js.map +0 -1
- package/dist/chunk-SZDACK6O.js +0 -2
- package/dist/chunk-SZDACK6O.js.map +0 -1
- package/dist/registry-3J5U67DS.js +0 -2
- package/dist/runner-56G3N7M4.js +0 -2
- /package/dist/{agent-UDKXN4QV.js.map → agent-DXKDG4DQ.js.map} +0 -0
- /package/dist/{chunk-RHNOMUYZ.js.map → chunk-575LJSX2.js.map} +0 -0
- /package/dist/{chunk-XQH4LCZR.js.map → chunk-74MHOALB.js.map} +0 -0
- /package/dist/{chunk-5XN2OMBS.js.map → chunk-AAPHOKWS.js.map} +0 -0
- /package/dist/{chunk-SYIDD7CI.js.map → chunk-KQ3LPQ2Z.js.map} +0 -0
- /package/dist/{chunk-M6TZ7IIJ.js.map → chunk-LO5A3VKY.js.map} +0 -0
- /package/dist/{chunk-PSUOF7O5.js.map → chunk-O4EQAPBB.js.map} +0 -0
- /package/dist/{chunk-E3SA7KIZ.js.map → chunk-RMB6G7X2.js.map} +0 -0
- /package/dist/{chunk-5CUOKXOD.js.map → chunk-VYNM7HYU.js.map} +0 -0
- /package/dist/{doctor-PLN3QJE4.js.map → doctor-AW53DQDU.js.map} +0 -0
- /package/dist/{follow-up-tool-LS4OUMLZ.js.map → follow-up-tool-N5U7U5WN.js.map} +0 -0
- /package/dist/{grants-ZA35QVTX.js.map → grants-AIUWETYP.js.map} +0 -0
- /package/dist/{org-tool-NVCSDX4I.js.map → org-tool-VNDHR7WM.js.map} +0 -0
- /package/dist/{registry-3J5U67DS.js.map → registry-Q3H6QR6Q.js.map} +0 -0
- /package/dist/{runner-56G3N7M4.js.map → runner-KWSARUS4.js.map} +0 -0
- /package/dist/{sprint-tool-B2LNMNPB.js.map → sprint-tool-5NJYOFIZ.js.map} +0 -0
- /package/dist/{workspace-setup-CQ5FMT2B.js.map → step-proof-GLY7XVPD.js.map} +0 -0
- /package/dist/{tool-OVW6DDOO.js.map → tool-2DOU5XCQ.js.map} +0 -0
- /package/dist/{tool-EG6PL6NM.js.map → tool-ZSNE7YWS.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Uy,b as ka,g as Wy}from"./chunk-U476QMLK.js";import{a as qy,b as Fy}from"./chunk-XPYZBWI7.js";import{b as Ly}from"./chunk-WQTPSXVB.js";import{$ as yy,A as ny,B as ay,C as cy,E as ly,G as dy,H as uy,I as od,J as gy,U as my,V as py,W as nd,X as fy,_ as hy,aa as wy,ba as by,ca as xy,da as Sy,ea as Ey,fa as Ay,g as Jh,ga as Ry,h as Hh,ha as Ty,ja as sd,ka as Cy,l as Gh,la as Oy,m as zh,na as Iy,o as Fs,p as Us,q as Yh,qa as Ny,r as Kh,ra as jy,s as Xh,sa as _y,t as Vh,u as Qh,v as Zh,x as Xt,z as oy}from"./chunk-5XN2OMBS.js";import"./chunk-EFGAPAYZ.js";import{a as $y,c as ky,d as vy}from"./chunk-FFOGEFPT.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{n as rd}from"./chunk-XV7IHWQE.js";import{a as Dy,b as Py,d as Ur,e as My}from"./chunk-AZCGU5XU.js";import{b as Mo}from"./chunk-7NQQIDDI.js";import{a as ey,c as ty}from"./chunk-PSUOF7O5.js";import"./chunk-WMZ4TGMR.js";import{d as sy,e as td,h as ry,i as iy}from"./chunk-6UI7GJSB.js";import"./chunk-2YDG5CSS.js";import{a as Zl}from"./chunk-LNY6N73E.js";import{b as Yp}from"./chunk-TN3XNBQN.js";import{a as Wp,b as Il}from"./chunk-GMP2IB4E.js";import{a as Al,b as xp}from"./chunk-CIW37UJT.js";import{$ as mh,A as Ll,Aa as qr,B as qf,Ba as Mh,C as ql,Ca as ht,D as Ff,Da as ya,E as Uf,Ea as wa,F as Wf,Fa as Fr,G as Bf,Ga as Xl,H as Jf,Ha as Lh,I as Gf,Ia as Fh,J as Fl,Ja as Ql,K as zf,Ka as Wh,L as da,La as ba,M as Yf,Ma as qs,N as Ul,Na as $a,O as Xf,Oa as ed,P as Vf,Pa as Bh,Q as Qf,R as Zf,S as eh,T as ua,U as rh,V as ch,W as lh,X as dh,Y as uh,Z as gh,_ as Bl,a as Kp,aa as ph,b as Xp,ba as fh,ca as hh,da as yh,ea as wh,fa as bh,ga as $h,h as ea,ha as kh,i as Ds,ia as vh,j as ef,ja as Ch,k as Dr,ka as pa,l as ta,la as Po,m as of,ma as Qo,n as sf,na as Ps,o as $f,oa as fa,p as kf,pa as ha,q as aa,qa as Kl,r as Ml,ra as Oh,s as Tf,sa as Ih,t as jf,ta as Nh,u as _f,ua as jh,v as Df,va as _h,w as Pf,wa as Dh,x as la,xa as Ms,y as Mf,ya as Ls,z as Lf,za as Ph}from"./chunk-3XS7M5LM.js";import{Bb as Rh,Cb as Th,Db as zl,Kb as Yl,M as Pr,N as Cf,Q as Of,R as ca,Zb as qh,_b as Vl,ab as Mr,db as Jl,eb as ga,fb as xh,ia as Hf,ja as Kf,mb as Vo,mc as fo,nb as Sh,ob as Hl,oc as Uh,pa as th,qa as oh,qb as Gl,ra as nh,sa as Wl,sb as Eh,t as nf,tb as Ah,ub as Lr,va as sh,yb as ma}from"./chunk-E3SA7KIZ.js";import"./chunk-GTJIKXDB.js";import{a as Vp,c as _l,d as _r,f as Qp,g as Zp}from"./chunk-NCMPJPXG.js";import{A as oa,B as na,C as af,D as cf,E as lf,G as df,H as uf,I as gf,J as mf,K as pf,L as ff,M as hf,N as yf,S as sa,T as wf,U as bf,Y as If,Z as Nf,i as Sl,j as yp,m as wp,n as bp,w as rf}from"./chunk-5CUOKXOD.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-SYIDD7CI.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as ih,b as ah}from"./chunk-EKJG63EJ.js";import"./chunk-GO4J44UD.js";import{c as vf}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import{c as Pl}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as xf,e as ra,g as ia}from"./chunk-LQE73AZR.js";import{a as Sf,b as Ef,c as Af,d as Rf}from"./chunk-2D3RYIDU.js";import{a as Ut}from"./chunk-4UJDRI7W.js";import"./chunk-MRIVENBY.js";import"./chunk-A5GYG56I.js";import{a as Dl,p as tf}from"./chunk-XC3466Z4.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Ft}from"./chunk-UKUH662W.js";import{a as Ip,b as Np,c as jp,d as _p,e as Tl,f as Dp,g as Cl,h as Ol,l as Pp,m as Mp}from"./chunk-RX5O5637.js";import{f as Lp,i as qp,l as Fp,m as Up}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{n as Bp,o as Jp,p as Nl,q as Zi,r as Hp,s as Gp}from"./chunk-D5LIMOI6.js";import{b as jl,d as zp}from"./chunk-SQP6A5AG.js";import{a as El,d as $p,e as Qi}from"./chunk-QPABR72X.js";import{b as _s,e as vp}from"./chunk-IFUAP7UD.js";import{c as kp}from"./chunk-KP7KDLZ2.js";import{J as bl,K as Vm,Na as hp,Y as Xo,ca as gp,fa as pp,ga as fp,l as Um,w as Wm,x as Bm,y as Jm}from"./chunk-RHNOMUYZ.js";import{I as Cs,J as Xi,K as Vi,L as Os,M as Zm,N as Yo,P as Ko,b as Ts,ha as dp,r as jo,s as $l,t as Qm,u as kl,w as _o,wa as up,x as Ki,ya as mp}from"./chunk-5RCWAXVK.js";import{b as Tn}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-M6TZ7IIJ.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{a as jr,e as Sp,f as Ep,g as Rl,i as Ap,j as Rp,l as Tp,m as Cp,n as Op}from"./chunk-AEFO6ES5.js";import{f as op,g as np,h as vl}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import{e as rp,f as Do,k as Ns}from"./chunk-IH65GDJR.js";import{a as Km,l as sp,o as lp}from"./chunk-NW7B53KD.js";import{a as Fe,b as pe,c as Ge,d as js,e as ip}from"./chunk-5BT4VPJC.js";import{a as ap,b as xl,h as cp}from"./chunk-3UOTLMXD.js";import"./chunk-XVV7ZZ77.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Xm}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import{a as Is}from"./chunk-GV7S5BAX.js";import{e as ep}from"./chunk-GSX4NK2N.js";import{c as tp}from"./chunk-SZDACK6O.js";import"./chunk-VWTBHLMX.js";import"./chunk-6EJJKOMW.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as Gm,j as zm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as wl,b as Ym}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as hl,p as qm,w as Fm}from"./chunk-XQH4LCZR.js";import{e as _m,f as Rn,g as Dm,h as Rs,k as Pm,l as Mm,n as Lm,o as fl,s as Gi,t as jt,u as zi}from"./chunk-BXK5S2KK.js";import{a as po}from"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import{b as yl}from"./chunk-JMRFYGET.js";import"./chunk-ABMDDRZL.js";import{g as zo,i as Yi}from"./chunk-5QXRGX2F.js";import"./chunk-WPNRDEHW.js";import{c as Hm}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-JD5TCX4X.js";import{a as rl,b as Gg,c as xS,d as Di,e as zg,f as Am,g as DS,h as Rm,i as PS,m as As,n as Cm,q as Om,u as Im,y as mo,z as Nr}from"./chunk-Y6KR7NXL.js";import{a as No,b as Es,e as xm,f as Ir}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Hi,b as Tm}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as jm}from"./chunk-BYEL7KKR.js";import{h as Go,j as Nm}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as go,b as vS}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as im,Ca as dm,Cc as Z,Da as um,Ea as ll,I as qi,Ib as bm,J as om,Jb as En,Lb as ul,M as qt,N as al,Oa as Ui,P as nm,Pa as Wi,Q as Fi,S as RS,Sa as gm,Sb as gl,Tb as ml,Ua as mm,Va as Ss,Vb as $m,Wa as dl,Wb as NS,Xa as pm,_ as rm,aa as am,ac as vm,b as il,c as Yg,ca as cm,d as Pi,da as lm,db as fm,e as Kg,ea as CS,f as Xg,fb as hm,gb as ym,h as Vg,i as Mi,j as Qg,l as SS,mc as pl,na as cl,oa as OS,q as Zg,qc as Bi,r as ES,rc as An,sc as O,t as em,vb as wm,vc as Ji,w as AS,x as Li,y as tm,ya as xs,za as Or,zb as IS}from"./chunk-VOVDWFFP.js";import"./chunk-KEUW6YLL.js";import{j as He,r as Io}from"./chunk-N47Y5ADQ.js";import{a as sm,e as TS}from"./chunk-VQRY4IDI.js";import{a as km,c as jS}from"./chunk-YSCT6DPR.js";import{g as Sm,k as Em,l as _S}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as MS}from"commander";var By=new MS().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 Xp({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()});Z();import{Command as LS}from"commander";import{execFileSync as ho}from"node:child_process";import{cpSync as Jy,existsSync as cd,mkdirSync as id,mkdtempSync as qS,readdirSync as FS,rmSync as Hy,writeFileSync as Gy}from"node:fs";import{dirname as zy,join as yt}from"node:path";import{homedir as va,release as US,tmpdir as WS}from"node:os";import{setTimeout as BS}from"node:timers/promises";function xa(){let e=af(process.platform,process.arch,US());if(e)throw new Error(e)}function Sa(){let e=yt(va(),"Library/LaunchAgents"),t=[];try{t=FS(e).filter(df)}catch{}let o=t.flatMap(n=>{let s=yt(e,n);try{return[{file:s,plist:ho("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return uf(e,o)}function Wr(e){return`gui/${process.getuid()}/${e.label}`}async function ad(e){try{ho("launchctl",["bootout",Wr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{return}await BS(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Yy(e){if(!cd(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{t=!1}t||ho("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ho("launchctl",["kickstart",Wr(e)],{stdio:"pipe"})}function JS(){let e=yf();if(e&&cd(yt(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 Ws=new LS("desktop").description("install and control the macOS desktop assistant");Ws.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=>{xa();let t=O(),o=cf(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=JS(),i=yt(va(),"Applications"),{keep:a,remove:c}=Sa();if(console.log(`Desktop assistant \u2192 ${yt(i,oa)}
|
|
1
|
+
import{a as Uy,b as ka,g as Wy}from"./chunk-U476QMLK.js";import{n as rd}from"./chunk-XV7IHWQE.js";import{a as qy,b as Fy}from"./chunk-XPYZBWI7.js";import{b as Ly}from"./chunk-WQTPSXVB.js";import{a as Dy,b as Py,d as Ur,e as My}from"./chunk-AZCGU5XU.js";import{d as sy,e as td,h as ry,i as iy}from"./chunk-6UI7GJSB.js";import{$ as yy,A as ny,B as ay,C as cy,E as ly,G as dy,H as uy,I as od,J as gy,U as my,V as py,W as nd,X as fy,_ as hy,aa as wy,ba as by,ca as xy,da as Sy,ea as Ey,fa as Ay,g as Jh,ga as Ry,h as Hh,ha as Ty,ja as sd,ka as Cy,l as Gh,la as Oy,m as zh,na as Iy,o as Fs,p as Us,q as Yh,qa as Ny,r as Kh,ra as jy,s as Xh,sa as _y,t as Vh,u as Qh,v as Zh,x as Xt,z as oy}from"./chunk-AAPHOKWS.js";import"./chunk-EFGAPAYZ.js";import{a as $y,c as ky,d as vy}from"./chunk-FFOGEFPT.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{b as Mo}from"./chunk-7NQQIDDI.js";import{a as ey,c as ty}from"./chunk-O4EQAPBB.js";import"./chunk-WMZ4TGMR.js";import"./chunk-2YDG5CSS.js";import{a as Zl}from"./chunk-LNY6N73E.js";import{b as Yp}from"./chunk-TN3XNBQN.js";import{a as Wp,b as Il}from"./chunk-GMP2IB4E.js";import{a as Al,b as xp}from"./chunk-CIW37UJT.js";import{$ as mh,A as Ll,Aa as qr,B as qf,Ba as Mh,C as ql,Ca as ht,D as Ff,Da as ya,E as Uf,Ea as wa,F as Wf,Fa as Fr,G as Bf,Ga as Xl,H as Jf,Ha as Lh,I as Gf,Ia as Fh,J as Fl,Ja as Ql,K as zf,Ka as Wh,L as da,La as ba,M as Yf,Ma as qs,N as Ul,Na as $a,O as Xf,Oa as ed,P as Vf,Pa as Bh,Q as Qf,R as Zf,S as eh,T as ua,U as rh,V as ch,W as lh,X as dh,Y as uh,Z as gh,_ as Bl,a as Kp,aa as ph,b as Xp,ba as fh,ca as hh,da as yh,ea as wh,fa as bh,ga as $h,h as ea,ha as kh,i as Ds,ia as vh,j as ef,ja as Ch,k as Dr,ka as pa,l as ta,la as Po,m as of,ma as Qo,n as sf,na as Ps,o as $f,oa as fa,p as kf,pa as ha,q as aa,qa as Kl,r as Ml,ra as Oh,s as Tf,sa as Ih,t as jf,ta as Nh,u as _f,ua as jh,v as Df,va as _h,w as Pf,wa as Dh,x as la,xa as Ms,y as Mf,ya as Ls,z as Lf,za as Ph}from"./chunk-AAQOXNLE.js";import{Bb as Rh,Cb as Th,Db as zl,Kb as Yl,M as Pr,N as Cf,Q as Of,R as ca,Zb as qh,_b as Vl,ab as Mr,db as Jl,eb as ga,fb as xh,ia as Hf,ja as Kf,mb as Vo,mc as fo,nb as Sh,ob as Hl,oc as Uh,pa as th,qa as oh,qb as Gl,ra as nh,sa as Wl,sb as Eh,t as nf,tb as Ah,ub as Lr,va as sh,yb as ma}from"./chunk-RMB6G7X2.js";import"./chunk-GTJIKXDB.js";import{a as Vp,c as _l,d as _r,f as Qp,g as Zp}from"./chunk-NCMPJPXG.js";import{A as oa,B as na,C as af,D as cf,E as lf,G as df,H as uf,I as gf,J as mf,K as pf,L as ff,M as hf,N as yf,S as sa,T as wf,U as bf,Y as If,Z as Nf,i as Sl,j as yp,m as wp,n as bp,w as rf}from"./chunk-VYNM7HYU.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-KQ3LPQ2Z.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as ih,b as ah}from"./chunk-EKJG63EJ.js";import"./chunk-GO4J44UD.js";import{b as Ft}from"./chunk-UKUH662W.js";import{c as vf}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import{c as Pl}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as xf,e as ra,g as ia}from"./chunk-LQE73AZR.js";import{a as Sf,b as Ef,c as Af,d as Rf}from"./chunk-2D3RYIDU.js";import{a as Ut}from"./chunk-4UJDRI7W.js";import"./chunk-A5GYG56I.js";import{a as Dl,p as tf}from"./chunk-XC3466Z4.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{a as Ip,b as Np,c as jp,d as _p,e as Tl,f as Dp,g as Cl,h as Ol,l as Pp,m as Mp}from"./chunk-RX5O5637.js";import{f as Lp,i as qp,l as Fp,m as Up}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{n as Bp,o as Jp,p as Nl,q as Zi,r as Hp,s as Gp}from"./chunk-D5LIMOI6.js";import{b as jl,d as zp}from"./chunk-SQP6A5AG.js";import{a as El,d as $p,e as Qi}from"./chunk-QPABR72X.js";import{a as jr,e as Sp,f as Ep,g as Rl,i as Ap,j as Rp,l as Tp,m as Cp,n as Op}from"./chunk-AEFO6ES5.js";import{b as _s,e as vp}from"./chunk-IFUAP7UD.js";import{c as kp}from"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{J as bl,K as Vm,Na as hp,Y as Xo,ca as gp,fa as pp,ga as fp,l as Um,w as Wm,x as Bm,y as Jm}from"./chunk-575LJSX2.js";import{I as Cs,J as Xi,K as Vi,L as Os,M as Zm,N as Yo,P as Ko,b as Ts,ha as dp,r as jo,s as $l,t as Qm,u as kl,w as _o,wa as up,x as Ki,ya as mp}from"./chunk-FRYEUVYD.js";import{b as Tn}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-LO5A3VKY.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as tp}from"./chunk-EFXZACH4.js";import{f as op,g as np,h as vl}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import{e as rp,f as Do,k as Ns}from"./chunk-IH65GDJR.js";import{a as Km,l as sp,o as lp}from"./chunk-NW7B53KD.js";import{a as Fe,b as pe,c as Ge,d as js,e as ip}from"./chunk-5BT4VPJC.js";import{a as ap,b as xl,h as cp}from"./chunk-3UOTLMXD.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Xm}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import{a as Is}from"./chunk-GV7S5BAX.js";import{e as ep}from"./chunk-GSX4NK2N.js";import"./chunk-FG2FPOML.js";import"./chunk-VWTBHLMX.js";import"./chunk-6EJJKOMW.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as Gm,j as zm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as wl,b as Ym}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as hl,p as qm,w as Fm}from"./chunk-74MHOALB.js";import{e as _m,f as Rn,g as Dm,h as Rs,k as Pm,l as Mm,n as Lm,o as fl,s as Gi,t as jt,u as zi}from"./chunk-3323WFVK.js";import{a as po}from"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import{b as yl}from"./chunk-JMRFYGET.js";import"./chunk-ABMDDRZL.js";import{g as zo,i as Yi}from"./chunk-5QXRGX2F.js";import"./chunk-WPNRDEHW.js";import{c as Hm}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-JD5TCX4X.js";import{a as rl,b as Gg,c as xS,d as Di,e as zg,f as Am,g as DS,h as Rm,i as PS,m as As,n as Cm,q as Om,u as Im,y as mo,z as Nr}from"./chunk-Y6KR7NXL.js";import{a as No,b as Es,e as xm,f as Ir}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Hi,b as Tm}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as jm}from"./chunk-BYEL7KKR.js";import{h as Go,j as Nm}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as go,b as vS}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as im,Ca as dm,Cc as Z,Da as um,Ea as ll,I as qi,Ib as bm,J as om,Jb as En,Lb as ul,M as qt,N as al,Oa as Ui,P as nm,Pa as Wi,Q as Fi,S as RS,Sa as gm,Sb as gl,Tb as ml,Ua as mm,Va as Ss,Vb as $m,Wa as dl,Wb as NS,Xa as pm,_ as rm,aa as am,ac as vm,b as il,c as Yg,ca as cm,d as Pi,da as lm,db as fm,e as Kg,ea as CS,f as Xg,fb as hm,gb as ym,h as Vg,i as Mi,j as Qg,l as SS,mc as pl,na as cl,oa as OS,q as Zg,qc as Bi,r as ES,rc as An,sc as O,t as em,vb as wm,vc as Ji,w as AS,x as Li,y as tm,ya as xs,za as Or,zb as IS}from"./chunk-VOVDWFFP.js";import"./chunk-KEUW6YLL.js";import{j as He,r as Io}from"./chunk-N47Y5ADQ.js";import{a as sm,e as TS}from"./chunk-VQRY4IDI.js";import{a as km,c as jS}from"./chunk-YSCT6DPR.js";import{g as Sm,k as Em,l as _S}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as MS}from"commander";var By=new MS().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 Xp({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()});Z();import{Command as LS}from"commander";import{execFileSync as ho}from"node:child_process";import{cpSync as Jy,existsSync as cd,mkdirSync as id,mkdtempSync as qS,readdirSync as FS,rmSync as Hy,writeFileSync as Gy}from"node:fs";import{dirname as zy,join as yt}from"node:path";import{homedir as va,release as US,tmpdir as WS}from"node:os";import{setTimeout as BS}from"node:timers/promises";function xa(){let e=af(process.platform,process.arch,US());if(e)throw new Error(e)}function Sa(){let e=yt(va(),"Library/LaunchAgents"),t=[];try{t=FS(e).filter(df)}catch{}let o=t.flatMap(n=>{let s=yt(e,n);try{return[{file:s,plist:ho("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return uf(e,o)}function Wr(e){return`gui/${process.getuid()}/${e.label}`}async function ad(e){try{ho("launchctl",["bootout",Wr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{return}await BS(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Yy(e){if(!cd(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{t=!1}t||ho("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ho("launchctl",["kickstart",Wr(e)],{stdio:"pipe"})}function JS(){let e=yf();if(e&&cd(yt(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 Ws=new LS("desktop").description("install and control the macOS desktop assistant");Ws.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=>{xa();let t=O(),o=cf(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=JS(),i=yt(va(),"Applications"),{keep:a,remove:c}=Sa();if(console.log(`Desktop assistant \u2192 ${yt(i,oa)}
|
|
2
2
|
Computer-use helper \u2192 ${yt(i,na)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -39,7 +39,7 @@ ${o.map(n=>` ${n}`).join(`
|
|
|
39
39
|
`)}}}},schedules:{"support-evening-open-questions":{agent:"support",schedule:"0 18 * * 1-5",prompt:"List the questions in open-questions.md that are still open: customer, question, since when. Then a count of the questions you answered today from docs/. Six lines at most. If nothing is open, say so in one line.",timeout:600,maxOutputTokens:500,autonomy:"report"},"support-weekly-doc-gaps":{agent:"support",schedule:"0 16 * * 5",prompt:"Read this week's lines in open-questions.md. Group the questions by topic and, for each topic, say which document in docs/ should answer it next time and the one sentence to add. Five topics at most. If there were no open questions this week, say so in one line.",timeout:600,maxOutputTokens:600,autonomy:"report"}},channels:[{kind:"telegram",agent:"support",why:"where customers ask their questions"},{kind:"email",agent:"support",why:"optional: a support mailbox; each reply waits for your approval, with its source"}]};var Vw=[Gw,Xw,zw,Yw,Kw];function ja(){return Vw.map(e=>Ys(e))}function Zo(e){let t=Vw.find(o=>o.name===e);return t?Ys(t):void 0}Z();import{existsSync as iA,readFileSync as aA}from"fs";import{connect as cA}from"net";import{cpus as lA,loadavg as dA}from"os";import{basename as uA,resolve as gA}from"path";function _a(e=process.argv[1]??"",t=process.env){let o=e.replace(/\\/g,"/");return t.npm_command==="exec"||o.includes("/_npx/")?"npx agentix-cli":uA(o)==="cli.js"&&!o.includes("/node_modules/")?"node dist/cli.js":"agentx"}function eb(e,t){return t?` Every hop of this run is in the ledgers, one per node: \`${e} ledger events --cwd .agentx-demo/node-a\`.`:""}async function tb(e,t="127.0.0.1"){let o=await Promise.all(e.map(n=>new Promise(s=>{let r=cA({port:n,host:t}),i=a=>{r.destroy(),s(a)};r.setTimeout(1e3,()=>i(!1)),r.once("connect",()=>i(!0)),r.once("error",()=>i(!1))})));return e.filter((n,s)=>o[s])}var Qw="AGENTX_DEMO_STARTUP_TIMEOUT",mA=60,pA=300;function fA(e,t){let o=Math.max(1,e/Math.max(1,t));return Math.min(pA,Math.ceil(mA*o))}function Zw(e,t){if(e===void 0||e.trim()==="")return;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new Error(`${t} must be a positive number of seconds, got "${e}"`);return o}function ob(e){let t=gA(e,"agentx.json");if(!iA(t))return;let o;try{o=JSON.parse(aA(t,"utf8"))}catch{return}let n=Bi.shape.demo.safeParse(o?.demo);if(!n.success)throw new Error(`${t}: demo.startupTimeoutSeconds must be a whole number of seconds (1\u20133600)`);return n.data.startupTimeoutSeconds}function nb(e){let t=Zw(e.flag,"--startup-timeout");if(t!==void 0)return{seconds:t,source:"--startup-timeout"};let o=Zw(e.env,Qw);if(o!==void 0)return{seconds:o,source:Qw};if(e.config!==void 0)return{seconds:e.config,source:"demo.startupTimeoutSeconds"};let n=e.load1??dA()[0],s=e.cpuCount??lA().length;return{seconds:fA(n,s),source:`default for load ${n.toFixed(1)} on ${s} CPUs`}}import{Command as hA}from"commander";import ye from"chalk";import{cpSync as yA,existsSync as Xs,mkdirSync as sb,readFileSync as Ed,writeFileSync as wA}from"fs";import{dirname as Sd,resolve as jn}from"path";import{fileURLToPath as bA}from"url";var rb=["claude-code","codex-cli","opencode","sdk","orchestrator"];function Ad(e){let t=Fe(e);return Xs(t)||(console.log(ye.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),{path:t,config:JSON.parse(Ed(t,"utf-8"))}}function _t(e){console.log(ye.red(` ${e.split(`
|
|
40
40
|
`).join(`
|
|
41
41
|
`)}`)),process.exit(1)}function ib(e){let t=jn(e);Xs(t)||_t(`No file at ${t}`);let o;try{o=JSON.parse(Ed(t,"utf-8"))}catch(n){_t(`${t} is not JSON: ${n.message}`)}try{return Ys(o)}catch(n){_t(n.message)}}function $A(e){let t=Zo(e);if(t)return t;if(Xs(jn(e))||e.endsWith(".json"))return ib(e);_t(`No team named "${e}". Run: agentx team list`)}async function Da(e,t){t.tier&&!rb.includes(t.tier)&&_t(`--tier must be one of: ${rb.join(", ")}`);let{path:o,config:n}=Ad(t.config),s=jn(Sd(o),t.workspaces??"agents"),r=Ks(n,e,{workspaceRoot:s,force:t.force});r.length&&_t(`Already in this install: ${r.join(", ")}.
|
|
42
|
-
Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choose another --workspaces folder, or edit the package's ids.`);let i,a=await pe(d=>{i=Uw(d,e,{workspaceRoot:s,tier:t.tier,provider:t.provider,timezone:t.timezone,force:t.force})},{configPath:o,dryRun:!!t.dryRun});(!a.success||!i)&&_t(`Config save failed: ${a.error}`),console.log(),console.log(` ${ye.bold(e.title)}${t.dryRun?ye.yellow(" (dry run: nothing written)"):""}`),console.log(ye.dim(` ${e.result}`)),console.log();let c=[];if(!t.dryRun){let{setupWorkspace:d}=await import("./workspace-setup-
|
|
42
|
+
Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choose another --workspaces folder, or edit the package's ids.`);let i,a=await pe(d=>{i=Uw(d,e,{workspaceRoot:s,tier:t.tier,provider:t.provider,timezone:t.timezone,force:t.force})},{configPath:o,dryRun:!!t.dryRun});(!a.success||!i)&&_t(`Config save failed: ${a.error}`),console.log(),console.log(` ${ye.bold(e.title)}${t.dryRun?ye.yellow(" (dry run: nothing written)"):""}`),console.log(ye.dim(` ${e.result}`)),console.log();let c=[];if(!t.dryRun){let{setupWorkspace:d}=await import("./workspace-setup-W32C7WXN.js"),p=kA();for(let f of i.agents){sb(f.workspace,{recursive:!0}),d(f.id,a.after&&a.after.agents[f.id],"19900",()=>{});let g=jn(f.workspace,".claude/skills/wiki/SKILL.md");p&&f.tier==="claude-code"&&!Xs(g)&&(sb(Sd(g),{recursive:!0}),yA(p,g,{errorOnExist:!0,force:!1}))}c=Bw(e,i).kept}let l=t.dryRun?void 0:Ki(jo(),i.agents.map(d=>d.id));for(let d of i.agents){let p=d.skills.length?ye.dim(` skills: ${d.skills.join(", ")}`):"";console.log(` ${ye.green("+")} agent ${ye.cyan(d.id)} (${d.tier})${p}`),console.log(ye.dim(` ${d.workspace}`))}for(let d of i.schedules){let p=a.after.crons[d];console.log(` ${ye.green("+")} schedule ${ye.cyan(d)} \u2014 ${p.schedule} (${p.timezone})${p.enabled?"":ye.dim(" disabled")}`)}if(a.reloaded&&console.log(ye.dim(" (daemon hot-reloaded)")),l&&console.log(ye.yellow(` Added by agent "${l}": these agents start once the owner approves each one (agentx approvals list).`)),c.length){console.log(ye.yellow(` Kept ${c.length} file${c.length===1?"":"s"} already there instead of the team's version:`));for(let d of c)console.log(ye.dim(` ${d}`))}if(i.channels.length){console.log(),console.log(ye.bold(" One step left: connect the channel"));let d=[...new Set(i.channels.map(p=>p.kind))];for(let p of d){let f=i.channels.filter(g=>g.kind===p);console.log(` ${f[0].step}`);for(let g of f)g.why&&console.log(ye.dim(` ${g.agent}: ${g.why}`))}}let{delivery:u}=i;u.schedules.length&&(console.log(),u.to?console.log(` Results go to you on ${u.to.channel} (${u.to.chatId}): ${u.schedules.join(", ")}`):(console.log(ye.bold(" Then tell AgentX where to send you the results")),console.log(` ${u.schedules.join(", ")} will send ${u.schedules.length===1?"its":"their"} answers once you do one of these:`),console.log(` agentx connect telegram ${ye.dim("(say yes when it offers to listen for your first message)")}`),console.log(` agentx team notify ${e.name} telegram:<chat id>`))),console.log()}function kA(){return[jn(process.cwd(),"src/wiki/SKILL.md"),jn(Sd(bA(import.meta.url)),"../wiki/SKILL.md")].find(t=>Xs(t))??null}var _n=new hA().name("team").description("ready-made teams \u2014 list, add one in one step, export and import");_n.command("list").alias("ls").description("list the teams you can add, and the teams installed here").option("-c, --config <path>","path to agentx.json").action(e=>{let t=Fe(e.config),o=Xs(t)?JSON.parse(Ed(t,"utf-8")):{},n=new Set(Object.values(o.agents||{}).map(r=>r?.team).filter(Boolean));console.log(),console.log(ye.bold(" Teams you can add"));for(let r of ja()){let i=n.has(r.name)?ye.green(" installed"):"";console.log(` ${ye.cyan(r.name)} \u2014 ${r.title}${i}`),console.log(ye.dim(` ${r.result}`))}let s=[...n].filter(r=>!Zo(r)).sort();if(s.length){console.log(),console.log(ye.bold(" Other teams installed here"));for(let r of s)console.log(` ${ye.cyan(r)} \u2014 ${Nn(o,r).join(", ")}`)}console.log(),console.log(ye.dim(" Add one: agentx team add <name>")),console.log()});_n.command("add <name>").description("add a team: its agents, skills and schedules. <name> is a team from `team list` or a package file").option("--tier <tier>","runtime for every agent of the team (default: the package's, else claude-code)").option("--timezone <tz>","time zone for schedules that do not set one (default: this machine's)").option("--workspaces <dir>","folder for the agents' workspaces, next to agentx.json","agents").option("--force","use workspace folders that already exist; files in them are never overwritten").option("--dry-run","show what would be added, write nothing").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Da($A(e),t)});_n.command("import <file>").description("add a team from a package file made by `team export`").option("--tier <tier>","runtime for every agent of the team (default: the package's, else claude-code)").option("--timezone <tz>","time zone for schedules that do not set one (default: this machine's)").option("--workspaces <dir>","folder for the agents' workspaces, next to agentx.json","agents").option("--force","use workspace folders that already exist; files in them are never overwritten").option("--dry-run","show what would be added, write nothing").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await Da(ib(e),t)});_n.command("notify <name> [target]").description(`send the answers of a team's schedules to you. [target]: "me" (notifications.destination, the default) or "channel:chatId[:accountId]"`).option("-c, --config <path>","path to agentx.json").action(async(e,t,o)=>{let{path:n,config:s}=Ad(o.config),r=Nn(s,e);r.length||_t(`No agents belong to team "${e}". Run: agentx team list`);let i=vA(t??"me",s),a=Object.entries(s.crons||{}).filter(([,u])=>r.includes(u?.agent)&&u.deliverResult===!0).map(([u])=>u);a.length||_t(`Team "${e}" has no schedules that report to you.`);let c=[],l=await pe(u=>{c=Na(u,i,{ids:a,replace:!0})},{configPath:n});l.success||_t(`Config save failed: ${l.error}`),console.log(ye.green(` Results of ${c.join(", ")} now go to ${i.channel} (${i.chatId})`)),l.reloaded&&console.log(ye.dim(" (daemon hot-reloaded)"))});function vA(e,t){if(e==="me"){let r=xd(t);return r||_t('No notifications.destination yet. Run: agentx connect telegram, or give "channel:chatId".'),r}let[o,n,s]=e.split(":");return(!o||!n)&&_t(`Not a target: ${e} (use "me" or "channel:chatId[:accountId]")`),s?{channel:o,chatId:n,accountId:s}:{channel:o,chatId:n}}_n.command("export <name>").description("write a team to one file you can share: agents, prompts, skills, schedules, channel kinds. No channel config, tokens checked").option("-o, --output <file>","file to write; - prints it (default: <name>.team.json)").option("--agents <ids...>","agents to export (default: the agents installed with this team)").option("--title <text>","title shown in `team list`").option("--result <text>","one line: the result this team delivers").option("--description <text>","a few lines on how the team works").option("-c, --config <path>","path to agentx.json").action((e,t)=>{let{config:o}=Ad(t.config),n=Zo(e),s;try{s=Jw(o,e,{agents:t.agents,title:t.title??n?.title,result:t.result??n?.result,description:t.description??n?.description,expectedChannels:n?.channels})}catch(l){_t(l.message)}let r=JSON.stringify(s,null,2)+`
|
|
43
43
|
`;if(t.output==="-"){process.stdout.write(r);return}let i=jn(t.output??`${e}.team.json`);wA(i,r);let a=Object.keys(s.agents).length,c=Object.keys(s.schedules).length;console.log(ye.green(` Team "${e}" written to ${i}`)),console.log(ye.dim(` ${a} agent${a===1?"":"s"}, ${c} schedule${c===1?"":"s"}; no chat ids, contacts, routes or commands`)),console.log(ye.dim(" Common token formats were checked; read the prompts and skills for passwords before you share it.")),console.log(ye.dim(` On the other install: agentx team import ${i.split("/").pop()}`))});import{existsSync as xA}from"fs";import{resolve as ab}from"path";var Rd="assistant";function cb(e){for(let t of[ab(e,"agentx.json"),ab(e,".agentx/config.json")])if(xA(t))return t;return null}function lb(e,t){return{nodeName:e.trim()||"My team",agent:{id:Rd,name:"Assistant",triggerWords:`@${Rd}, ${Rd}`,...t?{tier:"claude-code"}:{tier:"orchestrator",provider:"claude"}}}}function Td(e){let t=Object.keys(e.agents||{}),o=e.node?.defaultAgent;return o&&t.includes(o)?o:t[0]??null}function db(e){return`http://${e.replace(/^0\.0\.0\.0(?=:)/,"127.0.0.1").replace(/^\[::\](?=:)/,"127.0.0.1")}`}function ub(e){return db(e.node?.bind||"127.0.0.1:18800")}function Cd(e){return db(`${e.dashboard?.bind||"127.0.0.1"}:${e.dashboard?.port||4202}`)}function gb(e,t){return`${Cd(e)}/admin/agents/${encodeURIComponent(t)}#chat`}function mb(e,t){let o=e?.node?.id;return!o||!t.node?.id||o===t.node.id}function pb(e,t,o){let n=Zo(t);if(!n)return{error:`No team named "${t}".`};if(Nn(e,n.name).length)return{skip:`Team ${n.name} is already added (left as it is)`};let s=o?.workspaceRoot?Ks(e,n,{workspaceRoot:o.workspaceRoot}):Ks(e,n);if(s.length)return{error:`Team ${n.name} can't be added: already in this folder: ${s.join(", ")}. Remove or rename them, or run start without --team.`};let r=e.agents?.[Td(e)??""];return{add:{team:n.name,tier:r?.tier,provider:r?.provider}}}var vb=new SA().name("start").description("one command to a working agent: config, daemon, dashboard, and the chat in your browser").option("--port <n>","daemon port for a new install (default 18800; an existing agentx.json keeps its own)").option("--dashboard-port <n>","dashboard port for a new install (default 4202)").option("--startup-timeout <seconds>","seconds the daemon and the dashboard each may take to answer","60").option("--team <name>","also add a ready-made team (see `agentx team list`); a first run in a terminal asks").option("--no-open","don't open the browser").action(async e=>{let t=process.cwd(),o=_a(),n=process.argv[1];(!n||!fb(n))&&Dn("Cannot resolve the agentx CLI entrypoint. Run it as `agentx start` or `npx agentix-cli start`.");let s=Math.max(1,Number(e.startupTimeout)||60)*1e3;console.log(),console.log(at.bold(" agentx start"));let r=cb(t),i=!r,a=i?lb(OA().replace(/\.local$/,""),!!Yl("claude")):void 0,c=e.team??(i&&process.stdin.isTTY&&process.stdout.isTTY?await NA():void 0),l=c?pb(r?JSON.parse(hb(r,"utf-8")):{agents:{[a.agent.id]:a.agent}},c,{workspaceRoot:Ma(r?IA(r):t,"agents")}):void 0;l&&"error"in l&&Dn(`${l.error} See \`${o} team list\`.`),r?console.log(at.dim(` Using ${r} (left as it is)`)):(Hh(a,t,{daemonPort:yb(e.port,"--port"),dashboardPort:yb(e.dashboardPort,"--dashboard-port")}),r=Ma(t,"agentx.json"),console.log(at.green(` \u2713 Created agentx.json with one agent, ${a.agent.id} (engine: ${a.agent.tier})`)));let u=!1;l&&"skip"in l&&console.log(at.dim(` ${l.skip}`)),l&&"add"in l&&(await Da(Zo(l.add.team),{config:r,tier:l.add.tier,provider:l.add.provider}),u=!0);let d;try{d=O(r)}catch(x){Dn(`${r}: ${x.message}`)}let p=Td(d);p||Dn(`No agent in ${r}. Add one with \`${o} setup\`, then run \`${o} start\` again.`);let f=Ma(t,".agentx");RA(f,{recursive:!0});let g=ub(d),h=await bb(g);if(h&&!mb(h,d)&&Dn(`${g} is another AgentX install (${h.node?.name||h.node?.id}). Run this one on another port: set node.bind in ${r}, or for a new folder use \`${o} start --port 18810 --dashboard-port 4212\`.`),h)console.log(at.green(` \u2713 Daemon already running at ${g}`)),u&&console.log(at.yellow(` Restart it to start the team's agents: ${o} daemon restart`));else{let x=Pa(f,"daemon.log");wb(n,["daemon","start","-c",r],t,x),await kb(`the daemon at ${g}`,async()=>!!await bb(g),s,x),console.log(at.green(` \u2713 Daemon started at ${g}`)+at.dim(` (log: ${x})`))}let y=Cd(d);if(await $b(`${y}/live`))console.log(at.green(` \u2713 Dashboard already running at ${y}`));else{let x=Pa(f,"board.log"),k=wb(n,["board","serve"],t,x);k&&CA(Pa(f,"board.pid"),String(k)),await kb(`the dashboard at ${y}`,()=>$b(`${y}/live`),s,x),console.log(at.green(` \u2713 Dashboard started at ${y}`)+at.dim(` (log: ${x})`))}let w=gb(d,p),$=d.agents[p]?.name||p,S=Gh({rawConfig:JSON.parse(hb(r,"utf-8")),agentId:p,env:process.env,dotenv:jm(Ma(t,".env")),hasBinary:x=>!!Yl(x),cliLoggedIn:zh});console.log(),S.ready?console.log(at.bold(` Your first agent, ${$}, is answering at ${at.cyan(w)}`)):(console.log(at.bold(` Your first agent, ${$}, is waiting for a model at ${at.cyan(w)}`)),S.hint&&console.log(` ${S.hint}`)),console.log(at.dim(` Run \`${o} start\` again any time: it reuses what is running.`));let v=Pa(f,"board.pid");console.log(at.dim(` Stop the daemon: ${o} daemon stop`+(fb(v)?" \xB7 the dashboard: kill $(cat .agentx/board.pid)":""))),console.log(),e.open!==!1&&Mo(w)});async function NA(){let{team:e}=await EA({type:"select",name:"team",message:"Start with a ready-made team as well?",choices:[{title:"No, one assistant for now",value:""},...ja().map(t=>({title:`${t.name}: ${t.title}`,description:t.result,value:t.name}))],initial:0});return e||void 0}function Dn(e){console.error(at.red(` ${e}`)),process.exit(1)}function yb(e,t){if(e===void 0)return;let o=Number(e);return(!Number.isInteger(o)||o<1||o>65535)&&Dn(`${t} must be a port number, got "${e}"`),o}function wb(e,t,o,n){let s=TA(n,"a"),r=AA(process.execPath,[e,...t],{cwd:o,detached:!0,stdio:["ignore",s,s]});return r.unref(),r.pid}async function bb(e){try{let t=await fetch(`${e}/health`,{signal:AbortSignal.timeout(3e3)});return t.ok?await t.json().catch(()=>({})):null}catch{return null}}async function $b(e){try{return(await fetch(e,{signal:AbortSignal.timeout(3e3)})).ok}catch{return!1}}async function kb(e,t,o,n){let s=Date.now()+o;for(;Date.now()<s;){if(await t())return;await new Promise(r=>setTimeout(r,400))}Dn(`Timed out after ${o/1e3}s waiting for ${e}. See ${n}, or raise --startup-timeout.`)}import{Command as jA}from"commander";import tt from"chalk";var Xr=new jA().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Xr.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let t=new Ft,o=String(e.scope).split(",").map(i=>i.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:r}=t.create({name:e.name,scopes:o,expiresInDays:n});console.log(),console.log(tt.bold(" Token created.")),console.log(),console.log(` id: ${tt.cyan(r.id)}`),console.log(` name: ${r.name}`),console.log(` scopes: ${r.scopes.join(", ")}`),console.log(` expires: ${r.expiresAt||tt.dim("never")}`),console.log(),console.log(tt.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${tt.green.bold(s)}`),console.log(),console.log(tt.dim(" Use it via the Authorization header:")),console.log(tt.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(t){console.log(tt.red(` ${t.message}`)),process.exit(1)}});Xr.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new Ft().list();if(e.length===0){console.log(tt.dim(`
|
|
44
44
|
No tokens issued.
|
|
45
45
|
`));return}console.log();for(let t of e){let o=t.revokedAt?tt.red("revoked"):t.expiresAt&&Date.parse(t.expiresAt)<Date.now()?tt.red("expired"):tt.green("active");console.log(` ${tt.cyan(t.id)} ${o} ${t.name}`),console.log(tt.dim(` prefix: ${t.prefix}\u2026 scopes: ${t.scopes.join(", ")}`)),console.log(tt.dim(` created: ${t.createdAt}${t.expiresAt?` expires: ${t.expiresAt}`:""}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(tt.red(` ${e.message}`)),process.exit(1)}});Xr.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let t=new Ft().revoke(e);t||(console.log(tt.red(` Token ${e} not found.`)),process.exit(1)),console.log(tt.green(`
|
|
@@ -62,7 +62,7 @@ Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choos
|
|
|
62
62
|
`))});yo.command("unpin <id-or-label>").description("remove a pinned page from the phone app").action(e=>{let{store:t}=Od(),o=t.list().find(s=>s.id===e||s.label.toLowerCase()===e.toLowerCase());o||(console.log(se.red(` No pinned page ${e}. See: agentx app pins`)),process.exit(1));let n=t.remove(o.id);n.ok||(console.log(se.red(` ${n.error}`)),process.exit(1)),console.log(se.green(`
|
|
63
63
|
\u2713 Removed ${o.label}.
|
|
64
64
|
`))});function Ab(e){let t=He();return t||(console.log(se.red(" The database (.agentx/db.sqlite) can't be opened here.")),process.exit(1)),e(new Zl(t))}function MA(){let e=He({quiet:!0});if(!e)return[];let t=new Map;for(let o of new Zl(e).list()){if(!Pl(o.deviceId))continue;let n=t.get(o.deviceId)??{deviceId:o.deviceId,deviceName:o.deviceName,createdAt:o.createdAt,subscriptions:0};n.subscriptions++,n.createdAt=Math.max(n.createdAt,o.createdAt),t.set(o.deviceId,n)}return[...t.values()]}function LA(e){let t=Math.round(xf/6e4),o=[` Pairing code: ${se.bold.cyan(ra(e.code))}`,se.dim(` Open the app from the phone's home screen and type this code. It works once, for ${t} minutes.`)," Or scan the QR code with the phone's camera and open the link.",` Device ${se.cyan(e.deviceId)} (${e.deviceName}) paired to ${e.origin}.`,se.yellow(" \u26A0 Anyone who scans the QR code or types the code can use the app. Clear the terminal when done.")];return e.origin.startsWith("https://")||o.push(se.yellow(` \u26A0 ${e.origin} is not HTTPS: the phone can't install the app or keep the session from there.`)),o}function Id(){let e;try{e=JSON.parse(Eb("tailscale",["status","--json"],{encoding:"utf-8",timeout:5e3}))}catch{throw new Error("Could not read this machine's Tailscale name. Is Tailscale running? Or pass --url https://<address>.")}let t=String(e?.Self?.DNSName||"").replace(/\.$/,"");if(!t)throw new Error("Tailscale has no MagicDNS name for this machine. Pass --url https://<address>.");return`https://${t}`}var qA=new Set(["/app","/api/app","/member","/api/member"]),Sb="/.well-known/assetlinks.json";function FA(){let e=new Set(["localhost","0.0.0.0","::","::1"]);try{let t=DA().toLowerCase().replace(/\.$/,"");t&&e.add(t).add(t.replace(/\.local$/,"")).add(`${t.replace(/\.local$/,"")}.local`)}catch{}try{for(let t of Object.values(PA()))for(let o of t??[])e.add(Rb(o.address.toLowerCase().replace(/%.*$/,"")))}catch{}return e}var UA={http:80,https:443,"https+insecure":443};function WA(e){let t=e.match(/^(\d+)(\/[^?#]*)?$/);if(t)return{host:"localhost",port:Number(t[1]),path:t[2]??""};let o=e.match(/^(?:([a-z][a-z0-9+.-]*):\/\/)?(?:[^@/?#]*@)?(\[[^\]]*\]|[^/:?#]*)(?::(\d+))?([^?#]*)/i);if(!o)return null;let n=o[3]?Number(o[3]):UA[(o[1]??"http").toLowerCase()];return n?{host:Rb(o[2].replace(/^\[|\]$/g,"").replace(/%.*$/,"").replace(/\.$/,"").toLowerCase()),port:n,path:o[4]}:null}function Rb(e){let t=e.includes(":");if(!t&&!/^[0-9a-fx.]+$/.test(e))return e;let o;try{o=new URL(`http://${t?`[${e}]`:e}/`).hostname.replace(/^\[|\]$/g,"")}catch{return e}let n=o.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);if(!n)return o;let[s,r]=[parseInt(n[1],16),parseInt(n[2],16)];return`::ffff:${s>>8}.${s&255}.${r>>8}.${r&255}`}function BA(e,t){let o=e.replace(/^::ffff:/,"");return t.has(e)||t.has(o)||e===""||e.endsWith(".localhost")||/^127\.\d+\.\d+\.\d+$/.test(o)||o==="0.0.0.0"}function Nd(e,t,o=FA()){let n=[e,...Object.values(e?.Foreground??{})],s=[];for(let c of n){s.push({label:"",cfg:c});for(let[l,u]of Object.entries(c?.Services??{}))s.push({label:`${l} `,cfg:u})}let r=new Set(o);for(let{cfg:c}of s){for(let l of Object.keys(c?.Web??{}))r.add(l.replace(/:\d+$/,"").replace(/\.$/,"").toLowerCase());for(let l of Object.values(c?.TCP??{}))l?.TerminateTLS&&r.add(String(l.TerminateTLS).replace(/\.$/,"").toLowerCase())}let i=c=>{let l=WA(c.trim());return l&&l.port===t&&BA(l.host,r)?l:null},a=[];for(let{label:c,cfg:l}of s){for(let[u,d]of Object.entries(l?.Web??{}))for(let[p,f]of Object.entries(d?.Handlers??{})){if(f?.Proxy==null)continue;let g=i(String(f.Proxy));if(!g)continue;let h=p.replace(/\/+$/,"")||"/",y=h===Sb&&g.path===Sb;!qA.has(h)&&!y&&a.push(`${c}${u}${p}`)}for(let[u,d]of Object.entries(l?.TCP??{}))d?.TCPForward==null||!i(String(d.TCPForward))||a.push(`${c}TCP port ${u}`)}return a}function jd(){try{return JSON.parse(Eb("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Vr(){try{return O().dashboard.port||4202}catch{return 4202}}Z();import{Command as bo}from"commander";import b from"chalk";import ct from"prompts";import{readFileSync as tn,writeFileSync as Vs,existsSync as Ve,mkdirSync as wo,cpSync as Dd,readdirSync as JA}from"fs";import{resolve as ce,join as en,dirname as HA}from"path";import{fileURLToPath as GA}from"url";import{Command as Cb}from"commander";import Pn from"chalk";Z();gl();var Tb=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function Mn(e){console.error(Pn.red(` ${e}`)),process.exitCode=1}function Ob(e,t){let o;try{o=O()}catch(s){return Mn(`${s.message.split(`
|
|
65
|
-
`)[0]}. Run this from the folder that holds agentx.json.`),!1}let n=e==="agent"?!!o.agents?.[t]:t===En||(o.people??[]).some(s=>s.id===t);return n||Mn(e==="agent"?`No agent "${t}" in agentx.json.`:`No person "${t}" in agentx.json: agentx people list`),n}async function Ib(e,t,o){if(Ob(e,t))try{await Fp(process.cwd(),e,t,Wp(o)),console.log(Pn.green(` \u2713 picture set for ${e} "${t}". Pages show it on their next load.`))}catch(n){if(n instanceof Lp){Mn(n.message);return}throw n}}function Nb(e,t){Ob(e,t)&&console.log(Up(process.cwd(),e,t)?Pn.green(` \u2713 picture removed for ${e} "${t}"; the initials show again.`):Pn.dim(` ${e} "${t}" has no picture.`))}function _d(e){let t=e.agent?.trim()||_o();return t||Mn("Say which agent: --agent <id>"),t}function jb(){let e=new Cb("picture").description("an agent's profile picture: set, remove or show (an agent may set its own)");return e.command("set <file>").description("set the picture from a PNG, JPEG or WebP file (1 MB at most); it is cut to a square, metadata dropped").option("--agent <id>","which agent (default: the agent running this command)").action(async(t,o)=>{if(_o()){let s=await Il(t,o.agent?.trim(),{daemonUrl:Tb()});return s.ok?console.log(Pn.green(` \u2713 ${s.message}`)):Mn(s.message)}let n=_d(o);n&&await Ib("agent",n,t)}),e.command("remove").alias("rm").description("remove the picture: the initials show again").option("--agent <id>","which agent (default: the agent running this command)").action(async t=>{if(_o()){let n=await Il(null,t.agent?.trim(),{daemonUrl:Tb()});return n.ok?console.log(Pn.green(` \u2713 ${n.message}`)):Mn(n.message)}let o=_d(t);o&&Nb("agent",o)}),e.command("show").description("say whether the agent has a picture").option("--agent <id>","which agent (default: the agent running this command)").action(t=>{let o=_d(t);if(!o)return;let n=qp(process.cwd(),"agent",o);console.log(n?` ${o}: picture set (.agentx/pictures/agent/${o}.${n}.webp)`:Pn.dim(` ${o}: no picture, the initials show`))}),e}function _b(){let e=new Cb("picture").description("a person's profile picture: set or remove (the owner only)"),t=()=>{let o=_o();return o&&Mn(`Only the owner sets a person's picture; agent "${o}" asked.`),!o};return e.command("set <id> <file>").description("set the picture from a PNG, JPEG or WebP file (1 MB at most); it is cut to a square, metadata dropped").action(async(o,n)=>{t()&&await Ib("person",o,n)}),e.command("remove <id>").alias("rm").description("remove the picture: the initials show again").action(o=>{t()&&Nb("person",o)}),e}function Se(){let e=ce(process.cwd(),"agentx.json");if(!Ve(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(tn(e,"utf-8"))}function mt(e){return pe(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(b.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(b.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(b.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var $o=new bo().name("agent").description("manage agents \u2014 add, list, remove, pause, resume");$o.command("list").alias("ls").description("list configured agents").action(()=>{let e=Se();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${b.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(b.dim(` workspace: ${o.workspace}`)),n&&console.log(b.dim(` mentions: ${n}`))}console.log()});$o.command("add").description("add a new agent interactively").action(async()=>{let e=Se(),t=await ct([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:u=>/^[a-z0-9-]+$/.test(u)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:ce(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!t.id)return;let o=t.workspace.endsWith(t.id)?t.workspace:en(t.workspace,t.id);wo(ce(o,".claude/skills"),{recursive:!0});let n={name:t.name,workspace:o,tier:t.tier,model:t.model,mentions:t.mentions?.map(u=>u.trim()).filter(Boolean)||[],maxConcurrent:t.maxConcurrent,systemPrompt:t.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-
|
|
65
|
+
`)[0]}. Run this from the folder that holds agentx.json.`),!1}let n=e==="agent"?!!o.agents?.[t]:t===En||(o.people??[]).some(s=>s.id===t);return n||Mn(e==="agent"?`No agent "${t}" in agentx.json.`:`No person "${t}" in agentx.json: agentx people list`),n}async function Ib(e,t,o){if(Ob(e,t))try{await Fp(process.cwd(),e,t,Wp(o)),console.log(Pn.green(` \u2713 picture set for ${e} "${t}". Pages show it on their next load.`))}catch(n){if(n instanceof Lp){Mn(n.message);return}throw n}}function Nb(e,t){Ob(e,t)&&console.log(Up(process.cwd(),e,t)?Pn.green(` \u2713 picture removed for ${e} "${t}"; the initials show again.`):Pn.dim(` ${e} "${t}" has no picture.`))}function _d(e){let t=e.agent?.trim()||_o();return t||Mn("Say which agent: --agent <id>"),t}function jb(){let e=new Cb("picture").description("an agent's profile picture: set, remove or show (an agent may set its own)");return e.command("set <file>").description("set the picture from a PNG, JPEG or WebP file (1 MB at most); it is cut to a square, metadata dropped").option("--agent <id>","which agent (default: the agent running this command)").action(async(t,o)=>{if(_o()){let s=await Il(t,o.agent?.trim(),{daemonUrl:Tb()});return s.ok?console.log(Pn.green(` \u2713 ${s.message}`)):Mn(s.message)}let n=_d(o);n&&await Ib("agent",n,t)}),e.command("remove").alias("rm").description("remove the picture: the initials show again").option("--agent <id>","which agent (default: the agent running this command)").action(async t=>{if(_o()){let n=await Il(null,t.agent?.trim(),{daemonUrl:Tb()});return n.ok?console.log(Pn.green(` \u2713 ${n.message}`)):Mn(n.message)}let o=_d(t);o&&Nb("agent",o)}),e.command("show").description("say whether the agent has a picture").option("--agent <id>","which agent (default: the agent running this command)").action(t=>{let o=_d(t);if(!o)return;let n=qp(process.cwd(),"agent",o);console.log(n?` ${o}: picture set (.agentx/pictures/agent/${o}.${n}.webp)`:Pn.dim(` ${o}: no picture, the initials show`))}),e}function _b(){let e=new Cb("picture").description("a person's profile picture: set or remove (the owner only)"),t=()=>{let o=_o();return o&&Mn(`Only the owner sets a person's picture; agent "${o}" asked.`),!o};return e.command("set <id> <file>").description("set the picture from a PNG, JPEG or WebP file (1 MB at most); it is cut to a square, metadata dropped").action(async(o,n)=>{t()&&await Ib("person",o,n)}),e.command("remove <id>").alias("rm").description("remove the picture: the initials show again").action(o=>{t()&&Nb("person",o)}),e}function Se(){let e=ce(process.cwd(),"agentx.json");if(!Ve(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(tn(e,"utf-8"))}function mt(e){return pe(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(b.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(b.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(b.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var $o=new bo().name("agent").description("manage agents \u2014 add, list, remove, pause, resume");$o.command("list").alias("ls").description("list configured agents").action(()=>{let e=Se();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${b.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(b.dim(` workspace: ${o.workspace}`)),n&&console.log(b.dim(` mentions: ${n}`))}console.log()});$o.command("add").description("add a new agent interactively").action(async()=>{let e=Se(),t=await ct([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:u=>/^[a-z0-9-]+$/.test(u)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:ce(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!t.id)return;let o=t.workspace.endsWith(t.id)?t.workspace:en(t.workspace,t.id);wo(ce(o,".claude/skills"),{recursive:!0});let n={name:t.name,workspace:o,tier:t.tier,model:t.model,mentions:t.mentions?.map(u=>u.trim()).filter(Boolean)||[],maxConcurrent:t.maxConcurrent,systemPrompt:t.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-W32C7WXN.js"),r=s(t.id,n,"19900",(...u)=>{console.log(b.dim(` ${u.join(" ")}`))}),i=ce(process.cwd(),"src/wiki/SKILL.md"),a=ce(HA(GA(import.meta.url)),"../wiki/SKILL.md"),c=Ve(i)?i:a;Ve(c)&&(wo(ce(o,".claude/skills/wiki"),{recursive:!0}),Dd(c,ce(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await mt(e),console.log(b.green(`
|
|
66
66
|
Agent "${t.id}" added`)),console.log(b.dim(` Workspace: ${o}`)),console.log(b.dim(` Created: ${r.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`));let l=Ki(jo(),[t.id]);l&&console.log(b.yellow(` Created by agent "${l}": it starts once the owner approves it (agentx approvals approve agent:${t.id}).`)),console.log()});$o.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=Se();if(!t.agents?.[e]){console.log(b.red(` Agent "${e}" not found`));return}delete t.agents[e],await mt(t),kl(jo(),e),console.log(b.green(` Agent "${e}" removed from config (workspace preserved)`))});$o.addCommand(jb());function Db(e){let t=_o();return t?(console.log(b.red(` Only the owner can ${e}; agent "${t}" asked. Ask the owner, or raise a card.`)),process.exitCode=1,!1):!0}$o.command("pause <id>").description("pause an agent: it starts no run until resumed (applies at once)").action(e=>{if(Db("pause an agent")){if(!Se().agents?.[e]){console.log(b.red(` Agent "${e}" not found`)),process.exitCode=1;return}if($l(jo())[e]?.kind==="approval"){console.log(b.yellow(` "${e}" waits for your approval and does not run yet: agentx approvals list`));return}Qm(jo(),e,"paused","the owner"),console.log(b.green(` "${e}" paused. Messages and schedules for it are refused until you run: agentx agent resume ${e}`))}});$o.command("resume <id>").description("resume a paused agent").action(e=>{if(!Db("resume an agent"))return;let t=$l(jo())[e];if(t?.kind==="approval"){console.log(b.yellow(` "${e}" was created by ${t.by} and waits for your approval: agentx approvals approve agent:${e}`));return}console.log(kl(jo(),e,"paused")?b.green(` "${e}" resumed`):b.dim(` "${e}" was not paused`))});$o.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,t)=>{let o=Se(),n=o.agents?.[e];if(n||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log(b.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):b.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":b.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||b.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(t.intents!==void 0&&(t.intents==="-"||t.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(t.intents).split(",").map(r=>r.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),t.maxDelegationDepth!==void 0){let r=parseInt(t.maxDelegationDepth,10);(!Number.isFinite(r)||r<0||r>50)&&(console.log(b.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=r,s.push(`maxDelegationDepth=${r}`)}if(t.contextReferences!==void 0){let r=String(t.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(r)||(console.log(b.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=r==="true"||r==="on"||r==="1",s.push(`contextReferences=${n.contextReferences}`)}if(t.contextStrategy!==void 0&&(t.contextStrategy==="-"||t.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(t.contextStrategy)?(n.contextStrategy=t.contextStrategy,s.push(`contextStrategy=${t.contextStrategy}`)):(console.log(b.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),t.maxExecutionMinutes!==void 0){let r=parseInt(t.maxExecutionMinutes,10);(!Number.isFinite(r)||r<1||r>240)&&(console.log(b.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=r,s.push(`maxExecutionMinutes=${r}`)}s.length===0&&(console.log(b.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await mt(o),console.log(b.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(b.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var on=new bo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");on.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,t)=>{let n=Se().agents?.[e];n||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(t.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(b.dim(`
|
|
67
67
|
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
68
68
|
`));return}console.log(),console.log(b.bold(` ${e}`));for(let r of s){let i=r.enabled!==!1,a=[],c=r.credentials??{};for(let[u,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?b.green(`${u}:${d}=set`):b.yellow(`${u}:${d}=UNSET`)):u==="auth"&&d==="keyring"?a.push(b.dim("auth:keyring")):u==="sessionDir"&&typeof d=="string"&&a.push(b.dim(`sessionDir:${d}`));let l=Object.entries(r.metadata??{}).map(([u,d])=>`${u}=${d}`).join(" ");console.log(` ${i?b.cyan(r.kind.padEnd(14)):b.dim(r.kind.padEnd(14))} ${b.bold(r.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${b.dim(l)}`),i||console.log(` ${b.dim("(disabled)")}`)}console.log()});on.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,t)=>{let o=Se();o.agents?.[e]||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-ZVRI3GFZ.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await ct({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(f=>({title:f,value:f}))})).kind||"").trim()),r||(console.log(b.red(" --kind is required")),process.exit(1));let i=String(t.label||"").trim();!i&&n&&(i=((await ct({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),i||(console.log(b.red(" --label is required")),process.exit(1));let a=String(t.tokenEnv||"").trim(),c=String(t.auth||"").trim(),l=String(t.sessionDir||"").trim();if(!a&&!c&&!l&&n){let p=await ct({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});p.scheme==="tokenEnv"?a=((await ct({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():p.scheme==="keyring"?c="keyring":p.scheme==="sessionDir"&&(l=((await ct({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${r}-sessions/${e}`})).sessionDir||"").trim())}let u={};if(t.metadata)for(let p of String(t.metadata).split(",")){let[f,...g]=p.split("=");f&&(u[f.trim()]=g.join("=").trim())}else if(n){let p=await ct({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(p.metadata)for(let f of String(p.metadata).split(",")){let[g,...h]=f.split("=");g&&(u[g.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(b.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(b.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),o.agents[e].integrations=o.agents[e].integrations??[],o.agents[e].integrations.find(p=>p.kind===r&&p.label===i)&&(console.log(b.red(` Integration (${r}, ${i}) already exists on ${e}`)),process.exit(1)),o.agents[e].integrations.push({kind:r,label:i,credentials:d,metadata:u,enabled:!0}),await mt(o),console.log(b.green(` \u2713 ${e}: added ${r} integration "${i}"`)),a&&!process.env[a]&&console.log(b.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});on.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=Se(),n=o.agents?.[e];n||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[r,i]=t.includes(":")?t.split(":",2):[t,""],a=s.findIndex(l=>l.kind===r&&(!i||l.label===i)||l.label===t);a===-1&&(console.log(b.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await mt(o),console.log(b.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});on.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=Se().agents?.[e];n||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],r=t?s.filter(a=>a.kind===t||a.label===t||`${a.kind}:${a.label}`===t):s;if(!r.length){console.log(b.yellow(" no integrations to test"));return}let i=0;console.log();for(let a of r){let c=a.credentials??{},l=[];for(let[u,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${u}: env var ${d} is unset`);if(l.length){i+=1,console.log(` ${b.red("\u2717")} ${a.kind} "${a.label}"`);for(let u of l)console.log(` ${b.dim(u)}`)}else console.log(` ${b.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),i>0&&process.exit(1)});function Pb(e,t,o,n){let s=e.agents[t];s.integrations=s.integrations??[];let r=s.integrations,i=r.findIndex(a=>a.kind===o&&(!n||a.label===n));return{list:r,idx:i}}on.command("connect <agentId> <kind>").description("sign in to an outside API (OAuth) and store the token for an agent").option("--label <text>","which integration of this kind (created when missing; default: the kind)").option("--client-id-env <name>","env var with the app's client id (default: <KIND>_CLIENT_ID)").option("--client-secret-env <name>","env var with the app's client secret (default: <KIND>_CLIENT_SECRET)").option("--with <names>","comma-separated optional permissions the provider offers (e.g. revenue)").option("--reads <names>","comma-separated reads this integration allows (default: every read the provider offers)").option("--store <where>","keyring or env (default: keyring when this machine has one)").option("--port <n>","loopback port for the sign-in answer","19876").option("--paste","no loopback: paste the address the browser lands on (for a machine without a browser)").option("--redirect-uri <url>","with --paste: the return address registered in the app, when it cannot be localhost (e.g. an https page for a Meta app in Live mode)").option("--no-browser","print the sign-in address instead of opening it").action(async(e,t,o)=>{let{providerFor:n,BUILTIN_PROVIDERS:s}=await import("./providers-D6IUAHQJ.js"),{resolveClient:r}=await import("./resolve-AYTQGEP2.js"),{signIn:i,storeGrant:a}=await import("./connect-AJKMRKXC.js"),{systemKeyring:c}=await import("./keyring-EKFUNQAO.js"),{waitForLoopbackCallback:l,parseCallback:u}=await import("./oauth-7J7DJMKN.js"),{setDotenvKey:d}=await import("./dotenv-DGZD3EDY.js"),p=Se();p.agents?.[e]||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let f=n(t);if(!f){let R=Object.keys(s);console.log(b.red(` No sign-in support for "${t}". ${R.length?`Supported: ${R.join(", ")}`:"No provider is built in yet."}`)),process.exit(1)}let g=Number(o.port);(!Number.isInteger(g)||g<1024||g>65535)&&(console.log(b.red(" --port must be 1024-65535")),process.exit(1));let h=String(o.store||"").trim()||(c().available()?"keyring":"env");h!=="keyring"&&h!=="env"&&(console.log(b.red(" --store must be keyring or env")),process.exit(1)),h==="keyring"&&!c().available()&&(console.log(b.red(" No OS keyring on this machine (macOS Keychain or Linux secret-tool). Use --store env.")),process.exit(1));let y=String(o.label||"").trim()||void 0,{list:w,idx:$}=Pb(p,e,t,y),S=R=>R.replace(/[^A-Za-z0-9]+/g,"_").toUpperCase();if($===-1?(w.push({kind:t,label:y??t,credentials:{clientIdEnv:String(o.clientIdEnv||`${S(t)}_CLIENT_ID`),clientSecretEnv:String(o.clientSecretEnv||`${S(t)}_CLIENT_SECRET`)},metadata:{},enabled:!0}),$=w.length-1):(w[$].credentials={...w[$].credentials??{}},o.clientIdEnv&&(w[$].credentials.clientIdEnv=String(o.clientIdEnv)),o.clientSecretEnv&&(w[$].credentials.clientSecretEnv=String(o.clientSecretEnv)),w[$].credentials.clientIdEnv??=`${S(t)}_CLIENT_ID`,w[$].credentials.clientSecretEnv??=`${S(t)}_CLIENT_SECRET`),o.reads!==void 0){let R=String(o.reads).split(",").map(I=>I.trim()).filter(Boolean),T=R.filter(I=>!Object.prototype.hasOwnProperty.call(f.reads,I));T.length&&(console.log(b.red(` Unknown read(s): ${T.join(", ")}. ${f.title} offers: ${Object.keys(f.reads).join(", ")}`)),process.exit(1)),w[$].metadata={...w[$].metadata??{}},R.length?w[$].metadata.reads=R.join(","):delete w[$].metadata.reads}let v=w[$];for(let[R,T]of Object.entries(v.credentials))!/^[A-Z][A-Z0-9_]*$/.test(String(T))&&R.endsWith("Env")&&(console.log(b.red(` ${R} must be an uppercase env var name (got "${T}")`)),process.exit(1));let x=r(v);x.ok||(console.log(b.red(` ${x.reason}`)),console.log(b.dim(" Put the app's client id and secret in .env next to agentx.json, then run this again.")),process.exit(1));let k=`http://localhost:${g}/callback`;if(o.redirectUri!==void 0){o.paste||(console.log(b.red(" --redirect-uri works with --paste only: AgentX can wait for the answer on localhost only")),process.exit(1));let{checkRedirectUri:R}=await import("./connect-AJKMRKXC.js"),T=R(String(o.redirectUri));T||(console.log(b.red(" --redirect-uri must be an https address (or http://localhost) without #")),process.exit(1)),k=T}console.log(),console.log(b.bold(` Connect ${f.title} for ${e} ("${v.label}")`)),console.log(b.dim(` Redirect address (add it to your app's allowed redirects): ${k}`));let A=String(o.with||"").split(",").map(R=>R.trim()).filter(Boolean);try{let R=await i({agentId:e,spec:f,integration:v,clientId:x.clientId,clientSecret:x.clientSecret,redirectUri:k,extras:A,warn:I=>console.log(b.yellow(` ${I}`)),getCallback:async(I,M)=>{let D=o.paste?null:l(g,M);if(D&&await D.ready,console.log(`
|
|
@@ -71,7 +71,7 @@ Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choos
|
|
|
71
71
|
${b.cyan(I)}
|
|
72
72
|
`),o.browser!==!1&&!o.paste){let{openBrowser:U}=await import("./open-browser-BTEYT7G4.js");U(I)}if(D)return console.log(b.dim(" Waiting for the browser (5 minutes)...")),D.result;let J=await ct({type:"text",name:"url",message:"Paste the whole address the browser landed on"});return u(String(J.url||""),M)}}),T=a(e,v,R,h,{keyring:c(),writeEnv:(I,M)=>d(ce(process.cwd(),".env"),I,M)});w[$]=T.integration,await mt(p),console.log(b.green(` \u2713 ${e}: ${f.title} connected; token kept in ${T.where}`)),console.log(b.dim(` Granted: ${R.scopes.join(" ")||"(not reported)"}`)),!R.refreshToken&&R.expiresAt&&console.log(b.yellow(` This token cannot refresh itself; it expires on ${new Date(R.expiresAt).toISOString().slice(0,10)}. Connect again before then.`)),h==="env"&&console.log(b.dim(" Restart the daemon so it reads the new .env value: agentx daemon restart")),console.log(b.dim(` Check it: agentx agent integrations status ${e}`))}catch(R){console.log(b.red(` \u2717 not connected: ${R?.message??R}`)),process.exit(1)}process.exit(0)});on.command("status <agentId>").description("show sign-in status of an agent's outside-API integrations: connected, expiry, missing permissions").option("--json","emit JSON").action(async(e,t)=>{let{providerFor:o}=await import("./providers-D6IUAHQJ.js"),{integrationStatus:n}=await import("./status-FK4ESDJS.js"),r=Se().agents?.[e];r||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let i=(r.integrations??[]).map(a=>({i:a,spec:o(a.kind)})).filter(a=>a.spec).map(({i:a,spec:c})=>({kind:a.kind,label:a.label,enabled:a.enabled!==!1,...n(e,a,c)}));if(t.json){console.log(JSON.stringify(i,null,2));return}if(!i.length){console.log(b.dim(`
|
|
73
73
|
${e}: no outside-API integrations. Add one with: agentx agent integrations connect ${e} <kind>
|
|
74
|
-
`));return}console.log();for(let a of i){let c=a.connected&&!a.problems.length?b.green("\u2713"):a.connected?b.yellow("!"):b.red("\u2717"),l=[a.connected?"connected":"not connected"];a.store&&l.push(`token in ${a.store}`),a.refreshes&&l.push("refreshes itself"),a.expiresAt&&l.push(`expires ${new Date(a.expiresAt).toISOString().slice(0,10)}`),a.enabled||l.push("disabled"),console.log(` ${c} ${a.kind} "${a.label}": ${l.join(", ")}`);for(let u of a.problems)console.log(` ${b.dim(u)}`)}console.log(),i.some(a=>!a.connected)&&(process.exitCode=1)});on.command("disconnect <agentId> <kind>").description("forget the stored sign-in for an outside-API integration (the entry stays)").option("--label <text>","which integration of this kind").action(async(e,t,o)=>{let{forgetGrant:n}=await import("./connect-AJKMRKXC.js"),{systemKeyring:s}=await import("./keyring-EKFUNQAO.js"),r=Se();r.agents?.[e]||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let{list:i,idx:a}=Pb(r,e,t,o.label?String(o.label):void 0);a===-1&&(console.log(b.red(` ${e} has no ${t} integration`)),process.exit(1));let c=n(e,i[a],s());i[a]=c.integration,await mt(r),console.log(b.green(` \u2713 ${e}: ${t} "${c.integration.label}" disconnected${c.removedFromKeyring?" (removed from the OS keyring)":""}`)),c.envLeft.length&&console.log(b.yellow(` Delete ${c.envLeft.join(" and ")} from .env yourself, then restart the daemon.`)),console.log(b.dim(" To remove the app's access entirely, also revoke it in the provider's account settings."))});$o.addCommand(on);var La=new bo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");La.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Se();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(b.bold(" Telegram:"));for(let[r,i]of Object.entries(t.accounts||{}))console.log(` ${b.cyan(r)} -> agent: ${i.agentBinding}`)}else console.log(b.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(b.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let r of o.routes||[]){let i=r.contact?`contact ${r.contact}`:`group "${r.group}"`;console.log(` ${i} -> agent: ${r.agent}`)}}else console.log(b.dim(" WhatsApp: disabled"));let n=e.channels?.email;if(n?.enabled&&Object.keys(n.accounts||{}).length){console.log(b.bold(" Email:"));for(let[r,i]of Object.entries(n.accounts))console.log(` ${r}: ${i.address} -> agent: ${i.agent}, replies ${i.send==="auto"?"sent at once":"wait for approval"}`)}else console.log(b.dim(" Email: disabled (agentx connect email)"));let s=e.channels?.gitlab;if(s?.enabled){console.log(b.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let r of s.routes||[])console.log(` ${r.project} -> agent: ${r.agent}`)}else console.log(b.dim(" GitLab: disabled"));console.log()});La.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=Se(),t=Object.keys(e.agents||{});if(!t.length){console.log(b.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await ct({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await ct([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:o}]);if(!s.accountName||!s.token)return;try{let i=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!i.ok)throw new Error(i.description);console.log(b.green(` Bot verified: @${i.result.username}`));let a=`@${i.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,i.result.username),e.agents[s.agentBinding].mentions=c)}catch(r){console.log(b.red(` Invalid token: ${r.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await mt(e),console.log(b.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await ct([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let r=[],i=s.addRoute;for(;i;){let a=await ct([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&r.push({[a.type]:a.value,agent:a.agent}),i=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:r},await mt(e),wo(ce(process.cwd(),s.sessionDir),{recursive:!0}),console.log(b.green(` WhatsApp enabled (${r.length} routes, default: ${s.defaultAgent})`)),console.log(b.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await ct([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let r=[],i=s.addRoute;for(;i;){let a=await ct([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&r.push({project:a.project,agent:a.agent}),i=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:r},await mt(e),console.log(b.green(` GitLab enabled (${r.length} routes, webhook :${s.webhookPort})`)),console.log(b.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(b.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(b.dim(` Secret token: ${s.webhookSecret}`)),console.log(b.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(b.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Qs=new bo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Qs.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Se();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?b.green("\u25CF"):b.dim("\u25CB");console.log(` ${n} ${b.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(b.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(b.dim(" No cron jobs configured")),console.log()});Qs.command("add").description("add a cron job").action(async()=>{let e=Se(),t=Object.keys(e.agents||{}),o=await ct([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:t.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await mt(e),console.log(b.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});Qs.command("enable <id>").description("enable a cron job").action(async e=>{let t=Se();if(!t.crons?.[e]){console.log(b.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(b.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await mt(t),console.log(b.green(` Cron "${e}" enabled`))});Qs.command("disable <id>").description("disable a cron job").action(async e=>{let t=Se();if(!t.crons?.[e]){console.log(b.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await mt(t),console.log(b.green(` Cron "${e}" disabled`))});var Jt=new bo().name("mesh").description("manage mesh peers \u2014 add, list, remove");Jt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Se();if(console.log(),!e.mesh?.enabled)console.log(b.dim(" Mesh: disabled"));else{console.log(b.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=b.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=b.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${b.cyan(t.name)} ${b.dim(t.url)} ${o}`)}}console.log()});Jt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Se(),t=await ct([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(b.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(b.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:t.url,name:t.name,...t.token?{token:t.token}:{}}),await mt(e),console.log(b.green(` Peer "${t.name}" added`)),console.log()}});Jt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=Se();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await mt(t),console.log(b.green(` Peer "${e}" removed`)))});Jt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let t=Se();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(b.red(" --interval must be 5..3600 seconds")),process.exit(1)),t.mesh.healthCheck.interval=n,o.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(b.red(" --timeout must be 1..60 seconds")),process.exit(1)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log(b.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await mt(t),console.log(b.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(b.dim(" Restart the daemon for the new cadence to take effect."))});Jt.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,t)=>{let o=t.node||"";if(!o)try{o=O().dashboard?.daemonUrl||""}catch{}o=(o||"http://localhost:18800").replace(/\/+$/,"");let n=t.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let r=await fetch(`${o}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...t.by?{by:t.by}:{}}),signal:AbortSignal.timeout(1e4)}),i=await r.json().catch(()=>({}));r.ok||(console.log(b.red(` Announcement refused (${r.status}): ${i.error||"unknown error"}`)),process.exit(1)),console.log(b.green(` \u2713 Announced from ${i.event?.node??"this machine"}`)+b.dim(` (event ${i.event?.id??"?"})`))}catch(r){console.log(b.red(` Could not reach the daemon at ${o}: ${r?.message||r}`)),process.exit(1)}});var Mb=e=>{let t=e||"";if(!t)try{t=O().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function qa(e,t,o={}){let n=Mb(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let r=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:s,body:JSON.stringify(o),signal:AbortSignal.timeout(15e3)}),i=await r.json().catch(()=>({}));r.ok||(console.log(b.red(` ${i.error||`HTTP ${r.status}`}`)),process.exit(1));let a=i.grant;console.log(b.green(` \u2713 ${a?.name??e}: ${a?.state}${i.stopped?`, ${i.stopped} running turn(s) stopped`:""}`))}catch(r){console.log(b.red(` Could not reach the daemon at ${n}: ${r?.message||r}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var Ln=Jt.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");Ln.command("invite").description("open a grant to a guest mesh and print the one-time code it joins with").requiredOption("--name <name>",'what you call it, e.g. "Support session for company X"').requiredOption("--guest <name>","the other organisation's name").requiredOption("--agent <id>","the agent of this node that works for them").option("--folders <list>","folders that agent may touch for them, comma-separated").option("--skills <list>","skills it may use for them, comma-separated").option("--commands <list>","commands it may run for them, comma-separated").option("--level <level>","report (read only) | propose (no merge, deploy or delete) | act","propose").option("--days <n>","how long the grant lasts (1 to 365)","7").option("--url <origin>","the address the guest reaches this node on (default: dashboard.daemonUrl)").action(async e=>{let{TokenStore:t}=await import("./token-store-F2PHHO5A.js"),{PairCodeStore:o,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:r}=await import("./grants-ZA35QVTX.js"),i=O(),a=r({tokens:new t,codes:new o,guests:new s,hasAgent:l=>!!i.agents[l]},{name:e.name,guest:e.guest,agentId:e.agent,folders:e.folders?.split(","),skills:e.skills?.split(","),commands:e.commands?.split(","),level:e.level,days:Number(e.days)});a.ok||(console.log(b.red(` ${a.error}`)),process.exit(1));let c=(e.url||Mb()).replace(/\/+$/,"");console.log(),console.log(` Grant ${b.bold(a.grant.name)} for ${b.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(b.dim(` id ${a.grant.id} \xB7 folders: ${a.grant.folders.join(", ")||"none"} \xB7 skills: ${a.grant.skills.join(", ")||"none"} \xB7 commands: ${a.grant.commands.join(", ")||"none"}`)),console.log(),console.log(" Send the guest this address and code. The code works once, for 10 minutes:"),console.log(),console.log(` ${b.cyan(c)}`),console.log(` ${b.bold(n(a.code))}`),console.log(),console.log(` They run: ${b.cyan(`agentx mesh join ${c} --code ${n(a.code)} --name <what-they-call-you>`)}`),console.log(` When they join, a card "Guest mesh: ${a.grant.guest} wants to join" asks you to approve it.`),console.log()});Ln.command("list",{isDefault:!0}).alias("ls").description("every grant: state, guest, agent, level, end date, usage").option("--json","machine-readable output").action(async e=>{let{GuestStore:t}=await import("./store-7W2AP5H4.js"),o=new t().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(b.dim(`
|
|
74
|
+
`));return}console.log();for(let a of i){let c=a.connected&&!a.problems.length?b.green("\u2713"):a.connected?b.yellow("!"):b.red("\u2717"),l=[a.connected?"connected":"not connected"];a.store&&l.push(`token in ${a.store}`),a.refreshes&&l.push("refreshes itself"),a.expiresAt&&l.push(`expires ${new Date(a.expiresAt).toISOString().slice(0,10)}`),a.enabled||l.push("disabled"),console.log(` ${c} ${a.kind} "${a.label}": ${l.join(", ")}`);for(let u of a.problems)console.log(` ${b.dim(u)}`)}console.log(),i.some(a=>!a.connected)&&(process.exitCode=1)});on.command("disconnect <agentId> <kind>").description("forget the stored sign-in for an outside-API integration (the entry stays)").option("--label <text>","which integration of this kind").action(async(e,t,o)=>{let{forgetGrant:n}=await import("./connect-AJKMRKXC.js"),{systemKeyring:s}=await import("./keyring-EKFUNQAO.js"),r=Se();r.agents?.[e]||(console.log(b.red(` Agent "${e}" not found`)),process.exit(1));let{list:i,idx:a}=Pb(r,e,t,o.label?String(o.label):void 0);a===-1&&(console.log(b.red(` ${e} has no ${t} integration`)),process.exit(1));let c=n(e,i[a],s());i[a]=c.integration,await mt(r),console.log(b.green(` \u2713 ${e}: ${t} "${c.integration.label}" disconnected${c.removedFromKeyring?" (removed from the OS keyring)":""}`)),c.envLeft.length&&console.log(b.yellow(` Delete ${c.envLeft.join(" and ")} from .env yourself, then restart the daemon.`)),console.log(b.dim(" To remove the app's access entirely, also revoke it in the provider's account settings."))});$o.addCommand(on);var La=new bo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");La.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Se();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(b.bold(" Telegram:"));for(let[r,i]of Object.entries(t.accounts||{}))console.log(` ${b.cyan(r)} -> agent: ${i.agentBinding}`)}else console.log(b.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(b.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let r of o.routes||[]){let i=r.contact?`contact ${r.contact}`:`group "${r.group}"`;console.log(` ${i} -> agent: ${r.agent}`)}}else console.log(b.dim(" WhatsApp: disabled"));let n=e.channels?.email;if(n?.enabled&&Object.keys(n.accounts||{}).length){console.log(b.bold(" Email:"));for(let[r,i]of Object.entries(n.accounts))console.log(` ${r}: ${i.address} -> agent: ${i.agent}, replies ${i.send==="auto"?"sent at once":"wait for approval"}`)}else console.log(b.dim(" Email: disabled (agentx connect email)"));let s=e.channels?.gitlab;if(s?.enabled){console.log(b.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let r of s.routes||[])console.log(` ${r.project} -> agent: ${r.agent}`)}else console.log(b.dim(" GitLab: disabled"));console.log()});La.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=Se(),t=Object.keys(e.agents||{});if(!t.length){console.log(b.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await ct({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await ct([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:o}]);if(!s.accountName||!s.token)return;try{let i=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!i.ok)throw new Error(i.description);console.log(b.green(` Bot verified: @${i.result.username}`));let a=`@${i.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,i.result.username),e.agents[s.agentBinding].mentions=c)}catch(r){console.log(b.red(` Invalid token: ${r.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await mt(e),console.log(b.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await ct([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let r=[],i=s.addRoute;for(;i;){let a=await ct([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&r.push({[a.type]:a.value,agent:a.agent}),i=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:r},await mt(e),wo(ce(process.cwd(),s.sessionDir),{recursive:!0}),console.log(b.green(` WhatsApp enabled (${r.length} routes, default: ${s.defaultAgent})`)),console.log(b.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await ct([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let r=[],i=s.addRoute;for(;i;){let a=await ct([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&r.push({project:a.project,agent:a.agent}),i=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:r},await mt(e),console.log(b.green(` GitLab enabled (${r.length} routes, webhook :${s.webhookPort})`)),console.log(b.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(b.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(b.dim(` Secret token: ${s.webhookSecret}`)),console.log(b.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(b.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Qs=new bo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Qs.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Se();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?b.green("\u25CF"):b.dim("\u25CB");console.log(` ${n} ${b.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(b.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(b.dim(" No cron jobs configured")),console.log()});Qs.command("add").description("add a cron job").action(async()=>{let e=Se(),t=Object.keys(e.agents||{}),o=await ct([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:t.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await mt(e),console.log(b.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});Qs.command("enable <id>").description("enable a cron job").action(async e=>{let t=Se();if(!t.crons?.[e]){console.log(b.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(b.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await mt(t),console.log(b.green(` Cron "${e}" enabled`))});Qs.command("disable <id>").description("disable a cron job").action(async e=>{let t=Se();if(!t.crons?.[e]){console.log(b.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await mt(t),console.log(b.green(` Cron "${e}" disabled`))});var Jt=new bo().name("mesh").description("manage mesh peers \u2014 add, list, remove");Jt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Se();if(console.log(),!e.mesh?.enabled)console.log(b.dim(" Mesh: disabled"));else{console.log(b.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=b.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=b.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${b.cyan(t.name)} ${b.dim(t.url)} ${o}`)}}console.log()});Jt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Se(),t=await ct([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(b.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(b.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:t.url,name:t.name,...t.token?{token:t.token}:{}}),await mt(e),console.log(b.green(` Peer "${t.name}" added`)),console.log()}});Jt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=Se();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await mt(t),console.log(b.green(` Peer "${e}" removed`)))});Jt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let t=Se();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(b.red(" --interval must be 5..3600 seconds")),process.exit(1)),t.mesh.healthCheck.interval=n,o.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(b.red(" --timeout must be 1..60 seconds")),process.exit(1)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log(b.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await mt(t),console.log(b.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(b.dim(" Restart the daemon for the new cadence to take effect."))});Jt.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,t)=>{let o=t.node||"";if(!o)try{o=O().dashboard?.daemonUrl||""}catch{}o=(o||"http://localhost:18800").replace(/\/+$/,"");let n=t.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let r=await fetch(`${o}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...t.by?{by:t.by}:{}}),signal:AbortSignal.timeout(1e4)}),i=await r.json().catch(()=>({}));r.ok||(console.log(b.red(` Announcement refused (${r.status}): ${i.error||"unknown error"}`)),process.exit(1)),console.log(b.green(` \u2713 Announced from ${i.event?.node??"this machine"}`)+b.dim(` (event ${i.event?.id??"?"})`))}catch(r){console.log(b.red(` Could not reach the daemon at ${o}: ${r?.message||r}`)),process.exit(1)}});var Mb=e=>{let t=e||"";if(!t)try{t=O().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function qa(e,t,o={}){let n=Mb(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let r=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:s,body:JSON.stringify(o),signal:AbortSignal.timeout(15e3)}),i=await r.json().catch(()=>({}));r.ok||(console.log(b.red(` ${i.error||`HTTP ${r.status}`}`)),process.exit(1));let a=i.grant;console.log(b.green(` \u2713 ${a?.name??e}: ${a?.state}${i.stopped?`, ${i.stopped} running turn(s) stopped`:""}`))}catch(r){console.log(b.red(` Could not reach the daemon at ${n}: ${r?.message||r}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var Ln=Jt.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");Ln.command("invite").description("open a grant to a guest mesh and print the one-time code it joins with").requiredOption("--name <name>",'what you call it, e.g. "Support session for company X"').requiredOption("--guest <name>","the other organisation's name").requiredOption("--agent <id>","the agent of this node that works for them").option("--folders <list>","folders that agent may touch for them, comma-separated").option("--skills <list>","skills it may use for them, comma-separated").option("--commands <list>","commands it may run for them, comma-separated").option("--level <level>","report (read only) | propose (no merge, deploy or delete) | act","propose").option("--days <n>","how long the grant lasts (1 to 365)","7").option("--url <origin>","the address the guest reaches this node on (default: dashboard.daemonUrl)").action(async e=>{let{TokenStore:t}=await import("./token-store-F2PHHO5A.js"),{PairCodeStore:o,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:r}=await import("./grants-AIUWETYP.js"),i=O(),a=r({tokens:new t,codes:new o,guests:new s,hasAgent:l=>!!i.agents[l]},{name:e.name,guest:e.guest,agentId:e.agent,folders:e.folders?.split(","),skills:e.skills?.split(","),commands:e.commands?.split(","),level:e.level,days:Number(e.days)});a.ok||(console.log(b.red(` ${a.error}`)),process.exit(1));let c=(e.url||Mb()).replace(/\/+$/,"");console.log(),console.log(` Grant ${b.bold(a.grant.name)} for ${b.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(b.dim(` id ${a.grant.id} \xB7 folders: ${a.grant.folders.join(", ")||"none"} \xB7 skills: ${a.grant.skills.join(", ")||"none"} \xB7 commands: ${a.grant.commands.join(", ")||"none"}`)),console.log(),console.log(" Send the guest this address and code. The code works once, for 10 minutes:"),console.log(),console.log(` ${b.cyan(c)}`),console.log(` ${b.bold(n(a.code))}`),console.log(),console.log(` They run: ${b.cyan(`agentx mesh join ${c} --code ${n(a.code)} --name <what-they-call-you>`)}`),console.log(` When they join, a card "Guest mesh: ${a.grant.guest} wants to join" asks you to approve it.`),console.log()});Ln.command("list",{isDefault:!0}).alias("ls").description("every grant: state, guest, agent, level, end date, usage").option("--json","machine-readable output").action(async e=>{let{GuestStore:t}=await import("./store-7W2AP5H4.js"),o=new t().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(b.dim(`
|
|
75
75
|
No guest grants. Open one: agentx mesh guests invite --name \u2026 --guest \u2026 --agent \u2026
|
|
76
76
|
`));return}console.log();for(let n of o){let s=n.state==="active"?b.green("active"):n.state==="pending"?b.yellow(n.guestNode?"waiting for your approval":"not joined yet"):n.state==="paused"?b.yellow("paused"):b.red(`ended${n.endedReason?`: ${n.endedReason}`:""}`);console.log(` ${b.cyan(n.id)} ${b.bold(n.name)} ${n.guest} \u2192 ${n.agentId} ${n.level} ${s}`),console.log(b.dim(` until ${n.expiresAt.slice(0,10)} \xB7 ${n.usage.turns} turn(s), ${n.usage.tokens} tokens${n.usage.lastAt?` \xB7 last ${n.usage.lastAt.slice(0,16).replace("T"," ")} UTC`:""}${n.guestNode?.name?` \xB7 node ${n.guestNode.name}`:""}`))}console.log()});Ln.command("show <id>").description("one grant, what it opens and what the guest did").action(async e=>{let{GuestStore:t}=await import("./store-7W2AP5H4.js"),o=new t,n=o.get(e);n||(console.log(b.red(` No grant "${e}". See \`agentx mesh guests\`.`)),process.exit(1)),console.log(),console.log(` ${b.bold(n.name)} (${n.id}) \xB7 ${n.state}`),console.log(` guest: ${n.guest}${n.guestNode?` \xB7 node ${n.guestNode.name??n.guestNode.id??"?"} at ${n.guestNode.address??"?"}`:""}`),console.log(` agent: ${n.agentId} \xB7 level: ${n.level} \xB7 until ${n.expiresAt.slice(0,10)}`),console.log(` folders: ${n.folders.join(", ")||"none"}
|
|
77
77
|
skills: ${n.skills.join(", ")||"none"}
|
|
@@ -89,7 +89,7 @@ ${r.content}
|
|
|
89
89
|
`).slice(0,30).map(w=>` ${w}`).join(`
|
|
90
90
|
`)),y.split(`
|
|
91
91
|
`).length>30&&console.log(b.dim(` \u2026 (${y.split(`
|
|
92
|
-
`).length-30} more lines truncated in preview)`));console.log(),console.log(b.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}wo(p,{recursive:!0});let f=0,g=0;for(let[h,y]of Object.entries(u)){let w=en(p,h);if(Ve(w)&&!t.force){console.log(b.dim(` skip ${w} (exists; --force to overwrite)`)),g++;continue}Vs(w,y),console.log(b.green(` + ${w}`)),f++}console.log(),console.log(b.dim(` ${f} written, ${g} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(b.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Qr.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:t}=await import("./loader-KKMG24O5.js"),o=await t(ce(e.cwd)),n=[...o.byId.values()].sort((s,r)=>s.id.localeCompare(r.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(b.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let r=o.sourceById.get(s.id);console.log(` ${b.cyan(s.id)} ${b.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),r&&console.log(b.dim(` ${r}`))}console.log(),console.log(b.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Md=new bo().name("hook").description("manage hooks \u2014 add to agent workspace");Md.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=Se().agents?.[e];if(!o){console.log(b.red(` Agent "${e}" not found`));return}let n=ce(o.workspace,".claude/settings.json"),s=Ve(n)?JSON.parse(tn(n,"utf-8")):{},r=await ct([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!r.event||!r.value)return;s.hooks=s.hooks||{},s.hooks[r.event]=s.hooks[r.event]||[];let a={hooks:[{type:r.type,...r.type==="command"?{command:r.value}:{url:r.value}}]};r.matcher&&(a.matcher=r.matcher),s.hooks[r.event].push(a),wo(ce(o.workspace,".claude"),{recursive:!0}),Vs(n,JSON.stringify(s,null,2)),console.log(b.green(` Hook added to ${e}: ${r.event} -> ${r.type}`)),console.log()});var Ld=new bo().name("migrate").description("import configuration from OpenClaw or other tools");Ld.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,t)=>{let o=[e,ce(process.env.HOME||"",".openclaw/openclaw.json"),ce(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of o)if(f&&Ve(f)){n=f;break}if(!n){console.log(b.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(b.dim(` Reading: ${n}`));let s=JSON.parse(tn(n,"utf-8")),r=Ve(ce(process.cwd(),"agentx.json"))?Se():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},i=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);i.find(f=>f.id==="main"||f.default)&&(c.default="main");let l=0;for(let f of i){if(f.workspace?.startsWith("/data"))continue;let g=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),h=f.groupChat?.mentionPatterns||[];if(h.some(y=>y===g)||h.push(g),r.agents[g]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:h,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!t.dryRun){wo(ce(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-
|
|
92
|
+
`).length-30} more lines truncated in preview)`));console.log(),console.log(b.dim(` Re-run with --write to commit these to ${p}/`)),console.log();return}wo(p,{recursive:!0});let f=0,g=0;for(let[h,y]of Object.entries(u)){let w=en(p,h);if(Ve(w)&&!t.force){console.log(b.dim(` skip ${w} (exists; --force to overwrite)`)),g++;continue}Vs(w,y),console.log(b.green(` + ${w}`)),f++}console.log(),console.log(b.dim(` ${f} written, ${g} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(b.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Qr.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:t}=await import("./loader-KKMG24O5.js"),o=await t(ce(e.cwd)),n=[...o.byId.values()].sort((s,r)=>s.id.localeCompare(r.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(b.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let r=o.sourceById.get(s.id);console.log(` ${b.cyan(s.id)} ${b.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),r&&console.log(b.dim(` ${r}`))}console.log(),console.log(b.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Md=new bo().name("hook").description("manage hooks \u2014 add to agent workspace");Md.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=Se().agents?.[e];if(!o){console.log(b.red(` Agent "${e}" not found`));return}let n=ce(o.workspace,".claude/settings.json"),s=Ve(n)?JSON.parse(tn(n,"utf-8")):{},r=await ct([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!r.event||!r.value)return;s.hooks=s.hooks||{},s.hooks[r.event]=s.hooks[r.event]||[];let a={hooks:[{type:r.type,...r.type==="command"?{command:r.value}:{url:r.value}}]};r.matcher&&(a.matcher=r.matcher),s.hooks[r.event].push(a),wo(ce(o.workspace,".claude"),{recursive:!0}),Vs(n,JSON.stringify(s,null,2)),console.log(b.green(` Hook added to ${e}: ${r.event} -> ${r.type}`)),console.log()});var Ld=new bo().name("migrate").description("import configuration from OpenClaw or other tools");Ld.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,t)=>{let o=[e,ce(process.env.HOME||"",".openclaw/openclaw.json"),ce(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of o)if(f&&Ve(f)){n=f;break}if(!n){console.log(b.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(b.dim(` Reading: ${n}`));let s=JSON.parse(tn(n,"utf-8")),r=Ve(ce(process.cwd(),"agentx.json"))?Se():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},i=s.agents?.list||[],a=s.bindings||[],c={};for(let f of a)f.match?.channel==="telegram"&&(c[f.match.accountId]=f.agentId);i.find(f=>f.id==="main"||f.default)&&(c.default="main");let l=0;for(let f of i){if(f.workspace?.startsWith("/data"))continue;let g=f.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),h=f.groupChat?.mentionPatterns||[];if(h.some(y=>y===g)||h.push(g),r.agents[g]={name:f.name,workspace:f.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:h,maxConcurrent:f.id==="main"?2:1,systemPrompt:`You are ${f.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!t.dryRun){wo(ce(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-W32C7WXN.js");y(g,r.agents[g])}}console.log(` ${b.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let u=s.channels?.telegram?.accounts||{},d=0;for(let[f,g]of Object.entries(u)){if(!g.botToken)continue;let y=c[f]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.channels.telegram.accounts[f]={token:g.botToken,agentBinding:y},r.channels.telegram.enabled=!0,d++}console.log(` ${b.green(d)} Telegram accounts imported`);let p=ce(n,"../cron/jobs.json");if(Ve(p)){let f=JSON.parse(tn(p,"utf-8")),g=0;for(let h of f.jobs||[]){let y=h.name||h.id,w=h.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";r.crons[y]={enabled:h.enabled||!1,schedule:h.schedule?.expr||"0 9 * * *",timezone:h.schedule?.tz||"UTC",agent:w,prompt:h.payload?.message||"",timeout:h.payload?.timeoutSeconds||600,onError:["log"]},g++}console.log(` ${b.green(g)} cron jobs imported`)}t.dryRun?(console.log(b.yellow(`
|
|
93
93
|
Dry run \u2014 nothing written`)),console.log(JSON.stringify(r,null,2))):(await mt(r),console.log(b.green(`
|
|
94
94
|
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var nn=new bo().name("config").description("validate and inspect configuration");nn.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let t=O(e.config);console.log(b.green(" \u2713 Config valid")),console.log(b.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(b.dim(` Bind: ${t.node.bind}`)),console.log(b.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(b.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(b.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(b.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(b.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=Ji(t);if(n.length){console.log(),console.log(b.yellow(" Warnings:"));for(let s of n)console.log(b.yellow(` \u26A0 ${s}`))}else console.log(b.green(" \u2713 All workspaces valid"));console.log();for(let[s,r]of Object.entries(t.agents)){let i=r.workspace,a=Ve(ce(i,".claude")),c=Ve(ce(i,"CLAUDE.md")),l=Ve(ce(i,".claude/settings.json")),u=Us(r.tier,i).length,d=[a?b.green("\u2713"):b.red("\u2717"),".claude",c?b.green("\u2713"):b.yellow("\u25CB"),"CLAUDE.md",l?b.green("\u2713"):b.yellow("\u25CB"),"settings",`${u} skills`];console.log(` ${b.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(b.red(` \u2717 ${t.message}`))}console.log()});nn.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=O(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(b.red(t.message))}});function zA(e,t){if(t)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(o=>o.trim()).filter(Boolean):e}function Pd(e){return e===void 0?b.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}nn.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,t)=>{let{readFileSync:o,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:r}=await import("./config-mutator-RK3UQORI.js"),{expandEnvVars:i}=await import("./config-ZVRI3GFZ.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(b.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(o(a,"utf-8")),l=t.raw?c:i(c),u=r(l,e);t.json?console.log(JSON.stringify(u)):console.log(Pd(u))});nn.command("set <path> <value>").description("write a config value by dot-path; validates against schema and hot-reloads the daemon").option("-c, --config <path>","path to agentx.json").option("--string","treat the value as a literal string (skip JSON parsing)").option("--dry-run","validate and diff without writing").action(async(e,t,o)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:r}=await import("./config-mutator-RK3UQORI.js"),i=zA(t,!!o.string),a=await n(l=>{s(l,e,i)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(b.red(` \u2717 ${a.error}`)),process.exit(1));let c=r(a.after,e);o.dryRun?console.log(b.yellow(` (dry-run) ${b.cyan(e)} would become: ${Pd(c)}`)):(console.log(b.green(` \u2713 ${b.cyan(e)} = ${Pd(c)}`)),a.reloaded?console.log(b.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(b.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});nn.command("unset <path>").description("remove a config value by dot-path (validates + hot-reloads)").option("-c, --config <path>","path to agentx.json").option("--dry-run","validate without writing").action(async(e,t)=>{let{applyConfigMutation:o,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-RK3UQORI.js"),r=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(r.success||(console.log(b.red(` \u2717 ${r.error}`)),process.exit(1)),n(r.after,e)!==void 0){console.log(b.dim(` (no-op) ${b.cyan(e)} was not set`));return}t.dryRun?console.log(b.yellow(` (dry-run) ${b.cyan(e)} would be removed`)):(console.log(b.green(` \u2713 ${b.cyan(e)} removed`)),r.reloaded&&console.log(b.dim(" Daemon hot-reloaded.")))});nn.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let t=!1,o=0,n;try{let d=O(e.config);t=!!d.business?.enabled,o=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),r=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),i=r==="true"||r==="1"||r==="yes",a=i&&t,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:i,businessEnabled:t,active:a,projects:o},configError:n},null,2));return}console.log(),console.log(b.bold(" Governance flags")),console.log(),n&&(console.log(b.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?b.green:s==="shadow"?b.cyan:s==="off"?b.dim:b.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":b.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let u=a?b.green("active"):i?b.yellow("env=true but business.enabled=false \u2192 inactive"):b.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${u}`),console.log(b.dim(` business.enabled ${t?b.green("true"):b.dim("false")}`)),console.log(b.dim(` business.projects[] ${o}`)),console.log(),console.log(b.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(b.dim(" See: https://github.com/anis-marrouchi/agentx/blob/main/docs/architecture/research-rescue-plan.md")),console.log()});Io();import{Command as YA}from"commander";import sn from"chalk";import{resolve as rn}from"path";import{existsSync as KA}from"fs";var Lo=new YA().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Fn(e){let t=rn(e,".agentx/db.sqlite");KA(t)||(console.log(sn.red(` No SQLite at ${t}`)),console.log(sn.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=He({path:t});return o||(console.log(sn.red(` Could not open ${t}`)),console.log(sn.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function Un(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(sn.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.map(r=>Math.max(r.length,...e.map(i=>String(i[r]??"").length))),s=r=>r.map((i,a)=>String(i??"").padEnd(n[a])).join(" ");console.log(s(o)),console.log(o.map((r,i)=>"-".repeat(n[i])).join(" "));for(let r of e)console.log(s(o.map(i=>r[i])))}Lo.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let t=Fn(rn(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.day&&(o.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(o.push("status = @status"),n.status=e.status);let s=`
|
|
95
95
|
SELECT agent_id, channel, status, duration_ms,
|
|
@@ -607,7 +607,7 @@ ${oe.text}`));T.delivery.reached.of++,ie&&T.delivery.reached.n++;let j=P[0]??Q[0
|
|
|
607
607
|
Plan ${q.dim(`[${r.state}] by ${r.createdBy}, ${rs(r.createdAt)}`)}`),Hv(s.steps(e)),console.log(`
|
|
608
608
|
Log`);for(let i of s.events(e))console.log(q.dim(` ${rs(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});Fo.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=fr();if(!s)return;let r=Sc();if(!r){process.exitCode=1;return}let i=Number(t),a=Yf(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)")),Hv(r.steps(e))});function Gv(e,t,o,n){let s=Fo.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=fr();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}let u=process.env.AGENTX_AGENT_ID?.trim()||pm;if(!a.close(r,e==="done"?"done":"dropped",c,Date.now(),null,u)){console.error(q.red(` ${r} is already closed (${Gu[l.state]??l.state})`)),process.exitCode=1;return}console.log(q.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}Gv("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>");Gv("drop","drop a request you no longer want","--reason <text>","");Fo.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 (${Ui.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=(y,w)=>{if(w===void 0)return;let $=Number(w);if(!($>0))throw new Error(`${y} must be a positive number`);return $},d=(y,w)=>y===void 0?void 0:y===w?[]:y.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 y=u("--catch-cap",e.catchCap);if(y!==void 0&&!Number.isInteger(y))throw new Error("--catch-cap must be a whole number");t.catchPromises={...e.catch!==void 0?{enabled:e.catch==="on"}:{},...y!==void 0?{dailyCap:y}:{}}}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 p={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");p.enabled=e.plans==="on"}if(p.stallMinutes=u("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let y=Number(e.maxNudges);if(!Number.isInteger(y)||y<0)throw new Error("--max-nudges must be a whole number, 0 or more");p.maxNudges=y}if(p.approveKinds=d(e.approveKinds,"none"),p.disabledAgents=d(e.plansOffFor,"none"),p.requireForWork=d(e.planFor,"none"),e.planOver!==void 0){let y=Number(e.planOver);if(!(y>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");p.requireOverMinutes=y}Object.values(p).some(y=>y!==void 0)&&(t.plans=p);let f={},g=d(e.checks,"none");if(g){let y=g.filter(w=>!Ui.includes(w));if(y.length)throw new Error(`unknown check ${y.join(", ")}: use ${Ui.join(", ")}`);f.enabled=g}f.checkEveryMinutes=u("--check-every",e.checkEvery),Object.values(f).some(y=>y!==void 0)&&(t.checkers=f);let h={};if(e.autoResend!==void 0){if(e.autoResend!=="on"&&e.autoResend!=="off")throw new Error("--auto-resend takes on or off");h.enabled=e.autoResend==="on"}if(e.resendAfter!==void 0){let y=Number(e.resendAfter);if(!(y>=0))throw new Error("--resend-after must be a number of minutes, 0 or more");h.afterMinutes=y}h.holdMaxHours=u("--resend-hold-hours",e.resendHoldHours),Object.values(h).some(y=>y!==void 0)&&(t.autoResend=h),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 Cf(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=Pr();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??da;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??da.requireOverMinutes,i=s.requireForWork??da.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??zf;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??Wi;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 NI}from"commander";import hr from"chalk";Z();var zv=new NI("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",nd.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(hr.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await pe(r=>{n=fy(r,e,t==="on")});s.success||(console.error(hr.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(hr.green(`\u2713 ${n}`)),s.reloaded&&console.log(hr.dim(" daemon hot-reloaded"))}let o=O().requestStatus.channels.map(n=>n.toLowerCase());for(let n of nd)console.log(` ${n.padEnd(8)} ${o.includes(n)?hr.green("on"):hr.dim("off")}`)});import{Command as aN}from"commander";import yr from"chalk";import Ee from"chalk";import wi from"prompts";import{readFileSync as jI,writeFileSync as _I,existsSync as DI}from"fs";import{resolve as Yv}from"path";var PI=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function MI(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Yu(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Kv(e=".env"){let t=Yv(e);if(!DI(t))return[];let o=jI(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(PI);r?n.push({kind:"kv",key:r[1],value:MI(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function LI(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Yu(t.value)}`:t.raw).join(`
|
|
609
609
|
`)+`
|
|
610
|
-
`}function is(e,t,o=".env"){let n=Yv(o),s=Kv(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`})),_I(n,LI(s))}function Ku(e,t=".env"){return Kv(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Xv="https://t.me/BotFather";async function qI(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 FI(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 Vv(e={}){console.log(),console.log(Ee.bold(" Connect Telegram")),console.log(),console.log(Ee.dim(` 1. Open ${Xv}`)),console.log(Ee.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Ee.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await wi({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Mo(Xv);let{token:o}=await wi({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(Ee.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await qI(o.trim());n||(console.log(Ee.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Ee.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(Ee.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(Ee.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await wi({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),u||(console.log(Ee.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await wi({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Ee.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;is(f,o.trim()),process.env[f]=o.trim();let g=await pe(v=>{Ge(v,"channels.telegram.enabled",!0),Ge(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let x=js(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),Ge(v,`agents.${u}.mentions`,x))},{configPath:e.configPath});if(g.success||(console.log(Ee.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(Ee.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(Ee.dim(` Token stored in .env as ${f}`)),console.log(Ee.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await wi({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(Ee.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Ee.dim(" Waiting up to 90s..."));let y=await FI(o.trim(),9e4);if(!y){console.log(Ee.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Ee.dim(" agentx config set notifications.destination.channel telegram")),console.log(Ee.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Ee.dim(` agentx config set notifications.destination.accountId ${p}`));return}let w={channel:"telegram",chatId:String(y.chatId),accountId:p},$=[],S=await pe(v=>{Ge(v,"notifications.destination",w),$=Na(v,w)},{configPath:e.configPath});if(!S.success){console.log(Ee.red(` \u2717 failed to save destination: ${S.error}`));return}console.log(Ee.green(" \u2713 Default --notify target set")),console.log(Ee.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Ee.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(Ee.dim(` Schedules that now report here: ${$.join(", ")}`)),S.reloaded&&console.log(Ee.dim(" Daemon hot-reloaded."))}import qe from"chalk";import Xu from"prompts";import{existsSync as Qu,mkdirSync as UI,readdirSync as WI,readFileSync as Qv}from"fs";import{resolve as Vu}from"path";var BI=".agentx/whatsapp-sessions";function JI(){let e=Vu(process.cwd(),".agentx/daemon.pid");if(!Qu(e))return!1;try{let t=parseInt(Qv(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function HI(e){if(!Qu(e))return!1;try{return WI(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function GI(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(qe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(qe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;UI(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 p=setTimeout(()=>{t(qe.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}u(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){t(qe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(p),t(qe.green(" \u2713 Paired"));try{l.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(qe.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Zv(e={}){if(console.log(),console.log(qe.bold(" Connect WhatsApp")),console.log(),JI()){console.log(qe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(qe.dim(" agentx daemon stop")),console.log();let{cont:l}=await Xu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(qe.red(" Aborted")),process.exit(1))}let t=e.configPath||Vu(process.cwd(),"agentx.json");Qu(t)||(console.log(qe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Qv(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||BI,s=Vu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(qe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Xu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(qe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(HI(s)&&a){let{keep:l}=await Xu({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(qe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await GI(s,u=>console.log(u))||(console.log(qe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await pe(l=>{Ge(l,"channels.whatsapp.enabled",!0),Ge(l,"channels.whatsapp.sessionDir",n),Ge(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(qe.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(qe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(qe.dim(` Session: ${n}`)),console.log(qe.dim(" Start the daemon to begin receiving:")),console.log(qe.dim(" agentx daemon start")),console.log(qe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(qe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(qe.dim(" Add routes later with:")),console.log(qe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Ot from"chalk";import zI from"prompts";import{existsSync as YI,readFileSync as KI}from"fs";import{resolve as XI}from"path";async function VI(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 QI(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 Uo(e){console.log(Ot.red(` ${e}`)),process.exit(1)}async function as(e){return(await zI(e,{onCancel:()=>Uo("Aborted")}))[e.name]}async function ex(e={}){console.log(),console.log(Ot.bold(" Connect email")),console.log();let t=e.configPath||XI(process.cwd(),"agentx.json");YI(t)||Uo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(KI(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Uo("No agents configured. Run: agentx agent add");let s=e.agent??await as({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(w=>({title:w,value:w}))});o.agents?.[s]||Uo(`No agent "${s}" in ${t}`);let r=(e.address??await as({type:"text",name:"address",message:"Email address customers write to:",validate:w=>/^\S+@\S+\.\S+$/.test(w.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=yy(r),c=e.imapHost??a?.imapHost??await as({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await as({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await as({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await as({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Uo("Ports must be numbers.");let p=e.passwordEnv||by(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Uo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Ot.dim(` Gmail needs an app password, not your account password: ${hy}`)),console.log(Ot.dim(" (2-step verification must be on for that page to show.)"))),f=(await as({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Uo("Aborted");let g={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:p,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let w=await VI(g,f);w&&(console.log(Ot.red("\u2717")),Uo(w)),console.log(Ot.green("\u2713"))}e.passwordEnv||(is(p,f),process.env[p]=f);let h=await pe(w=>{Ge(w,"channels.email.enabled",!0),Ge(w,`channels.email.accounts.${i}`,wy(g))},{configPath:e.configPath});h.success||Uo(`Config save failed: ${h.error}`),console.log(),console.log(Ot.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Ot.dim(` Password stored in .env as ${p}`)),console.log(Ot.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let y=QI(o.agents[s]?.tier,g.allowFrom);y&&console.log(Ot.yellow(` ${y}`)),console.log(g.send==="auto"?Ot.yellow(" Replies are sent as soon as the agent writes them."):Ot.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Ot.dim(" Only mail that arrives from now on is answered.")),console.log(Ot.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as ZI}from"crypto";import Ze from"chalk";import tx from"prompts";var Ec="agentx-mesh:",Ac="//join/";function eN(e){return Buffer.from(e,"utf-8").toString("base64url")}function tN(e){return Buffer.from(e,"base64url").toString("utf-8")}function oN(e){return`${Ec}${Ac}${eN(JSON.stringify(e))}`}function nN(e){if(!e.startsWith(`${Ec}${Ac}`))throw new Error(`Not a mesh invite link \u2014 expected ${Ec}${Ac}\u2026`);let t=e.slice(Ec.length+Ac.length),o=JSON.parse(tN(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 sN(){return ZI(32).toString("hex")}function rN(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function iN(e){return e?.node?.name||e?.node?.id||"node"}async function ox(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ze.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Ku("MESH_TOKEN");i||(i=sN(),is("MESH_TOKEN",i),console.log(Ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||rN(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await tx({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:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(Ze.red(" Aborted")),process.exit(1)),a=d}let l=await pe(d=>{Ge(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ze.red(` \u2717 ${l.error}`)),process.exit(1));let u=oN({url:a,token:i,name:iN(r),version:1});console.log(),console.log(Ze.bold(" Mesh invite")),console.log(),console.log(` ${Ze.cyan(u)}`),console.log(),console.log(Ze.dim(" Run on the other node:")),console.log(Ze.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ze.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function nx(e,t={}){let o;try{o=nN(e)}catch(r){console.log(Ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Ku("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await tx({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ze.red(" Aborted (keeping existing .env)")),process.exit(1))}is("MESH_TOKEN",o.token);let s=await pe(r=>{Ge(r,"mesh.enabled",!0);let i=js(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),Ge(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ze.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ze.green(" \u2713 Joined mesh")),console.log(Ze.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ze.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ze.dim(" Daemon hot-reloaded.")):console.log(Ze.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Ze.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ze.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ze.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var cs=new aN().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");cs.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 Vv({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});cs.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 Zv({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});cs.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 ex({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 sx=cs.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");sx.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 ox({url:e.url,configPath:e.config})});sx.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 nx(e,{configPath:t.config})});cs.action(()=>{console.log(),console.log(yr.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${yr.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${yr.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${yr.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${yr.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(yr.dim(" GitLab connect is the next slice.")),console.log()});Z();import{Command as cN}from"commander";import le from"chalk";var ls=new cN().name("usage").description("token usage analysis and reporting");ls.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}`))}});ls.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(p=>a(p.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 p=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=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`:"",y=l.has(d.window)?le.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${p.padEnd(12)} ${[f,h,y].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}`))}});ls.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?"))}});ls.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 f=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(g=>[g,a.channels[g],c?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,c?.total]);for(let[g,h,y]of f){let w=r(h),$=` ${g.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${u(h?.cacheRead||0).padStart(11)} ${u(h?.cacheCreate||0).padStart(11)} ${u(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l(w).padStart(9)}`;if(c){let S=r(y),v=w!==null&&S?`${((w-S)/S*100).toFixed(0)}%`:"-";$+=` ${l(S).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()});ls.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-Y23TE5AN.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-BRFPOZLO.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();c.push(g),l(f,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 lN}from"commander";import Ke from"chalk";import{readFileSync as dN}from"fs";import{resolve as uN}from"path";Z();var fn=new lN().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");fn.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{Nm(uN(process.cwd(),".env"))}catch{}let t=gN(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-CZXKVKK7.js");o(t)}catch(t){console.log(Ke.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ke.dim(t.stack)),process.exit(1)}});function gN(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ke.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ke.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
610
|
+
`}function is(e,t,o=".env"){let n=Yv(o),s=Kv(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`})),_I(n,LI(s))}function Ku(e,t=".env"){return Kv(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Xv="https://t.me/BotFather";async function qI(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 FI(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 Vv(e={}){console.log(),console.log(Ee.bold(" Connect Telegram")),console.log(),console.log(Ee.dim(` 1. Open ${Xv}`)),console.log(Ee.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Ee.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await wi({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Mo(Xv);let{token:o}=await wi({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(Ee.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await qI(o.trim());n||(console.log(Ee.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Ee.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(Ee.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(Ee.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await wi({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),u||(console.log(Ee.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await wi({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Ee.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;is(f,o.trim()),process.env[f]=o.trim();let g=await pe(v=>{Ge(v,"channels.telegram.enabled",!0),Ge(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let x=js(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),Ge(v,`agents.${u}.mentions`,x))},{configPath:e.configPath});if(g.success||(console.log(Ee.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(Ee.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(Ee.dim(` Token stored in .env as ${f}`)),console.log(Ee.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await wi({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(Ee.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Ee.dim(" Waiting up to 90s..."));let y=await FI(o.trim(),9e4);if(!y){console.log(Ee.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Ee.dim(" agentx config set notifications.destination.channel telegram")),console.log(Ee.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Ee.dim(` agentx config set notifications.destination.accountId ${p}`));return}let w={channel:"telegram",chatId:String(y.chatId),accountId:p},$=[],S=await pe(v=>{Ge(v,"notifications.destination",w),$=Na(v,w)},{configPath:e.configPath});if(!S.success){console.log(Ee.red(` \u2717 failed to save destination: ${S.error}`));return}console.log(Ee.green(" \u2713 Default --notify target set")),console.log(Ee.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Ee.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(Ee.dim(` Schedules that now report here: ${$.join(", ")}`)),S.reloaded&&console.log(Ee.dim(" Daemon hot-reloaded."))}import qe from"chalk";import Xu from"prompts";import{existsSync as Qu,mkdirSync as UI,readdirSync as WI,readFileSync as Qv}from"fs";import{resolve as Vu}from"path";var BI=".agentx/whatsapp-sessions";function JI(){let e=Vu(process.cwd(),".agentx/daemon.pid");if(!Qu(e))return!1;try{let t=parseInt(Qv(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function HI(e){if(!Qu(e))return!1;try{return WI(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function GI(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(qe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(qe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;UI(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 p=setTimeout(()=>{t(qe.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}u(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){t(qe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(p),t(qe.green(" \u2713 Paired"));try{l.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(qe.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Zv(e={}){if(console.log(),console.log(qe.bold(" Connect WhatsApp")),console.log(),JI()){console.log(qe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(qe.dim(" agentx daemon stop")),console.log();let{cont:l}=await Xu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(qe.red(" Aborted")),process.exit(1))}let t=e.configPath||Vu(process.cwd(),"agentx.json");Qu(t)||(console.log(qe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Qv(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||BI,s=Vu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(qe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Xu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(qe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(HI(s)&&a){let{keep:l}=await Xu({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(qe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await GI(s,u=>console.log(u))||(console.log(qe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await pe(l=>{Ge(l,"channels.whatsapp.enabled",!0),Ge(l,"channels.whatsapp.sessionDir",n),Ge(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(qe.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(qe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(qe.dim(` Session: ${n}`)),console.log(qe.dim(" Start the daemon to begin receiving:")),console.log(qe.dim(" agentx daemon start")),console.log(qe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(qe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(qe.dim(" Add routes later with:")),console.log(qe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Ot from"chalk";import zI from"prompts";import{existsSync as YI,readFileSync as KI}from"fs";import{resolve as XI}from"path";async function VI(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 QI(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 Uo(e){console.log(Ot.red(` ${e}`)),process.exit(1)}async function as(e){return(await zI(e,{onCancel:()=>Uo("Aborted")}))[e.name]}async function ex(e={}){console.log(),console.log(Ot.bold(" Connect email")),console.log();let t=e.configPath||XI(process.cwd(),"agentx.json");YI(t)||Uo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(KI(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Uo("No agents configured. Run: agentx agent add");let s=e.agent??await as({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(w=>({title:w,value:w}))});o.agents?.[s]||Uo(`No agent "${s}" in ${t}`);let r=(e.address??await as({type:"text",name:"address",message:"Email address customers write to:",validate:w=>/^\S+@\S+\.\S+$/.test(w.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=yy(r),c=e.imapHost??a?.imapHost??await as({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await as({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await as({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await as({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Uo("Ports must be numbers.");let p=e.passwordEnv||by(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Uo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Ot.dim(` Gmail needs an app password, not your account password: ${hy}`)),console.log(Ot.dim(" (2-step verification must be on for that page to show.)"))),f=(await as({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Uo("Aborted");let g={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:p,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let w=await VI(g,f);w&&(console.log(Ot.red("\u2717")),Uo(w)),console.log(Ot.green("\u2713"))}e.passwordEnv||(is(p,f),process.env[p]=f);let h=await pe(w=>{Ge(w,"channels.email.enabled",!0),Ge(w,`channels.email.accounts.${i}`,wy(g))},{configPath:e.configPath});h.success||Uo(`Config save failed: ${h.error}`),console.log(),console.log(Ot.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Ot.dim(` Password stored in .env as ${p}`)),console.log(Ot.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let y=QI(o.agents[s]?.tier,g.allowFrom);y&&console.log(Ot.yellow(` ${y}`)),console.log(g.send==="auto"?Ot.yellow(" Replies are sent as soon as the agent writes them."):Ot.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Ot.dim(" Only mail that arrives from now on is answered.")),console.log(Ot.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as ZI}from"crypto";import Ze from"chalk";import tx from"prompts";var Ec="agentx-mesh:",Ac="//join/";function eN(e){return Buffer.from(e,"utf-8").toString("base64url")}function tN(e){return Buffer.from(e,"base64url").toString("utf-8")}function oN(e){return`${Ec}${Ac}${eN(JSON.stringify(e))}`}function nN(e){if(!e.startsWith(`${Ec}${Ac}`))throw new Error(`Not a mesh invite link \u2014 expected ${Ec}${Ac}\u2026`);let t=e.slice(Ec.length+Ac.length),o=JSON.parse(tN(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 sN(){return ZI(32).toString("hex")}function rN(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function iN(e){return e?.node?.name||e?.node?.id||"node"}async function ox(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ze.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Ku("MESH_TOKEN");i||(i=sN(),is("MESH_TOKEN",i),console.log(Ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||rN(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await tx({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:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(Ze.red(" Aborted")),process.exit(1)),a=d}let l=await pe(d=>{Ge(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ze.red(` \u2717 ${l.error}`)),process.exit(1));let u=oN({url:a,token:i,name:iN(r),version:1});console.log(),console.log(Ze.bold(" Mesh invite")),console.log(),console.log(` ${Ze.cyan(u)}`),console.log(),console.log(Ze.dim(" Run on the other node:")),console.log(Ze.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ze.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function nx(e,t={}){let o;try{o=nN(e)}catch(r){console.log(Ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Ku("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await tx({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ze.red(" Aborted (keeping existing .env)")),process.exit(1))}is("MESH_TOKEN",o.token);let s=await pe(r=>{Ge(r,"mesh.enabled",!0);let i=js(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),Ge(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ze.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ze.green(" \u2713 Joined mesh")),console.log(Ze.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ze.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ze.dim(" Daemon hot-reloaded.")):console.log(Ze.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Ze.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ze.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ze.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var cs=new aN().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");cs.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 Vv({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});cs.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 Zv({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});cs.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 ex({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 sx=cs.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");sx.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 ox({url:e.url,configPath:e.config})});sx.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 nx(e,{configPath:t.config})});cs.action(()=>{console.log(),console.log(yr.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${yr.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${yr.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${yr.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${yr.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(yr.dim(" GitLab connect is the next slice.")),console.log()});Z();import{Command as cN}from"commander";import le from"chalk";var ls=new cN().name("usage").description("token usage analysis and reporting");ls.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}`))}});ls.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(p=>a(p.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 p=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=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`:"",y=l.has(d.window)?le.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${p.padEnd(12)} ${[f,h,y].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}`))}});ls.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?"))}});ls.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 f=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(g=>[g,a.channels[g],c?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,c?.total]);for(let[g,h,y]of f){let w=r(h),$=` ${g.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${u(h?.cacheRead||0).padStart(11)} ${u(h?.cacheCreate||0).padStart(11)} ${u(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l(w).padStart(9)}`;if(c){let S=r(y),v=w!==null&&S?`${((w-S)/S*100).toFixed(0)}%`:"-";$+=` ${l(S).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()});ls.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-Y23TE5AN.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-Q4DXWAQU.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();c.push(g),l(f,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 lN}from"commander";import Ke from"chalk";import{readFileSync as dN}from"fs";import{resolve as uN}from"path";Z();var fn=new lN().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");fn.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{Nm(uN(process.cwd(),".env"))}catch{}let t=gN(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-QV7OD4SO.js");o(t)}catch(t){console.log(Ke.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ke.dim(t.stack)),process.exit(1)}});function gN(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ke.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ke.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
611
611
|
`)),{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}}}}fn.command("list").description("list configured boards").action(()=>{try{let e=O();if(!e.boards?.length){console.log(Ke.dim(`
|
|
612
612
|
No boards configured.
|
|
613
613
|
`));return}console.log();for(let t of e.boards){console.log(` ${Ke.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(Ke.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(Ke.dim(` primary label: ${t.primaryToolLabel}`)),console.log(Ke.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(Ke.red(` ${e.message}`)),process.exit(1)}});fn.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{bi(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(Ke.red(` ${o.message}`)),process.exit(1)}});fn.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{bi(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(Ke.red(` ${o.message}`)),process.exit(1)}});var Zu=fn.command("column").description("manage a board's columns (add / remove / edit / list)");Zu.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(dN("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(Ke.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(` ${Ke.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${Ke.dim(r)}`)}}catch(t){console.log(Ke.red(` ${t.message}`)),process.exit(1)}});Zu.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{bi(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(Ke.red(` ${n.message}`)),process.exit(1)}});Zu.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{bi(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(Ke.red(` ${o.message}`)),process.exit(1)}});fn.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{bi(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(Ke.red(` ${t.message}`)),process.exit(1)}});function bi(e){let{summary:t,backupPath:o}=Ut(n=>e(n));console.log(Ke.green(`
|
|
@@ -911,7 +911,7 @@ Restart the daemon to activate.
|
|
|
911
911
|
dist/
|
|
912
912
|
*.log
|
|
913
913
|
.env
|
|
914
|
-
`}import{Command as X_}from"commander";import ut from"chalk";import{writeFileSync as V_,mkdirSync as Q_,existsSync as tl,readFileSync as aS,appendFileSync as cS}from"fs";import{resolve as Rr,dirname as uS}from"path";import{homedir as qg}from"os";var gS=new X_().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-
|
|
914
|
+
`}import{Command as X_}from"commander";import ut from"chalk";import{writeFileSync as V_,mkdirSync as Q_,existsSync as tl,readFileSync as aS,appendFileSync as cS}from"fs";import{resolve as Rr,dirname as uS}from"path";import{homedir as qg}from"os";var gS=new X_().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-Q4DXWAQU.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=tD(o);break;case"bash":s=iD(o);break;case"fish":s=aD(o);break;default:console.error(ut.red(`unsupported shell: ${n}`)),console.error(ut.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?Rr(String(e.output)):Z_(n);Q_(uS(r),{recursive:!0}),V_(r,s),console.log(ut.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),eD(n,r,!!e.yes)});function Z_(e){let t=qg();switch(e){case"zsh":return Rr(t,".zsh","completions","_agentx");case"bash":return Rr(t,".bash_completion.d","agentx.bash");case"fish":return Rr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function eD(e,t,o){if(e==="zsh"){let n=Rr(qg(),".zshrc"),s=uS(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=tl(n)?aS(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(ut.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&tl(n)){let u=["","# agentx completion"];c&&u.push(r),l&&u.push(i),cS(n,u.join(`
|
|
915
915
|
`)+`
|
|
916
916
|
`),console.log(ut.green("\u2713 Patched ~/.zshrc")),console.log(ut.dim("Reload your shell: exec zsh"));return}console.log(ut.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(ut.cyan(` ${r}`)),l&&console.log(ut.cyan(` ${i}`)),console.log(),console.log(ut.dim("Then reload: exec zsh")),console.log(ut.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Rr(qg(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((tl(n)?aS(n,"utf-8"):"").includes(t)){console.log(ut.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&tl(n)){cS(n,`
|
|
917
917
|
# agentx completion
|
|
@@ -927,4 +927,4 @@ ${cD({...t,category:e.category})}`),u&&a.set(l.id,u)}let c=`https://github.com/$
|
|
|
927
927
|
${o.url}`)}catch(t){console.error(Cr.red(` ${t.message}`)),process.exitCode=1}});ji.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",Ug).action(async(e,t)=>{try{let o=await Jg(t.models);if(!Wg(t.model,o)){console.log(Bg(t.model,o)),process.exitCode=1;return}let n=e==="-"?await uD():await dD(e,"utf8"),s=JSON.parse(n),{version:r}=await ea(),i=hS({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(Cr.red(` ${o.message}`)),process.exitCode=1}});async function uD(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function V5(){let e=await ea(),t=new gD().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=ky(n);vy(s)&&$y("cli",s)});for(let o of[vb,Dw,_w,cs,Ws,yo,Wt,ty,zk,Kk,$o,La,qo,_n,ts,So,Fo,si,zv,pn,Ca,W0,dn,N$,j$,W$,gi,Z$,sk,C$,ak,ck,Ek,Ck,Ok,zt,ls,Y0,Xr,nn,gS,ji])t.addCommand(o);for(let o of wS)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=wS.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,mD(o,74," "),""].join(`
|
|
928
928
|
`)}),t}var wS=[X,$r,Bo,co,Qr,lr,rt,Wo,fn,es,ps,vr,wn,an,At,er,tc,hc,Qn,yc,wc,M0,F0,Lo,Ei,Jt,By,qn,Ii,Md,$n,xt,Qs,Ld,Jc,To,yg,Jo,eS,Er,tS,G0];function mD(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(`
|
|
929
929
|
`)}export{V5 as buildProgram};
|
|
930
|
-
//# sourceMappingURL=program-
|
|
930
|
+
//# sourceMappingURL=program-Q4DXWAQU.js.map
|