agentix-cli 0.213.0 → 0.213.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-TF6XQQGV.js → agent-6VEMBVRN.js} +2 -2
- package/dist/{chunk-36RIIHPS.js → chunk-2V43GUET.js} +68 -68
- package/dist/chunk-2V43GUET.js.map +1 -0
- package/dist/{chunk-X7UEV4O2.js → chunk-6PBYRK7J.js} +2 -2
- package/dist/{chunk-NZFWW2YG.js → chunk-DYH6KS3X.js} +3 -3
- package/dist/{chunk-7JWMLYOA.js → chunk-NERO7F3J.js} +2 -2
- package/dist/chunk-NERO7F3J.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{program-4WR4ZYXQ.js → program-3QOBRNT4.js} +7 -7
- package/dist/{registry-LD2IYY7L.js → registry-J3Y3DDFT.js} +2 -2
- package/dist/{workspace-setup-VLLF37SJ.js → workspace-setup-PIPGUMLG.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-36RIIHPS.js.map +0 -1
- package/dist/chunk-7JWMLYOA.js.map +0 -1
- /package/dist/{agent-TF6XQQGV.js.map → agent-6VEMBVRN.js.map} +0 -0
- /package/dist/{chunk-X7UEV4O2.js.map → chunk-6PBYRK7J.js.map} +0 -0
- /package/dist/{chunk-NZFWW2YG.js.map → chunk-DYH6KS3X.js.map} +0 -0
- /package/dist/{program-4WR4ZYXQ.js.map → program-3QOBRNT4.js.map} +0 -0
- /package/dist/{registry-LD2IYY7L.js.map → registry-J3Y3DDFT.js.map} +0 -0
- /package/dist/{workspace-setup-VLLF37SJ.js.map → workspace-setup-PIPGUMLG.js.map} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Oa as Tt,Pa as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-
|
|
1
|
+
import{Oa as Tt,Pa as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-DYH6KS3X.js";import"./chunk-Z6N7POAU.js";import"./chunk-GTJIKXDB.js";import"./chunk-NWE3B245.js";import"./chunk-EE5RZDQE.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-BU6V75KD.js";import"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-WKBGQGVL.js";import"./chunk-MRIVENBY.js";import"./chunk-GJOKXP5D.js";import"./chunk-A5GYG56I.js";import"./chunk-DSUL5L3T.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-DPA3IOMU.js";import"./chunk-QPABR72X.js";import"./chunk-IFUAP7UD.js";import"./chunk-KP7KDLZ2.js";import{Ia as yt,r as lt,s as ct,t as dt,u as mt,v as pt}from"./chunk-2V43GUET.js";import"./chunk-N7IX77SL.js";import"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import{a as L}from"./chunk-BAXGL6TY.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-6PBYRK7J.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-CUCIMPFI.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-IH65GDJR.js";import{u as ut}from"./chunk-ERKK22QV.js";import"./chunk-G3GFE3GK.js";import"./chunk-3UOTLMXD.js";import"./chunk-XVV7ZZ77.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-LIY5CHUV.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-VWTBHLMX.js";import"./chunk-FCF47R4W.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import"./chunk-NERO7F3J.js";import"./chunk-XL7UWG36.js";import"./chunk-MNG2AMKZ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-HPRLRD4P.js";import"./chunk-XBFXSSHA.js";import{a as ht}from"./chunk-DGCYMSXU.js";import{f as gt,g as ft}from"./chunk-I722PWJE.js";import"./chunk-WPNRDEHW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-D3FIIEDR.js";import{j as it,k as rt,l as at}from"./chunk-IXV3BPUZ.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import"./chunk-BYEL7KKR.js";import"./chunk-QUFIUXMQ.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-DCIYOPJF.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{Ob as tt,Qb as st,Tb as ot,_b as nt}from"./chunk-UWDDVDU6.js";import"./chunk-KEUW6YLL.js";import"./chunk-N47Y5ADQ.js";import"./chunk-YSCT6DPR.js";import"./chunk-VQRY4IDI.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
|
|
2
2
|
`)}
|
|
3
3
|
|
|
4
4
|
${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as by,b as ga,g as $y}from"./chunk-O4WFPH6H.js";import{a as yy,b as wy}from"./chunk-MOATCFT5.js";import{b as hy}from"./chunk-DNPPPUDP.js";import{$ as Kh,A as Dh,B as qh,C as Fh,E as Uh,G as Wh,H as Bh,I as Hc,J as Hh,U as Jh,V as Gh,W as Jc,X as zh,_ as Yh,aa as Xh,ba as Vh,ca as ty,da as oy,ea as ny,fa as sy,g as vh,ga as ry,h as xh,ha as iy,ja as Gc,ka as ay,l as Sh,la as ly,m as Eh,na as cy,o as Ds,p as Ps,q as Ah,qa as dy,r as Rh,ra as uy,s as Th,sa as gy,t as Ch,u as Oh,v as Ih,x as zt,z as _h}from"./chunk-D6H4DH32.js";import{a as Qh,c as Zh,d as ey}from"./chunk-FFOGEFPT.js";import{n as zc}from"./chunk-VKLTCUD7.js";import{a as my,b as py,d as Dr,e as fy}from"./chunk-4W5KRZTT.js";import"./chunk-EFGAPAYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as Nh,c as jh}from"./chunk-BERSMN6Y.js";import"./chunk-WMZ4TGMR.js";import{d as Ph,e as Bc,h as Mh,i as Lh}from"./chunk-6UI7GJSB.js";import"./chunk-2YDG5CSS.js";import{b as jo}from"./chunk-7NQQIDDI.js";import{a as Uc}from"./chunk-LNY6N73E.js";import{a as xp,b as $c}from"./chunk-GMP2IB4E.js";import{a as fc,b as sp}from"./chunk-RKPAVWXF.js";import{$ as Jf,A as Ac,Aa as jr,B as bf,Ba as fh,C as Rc,Ca as pt,D as $f,Da as la,E as kf,Ea as ca,F as vf,Fa as _r,G as xf,Ga as Lc,H as Sf,Ha as hh,I as Ef,Ia as wh,J as Tc,Ja as Fc,K as Af,Ka as $h,L as ta,La as da,M as Rf,Ma as _s,N as Cc,Na as ua,O as Tf,Oa as Wc,P as Cf,Pa as kh,Q as Of,R as If,S as Nf,T as oa,U as Mf,V as Ff,W as Uf,X as Wf,Y as Bf,Z as Hf,_ as Ic,a as Tp,aa as Gf,b as Cp,ba as zf,ca as Yf,da as Kf,ea as Xf,fa as Vf,ga as Qf,h as Ji,ha as Zf,i as Os,ia as eh,j as jp,ja as ah,k as Cr,ka as ra,l as Gi,la as No,m as Dp,ma as Xo,n as Mp,na as Is,o as Qp,oa as ia,p as Zp,pa as aa,q as Qi,qa as Mc,r as Ec,ra as lh,s as af,sa as ch,t as mf,ta as dh,u as pf,ua as uh,v as ff,va as gh,w as hf,wa as mh,x as ea,xa as Ns,y as yf,ya as js,z as wf,za as ph}from"./chunk-NZFWW2YG.js";import{Bb as rh,Cb as ih,Db as Dc,Kb as Pc,P as lf,R as Or,S as cf,V as df,W as Zi,Zb as yh,_b as qc,ab as Ir,db as Nc,eb as na,fb as th,mb as Ko,mc as go,nb as oh,ob as jc,oc as bh,pa as jf,qa as _f,qb as _c,ra as Df,sa as Oc,sb as nh,tb as sh,ub as Nr,v as Pp,va as Pf,yb as sa}from"./chunk-Z6N7POAU.js";import"./chunk-GTJIKXDB.js";import{a as Op,c as vc,d as Tr,f as Ip,g as Np}from"./chunk-NWE3B245.js";import{A as Hp,B as Jp,C as Gp,D as zp,E as Yp,F as Kp,K as Ki,L as Xp,M as Vp,Q as uf,R as gf,a as mc,b as Qm,e as Zm,f as ep,o as Lp,s as zi,t as Yi,u as qp,v as Fp,w as Up,y as Wp,z as Bp}from"./chunk-EE5RZDQE.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as Lf,b as qf}from"./chunk-EKJG63EJ.js";import"./chunk-BU6V75KD.js";import{c as ef}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import{c as Sc}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as tf,e as Xi,g as Vi}from"./chunk-LQE73AZR.js";import{a as of,b as nf,c as sf,d as rf}from"./chunk-2D3RYIDU.js";import{a as Lt}from"./chunk-WKBGQGVL.js";import"./chunk-MRIVENBY.js";import"./chunk-GJOKXP5D.js";import"./chunk-A5GYG56I.js";import{a as xc,p as _p}from"./chunk-DSUL5L3T.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Mt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import{a as gp,b as mp,c as pp,d as fp,e as yc,f as hp,g as wc,h as bc,l as yp,m as wp}from"./chunk-RX5O5637.js";import{f as bp,i as $p,l as kp,m as vp}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{m as Sp,n as Ep,o as kc,p as Hi,q as Ap,r as Rp}from"./chunk-DPA3IOMU.js";import{a as pc,d as tp,e as Bi}from"./chunk-QPABR72X.js";import{b as Cs,e as np}from"./chunk-IFUAP7UD.js";import{c as op}from"./chunk-KP7KDLZ2.js";import{Ia as Vm,J as lc,K as Nm,Y as Yo,ca as zm,fa as Km,ga as Xm,l as vm,w as xm,x as Sm,y as Em}from"./chunk-36RIIHPS.js";import{I as Ss,J as Ui,K as Wi,L as Es,M as _m,N as Go,P as zo,b as xs,fa as Jm,r as Co,s as cc,t as jm,u as dc,ua as Gm,w as Oo,wa as Ym,x as Fi}from"./chunk-N7IX77SL.js";import{b as En}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-X7UEV4O2.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{a as Rr,e as rp,f as ip,g as hc,i as ap,j as lp,l as cp,m as dp,n as up}from"./chunk-CUCIMPFI.js";import{f as Mm,g as Lm,h as uc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as Fm,f as Io,k as Rs}from"./chunk-IH65GDJR.js";import{a as Om,l as qm,o as Hm}from"./chunk-ERKK22QV.js";import{a as Ye,b as pe,c as Be,d as Ts,e as Um}from"./chunk-G3GFE3GK.js";import{a as Wm,b as gc,h as Bm}from"./chunk-3UOTLMXD.js";import"./chunk-XVV7ZZ77.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Im}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-LIY5CHUV.js";import{a as As}from"./chunk-GV7S5BAX.js";import{e as Dm}from"./chunk-GSX4NK2N.js";import{c as Pm}from"./chunk-SZDACK6O.js";import"./chunk-VWTBHLMX.js";import"./chunk-FCF47R4W.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as Rm,j as Tm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as ac,b as Cm}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as rc,p as $m,w as km}from"./chunk-7JWMLYOA.js";import{d as fm,e as Sn,f as hm,g as vs,j as ym,k as wm,m as bm,n as sc,r as Mi,s as It,t as Li}from"./chunk-XL7UWG36.js";import{a as uo}from"./chunk-MNG2AMKZ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-HPRLRD4P.js";import{a as ic}from"./chunk-XBFXSSHA.js";import"./chunk-DGCYMSXU.js";import{g as Jo,i as qi}from"./chunk-I722PWJE.js";import"./chunk-WPNRDEHW.js";import{c as Am}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-D3FIIEDR.js";import{a as Kl,b as _g,c as V0,d as Ci,e as Dg,f as am,g as aS,h as lm,i as lS,m as ks,n as dm,q as um,u as gm,y as co,z as Ar}from"./chunk-IXV3BPUZ.js";import{a as To,b as $s,e as sm,f as Er}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Pi,b as cm}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as pm}from"./chunk-BYEL7KKR.js";import{h as Ho,j as mm}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as lo,b as X0}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as Hg,B as Wg,C as Bg,Ca as Xg,D as eS,Ea as Vg,Fa as Qg,Lb as nc,M as Vl,N as tS,Ob as _i,Pb as xn,Qb as O,Tb as Di,Ua as Zg,X as ws,Y as Sr,Ya as nS,_b as Z,aa as Jg,ba as Ql,f as Oi,fb as em,g as Pg,ga as Gg,gb as vn,ha as oS,ib as ec,j as Pt,k as Xl,m as Mg,ma as Ni,n as Ii,na as ji,p as Q0,pb as tc,qa as zg,qb as oc,sa as Yg,sb as tm,ta as bs,tb as sS,ua as Zl,va as Kg,x as qg,y as Fg,z as Ug,zb as nm}from"./chunk-UWDDVDU6.js";import"./chunk-KEUW6YLL.js";import{j as Ve,r as Bo}from"./chunk-N47Y5ADQ.js";import{a as om,c as rS}from"./chunk-YSCT6DPR.js";import{a as Lg,e as Z0}from"./chunk-VQRY4IDI.js";import{g as rm,k as im,l as iS}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as cS}from"commander";var ky=new cS().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 Cp({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 dS}from"commander";import{execFileSync as mo}from"node:child_process";import{cpSync as vy,existsSync as Xc,mkdirSync as Yc,mkdtempSync as uS,readdirSync as gS,rmSync as xy,writeFileSync as Sy}from"node:fs";import{dirname as Ey,join as ft}from"node:path";import{homedir as ma,release as mS,tmpdir as pS}from"node:os";import{setTimeout as fS}from"node:timers/promises";function pa(){let e=qp(process.platform,process.arch,mS());if(e)throw new Error(e)}function fa(){let e=ft(ma(),"Library/LaunchAgents"),t=[];try{t=gS(e).filter(Wp)}catch{}let o=t.flatMap(n=>{let s=ft(e,n);try{return[{file:s,plist:mo("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Bp(e,o)}function Pr(e){return`gui/${process.getuid()}/${e.label}`}async function Kc(e){try{mo("launchctl",["bootout",Pr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{mo("launchctl",["print",Pr(e)],{stdio:"pipe"})}catch{return}await fS(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Ay(e){if(!Xc(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{mo("launchctl",["print",Pr(e)],{stdio:"pipe"})}catch{t=!1}t||mo("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),mo("launchctl",["kickstart",Pr(e)],{stdio:"pipe"})}function hS(){let e=Kp();if(e&&Xc(ft(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 Ms=new dS("desktop").description("install and control the macOS desktop assistant");Ms.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=>{pa();let t=O(),o=Fp(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=hS(),i=ft(ma(),"Applications"),{keep:a,remove:l}=fa();if(console.log(`Desktop assistant \u2192 ${ft(i,zi)}
|
|
1
|
+
import{a as by,b as ga,g as $y}from"./chunk-O4WFPH6H.js";import{a as yy,b as wy}from"./chunk-MOATCFT5.js";import{b as hy}from"./chunk-DNPPPUDP.js";import{$ as Kh,A as Dh,B as qh,C as Fh,E as Uh,G as Wh,H as Bh,I as Hc,J as Hh,U as Jh,V as Gh,W as Jc,X as zh,_ as Yh,aa as Xh,ba as Vh,ca as ty,da as oy,ea as ny,fa as sy,g as vh,ga as ry,h as xh,ha as iy,ja as Gc,ka as ay,l as Sh,la as ly,m as Eh,na as cy,o as Ds,p as Ps,q as Ah,qa as dy,r as Rh,ra as uy,s as Th,sa as gy,t as Ch,u as Oh,v as Ih,x as zt,z as _h}from"./chunk-D6H4DH32.js";import{a as Qh,c as Zh,d as ey}from"./chunk-FFOGEFPT.js";import{n as zc}from"./chunk-VKLTCUD7.js";import{a as my,b as py,d as Dr,e as fy}from"./chunk-4W5KRZTT.js";import"./chunk-EFGAPAYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as Nh,c as jh}from"./chunk-BERSMN6Y.js";import"./chunk-WMZ4TGMR.js";import{d as Ph,e as Bc,h as Mh,i as Lh}from"./chunk-6UI7GJSB.js";import"./chunk-2YDG5CSS.js";import{b as jo}from"./chunk-7NQQIDDI.js";import{a as Uc}from"./chunk-LNY6N73E.js";import{a as xp,b as $c}from"./chunk-GMP2IB4E.js";import{a as fc,b as sp}from"./chunk-RKPAVWXF.js";import{$ as Jf,A as Ac,Aa as jr,B as bf,Ba as fh,C as Rc,Ca as pt,D as $f,Da as la,E as kf,Ea as ca,F as vf,Fa as _r,G as xf,Ga as Lc,H as Sf,Ha as hh,I as Ef,Ia as wh,J as Tc,Ja as Fc,K as Af,Ka as $h,L as ta,La as da,M as Rf,Ma as _s,N as Cc,Na as ua,O as Tf,Oa as Wc,P as Cf,Pa as kh,Q as Of,R as If,S as Nf,T as oa,U as Mf,V as Ff,W as Uf,X as Wf,Y as Bf,Z as Hf,_ as Ic,a as Tp,aa as Gf,b as Cp,ba as zf,ca as Yf,da as Kf,ea as Xf,fa as Vf,ga as Qf,h as Ji,ha as Zf,i as Os,ia as eh,j as jp,ja as ah,k as Cr,ka as ra,l as Gi,la as No,m as Dp,ma as Xo,n as Mp,na as Is,o as Qp,oa as ia,p as Zp,pa as aa,q as Qi,qa as Mc,r as Ec,ra as lh,s as af,sa as ch,t as mf,ta as dh,u as pf,ua as uh,v as ff,va as gh,w as hf,wa as mh,x as ea,xa as Ns,y as yf,ya as js,z as wf,za as ph}from"./chunk-DYH6KS3X.js";import{Bb as rh,Cb as ih,Db as Dc,Kb as Pc,P as lf,R as Or,S as cf,V as df,W as Zi,Zb as yh,_b as qc,ab as Ir,db as Nc,eb as na,fb as th,mb as Ko,mc as go,nb as oh,ob as jc,oc as bh,pa as jf,qa as _f,qb as _c,ra as Df,sa as Oc,sb as nh,tb as sh,ub as Nr,v as Pp,va as Pf,yb as sa}from"./chunk-Z6N7POAU.js";import"./chunk-GTJIKXDB.js";import{a as Op,c as vc,d as Tr,f as Ip,g as Np}from"./chunk-NWE3B245.js";import{A as Hp,B as Jp,C as Gp,D as zp,E as Yp,F as Kp,K as Ki,L as Xp,M as Vp,Q as uf,R as gf,a as mc,b as Qm,e as Zm,f as ep,o as Lp,s as zi,t as Yi,u as qp,v as Fp,w as Up,y as Wp,z as Bp}from"./chunk-EE5RZDQE.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as Lf,b as qf}from"./chunk-EKJG63EJ.js";import"./chunk-BU6V75KD.js";import{c as ef}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import{c as Sc}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as tf,e as Xi,g as Vi}from"./chunk-LQE73AZR.js";import{a as of,b as nf,c as sf,d as rf}from"./chunk-2D3RYIDU.js";import{a as Lt}from"./chunk-WKBGQGVL.js";import"./chunk-MRIVENBY.js";import"./chunk-GJOKXP5D.js";import"./chunk-A5GYG56I.js";import{a as xc,p as _p}from"./chunk-DSUL5L3T.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Mt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import{a as gp,b as mp,c as pp,d as fp,e as yc,f as hp,g as wc,h as bc,l as yp,m as wp}from"./chunk-RX5O5637.js";import{f as bp,i as $p,l as kp,m as vp}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{m as Sp,n as Ep,o as kc,p as Hi,q as Ap,r as Rp}from"./chunk-DPA3IOMU.js";import{a as pc,d as tp,e as Bi}from"./chunk-QPABR72X.js";import{b as Cs,e as np}from"./chunk-IFUAP7UD.js";import{c as op}from"./chunk-KP7KDLZ2.js";import{Ia as Vm,J as lc,K as Nm,Y as Yo,ca as zm,fa as Km,ga as Xm,l as vm,w as xm,x as Sm,y as Em}from"./chunk-2V43GUET.js";import{I as Ss,J as Ui,K as Wi,L as Es,M as _m,N as Go,P as zo,b as xs,fa as Jm,r as Co,s as cc,t as jm,u as dc,ua as Gm,w as Oo,wa as Ym,x as Fi}from"./chunk-N7IX77SL.js";import{b as En}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-6PBYRK7J.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{a as Rr,e as rp,f as ip,g as hc,i as ap,j as lp,l as cp,m as dp,n as up}from"./chunk-CUCIMPFI.js";import{f as Mm,g as Lm,h as uc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as Fm,f as Io,k as Rs}from"./chunk-IH65GDJR.js";import{a as Om,l as qm,o as Hm}from"./chunk-ERKK22QV.js";import{a as Ye,b as pe,c as Be,d as Ts,e as Um}from"./chunk-G3GFE3GK.js";import{a as Wm,b as gc,h as Bm}from"./chunk-3UOTLMXD.js";import"./chunk-XVV7ZZ77.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Im}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-LIY5CHUV.js";import{a as As}from"./chunk-GV7S5BAX.js";import{e as Dm}from"./chunk-GSX4NK2N.js";import{c as Pm}from"./chunk-SZDACK6O.js";import"./chunk-VWTBHLMX.js";import"./chunk-FCF47R4W.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as Rm,j as Tm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as ac,b as Cm}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as rc,p as $m,w as km}from"./chunk-NERO7F3J.js";import{d as fm,e as Sn,f as hm,g as vs,j as ym,k as wm,m as bm,n as sc,r as Mi,s as It,t as Li}from"./chunk-XL7UWG36.js";import{a as uo}from"./chunk-MNG2AMKZ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-HPRLRD4P.js";import{a as ic}from"./chunk-XBFXSSHA.js";import"./chunk-DGCYMSXU.js";import{g as Jo,i as qi}from"./chunk-I722PWJE.js";import"./chunk-WPNRDEHW.js";import{c as Am}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-D3FIIEDR.js";import{a as Kl,b as _g,c as V0,d as Ci,e as Dg,f as am,g as aS,h as lm,i as lS,m as ks,n as dm,q as um,u as gm,y as co,z as Ar}from"./chunk-IXV3BPUZ.js";import{a as To,b as $s,e as sm,f as Er}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Pi,b as cm}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as pm}from"./chunk-BYEL7KKR.js";import{h as Ho,j as mm}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as lo,b as X0}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as Hg,B as Wg,C as Bg,Ca as Xg,D as eS,Ea as Vg,Fa as Qg,Lb as nc,M as Vl,N as tS,Ob as _i,Pb as xn,Qb as O,Tb as Di,Ua as Zg,X as ws,Y as Sr,Ya as nS,_b as Z,aa as Jg,ba as Ql,f as Oi,fb as em,g as Pg,ga as Gg,gb as vn,ha as oS,ib as ec,j as Pt,k as Xl,m as Mg,ma as Ni,n as Ii,na as ji,p as Q0,pb as tc,qa as zg,qb as oc,sa as Yg,sb as tm,ta as bs,tb as sS,ua as Zl,va as Kg,x as qg,y as Fg,z as Ug,zb as nm}from"./chunk-UWDDVDU6.js";import"./chunk-KEUW6YLL.js";import{j as Ve,r as Bo}from"./chunk-N47Y5ADQ.js";import{a as om,c as rS}from"./chunk-YSCT6DPR.js";import{a as Lg,e as Z0}from"./chunk-VQRY4IDI.js";import{g as rm,k as im,l as iS}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as cS}from"commander";var ky=new cS().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 Cp({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 dS}from"commander";import{execFileSync as mo}from"node:child_process";import{cpSync as vy,existsSync as Xc,mkdirSync as Yc,mkdtempSync as uS,readdirSync as gS,rmSync as xy,writeFileSync as Sy}from"node:fs";import{dirname as Ey,join as ft}from"node:path";import{homedir as ma,release as mS,tmpdir as pS}from"node:os";import{setTimeout as fS}from"node:timers/promises";function pa(){let e=qp(process.platform,process.arch,mS());if(e)throw new Error(e)}function fa(){let e=ft(ma(),"Library/LaunchAgents"),t=[];try{t=gS(e).filter(Wp)}catch{}let o=t.flatMap(n=>{let s=ft(e,n);try{return[{file:s,plist:mo("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Bp(e,o)}function Pr(e){return`gui/${process.getuid()}/${e.label}`}async function Kc(e){try{mo("launchctl",["bootout",Pr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{mo("launchctl",["print",Pr(e)],{stdio:"pipe"})}catch{return}await fS(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Ay(e){if(!Xc(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{mo("launchctl",["print",Pr(e)],{stdio:"pipe"})}catch{t=!1}t||mo("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),mo("launchctl",["kickstart",Pr(e)],{stdio:"pipe"})}function hS(){let e=Kp();if(e&&Xc(ft(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 Ms=new dS("desktop").description("install and control the macOS desktop assistant");Ms.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=>{pa();let t=O(),o=Fp(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=hS(),i=ft(ma(),"Applications"),{keep:a,remove:l}=fa();if(console.log(`Desktop assistant \u2192 ${ft(i,zi)}
|
|
2
2
|
Computer-use helper \u2192 ${ft(i,Yi)}
|
|
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 Cw=[Sw,Tw,Ew,Aw,Rw];function Sa(){return Cw.map(e=>Bs(e))}function Vo(e){let t=Cw.find(o=>o.name===e);return t?Bs(t):void 0}Z();import{existsSync as NE,readFileSync as jE}from"fs";import{connect as _E}from"net";import{cpus as DE,loadavg as PE}from"os";import{basename as ME,resolve as LE}from"path";function Ea(e=process.argv[1]??"",t=process.env){let o=e.replace(/\\/g,"/");return t.npm_command==="exec"||o.includes("/_npx/")?"npx agentix-cli":ME(o)==="cli.js"&&!o.includes("/node_modules/")?"node dist/cli.js":"agentx"}function Nw(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 jw(e,t="127.0.0.1"){let o=await Promise.all(e.map(n=>new Promise(s=>{let r=_E({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 Ow="AGENTX_DEMO_STARTUP_TIMEOUT",qE=60,FE=300;function UE(e,t){let o=Math.max(1,e/Math.max(1,t));return Math.min(FE,Math.ceil(qE*o))}function Iw(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 _w(e){let t=LE(e,"agentx.json");if(!NE(t))return;let o;try{o=JSON.parse(jE(t,"utf8"))}catch{return}let n=_i.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 Dw(e){let t=Iw(e.flag,"--startup-timeout");if(t!==void 0)return{seconds:t,source:"--startup-timeout"};let o=Iw(e.env,Ow);if(o!==void 0)return{seconds:o,source:Ow};if(e.config!==void 0)return{seconds:e.config,source:"demo.startupTimeoutSeconds"};let n=e.load1??PE()[0],s=e.cpuCount??DE().length;return{seconds:UE(n,s),source:`default for load ${n.toFixed(1)} on ${s} CPUs`}}import{Command as WE}from"commander";import ye from"chalk";import{cpSync as BE,existsSync as Js,mkdirSync as Pw,readFileSync as md,writeFileSync as HE}from"fs";import{dirname as gd,resolve as On}from"path";import{fileURLToPath as JE}from"url";var Mw=["claude-code","codex-cli","opencode","sdk","orchestrator"];function pd(e){let t=Ye(e);return Js(t)||(console.log(ye.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),{path:t,config:JSON.parse(md(t,"utf-8"))}}function Nt(e){console.log(ye.red(` ${e.split(`
|
|
40
40
|
`).join(`
|
|
41
41
|
`)}`)),process.exit(1)}function Lw(e){let t=On(e);Js(t)||Nt(`No file at ${t}`);let o;try{o=JSON.parse(md(t,"utf-8"))}catch(n){Nt(`${t} is not JSON: ${n.message}`)}try{return Bs(o)}catch(n){Nt(n.message)}}function GE(e){let t=Vo(e);if(t)return t;if(Js(On(e))||e.endsWith(".json"))return Lw(e);Nt(`No team named "${e}". Run: agentx team list`)}async function Aa(e,t){t.tier&&!Mw.includes(t.tier)&&Nt(`--tier must be one of: ${Mw.join(", ")}`);let{path:o,config:n}=pd(t.config),s=On(gd(o),t.workspaces??"agents"),r=Hs(n,e,{workspaceRoot:s,force:t.force});r.length&&Nt(`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=bw(d,e,{workspaceRoot:s,tier:t.tier,provider:t.provider,timezone:t.timezone,force:t.force})},{configPath:o,dryRun:!!t.dryRun});(!a.success||!i)&&Nt(`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 l=[];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=bw(d,e,{workspaceRoot:s,tier:t.tier,provider:t.provider,timezone:t.timezone,force:t.force})},{configPath:o,dryRun:!!t.dryRun});(!a.success||!i)&&Nt(`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 l=[];if(!t.dryRun){let{setupWorkspace:d}=await import("./workspace-setup-PIPGUMLG.js"),p=zE();for(let f of i.agents){Pw(f.workspace,{recursive:!0}),d(f.id,a.after&&a.after.agents[f.id],"19900",()=>{});let g=On(f.workspace,".claude/skills/wiki/SKILL.md");p&&f.tier==="claude-code"&&!Js(g)&&(Pw(gd(g),{recursive:!0}),BE(p,g,{errorOnExist:!0,force:!1}))}l=kw(e,i).kept}let c=t.dryRun?void 0:Fi(Co(),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)")),c&&console.log(ye.yellow(` Added by agent "${c}": these agents start once the owner approves each one (agentx approvals list).`)),l.length){console.log(ye.yellow(` Kept ${l.length} file${l.length===1?"":"s"} already there instead of the team's version:`));for(let d of l)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 zE(){return[On(process.cwd(),"src/wiki/SKILL.md"),On(gd(JE(import.meta.url)),"../wiki/SKILL.md")].find(t=>Js(t))??null}var In=new WE().name("team").description("ready-made teams \u2014 list, add one in one step, export and import");In.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=Ye(e.config),o=Js(t)?JSON.parse(md(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 Sa()){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=>!Vo(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 ${Cn(o,r).join(", ")}`)}console.log(),console.log(ye.dim(" Add one: agentx team add <name>")),console.log()});In.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 Aa(GE(e),t)});In.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 Aa(Lw(e),t)});In.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}=pd(o.config),r=Cn(s,e);r.length||Nt(`No agents belong to team "${e}". Run: agentx team list`);let i=YE(t??"me",s),a=Object.entries(s.crons||{}).filter(([,u])=>r.includes(u?.agent)&&u.deliverResult===!0).map(([u])=>u);a.length||Nt(`Team "${e}" has no schedules that report to you.`);let l=[],c=await pe(u=>{l=xa(u,i,{ids:a,replace:!0})},{configPath:n});c.success||Nt(`Config save failed: ${c.error}`),console.log(ye.green(` Results of ${l.join(", ")} now go to ${i.channel} (${i.chatId})`)),c.reloaded&&console.log(ye.dim(" (daemon hot-reloaded)"))});function YE(e,t){if(e==="me"){let r=ud(t);return r||Nt('No notifications.destination yet. Run: agentx connect telegram, or give "channel:chatId".'),r}let[o,n,s]=e.split(":");return(!o||!n)&&Nt(`Not a target: ${e} (use "me" or "channel:chatId[:accountId]")`),s?{channel:o,chatId:n,accountId:s}:{channel:o,chatId:n}}In.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}=pd(t.config),n=Vo(e),s;try{s=vw(o,e,{agents:t.agents,title:t.title??n?.title,result:t.result??n?.result,description:t.description??n?.description,expectedChannels:n?.channels})}catch(c){Nt(c.message)}let r=JSON.stringify(s,null,2)+`
|
|
43
43
|
`;if(t.output==="-"){process.stdout.write(r);return}let i=On(t.output??`${e}.team.json`);HE(i,r);let a=Object.keys(s.agents).length,l=Object.keys(s.schedules).length;console.log(ye.green(` Team "${e}" written to ${i}`)),console.log(ye.dim(` ${a} agent${a===1?"":"s"}, ${l} schedule${l===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 KE}from"fs";import{resolve as qw}from"path";var fd="assistant";function Fw(e){for(let t of[qw(e,"agentx.json"),qw(e,".agentx/config.json")])if(KE(t))return t;return null}function Uw(e,t){return{nodeName:e.trim()||"My team",agent:{id:fd,name:"Assistant",triggerWords:`@${fd}, ${fd}`,...t?{tier:"claude-code"}:{tier:"orchestrator",provider:"claude"}}}}function hd(e){let t=Object.keys(e.agents||{}),o=e.node?.defaultAgent;return o&&t.includes(o)?o:t[0]??null}function Ww(e){return`http://${e.replace(/^0\.0\.0\.0(?=:)/,"127.0.0.1").replace(/^\[::\](?=:)/,"127.0.0.1")}`}function Bw(e){return Ww(e.node?.bind||"127.0.0.1:18800")}function yd(e){return Ww(`${e.dashboard?.bind||"127.0.0.1"}:${e.dashboard?.port||4202}`)}function Hw(e,t){return`${yd(e)}/admin/agents/${encodeURIComponent(t)}#chat`}function Jw(e,t){let o=e?.node?.id;return!o||!t.node?.id||o===t.node.id}function Gw(e,t,o){let n=Vo(t);if(!n)return{error:`No team named "${t}".`};if(Cn(e,n.name).length)return{skip:`Team ${n.name} is already added (left as it is)`};let s=o?.workspaceRoot?Hs(e,n,{workspaceRoot:o.workspaceRoot}):Hs(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?.[hd(e)??""];return{add:{team:n.name,tier:r?.tier,provider:r?.provider}}}var eb=new XE().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=Ea(),n=process.argv[1];(!n||!zw(n))&&Nn("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(it.bold(" agentx start"));let r=Fw(t),i=!r,a=i?Uw(oA().replace(/\.local$/,""),!!Pc("claude")):void 0,l=e.team??(i&&process.stdin.isTTY&&process.stdout.isTTY?await sA():void 0),c=l?Gw(r?JSON.parse(Yw(r,"utf-8")):{agents:{[a.agent.id]:a.agent}},l,{workspaceRoot:Ta(r?nA(r):t,"agents")}):void 0;c&&"error"in c&&Nn(`${c.error} See \`${o} team list\`.`),r?console.log(it.dim(` Using ${r} (left as it is)`)):(xh(a,t,{daemonPort:Kw(e.port,"--port"),dashboardPort:Kw(e.dashboardPort,"--dashboard-port")}),r=Ta(t,"agentx.json"),console.log(it.green(` \u2713 Created agentx.json with one agent, ${a.agent.id} (engine: ${a.agent.tier})`)));let u=!1;c&&"skip"in c&&console.log(it.dim(` ${c.skip}`)),c&&"add"in c&&(await Aa(Vo(c.add.team),{config:r,tier:c.add.tier,provider:c.add.provider}),u=!0);let d;try{d=O(r)}catch(S){Nn(`${r}: ${S.message}`)}let p=hd(d);p||Nn(`No agent in ${r}. Add one with \`${o} setup\`, then run \`${o} start\` again.`);let f=Ta(t,".agentx");ZE(f,{recursive:!0});let g=Bw(d),h=await Vw(g);if(h&&!Jw(h,d)&&Nn(`${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(it.green(` \u2713 Daemon already running at ${g}`)),u&&console.log(it.yellow(` Restart it to start the team's agents: ${o} daemon restart`));else{let S=Ra(f,"daemon.log");Xw(n,["daemon","start","-c",r],t,S),await Zw(`the daemon at ${g}`,async()=>!!await Vw(g),s,S),console.log(it.green(` \u2713 Daemon started at ${g}`)+it.dim(` (log: ${S})`))}let y=yd(d);if(await Qw(`${y}/live`))console.log(it.green(` \u2713 Dashboard already running at ${y}`));else{let S=Ra(f,"board.log"),k=Xw(n,["board","serve"],t,S);k&&tA(Ra(f,"board.pid"),String(k)),await Zw(`the dashboard at ${y}`,()=>Qw(`${y}/live`),s,S),console.log(it.green(` \u2713 Dashboard started at ${y}`)+it.dim(` (log: ${S})`))}let w=Hw(d,p),$=d.agents[p]?.name||p,x=Sh({rawConfig:JSON.parse(Yw(r,"utf-8")),agentId:p,env:process.env,dotenv:pm(Ta(t,".env")),hasBinary:S=>!!Pc(S),cliLoggedIn:Eh});console.log(),x.ready?console.log(it.bold(` Your first agent, ${$}, is answering at ${it.cyan(w)}`)):(console.log(it.bold(` Your first agent, ${$}, is waiting for a model at ${it.cyan(w)}`)),x.hint&&console.log(` ${x.hint}`)),console.log(it.dim(` Run \`${o} start\` again any time: it reuses what is running.`));let v=Ra(f,"board.pid");console.log(it.dim(` Stop the daemon: ${o} daemon stop`+(zw(v)?" \xB7 the dashboard: kill $(cat .agentx/board.pid)":""))),console.log(),e.open!==!1&&jo(w)});async function sA(){let{team:e}=await VE({type:"select",name:"team",message:"Start with a ready-made team as well?",choices:[{title:"No, one assistant for now",value:""},...Sa().map(t=>({title:`${t.name}: ${t.title}`,description:t.result,value:t.name}))],initial:0});return e||void 0}function Nn(e){console.error(it.red(` ${e}`)),process.exit(1)}function Kw(e,t){if(e===void 0)return;let o=Number(e);return(!Number.isInteger(o)||o<1||o>65535)&&Nn(`${t} must be a port number, got "${e}"`),o}function Xw(e,t,o,n){let s=eA(n,"a"),r=QE(process.execPath,[e,...t],{cwd:o,detached:!0,stdio:["ignore",s,s]});return r.unref(),r.pid}async function Vw(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 Qw(e){try{return(await fetch(e,{signal:AbortSignal.timeout(3e3)})).ok}catch{return!1}}async function Zw(e,t,o,n){let s=Date.now()+o;for(;Date.now()<s;){if(await t())return;await new Promise(r=>setTimeout(r,400))}Nn(`Timed out after ${o/1e3}s waiting for ${e}. See ${n}, or raise --startup-timeout.`)}import{Command as rA}from"commander";import et from"chalk";var Hr=new rA().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Hr.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 Mt,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(et.bold(" Token created.")),console.log(),console.log(` id: ${et.cyan(r.id)}`),console.log(` name: ${r.name}`),console.log(` scopes: ${r.scopes.join(", ")}`),console.log(` expires: ${r.expiresAt||et.dim("never")}`),console.log(),console.log(et.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${et.green.bold(s)}`),console.log(),console.log(et.dim(" Use it via the Authorization header:")),console.log(et.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(t){console.log(et.red(` ${t.message}`)),process.exit(1)}});Hr.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new Mt().list();if(e.length===0){console.log(et.dim(`
|
|
44
44
|
No tokens issued.
|
|
45
45
|
`));return}console.log();for(let t of e){let o=t.revokedAt?et.red("revoked"):t.expiresAt&&Date.parse(t.expiresAt)<Date.now()?et.red("expired"):et.green("active");console.log(` ${et.cyan(t.id)} ${o} ${t.name}`),console.log(et.dim(` prefix: ${t.prefix}\u2026 scopes: ${t.scopes.join(", ")}`)),console.log(et.dim(` created: ${t.createdAt}${t.expiresAt?` expires: ${t.expiresAt}`:""}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(et.red(` ${e.message}`)),process.exit(1)}});Hr.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let t=new Mt().revoke(e);t||(console.log(et.red(` Token ${e} not found.`)),process.exit(1)),console.log(et.green(`
|
|
@@ -62,7 +62,7 @@ Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choos
|
|
|
62
62
|
`))});po.command("unpin <id-or-label>").description("remove a pinned page from the phone app").action(e=>{let{store:t}=wd(),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 sb(e){let t=Ve();return t||(console.log(se.red(" The database (.agentx/db.sqlite) can't be opened here.")),process.exit(1)),e(new Uc(t))}function cA(){let e=Ve({quiet:!0});if(!e)return[];let t=new Map;for(let o of new Uc(e).list()){if(!Sc(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 dA(e){let t=Math.round(tf/6e4),o=[` Pairing code: ${se.bold.cyan(Xi(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 bd(){let e;try{e=JSON.parse(nb("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 uA=new Set(["/app","/api/app","/member","/api/member"]),ob="/.well-known/assetlinks.json";function gA(){let e=new Set(["localhost","0.0.0.0","::","::1"]);try{let t=aA().toLowerCase().replace(/\.$/,"");t&&e.add(t).add(t.replace(/\.local$/,"")).add(`${t.replace(/\.local$/,"")}.local`)}catch{}try{for(let t of Object.values(lA()))for(let o of t??[])e.add(rb(o.address.toLowerCase().replace(/%.*$/,"")))}catch{}return e}var mA={http:80,https:443,"https+insecure":443};function pA(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]):mA[(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 fA(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 $d(e,t,o=gA()){let n=[e,...Object.values(e?.Foreground??{})],s=[];for(let l of n){s.push({label:"",cfg:l});for(let[c,u]of Object.entries(l?.Services??{}))s.push({label:`${c} `,cfg:u})}let r=new Set(o);for(let{cfg:l}of s){for(let c of Object.keys(l?.Web??{}))r.add(c.replace(/:\d+$/,"").replace(/\.$/,"").toLowerCase());for(let c of Object.values(l?.TCP??{}))c?.TerminateTLS&&r.add(String(c.TerminateTLS).replace(/\.$/,"").toLowerCase())}let i=l=>{let c=pA(l.trim());return c&&c.port===t&&fA(c.host,r)?c:null},a=[];for(let{label:l,cfg:c}of s){for(let[u,d]of Object.entries(c?.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===ob&&g.path===ob;!uA.has(h)&&!y&&a.push(`${l}${u}${p}`)}for(let[u,d]of Object.entries(c?.TCP??{}))d?.TCPForward==null||!i(String(d.TCPForward))||a.push(`${l}TCP port ${u}`)}return a}function kd(){try{return JSON.parse(nb("tailscale",["serve","status","--json"],{encoding:"utf-8",timeout:5e3})||"{}")}catch{return null}}function Jr(){try{return O().dashboard.port||4202}catch{return 4202}}Z();import{Command as ho}from"commander";import b from"chalk";import at from"prompts";import{readFileSync as Zo,writeFileSync as Gs,existsSync as Ke,mkdirSync as fo,cpSync as xd,readdirSync as hA}from"fs";import{resolve as le,join as Qo,dirname as yA}from"path";import{fileURLToPath as wA}from"url";import{Command as ab}from"commander";import jn from"chalk";Z();tc();var ib=()=>(process.env.AGENTX_DAEMON_URL||"http://127.0.0.1:18800").replace(/\/+$/,"");function _n(e){console.error(jn.red(` ${e}`)),process.exitCode=1}function lb(e,t){let o;try{o=O()}catch(s){return _n(`${s.message.split(`
|
|
65
|
-
`)[0]}. Run this from the folder that holds agentx.json.`),!1}let n=e==="agent"?!!o.agents?.[t]:t===vn||(o.people??[]).some(s=>s.id===t);return n||_n(e==="agent"?`No agent "${t}" in agentx.json.`:`No person "${t}" in agentx.json: agentx people list`),n}async function cb(e,t,o){if(lb(e,t))try{await kp(process.cwd(),e,t,xp(o)),console.log(jn.green(` \u2713 picture set for ${e} "${t}". Pages show it on their next load.`))}catch(n){if(n instanceof bp){_n(n.message);return}throw n}}function db(e,t){lb(e,t)&&console.log(vp(process.cwd(),e,t)?jn.green(` \u2713 picture removed for ${e} "${t}"; the initials show again.`):jn.dim(` ${e} "${t}" has no picture.`))}function vd(e){let t=e.agent?.trim()||Oo();return t||_n("Say which agent: --agent <id>"),t}function ub(){let e=new ab("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(Oo()){let s=await $c(t,o.agent?.trim(),{daemonUrl:ib()});return s.ok?console.log(jn.green(` \u2713 ${s.message}`)):_n(s.message)}let n=vd(o);n&&await cb("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(Oo()){let n=await $c(null,t.agent?.trim(),{daemonUrl:ib()});return n.ok?console.log(jn.green(` \u2713 ${n.message}`)):_n(n.message)}let o=vd(t);o&&db("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=vd(t);if(!o)return;let n=$p(process.cwd(),"agent",o);console.log(n?` ${o}: picture set (.agentx/pictures/agent/${o}.${n}.webp)`:jn.dim(` ${o}: no picture, the initials show`))}),e}function gb(){let e=new ab("picture").description("a person's profile picture: set or remove (the owner only)"),t=()=>{let o=Oo();return o&&_n(`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 cb("person",o,n)}),e.command("remove <id>").alias("rm").description("remove the picture: the initials show again").action(o=>{t()&&db("person",o)}),e}function Se(){let e=le(process.cwd(),"agentx.json");if(!Ke(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Zo(e,"utf-8"))}function gt(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 yo=new ho().name("agent").description("manage agents \u2014 add, list, remove, pause, resume");yo.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()});yo.command("add").description("add a new agent interactively").action(async()=>{let e=Se(),t=await at([{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:le(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:Qo(t.workspace,t.id);fo(le(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===vn||(o.people??[]).some(s=>s.id===t);return n||_n(e==="agent"?`No agent "${t}" in agentx.json.`:`No person "${t}" in agentx.json: agentx people list`),n}async function cb(e,t,o){if(lb(e,t))try{await kp(process.cwd(),e,t,xp(o)),console.log(jn.green(` \u2713 picture set for ${e} "${t}". Pages show it on their next load.`))}catch(n){if(n instanceof bp){_n(n.message);return}throw n}}function db(e,t){lb(e,t)&&console.log(vp(process.cwd(),e,t)?jn.green(` \u2713 picture removed for ${e} "${t}"; the initials show again.`):jn.dim(` ${e} "${t}" has no picture.`))}function vd(e){let t=e.agent?.trim()||Oo();return t||_n("Say which agent: --agent <id>"),t}function ub(){let e=new ab("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(Oo()){let s=await $c(t,o.agent?.trim(),{daemonUrl:ib()});return s.ok?console.log(jn.green(` \u2713 ${s.message}`)):_n(s.message)}let n=vd(o);n&&await cb("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(Oo()){let n=await $c(null,t.agent?.trim(),{daemonUrl:ib()});return n.ok?console.log(jn.green(` \u2713 ${n.message}`)):_n(n.message)}let o=vd(t);o&&db("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=vd(t);if(!o)return;let n=$p(process.cwd(),"agent",o);console.log(n?` ${o}: picture set (.agentx/pictures/agent/${o}.${n}.webp)`:jn.dim(` ${o}: no picture, the initials show`))}),e}function gb(){let e=new ab("picture").description("a person's profile picture: set or remove (the owner only)"),t=()=>{let o=Oo();return o&&_n(`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 cb("person",o,n)}),e.command("remove <id>").alias("rm").description("remove the picture: the initials show again").action(o=>{t()&&db("person",o)}),e}function Se(){let e=le(process.cwd(),"agentx.json");if(!Ke(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Zo(e,"utf-8"))}function gt(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 yo=new ho().name("agent").description("manage agents \u2014 add, list, remove, pause, resume");yo.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()});yo.command("add").description("add a new agent interactively").action(async()=>{let e=Se(),t=await at([{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:le(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:Qo(t.workspace,t.id);fo(le(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-PIPGUMLG.js"),r=s(t.id,n,"19900",(...u)=>{console.log(b.dim(` ${u.join(" ")}`))}),i=le(process.cwd(),"src/wiki/SKILL.md"),a=le(yA(wA(import.meta.url)),"../wiki/SKILL.md"),l=Ke(i)?i:a;Ke(l)&&(fo(le(o,".claude/skills/wiki"),{recursive:!0}),xd(l,le(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await gt(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 c=Fi(Co(),[t.id]);c&&console.log(b.yellow(` Created by agent "${c}": it starts once the owner approves it (agentx approvals approve agent:${t.id}).`)),console.log()});yo.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 gt(t),dc(Co(),e),console.log(b.green(` Agent "${e}" removed from config (workspace preserved)`))});yo.addCommand(ub());function mb(e){let t=Oo();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}yo.command("pause <id>").description("pause an agent: it starts no run until resumed (applies at once)").action(e=>{if(mb("pause an agent")){if(!Se().agents?.[e]){console.log(b.red(` Agent "${e}" not found`)),process.exitCode=1;return}if(cc(Co())[e]?.kind==="approval"){console.log(b.yellow(` "${e}" waits for your approval and does not run yet: agentx approvals list`));return}jm(Co(),e,"paused","the owner"),console.log(b.green(` "${e}" paused. Messages and schedules for it are refused until you run: agentx agent resume ${e}`))}});yo.command("resume <id>").description("resume a paused agent").action(e=>{if(!mb("resume an agent"))return;let t=cc(Co())[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(dc(Co(),e,"paused")?b.green(` "${e}" resumed`):b.dim(` "${e}" was not paused`))});yo.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 gt(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 en=new ho().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");en.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=[],l=r.credentials??{};for(let[u,d]of Object.entries(l))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 c=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(" ")}`),c&&console.log(` ${b.dim(c)}`),i||console.log(` ${b.dim("(disabled)")}`)}console.log()});en.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-LTXRWDRK.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await at({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 at({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(),l=String(t.auth||"").trim(),c=String(t.sessionDir||"").trim();if(!a&&!l&&!c&&n){let p=await at({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});p.scheme==="tokenEnv"?a=((await at({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():p.scheme==="keyring"?l="keyring":p.scheme==="sessionDir"&&(c=((await at({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 at({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),l==="keyring"&&(d.auth="keyring"),c&&(d.sessionDir=c),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 gt(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`))});en.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(c=>c.kind===r&&(!i||c.label===i)||c.label===t);a===-1&&(console.log(b.red(` No integration matched "${t}"`)),process.exit(1));let l=s.splice(a,1)[0];await gt(o),console.log(b.green(` \u2713 removed ${l.kind} integration "${l.label}" from ${e}`))});en.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 l=a.credentials??{},c=[];for(let[u,d]of Object.entries(l))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&c.push(`${u}: env var ${d} is unset`);if(c.length){i+=1,console.log(` ${b.red("\u2717")} ${a.kind} "${a.label}"`);for(let u of c)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}}en.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:l}=await import("./keyring-EKFUNQAO.js"),{waitForLoopbackCallback:c,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()||(l().available()?"keyring":"env");h!=="keyring"&&h!=="env"&&(console.log(b.red(" --store must be keyring or env")),process.exit(1)),h==="keyring"&&!l().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),x=R=>R.replace(/[^A-Za-z0-9]+/g,"_").toUpperCase();if($===-1?(w.push({kind:t,label:y??t,credentials:{clientIdEnv:String(o.clientIdEnv||`${x(t)}_CLIENT_ID`),clientSecretEnv:String(o.clientSecretEnv||`${x(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??=`${x(t)}_CLIENT_ID`,w[$].credentials.clientSecretEnv??=`${x(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 S=r(v);S.ok||(console.log(b.red(` ${S.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:S.clientId,clientSecret:S.clientSecret,redirectUri:k,extras:A,warn:I=>console.log(b.yellow(` ${I}`)),getCallback:async(I,M)=>{let D=o.paste?null:c(g,M);if(D&&await D.ready,console.log(`
|
|
@@ -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}fo(p,{recursive:!0});let f=0,g=0;for(let[h,y]of Object.entries(u)){let w=Qo(p,h);if(Ke(w)&&!t.force){console.log(b.dim(` skip ${w} (exists; --force to overwrite)`)),g++;continue}Gs(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()});Gr.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(le(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 Ed=new ho().name("hook").description("manage hooks \u2014 add to agent workspace");Ed.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=le(o.workspace,".claude/settings.json"),s=Ke(n)?JSON.parse(Zo(n,"utf-8")):{},r=await at([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:l=>l==="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),fo(le(o.workspace,".claude"),{recursive:!0}),Gs(n,JSON.stringify(s,null,2)),console.log(b.green(` Hook added to ${e}: ${r.event} -> ${r.type}`)),console.log()});var Ad=new ho().name("migrate").description("import configuration from OpenClaw or other tools");Ad.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,le(process.env.HOME||"",".openclaw/openclaw.json"),le(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of o)if(f&&Ke(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(Zo(n,"utf-8")),r=Ke(le(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||[],l={};for(let f of a)f.match?.channel==="telegram"&&(l[f.match.accountId]=f.agentId);i.find(f=>f.id==="main"||f.default)&&(l.default="main");let c=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"},c++,!t.dryRun){fo(le(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}fo(p,{recursive:!0});let f=0,g=0;for(let[h,y]of Object.entries(u)){let w=Qo(p,h);if(Ke(w)&&!t.force){console.log(b.dim(` skip ${w} (exists; --force to overwrite)`)),g++;continue}Gs(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()});Gr.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(le(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 Ed=new ho().name("hook").description("manage hooks \u2014 add to agent workspace");Ed.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=le(o.workspace,".claude/settings.json"),s=Ke(n)?JSON.parse(Zo(n,"utf-8")):{},r=await at([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:l=>l==="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),fo(le(o.workspace,".claude"),{recursive:!0}),Gs(n,JSON.stringify(s,null,2)),console.log(b.green(` Hook added to ${e}: ${r.event} -> ${r.type}`)),console.log()});var Ad=new ho().name("migrate").description("import configuration from OpenClaw or other tools");Ad.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,le(process.env.HOME||"",".openclaw/openclaw.json"),le(process.env.HOME||"",".openclaw/peerbot.json")].filter(Boolean),n;for(let f of o)if(f&&Ke(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(Zo(n,"utf-8")),r=Ke(le(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||[],l={};for(let f of a)f.match?.channel==="telegram"&&(l[f.match.accountId]=f.agentId);i.find(f=>f.id==="main"||f.default)&&(l.default="main");let c=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"},c++,!t.dryRun){fo(le(f.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-PIPGUMLG.js");y(g,r.agents[g])}}console.log(` ${b.green(c)} 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=l[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=le(n,"../cron/jobs.json");if(Ke(p)){let f=JSON.parse(Zo(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 gt(r),console.log(b.green(`
|
|
94
94
|
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var tn=new ho().name("config").description("validate and inspect configuration");tn.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=Di(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=Ke(le(i,".claude")),l=Ke(le(i,"CLAUDE.md")),c=Ke(le(i,".claude/settings.json")),u=Ps(r.tier,i).length,d=[a?b.green("\u2713"):b.red("\u2717"),".claude",l?b.green("\u2713"):b.yellow("\u25CB"),"CLAUDE.md",c?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()});tn.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 bA(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 Sd(e){return e===void 0?b.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}tn.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-RRKU33OL.js"),{expandEnvVars:i}=await import("./config-LTXRWDRK.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(b.red(` No config at ${a}`)),process.exit(1));let l=JSON.parse(o(a,"utf-8")),c=t.raw?l:i(l),u=r(c,e);t.json?console.log(JSON.stringify(u)):console.log(Sd(u))});tn.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-RRKU33OL.js"),i=bA(t,!!o.string),a=await n(c=>{s(c,e,i)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(b.red(` \u2717 ${a.error}`)),process.exit(1));let l=r(a.after,e);o.dryRun?console.log(b.yellow(` (dry-run) ${b.cyan(e)} would become: ${Sd(l)}`)):(console.log(b.green(` \u2713 ${b.cyan(e)} = ${Sd(l)}`)),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})`)))});tn.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-RRKU33OL.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.")))});tn.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,l=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:l},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 c=s==="authoritative"?b.green:s==="shadow"?b.cyan:s==="off"?b.dim:b.red;console.log(` INTENT_LEDGER_MODE ${c(s)}${l?"":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()});Bo();import{Command as $A}from"commander";import on from"chalk";import{resolve as nn}from"path";import{existsSync as kA}from"fs";var _o=new $A().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Mn(e){let t=nn(e,".agentx/db.sqlite");kA(t)||(console.log(on.red(` No SQLite at ${t}`)),console.log(on.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=Ve({path:t});return o||(console.log(on.red(` Could not open ${t}`)),console.log(on.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function Ln(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(on.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])))}_o.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=Mn(nn(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,
|
|
@@ -605,7 +605,7 @@ ${oe.text}`));T.delivery.reached.of++,ie&&T.delivery.reached.n++;let j=P[0]??Q[0
|
|
|
605
605
|
Plan ${q.dim(`[${r.state}] by ${r.createdBy}, ${os(r.createdAt)}`)}`),$v(s.steps(e)),console.log(`
|
|
606
606
|
Log`);for(let i of s.events(e))console.log(q.dim(` ${os(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});Mo.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(l=>o[l]);if(n.length!==1){console.error(q.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=cr();if(!s)return;let r=fl();if(!r){process.exitCode=1;return}let i=Number(t),a=Rf(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)")),$v(r.steps(e))});function kv(e,t,o,n){let s=Mo.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=cr();if(!a)return;let l=e==="done"?i.evidence??(i.reason?`closed by owner: ${i.reason}`:void 0):i.reason??"dropped by the owner";if(!l){console.error(q.red(` ${n}`)),process.exitCode=1;return}let c=a.get(r);if(!c||c.state==="candidate"){console.error(q.red(` no request "${r}"`)),process.exitCode=1;return}let u=process.env.AGENTX_AGENT_ID?.trim()||Kg;if(!a.close(r,e==="done"?"done":"dropped",l,Date.now(),null,u)){console.error(q.red(` ${r} is already closed (${_u[c.state]??c.state})`)),process.exitCode=1;return}console.log(q.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}kv("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>");kv("drop","drop a request you no longer want","--reason <text>","");Mo.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 (${Ni.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=>!Ni.includes(w));if(y.length)throw new Error(`unknown check ${y.join(", ")}: use ${Ni.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=Or();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??ta;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??ta.requireOverMinutes,i=s.requireForWork??ta.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??Af;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??kc).timeZone} days`);let l=o.checkers??ji;console.log(` Loop checks ${l.enabled.length?l.enabled.join(", "):"off"}, every ${l.checkEveryMinutes} minute(s)`);let c=Object.keys(l.repos);console.log(` Repos for git-ancestor ${c.length?c.join(", "):"none (requests.checkers.repos in agentx.json)"}`)});import{Command as sI}from"commander";import dr from"chalk";Z();var vv=new sI("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Jc.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(dr.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await pe(r=>{n=zh(r,e,t==="on")});s.success||(console.error(dr.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(dr.green(`\u2713 ${n}`)),s.reloaded&&console.log(dr.dim(" daemon hot-reloaded"))}let o=O().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Jc)console.log(` ${n.padEnd(8)} ${o.includes(n)?dr.green("on"):dr.dim("off")}`)});import{Command as jI}from"commander";import ur from"chalk";import Ee from"chalk";import gi from"prompts";import{readFileSync as rI,writeFileSync as iI,existsSync as aI}from"fs";import{resolve as xv}from"path";var lI=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function cI(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Pu(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Sv(e=".env"){let t=xv(e);if(!aI(t))return[];let o=rI(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(lI);r?n.push({kind:"kv",key:r[1],value:cI(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function dI(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Pu(t.value)}`:t.raw).join(`
|
|
607
607
|
`)+`
|
|
608
|
-
`}function ns(e,t,o=".env"){let n=xv(o),s=Sv(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Pu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Pu(t)}`})),iI(n,dI(s))}function Mu(e,t=".env"){return Sv(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Ev="https://t.me/BotFather";async function uI(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 gI(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 Av(e={}){console.log(),console.log(Ee.bold(" Connect Telegram")),console.log(),console.log(Ee.dim(` 1. Open ${Ev}`)),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 gi({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&jo(Ev);let{token:o}=await gi({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 uI(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 l=JSON.parse(s(a,"utf-8")),c=Object.keys(l.agents||{});c.length===0&&(console.log(Ee.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await gi({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:c.map(S=>({title:S,value:S})),initial:0})).agent),u||(console.log(Ee.red(" Aborted")),process.exit(1));let d=l.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await gi({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Ee.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;ns(f,o.trim()),process.env[f]=o.trim();let g=await pe(v=>{Be(v,"channels.telegram.enabled",!0),Be(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let S=Ts(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),Be(v,`agents.${u}.mentions`,S))},{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 gi({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 gI(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},$=[],x=await pe(v=>{Be(v,"notifications.destination",w),$=xa(v,w)},{configPath:e.configPath});if(!x.success){console.log(Ee.red(` \u2717 failed to save destination: ${x.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(", ")}`)),x.reloaded&&console.log(Ee.dim(" Daemon hot-reloaded."))}import Le from"chalk";import Lu from"prompts";import{existsSync as Fu,mkdirSync as mI,readdirSync as pI,readFileSync as Rv}from"fs";import{resolve as qu}from"path";var fI=".agentx/whatsapp-sessions";function hI(){let e=qu(process.cwd(),".agentx/daemon.pid");if(!Fu(e))return!1;try{let t=parseInt(Rv(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function yI(e){if(!Fu(e))return!1;try{return pI(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function wI(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Le.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Le.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;mI(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let l={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>l},c=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,l):r.keys},...a?{version:a}:{},logger:l,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return c.ev.on("creds.update",i),await new Promise(u=>{let p=setTimeout(()=>{t(Le.yellow(" Timed out waiting for scan (2min)."));try{c.end(void 0)}catch{}u(!1)},12e4);c.ev.on("connection.update",async f=>{if(f.qr){t(Le.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(Le.green(" \u2713 Paired"));try{c.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(Le.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Tv(e={}){if(console.log(),console.log(Le.bold(" Connect WhatsApp")),console.log(),hI()){console.log(Le.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Le.dim(" agentx daemon stop")),console.log();let{cont:c}=await Lu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});c||(console.log(Le.red(" Aborted")),process.exit(1))}let t=e.configPath||qu(process.cwd(),"agentx.json");Fu(t)||(console.log(Le.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Rv(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||fI,s=qu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Le.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Lu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(Le.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(yI(s)&&a){let{keep:c}=await Lu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!c,c&&console.log(Le.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await wI(s,u=>console.log(u))||(console.log(Le.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let l=await pe(c=>{Be(c,"channels.whatsapp.enabled",!0),Be(c,"channels.whatsapp.sessionDir",n),Be(c,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});l.success||(console.log(Le.red(` \u2717 ${l.error}`)),process.exit(1)),console.log(),console.log(Le.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Le.dim(` Session: ${n}`)),console.log(Le.dim(" Start the daemon to begin receiving:")),console.log(Le.dim(" agentx daemon start")),console.log(Le.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Le.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Le.dim(" Add routes later with:")),console.log(Le.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Tt from"chalk";import bI from"prompts";import{existsSync as $I,readFileSync as kI}from"fs";import{resolve as vI}from"path";async function xI(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 SI(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 Lo(e){console.log(Tt.red(` ${e}`)),process.exit(1)}async function ss(e){return(await bI(e,{onCancel:()=>Lo("Aborted")}))[e.name]}async function Cv(e={}){console.log(),console.log(Tt.bold(" Connect email")),console.log();let t=e.configPath||vI(process.cwd(),"agentx.json");$I(t)||Lo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(kI(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Lo("No agents configured. Run: agentx agent add");let s=e.agent??await ss({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(w=>({title:w,value:w}))});o.agents?.[s]||Lo(`No agent "${s}" in ${t}`);let r=(e.address??await ss({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=Kh(r),l=e.imapHost??a?.imapHost??await ss({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),c=Number(e.imapPort??a?.imapPort??await ss({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await ss({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await ss({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(c)||!Number.isInteger(d))&&Lo("Ports must be numbers.");let p=e.passwordEnv||Vh(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Lo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Tt.dim(` Gmail needs an app password, not your account password: ${Yh}`)),console.log(Tt.dim(" (2-step verification must be on for that page to show.)"))),f=(await ss({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Lo("Aborted");let g={agent:s,address:r,imapHost:l,imapPort:c,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 xI(g,f);w&&(console.log(Tt.red("\u2717")),Lo(w)),console.log(Tt.green("\u2713"))}e.passwordEnv||(ns(p,f),process.env[p]=f);let h=await pe(w=>{Be(w,"channels.email.enabled",!0),Be(w,`channels.email.accounts.${i}`,Xh(g))},{configPath:e.configPath});h.success||Lo(`Config save failed: ${h.error}`),console.log(),console.log(Tt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Tt.dim(` Password stored in .env as ${p}`)),console.log(Tt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let y=SI(o.agents[s]?.tier,g.allowFrom);y&&console.log(Tt.yellow(` ${y}`)),console.log(g.send==="auto"?Tt.yellow(" Replies are sent as soon as the agent writes them."):Tt.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Tt.dim(" Only mail that arrives from now on is answered.")),console.log(Tt.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as EI}from"crypto";import Qe from"chalk";import Ov from"prompts";var hl="agentx-mesh:",yl="//join/";function AI(e){return Buffer.from(e,"utf-8").toString("base64url")}function RI(e){return Buffer.from(e,"base64url").toString("utf-8")}function TI(e){return`${hl}${yl}${AI(JSON.stringify(e))}`}function CI(e){if(!e.startsWith(`${hl}${yl}`))throw new Error(`Not a mesh invite link \u2014 expected ${hl}${yl}\u2026`);let t=e.slice(hl.length+yl.length),o=JSON.parse(RI(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 OI(){return EI(32).toString("hex")}function II(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function NI(e){return e?.node?.name||e?.node?.id||"node"}async function Iv(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(Qe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Mu("MESH_TOKEN");i||(i=OI(),ns("MESH_TOKEN",i),console.log(Qe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||II(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Ov({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(Qe.red(" Aborted")),process.exit(1)),a=d}let c=await pe(d=>{Be(d,"mesh.enabled",!0)},{configPath:e.configPath});c.success||(console.log(Qe.red(` \u2717 ${c.error}`)),process.exit(1));let u=TI({url:a,token:i,name:NI(r),version:1});console.log(),console.log(Qe.bold(" Mesh invite")),console.log(),console.log(` ${Qe.cyan(u)}`),console.log(),console.log(Qe.dim(" Run on the other node:")),console.log(Qe.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Qe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Nv(e,t={}){let o;try{o=CI(e)}catch(r){console.log(Qe.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Mu("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Ov({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Qe.red(" Aborted (keeping existing .env)")),process.exit(1))}ns("MESH_TOKEN",o.token);let s=await pe(r=>{Be(r,"mesh.enabled",!0);let i=Ts(r,"mesh.peers")||[],a=i.findIndex(c=>c.name===o.name),l={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=l:i.push(l),Be(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Qe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Qe.green(" \u2713 Joined mesh")),console.log(Qe.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Qe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Qe.dim(" Daemon hot-reloaded.")):console.log(Qe.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(Qe.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Qe.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Qe.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var rs=new jI().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");rs.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 Av({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});rs.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 Tv({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});rs.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 Cv({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 jv=rs.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");jv.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 Iv({url:e.url,configPath:e.config})});jv.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 Nv(e,{configPath:t.config})});rs.action(()=>{console.log(),console.log(ur.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${ur.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${ur.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${ur.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${ur.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(ur.dim(" GitLab connect is the next slice.")),console.log()});Z();import{Command as _I}from"commander";import ce from"chalk";var is=new _I().name("usage").description("token usage analysis and reporting");is.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(ce.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ce.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${ce.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: ${ce.red(String(s.totalErrors))}`),console.log(),console.log(ce.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,l)=>l[1].total-a[1].total);for(let[a,l]of i){let c=r(l.total||l.input+l.output+l.cacheRead+l.cacheCreate),u=l.avgDuration?`${(l.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ce.cyan(a)}: ${c} tokens (${l.tasks} tasks) ${ce.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${e.message}`))}});is.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.`:ce.dim(" No hold to lift.")),console.log();return}let l=i.now,c=new Set(i.holds.map(d=>d.window));console.log(ce.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(ce.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-l)/6e4)),h=d.resetsAt>l?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",y=c.has(d.window)?ce.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`),c.size&&console.log(ce.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${t.message}`))}});is.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(ce.red(` Script not found: ${s}`)),console.log(ce.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ce.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ce.red(" Analysis failed. Is Python 3 installed?"))}});is.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(ce.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 l=null;if(e.baseline)try{l=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(ce.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(l?{baseline:l,current:a}:a,null,2));return}let c=g=>g===null?"-":`$${g.toFixed(g<10?3:2)}`,u=g=>`${(g/1e6).toFixed(1)}M`;console.log(),console.log(ce.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),l&&console.log(ce.dim(` Baseline: ${l.from} to ${l.to} (${l.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(ce.dim(l?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(l?.channels||{})])].map(g=>[g,a.channels[g],l?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,l?.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)} ${c(h?.cost||0).padStart(10)} ${c(w).padStart(9)}`;if(l){let x=r(y),v=w!==null&&x?`${((w-x)/x*100).toFixed(0)}%`:"-";$+=` ${c(x).padStart(9)} ${v.padStart(7)}`}console.log($)}console.log(),l&&console.log(ce.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(ce.dim(` Saved ${e.save}`)),console.log()});is.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-4WR4ZYXQ.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),l=[],c=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();l.push(g),c(f,g)}};c(i,"");let u=l.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(ce.bold(` Never used in the last ${e.days} days (${u.length}/${l.length})`)),console.log();for(let d of u)console.log(` ${ce.dim("\xB7")} ${d}`);console.log(),console.log(ce.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ce.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(ce.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ce.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ce.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(ce.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=ce.dim(`${r.days}d`);console.log(` ${ce.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(ce.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as DI}from"commander";import Ge from"chalk";import{readFileSync as PI}from"fs";import{resolve as MI}from"path";Z();var mn=new DI().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");mn.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{mm(MI(process.cwd(),".env"))}catch{}let t=LI(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-LDMIS7MM.js");o(t)}catch(t){console.log(Ge.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ge.dim(t.stack)),process.exit(1)}});function LI(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ge.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ge.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
608
|
+
`}function ns(e,t,o=".env"){let n=xv(o),s=Sv(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Pu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Pu(t)}`})),iI(n,dI(s))}function Mu(e,t=".env"){return Sv(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Ev="https://t.me/BotFather";async function uI(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 gI(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 Av(e={}){console.log(),console.log(Ee.bold(" Connect Telegram")),console.log(),console.log(Ee.dim(` 1. Open ${Ev}`)),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 gi({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&jo(Ev);let{token:o}=await gi({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 uI(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 l=JSON.parse(s(a,"utf-8")),c=Object.keys(l.agents||{});c.length===0&&(console.log(Ee.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await gi({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:c.map(S=>({title:S,value:S})),initial:0})).agent),u||(console.log(Ee.red(" Aborted")),process.exit(1));let d=l.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await gi({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Ee.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;ns(f,o.trim()),process.env[f]=o.trim();let g=await pe(v=>{Be(v,"channels.telegram.enabled",!0),Be(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let S=Ts(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),Be(v,`agents.${u}.mentions`,S))},{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 gi({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 gI(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},$=[],x=await pe(v=>{Be(v,"notifications.destination",w),$=xa(v,w)},{configPath:e.configPath});if(!x.success){console.log(Ee.red(` \u2717 failed to save destination: ${x.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(", ")}`)),x.reloaded&&console.log(Ee.dim(" Daemon hot-reloaded."))}import Le from"chalk";import Lu from"prompts";import{existsSync as Fu,mkdirSync as mI,readdirSync as pI,readFileSync as Rv}from"fs";import{resolve as qu}from"path";var fI=".agentx/whatsapp-sessions";function hI(){let e=qu(process.cwd(),".agentx/daemon.pid");if(!Fu(e))return!1;try{let t=parseInt(Rv(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function yI(e){if(!Fu(e))return!1;try{return pI(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function wI(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Le.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Le.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;mI(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let l={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>l},c=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,l):r.keys},...a?{version:a}:{},logger:l,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return c.ev.on("creds.update",i),await new Promise(u=>{let p=setTimeout(()=>{t(Le.yellow(" Timed out waiting for scan (2min)."));try{c.end(void 0)}catch{}u(!1)},12e4);c.ev.on("connection.update",async f=>{if(f.qr){t(Le.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(Le.green(" \u2713 Paired"));try{c.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(Le.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Tv(e={}){if(console.log(),console.log(Le.bold(" Connect WhatsApp")),console.log(),hI()){console.log(Le.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Le.dim(" agentx daemon stop")),console.log();let{cont:c}=await Lu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});c||(console.log(Le.red(" Aborted")),process.exit(1))}let t=e.configPath||qu(process.cwd(),"agentx.json");Fu(t)||(console.log(Le.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Rv(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||fI,s=qu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Le.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Lu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(Le.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(yI(s)&&a){let{keep:c}=await Lu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!c,c&&console.log(Le.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await wI(s,u=>console.log(u))||(console.log(Le.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let l=await pe(c=>{Be(c,"channels.whatsapp.enabled",!0),Be(c,"channels.whatsapp.sessionDir",n),Be(c,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});l.success||(console.log(Le.red(` \u2717 ${l.error}`)),process.exit(1)),console.log(),console.log(Le.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Le.dim(` Session: ${n}`)),console.log(Le.dim(" Start the daemon to begin receiving:")),console.log(Le.dim(" agentx daemon start")),console.log(Le.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Le.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Le.dim(" Add routes later with:")),console.log(Le.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Tt from"chalk";import bI from"prompts";import{existsSync as $I,readFileSync as kI}from"fs";import{resolve as vI}from"path";async function xI(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 SI(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 Lo(e){console.log(Tt.red(` ${e}`)),process.exit(1)}async function ss(e){return(await bI(e,{onCancel:()=>Lo("Aborted")}))[e.name]}async function Cv(e={}){console.log(),console.log(Tt.bold(" Connect email")),console.log();let t=e.configPath||vI(process.cwd(),"agentx.json");$I(t)||Lo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(kI(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Lo("No agents configured. Run: agentx agent add");let s=e.agent??await ss({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(w=>({title:w,value:w}))});o.agents?.[s]||Lo(`No agent "${s}" in ${t}`);let r=(e.address??await ss({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=Kh(r),l=e.imapHost??a?.imapHost??await ss({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),c=Number(e.imapPort??a?.imapPort??await ss({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await ss({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await ss({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(c)||!Number.isInteger(d))&&Lo("Ports must be numbers.");let p=e.passwordEnv||Vh(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Lo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Tt.dim(` Gmail needs an app password, not your account password: ${Yh}`)),console.log(Tt.dim(" (2-step verification must be on for that page to show.)"))),f=(await ss({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Lo("Aborted");let g={agent:s,address:r,imapHost:l,imapPort:c,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 xI(g,f);w&&(console.log(Tt.red("\u2717")),Lo(w)),console.log(Tt.green("\u2713"))}e.passwordEnv||(ns(p,f),process.env[p]=f);let h=await pe(w=>{Be(w,"channels.email.enabled",!0),Be(w,`channels.email.accounts.${i}`,Xh(g))},{configPath:e.configPath});h.success||Lo(`Config save failed: ${h.error}`),console.log(),console.log(Tt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Tt.dim(` Password stored in .env as ${p}`)),console.log(Tt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let y=SI(o.agents[s]?.tier,g.allowFrom);y&&console.log(Tt.yellow(` ${y}`)),console.log(g.send==="auto"?Tt.yellow(" Replies are sent as soon as the agent writes them."):Tt.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Tt.dim(" Only mail that arrives from now on is answered.")),console.log(Tt.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as EI}from"crypto";import Qe from"chalk";import Ov from"prompts";var hl="agentx-mesh:",yl="//join/";function AI(e){return Buffer.from(e,"utf-8").toString("base64url")}function RI(e){return Buffer.from(e,"base64url").toString("utf-8")}function TI(e){return`${hl}${yl}${AI(JSON.stringify(e))}`}function CI(e){if(!e.startsWith(`${hl}${yl}`))throw new Error(`Not a mesh invite link \u2014 expected ${hl}${yl}\u2026`);let t=e.slice(hl.length+yl.length),o=JSON.parse(RI(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 OI(){return EI(32).toString("hex")}function II(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function NI(e){return e?.node?.name||e?.node?.id||"node"}async function Iv(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(Qe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Mu("MESH_TOKEN");i||(i=OI(),ns("MESH_TOKEN",i),console.log(Qe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||II(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Ov({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(Qe.red(" Aborted")),process.exit(1)),a=d}let c=await pe(d=>{Be(d,"mesh.enabled",!0)},{configPath:e.configPath});c.success||(console.log(Qe.red(` \u2717 ${c.error}`)),process.exit(1));let u=TI({url:a,token:i,name:NI(r),version:1});console.log(),console.log(Qe.bold(" Mesh invite")),console.log(),console.log(` ${Qe.cyan(u)}`),console.log(),console.log(Qe.dim(" Run on the other node:")),console.log(Qe.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Qe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Nv(e,t={}){let o;try{o=CI(e)}catch(r){console.log(Qe.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Mu("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Ov({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Qe.red(" Aborted (keeping existing .env)")),process.exit(1))}ns("MESH_TOKEN",o.token);let s=await pe(r=>{Be(r,"mesh.enabled",!0);let i=Ts(r,"mesh.peers")||[],a=i.findIndex(c=>c.name===o.name),l={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=l:i.push(l),Be(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Qe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Qe.green(" \u2713 Joined mesh")),console.log(Qe.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Qe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Qe.dim(" Daemon hot-reloaded.")):console.log(Qe.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(Qe.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Qe.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Qe.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var rs=new jI().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");rs.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 Av({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});rs.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 Tv({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});rs.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 Cv({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 jv=rs.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");jv.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 Iv({url:e.url,configPath:e.config})});jv.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 Nv(e,{configPath:t.config})});rs.action(()=>{console.log(),console.log(ur.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${ur.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${ur.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${ur.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${ur.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(ur.dim(" GitLab connect is the next slice.")),console.log()});Z();import{Command as _I}from"commander";import ce from"chalk";var is=new _I().name("usage").description("token usage analysis and reporting");is.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(ce.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ce.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${ce.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: ${ce.red(String(s.totalErrors))}`),console.log(),console.log(ce.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,l)=>l[1].total-a[1].total);for(let[a,l]of i){let c=r(l.total||l.input+l.output+l.cacheRead+l.cacheCreate),u=l.avgDuration?`${(l.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${ce.cyan(a)}: ${c} tokens (${l.tasks} tasks) ${ce.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${e.message}`))}});is.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.`:ce.dim(" No hold to lift.")),console.log();return}let l=i.now,c=new Set(i.holds.map(d=>d.window));console.log(ce.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(ce.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-l)/6e4)),h=d.resetsAt>l?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",y=c.has(d.window)?ce.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`),c.size&&console.log(ce.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${t.message}`))}});is.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(ce.red(` Script not found: ${s}`)),console.log(ce.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ce.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ce.red(" Analysis failed. Is Python 3 installed?"))}});is.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(ce.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 l=null;if(e.baseline)try{l=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(ce.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(l?{baseline:l,current:a}:a,null,2));return}let c=g=>g===null?"-":`$${g.toFixed(g<10?3:2)}`,u=g=>`${(g/1e6).toFixed(1)}M`;console.log(),console.log(ce.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),l&&console.log(ce.dim(` Baseline: ${l.from} to ${l.to} (${l.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(ce.dim(l?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(l?.channels||{})])].map(g=>[g,a.channels[g],l?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,l?.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)} ${c(h?.cost||0).padStart(10)} ${c(w).padStart(9)}`;if(l){let x=r(y),v=w!==null&&x?`${((w-x)/x*100).toFixed(0)}%`:"-";$+=` ${c(x).padStart(9)} ${v.padStart(7)}`}console.log($)}console.log(),l&&console.log(ce.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(ce.dim(` Saved ${e.save}`)),console.log()});is.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-3QOBRNT4.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),l=[],c=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();l.push(g),c(f,g)}};c(i,"");let u=l.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(ce.bold(` Never used in the last ${e.days} days (${u.length}/${l.length})`)),console.log();for(let d of u)console.log(` ${ce.dim("\xB7")} ${d}`);console.log(),console.log(ce.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ce.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(ce.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ce.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ce.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(ce.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=ce.dim(`${r.days}d`);console.log(` ${ce.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(ce.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as DI}from"commander";import Ge from"chalk";import{readFileSync as PI}from"fs";import{resolve as MI}from"path";Z();var mn=new DI().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");mn.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{mm(MI(process.cwd(),".env"))}catch{}let t=LI(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-LDMIS7MM.js");o(t)}catch(t){console.log(Ge.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ge.dim(t.stack)),process.exit(1)}});function LI(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ge.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ge.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
609
609
|
`)),{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}}}}mn.command("list").description("list configured boards").action(()=>{try{let e=O();if(!e.boards?.length){console.log(Ge.dim(`
|
|
610
610
|
No boards configured.
|
|
611
611
|
`));return}console.log();for(let t of e.boards){console.log(` ${Ge.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(Ge.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(Ge.dim(` primary label: ${t.primaryToolLabel}`)),console.log(Ge.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(Ge.red(` ${e.message}`)),process.exit(1)}});mn.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{mi(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(Ge.red(` ${o.message}`)),process.exit(1)}});mn.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{mi(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(Ge.red(` ${o.message}`)),process.exit(1)}});var Uu=mn.command("column").description("manage a board's columns (add / remove / edit / list)");Uu.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(PI("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(Ge.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(` ${Ge.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${Ge.dim(r)}`)}}catch(t){console.log(Ge.red(` ${t.message}`)),process.exit(1)}});Uu.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{mi(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(Ge.red(` ${n.message}`)),process.exit(1)}});Uu.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{mi(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(Ge.red(` ${o.message}`)),process.exit(1)}});mn.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{mi(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(Ge.red(` ${t.message}`)),process.exit(1)}});function mi(e){let{summary:t,backupPath:o}=Lt(n=>e(n));console.log(Ge.green(`
|
|
@@ -909,7 +909,7 @@ Restart the daemon to activate.
|
|
|
909
909
|
dist/
|
|
910
910
|
*.log
|
|
911
911
|
.env
|
|
912
|
-
`}import{Command as b_}from"commander";import dt from"chalk";import{writeFileSync as $_,mkdirSync as k_,existsSync as Jl,readFileSync as D0,appendFileSync as P0}from"fs";import{resolve as kr,dirname as q0}from"path";import{homedir as Rg}from"os";var F0=new b_().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-
|
|
912
|
+
`}import{Command as b_}from"commander";import dt from"chalk";import{writeFileSync as $_,mkdirSync as k_,existsSync as Jl,readFileSync as D0,appendFileSync as P0}from"fs";import{resolve as kr,dirname as q0}from"path";import{homedir as Rg}from"os";var F0=new b_().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-3QOBRNT4.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=S_(o);break;case"bash":s=C_(o);break;case"fish":s=O_(o);break;default:console.error(dt.red(`unsupported shell: ${n}`)),console.error(dt.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?kr(String(e.output)):v_(n);k_(q0(r),{recursive:!0}),$_(r,s),console.log(dt.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),x_(n,r,!!e.yes)});function v_(e){let t=Rg();switch(e){case"zsh":return kr(t,".zsh","completions","_agentx");case"bash":return kr(t,".bash_completion.d","agentx.bash");case"fish":return kr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function x_(e,t,o){if(e==="zsh"){let n=kr(Rg(),".zshrc"),s=q0(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Jl(n)?D0(n,"utf-8"):"",l=!a.includes(s),c=!/autoload\s+-U\s+compinit/.test(a);if(!l&&!c){console.log(dt.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Jl(n)){let u=["","# agentx completion"];l&&u.push(r),c&&u.push(i),P0(n,u.join(`
|
|
913
913
|
`)+`
|
|
914
914
|
`),console.log(dt.green("\u2713 Patched ~/.zshrc")),console.log(dt.dim("Reload your shell: exec zsh"));return}console.log(dt.dim("Add this to ~/.zshrc if not already present:")),l&&console.log(dt.cyan(` ${r}`)),c&&console.log(dt.cyan(` ${i}`)),console.log(),console.log(dt.dim("Then reload: exec zsh")),console.log(dt.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=kr(Rg(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Jl(n)?D0(n,"utf-8"):"").includes(t)){console.log(dt.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&Jl(n)){P0(n,`
|
|
915
915
|
# agentx completion
|
|
@@ -925,4 +925,4 @@ ${I_({...t,category:e.category})}`),u&&a.set(c.id,u)}let l=`https://github.com/$
|
|
|
925
925
|
${o.url}`)}catch(t){console.error(xr.red(` ${t.message}`)),process.exitCode=1}});Ri.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",Cg).action(async(e,t)=>{try{let o=await Ng(t.models);if(!Og(t.model,o)){console.log(Ig(t.model,o)),process.exitCode=1;return}let n=e==="-"?await __():await j_(e,"utf8"),s=JSON.parse(n),{version:r}=await Ji(),i=H0({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(xr.red(` ${o.message}`)),process.exitCode=1}});async function __(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function o5(){let e=await Ji(),t=new D_().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=Zh(n);ey(s)&&Qh("cli",s)});for(let o of[eb,mw,gw,rs,Ms,po,qt,jh,Ek,Rk,yo,Ca,Do,In,Qn,ko,Mo,Qr,vv,gn,$a,h0,ln,d$,u$,$$,ii,I$,P$,a$,q$,F$,nk,ak,lk,Ht,is,v0,Hr,tn,F0,Ri])t.addCommand(o);for(let o of G0)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=G0.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,P_(o,74," "),""].join(`
|
|
926
926
|
`)}),t}var G0=[X,pr,Fo,ro,Gr,sr,st,qo,mn,Vn,us,hr,sn,St,Ks,Ga,al,Kn,ll,cl,u0,p0,_o,bi,Ut,ky,Pn,Ei,Ed,yn,kt,zs,Ad,_l,Eo,rg,Uo,T0,br,C0,$0];function P_(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(`
|
|
927
927
|
`)}export{o5 as buildProgram};
|
|
928
|
-
//# sourceMappingURL=program-
|
|
928
|
+
//# sourceMappingURL=program-3QOBRNT4.js.map
|