agentix-cli 0.226.3 → 0.226.4
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/{chunk-NVHEWULT.js → chunk-ZFMUF3NU.js} +3 -3
- package/dist/{chunk-NVHEWULT.js.map → chunk-ZFMUF3NU.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{program-FZBZUK5X.js → program-W6CGC2EO.js} +4 -4
- package/package.json +1 -1
- /package/dist/{program-FZBZUK5X.js.map → program-W6CGC2EO.js.map} +0 -0
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-
|
|
2
|
+
import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-W6CGC2EO.js"),{installCliSignalExit:r}=await import("./signal-exit-C5EUGHKI.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
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-ZFMUF3NU.js";import"./chunk-LLVVT5OB.js";import"./chunk-GTJIKXDB.js";import"./chunk-2TVJTWFC.js";import"./chunk-BDHWTWD7.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-KQ3LPQ2Z.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-UBONPGNT.js";import"./chunk-UKUH662W.js";import"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-A24QXLEG.js";import"./chunk-A5GYG56I.js";import"./chunk-7K7ZQU3C.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-EYVPRIO3.js";import"./chunk-LTOSEP7C.js";import"./chunk-QPABR72X.js";import"./chunk-QU7ICYFR.js";import"./chunk-IFUAP7UD.js";import"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{Xa as yt,r as lt,s as ct,t as dt,u as mt,v as pt}from"./chunk-4H5B42VW.js";import"./chunk-TA437DWX.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-LACHXOBO.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-EFXZACH4.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import"./chunk-IH65GDJR.js";import{x as ut}from"./chunk-CF2R6BOX.js";import"./chunk-Q6TGKWZE.js";import"./chunk-3UOTLMXD.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-FG2FPOML.js";import"./chunk-VWTBHLMX.js";import"./chunk-LGYIHB73.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-74MHOALB.js";import"./chunk-3323WFVK.js";import"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import"./chunk-MM7U4PWY.js";import{a as ht}from"./chunk-6ECXITK2.js";import{f as gt,g as ft}from"./chunk-2XQMUSGM.js";import"./chunk-WPNRDEHW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QZ24XACR.js";import{j as it,k as rt,l as at}from"./chunk-BTLADRMY.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{Dc as nt,rc as tt,tc as st,wc as ot}from"./chunk-FWNP27H4.js";import"./chunk-KEUW6YLL.js";import"./chunk-N47Y5ADQ.js";import"./chunk-VQRY4IDI.js";import"./chunk-YSCT6DPR.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 Uy,b as ka,g as Wy}from"./chunk-DG56PTYL.js";import{n as rd}from"./chunk-GMAORBGM.js";import{a as qy,b as Fy}from"./chunk-ZUZYJQJ4.js";import{b as Ly}from"./chunk-XV3QPZWH.js";import{a as Dy,b as Py,d as Ur,e as My}from"./chunk-I32TCCAK.js";import{d as sy,e as td,h as ry,i as iy}from"./chunk-6UI7GJSB.js";import{$ as yy,A as ny,B as ay,C as ly,E as cy,G as dy,H as uy,I as od,J as gy,U as my,V as py,W as nd,X as fy,_ as hy,aa as wy,ba as by,ca as xy,da as Sy,ea as Ey,fa as Ay,g as Jh,ga as Ry,h as Hh,ha as Ty,ja as sd,ka as Cy,l as Gh,la as Oy,m as zh,na as Iy,o as Fs,p as Us,q as Yh,qa as Ny,r as Kh,ra as jy,s as Xh,sa as _y,t as Vh,u as Qh,v as Zh,x as Xt,z as oy}from"./chunk-ATZRBMUZ.js";import"./chunk-EFGAPAYZ.js";import{a as $y,c as ky,d as vy}from"./chunk-FFOGEFPT.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{b as Mo}from"./chunk-7NQQIDDI.js";import{a as ey,c as ty}from"./chunk-D6LX27PO.js";import"./chunk-WMZ4TGMR.js";import"./chunk-2YDG5CSS.js";import{a as Zc}from"./chunk-LNY6N73E.js";import{b as Yp}from"./chunk-FGHJDZDB.js";import{a as Wp,b as Ic}from"./chunk-GMP2IB4E.js";import{a as Ac,b as xp}from"./chunk-VNXYQH45.js";import{$ as mh,A as Lc,Aa as qr,B as qf,Ba as Mh,C as qc,Ca as ht,D as Ff,Da as ya,E as Uf,Ea as wa,F as Wf,Fa as Fr,G as Bf,Ga as Xc,H as Jf,Ha as Lh,I as Gf,Ia as Fh,J as Fc,Ja as Qc,K as zf,Ka as Wh,L as da,La as ba,M as Yf,Ma as qs,N as Uc,Na as $a,O as Xf,Oa as ed,P as Vf,Pa as Bh,Q as Qf,R as Zf,S as eh,T as ua,U as rh,V as lh,W as ch,X as dh,Y as uh,Z as gh,_ as Bc,a as Kp,aa as ph,b as Xp,ba as fh,ca as hh,da as yh,ea as wh,fa as bh,ga as $h,h as ea,ha as kh,i as Ds,ia as vh,j as ef,ja as Ch,k as Dr,ka as pa,l as ta,la as Po,m as of,ma as Qo,n as sf,na as Ps,o as $f,oa as fa,p as kf,pa as ha,q as aa,qa as Kc,r as Mc,ra as Oh,s as Tf,sa as Ih,t as jf,ta as Nh,u as _f,ua as jh,v as Df,va as _h,w as Pf,wa as Dh,x as ca,xa as Ms,y as Mf,ya as Ls,z as Lf,za as Ph}from"./chunk-NVHEWULT.js";import{$b as Vc,Cb as Rh,Db as Th,Eb as zc,Lb as Yc,M as Pr,N as Cf,Q as Of,R as la,_b as qh,bb as Mr,eb as Jc,fb as ga,gb as xh,ia as Hf,ja as Kf,nb as Vo,nc as fo,ob as Sh,pb as Hc,pc as Uh,qa as th,ra as oh,rb as Gc,sa as nh,t as nf,ta as Wc,tb as Eh,ub as Ah,vb as Lr,wa as sh,zb as ma}from"./chunk-LLVVT5OB.js";import"./chunk-GTJIKXDB.js";import{a as Vp,c as _c,d as _r,f as Qp,g as Zp}from"./chunk-2TVJTWFC.js";import{A as oa,B as na,C as af,D as lf,E as cf,G as df,H as uf,I as gf,J as mf,K as pf,L as ff,M as hf,N as yf,S as sa,T as wf,U as bf,Y as If,Z as Nf,i as Sc,j as yp,m as wp,n as bp,w as rf}from"./chunk-BDHWTWD7.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-KQ3LPQ2Z.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as ih,b as ah}from"./chunk-EKJG63EJ.js";import"./chunk-UBONPGNT.js";import{b as Ft}from"./chunk-UKUH662W.js";import{c as vf}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import{c as Pc}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as xf,e as ra,g as ia}from"./chunk-LQE73AZR.js";import{a as Sf,b as Ef,c as Af,d as Rf}from"./chunk-2D3RYIDU.js";import{a as Ut}from"./chunk-A24QXLEG.js";import"./chunk-A5GYG56I.js";import{a as Dc,p as tf}from"./chunk-7K7ZQU3C.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{a as Ip,b as Np,c as jp,d as _p,e as Tc,f as Dp,g as Cc,h as Oc,l as Pp,m as Mp}from"./chunk-RX5O5637.js";import{f as Lp,i as qp,l as Fp,m as Up}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{n as Bp,o as Jp,p as Nc,q as Zi,r as Hp,s as Gp}from"./chunk-EYVPRIO3.js";import{b as jc,d as zp}from"./chunk-LTOSEP7C.js";import{a as Ec,d as $p,e as Qi}from"./chunk-QPABR72X.js";import{a as jr,e as Sp,f as Ep,g as Rc,i as Ap,j as Rp,l as Tp,m as Cp,n as Op}from"./chunk-QU7ICYFR.js";import{b as _s,e as vp}from"./chunk-IFUAP7UD.js";import{c as kp}from"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{O as bc,P as Vm,Xa as hp,ba as Xo,ha as gp,l as Um,oa as pp,pa as fp,w as Wm,x as Bm,y as Jm}from"./chunk-4H5B42VW.js";import{Da as mp,I as Cs,J as Xi,K as Vi,L as Os,M as Zm,N as Yo,P as Ko,b as Ts,ha as dp,r as jo,s as $c,t as Qm,u as kc,w as _o,wa as up,x as Ki}from"./chunk-TA437DWX.js";import{b as Tn}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-LACHXOBO.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as tp}from"./chunk-EFXZACH4.js";import{f as op,g as np,h as vc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import{e as rp,f as Do,k as Ns}from"./chunk-IH65GDJR.js";import{d as Km,o as sp,r as cp}from"./chunk-CF2R6BOX.js";import{a as Fe,b as pe,c as Ge,d as js,e as ip}from"./chunk-Q6TGKWZE.js";import{a as ap,b as xc,h as lp}from"./chunk-3UOTLMXD.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Xm}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import{a as Is}from"./chunk-GV7S5BAX.js";import{e as ep}from"./chunk-GSX4NK2N.js";import"./chunk-FG2FPOML.js";import"./chunk-VWTBHLMX.js";import"./chunk-LGYIHB73.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as Gm,j as zm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as wc,b as Ym}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as hc,p as qm,w as Fm}from"./chunk-74MHOALB.js";import{e as _m,f as Rn,g as Dm,h as Rs,k as Pm,l as Mm,n as Lm,o as fc,s as Gi,t as jt,u as zi}from"./chunk-3323WFVK.js";import{a as po}from"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import{b as yc}from"./chunk-MM7U4PWY.js";import"./chunk-6ECXITK2.js";import{g as zo,i as Yi}from"./chunk-2XQMUSGM.js";import"./chunk-WPNRDEHW.js";import{c as Hm}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QZ24XACR.js";import{a as rc,b as Gg,c as xS,d as Di,e as zg,f as Am,g as DS,h as Rm,i as PS,m as As,n as Cm,q as Om,u as Im,y as mo,z as Nr}from"./chunk-BTLADRMY.js";import{a as No,b as Es,e as xm,f as Ir}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Hi,b as Tm}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as jm}from"./chunk-BYEL7KKR.js";import{h as Go,j as Nm}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as go,b as vS}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as im,Ab as IS,Ca as dm,Da as um,Dc as Z,Ea as cc,I as qi,J as om,Jb as bm,Kb as En,M as qt,Mb as uc,N as ac,Oa as Ui,P as nm,Pa as Wi,Q as Fi,S as RS,Sa as gm,Tb as gc,Ua as mm,Ub as mc,Va as Ss,Wa as dc,Wb as $m,Xa as pm,Xb as NS,_ as rm,aa as am,b as ic,bc as vm,c as Yg,ca as lm,d as Pi,da as cm,e as Kg,ea as CS,eb as fm,f as Xg,gb as hm,h as Vg,hb as ym,i as Mi,j as Qg,l as SS,na as lc,nc as pc,oa as OS,q as Zg,r as ES,rc as Bi,sc as An,t as em,tc as O,w as AS,wb as wm,wc as Ji,x as Li,y as tm,ya as xs,za as Or}from"./chunk-FWNP27H4.js";import"./chunk-KEUW6YLL.js";import{j as He,r as Io}from"./chunk-N47Y5ADQ.js";import{a as sm,e as TS}from"./chunk-VQRY4IDI.js";import{a as km,c as jS}from"./chunk-YSCT6DPR.js";import{g as Sm,k as Em,l as _S}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as MS}from"commander";var By=new MS().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new Xp({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});Z();import{Command as LS}from"commander";import{execFileSync as ho}from"node:child_process";import{cpSync as Jy,existsSync as ld,mkdirSync as id,mkdtempSync as qS,readdirSync as FS,rmSync as Hy,writeFileSync as Gy}from"node:fs";import{dirname as zy,join as yt}from"node:path";import{homedir as va,release as US,tmpdir as WS}from"node:os";import{setTimeout as BS}from"node:timers/promises";function xa(){let e=af(process.platform,process.arch,US());if(e)throw new Error(e)}function Sa(){let e=yt(va(),"Library/LaunchAgents"),t=[];try{t=FS(e).filter(df)}catch{}let o=t.flatMap(n=>{let s=yt(e,n);try{return[{file:s,plist:ho("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return uf(e,o)}function Wr(e){return`gui/${process.getuid()}/${e.label}`}async function ad(e){try{ho("launchctl",["bootout",Wr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{return}await BS(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Yy(e){if(!ld(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{t=!1}t||ho("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ho("launchctl",["kickstart",Wr(e)],{stdio:"pipe"})}function JS(){let e=yf();if(e&&ld(yt(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Ws=new LS("desktop").description("install and control the macOS desktop assistant");Ws.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{xa();let t=O(),o=lf(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=JS(),i=yt(va(),"Applications"),{keep:a,remove:l}=Sa();if(console.log(`Desktop assistant \u2192 ${yt(i,oa)}
|
|
1
|
+
import{a as Uy,b as ka,g as Wy}from"./chunk-DG56PTYL.js";import{n as rd}from"./chunk-GMAORBGM.js";import{a as qy,b as Fy}from"./chunk-ZUZYJQJ4.js";import{b as Ly}from"./chunk-XV3QPZWH.js";import{a as Dy,b as Py,d as Ur,e as My}from"./chunk-I32TCCAK.js";import{d as sy,e as td,h as ry,i as iy}from"./chunk-6UI7GJSB.js";import{$ as yy,A as ny,B as ay,C as ly,E as cy,G as dy,H as uy,I as od,J as gy,U as my,V as py,W as nd,X as fy,_ as hy,aa as wy,ba as by,ca as xy,da as Sy,ea as Ey,fa as Ay,g as Jh,ga as Ry,h as Hh,ha as Ty,ja as sd,ka as Cy,l as Gh,la as Oy,m as zh,na as Iy,o as Fs,p as Us,q as Yh,qa as Ny,r as Kh,ra as jy,s as Xh,sa as _y,t as Vh,u as Qh,v as Zh,x as Xt,z as oy}from"./chunk-ATZRBMUZ.js";import"./chunk-EFGAPAYZ.js";import{a as $y,c as ky,d as vy}from"./chunk-FFOGEFPT.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{b as Mo}from"./chunk-7NQQIDDI.js";import{a as ey,c as ty}from"./chunk-D6LX27PO.js";import"./chunk-WMZ4TGMR.js";import"./chunk-2YDG5CSS.js";import{a as Zc}from"./chunk-LNY6N73E.js";import{b as Yp}from"./chunk-FGHJDZDB.js";import{a as Wp,b as Ic}from"./chunk-GMP2IB4E.js";import{a as Ac,b as xp}from"./chunk-VNXYQH45.js";import{$ as mh,A as Lc,Aa as qr,B as qf,Ba as Mh,C as qc,Ca as ht,D as Ff,Da as ya,E as Uf,Ea as wa,F as Wf,Fa as Fr,G as Bf,Ga as Xc,H as Jf,Ha as Lh,I as Gf,Ia as Fh,J as Fc,Ja as Qc,K as zf,Ka as Wh,L as da,La as ba,M as Yf,Ma as qs,N as Uc,Na as $a,O as Xf,Oa as ed,P as Vf,Pa as Bh,Q as Qf,R as Zf,S as eh,T as ua,U as rh,V as lh,W as ch,X as dh,Y as uh,Z as gh,_ as Bc,a as Kp,aa as ph,b as Xp,ba as fh,ca as hh,da as yh,ea as wh,fa as bh,ga as $h,h as ea,ha as kh,i as Ds,ia as vh,j as ef,ja as Ch,k as Dr,ka as pa,l as ta,la as Po,m as of,ma as Qo,n as sf,na as Ps,o as $f,oa as fa,p as kf,pa as ha,q as aa,qa as Kc,r as Mc,ra as Oh,s as Tf,sa as Ih,t as jf,ta as Nh,u as _f,ua as jh,v as Df,va as _h,w as Pf,wa as Dh,x as ca,xa as Ms,y as Mf,ya as Ls,z as Lf,za as Ph}from"./chunk-ZFMUF3NU.js";import{$b as Vc,Cb as Rh,Db as Th,Eb as zc,Lb as Yc,M as Pr,N as Cf,Q as Of,R as la,_b as qh,bb as Mr,eb as Jc,fb as ga,gb as xh,ia as Hf,ja as Kf,nb as Vo,nc as fo,ob as Sh,pb as Hc,pc as Uh,qa as th,ra as oh,rb as Gc,sa as nh,t as nf,ta as Wc,tb as Eh,ub as Ah,vb as Lr,wa as sh,zb as ma}from"./chunk-LLVVT5OB.js";import"./chunk-GTJIKXDB.js";import{a as Vp,c as _c,d as _r,f as Qp,g as Zp}from"./chunk-2TVJTWFC.js";import{A as oa,B as na,C as af,D as lf,E as cf,G as df,H as uf,I as gf,J as mf,K as pf,L as ff,M as hf,N as yf,S as sa,T as wf,U as bf,Y as If,Z as Nf,i as Sc,j as yp,m as wp,n as bp,w as rf}from"./chunk-BDHWTWD7.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-MRIVENBY.js";import"./chunk-KQ3LPQ2Z.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as ih,b as ah}from"./chunk-EKJG63EJ.js";import"./chunk-UBONPGNT.js";import{b as Ft}from"./chunk-UKUH662W.js";import{c as vf}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import{c as Pc}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as xf,e as ra,g as ia}from"./chunk-LQE73AZR.js";import{a as Sf,b as Ef,c as Af,d as Rf}from"./chunk-2D3RYIDU.js";import{a as Ut}from"./chunk-A24QXLEG.js";import"./chunk-A5GYG56I.js";import{a as Dc,p as tf}from"./chunk-7K7ZQU3C.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{a as Ip,b as Np,c as jp,d as _p,e as Tc,f as Dp,g as Cc,h as Oc,l as Pp,m as Mp}from"./chunk-RX5O5637.js";import{f as Lp,i as qp,l as Fp,m as Up}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{n as Bp,o as Jp,p as Nc,q as Zi,r as Hp,s as Gp}from"./chunk-EYVPRIO3.js";import{b as jc,d as zp}from"./chunk-LTOSEP7C.js";import{a as Ec,d as $p,e as Qi}from"./chunk-QPABR72X.js";import{a as jr,e as Sp,f as Ep,g as Rc,i as Ap,j as Rp,l as Tp,m as Cp,n as Op}from"./chunk-QU7ICYFR.js";import{b as _s,e as vp}from"./chunk-IFUAP7UD.js";import{c as kp}from"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{O as bc,P as Vm,Xa as hp,ba as Xo,ha as gp,l as Um,oa as pp,pa as fp,w as Wm,x as Bm,y as Jm}from"./chunk-4H5B42VW.js";import{Da as mp,I as Cs,J as Xi,K as Vi,L as Os,M as Zm,N as Yo,P as Ko,b as Ts,ha as dp,r as jo,s as $c,t as Qm,u as kc,w as _o,wa as up,x as Ki}from"./chunk-TA437DWX.js";import{b as Tn}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-LACHXOBO.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as tp}from"./chunk-EFXZACH4.js";import{f as op,g as np,h as vc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-7YOLZGB5.js";import{e as rp,f as Do,k as Ns}from"./chunk-IH65GDJR.js";import{d as Km,o as sp,r as cp}from"./chunk-CF2R6BOX.js";import{a as Fe,b as pe,c as Ge,d as js,e as ip}from"./chunk-Q6TGKWZE.js";import{a as ap,b as xc,h as lp}from"./chunk-3UOTLMXD.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Xm}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-HVMUYEQP.js";import{a as Is}from"./chunk-GV7S5BAX.js";import{e as ep}from"./chunk-GSX4NK2N.js";import"./chunk-FG2FPOML.js";import"./chunk-VWTBHLMX.js";import"./chunk-LGYIHB73.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as Gm,j as zm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as wc,b as Ym}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as hc,p as qm,w as Fm}from"./chunk-74MHOALB.js";import{e as _m,f as Rn,g as Dm,h as Rs,k as Pm,l as Mm,n as Lm,o as fc,s as Gi,t as jt,u as zi}from"./chunk-3323WFVK.js";import{a as po}from"./chunk-4NZ4T3TQ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-Z5CMA4JN.js";import{b as yc}from"./chunk-MM7U4PWY.js";import"./chunk-6ECXITK2.js";import{g as zo,i as Yi}from"./chunk-2XQMUSGM.js";import"./chunk-WPNRDEHW.js";import{c as Hm}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QZ24XACR.js";import{a as rc,b as Gg,c as xS,d as Di,e as zg,f as Am,g as DS,h as Rm,i as PS,m as As,n as Cm,q as Om,u as Im,y as mo,z as Nr}from"./chunk-BTLADRMY.js";import{a as No,b as Es,e as xm,f as Ir}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Hi,b as Tm}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as jm}from"./chunk-BYEL7KKR.js";import{h as Go,j as Nm}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as go,b as vS}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as im,Ab as IS,Ca as dm,Da as um,Dc as Z,Ea as cc,I as qi,J as om,Jb as bm,Kb as En,M as qt,Mb as uc,N as ac,Oa as Ui,P as nm,Pa as Wi,Q as Fi,S as RS,Sa as gm,Tb as gc,Ua as mm,Ub as mc,Va as Ss,Wa as dc,Wb as $m,Xa as pm,Xb as NS,_ as rm,aa as am,b as ic,bc as vm,c as Yg,ca as lm,d as Pi,da as cm,e as Kg,ea as CS,eb as fm,f as Xg,gb as hm,h as Vg,hb as ym,i as Mi,j as Qg,l as SS,na as lc,nc as pc,oa as OS,q as Zg,r as ES,rc as Bi,sc as An,t as em,tc as O,w as AS,wb as wm,wc as Ji,x as Li,y as tm,ya as xs,za as Or}from"./chunk-FWNP27H4.js";import"./chunk-KEUW6YLL.js";import{j as He,r as Io}from"./chunk-N47Y5ADQ.js";import{a as sm,e as TS}from"./chunk-VQRY4IDI.js";import{a as km,c as jS}from"./chunk-YSCT6DPR.js";import{g as Sm,k as Em,l as _S}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as MS}from"commander";var By=new MS().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new Xp({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});Z();import{Command as LS}from"commander";import{execFileSync as ho}from"node:child_process";import{cpSync as Jy,existsSync as ld,mkdirSync as id,mkdtempSync as qS,readdirSync as FS,rmSync as Hy,writeFileSync as Gy}from"node:fs";import{dirname as zy,join as yt}from"node:path";import{homedir as va,release as US,tmpdir as WS}from"node:os";import{setTimeout as BS}from"node:timers/promises";function xa(){let e=af(process.platform,process.arch,US());if(e)throw new Error(e)}function Sa(){let e=yt(va(),"Library/LaunchAgents"),t=[];try{t=FS(e).filter(df)}catch{}let o=t.flatMap(n=>{let s=yt(e,n);try{return[{file:s,plist:ho("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return uf(e,o)}function Wr(e){return`gui/${process.getuid()}/${e.label}`}async function ad(e){try{ho("launchctl",["bootout",Wr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{return}await BS(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Yy(e){if(!ld(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{ho("launchctl",["print",Wr(e)],{stdio:"pipe"})}catch{t=!1}t||ho("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ho("launchctl",["kickstart",Wr(e)],{stdio:"pipe"})}function JS(){let e=yf();if(e&&ld(yt(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var Ws=new LS("desktop").description("install and control the macOS desktop assistant");Ws.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{xa();let t=O(),o=lf(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=JS(),i=yt(va(),"Applications"),{keep:a,remove:l}=Sa();if(console.log(`Desktop assistant \u2192 ${yt(i,oa)}
|
|
2
2
|
Computer-use helper \u2192 ${yt(i,na)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -608,7 +608,7 @@ ${oe.text}`));T.delivery.reached.of++,ie&&T.delivery.reached.n++;let j=P[0]??Q[0
|
|
|
608
608
|
Plan ${q.dim(`[${r.state}] by ${r.createdBy}, ${rs(r.createdAt)}`)}`),Hv(s.steps(e)),console.log(`
|
|
609
609
|
Log`);for(let i of s.events(e))console.log(q.dim(` ${rs(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});Fo.command("step <id> <step>").description("move a step of a request's plan on: --retry, --skip or --done").option("--retry","hand the step to its agent again, with a fresh count of nudges (approves a message whose card expired)").option("--skip","leave the step out; the plan goes on with the next one").option("--done","mark the step done yourself").option("--note <text>","why, or the evidence for --done").action((e,t,o)=>{let n=["retry","skip","done"].filter(l=>o[l]);if(n.length!==1){console.error(q.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=fr();if(!s)return;let r=Sl();if(!r){process.exitCode=1;return}let i=Number(t),a=Yf(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(q.red(` ${a}`)),process.exitCode=1;return}console.log(q.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+q.dim(" (the daemon goes on within a minute)")),Hv(r.steps(e))});function Gv(e,t,o,n){let s=Fo.command(`${e} <id>`).description(t).option(o,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped");e==="done"&&s.option("--reason <text>",'close it by hand without a link, saying why ("checked by hand"); also closes a loop its check cannot verify'),s.action((r,i)=>{let a=fr();if(!a)return;let 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()||pm;if(!a.close(r,e==="done"?"done":"dropped",l,Date.now(),null,u)){console.error(q.red(` ${r} is already closed (${Gu[c.state]??c.state})`)),process.exitCode=1;return}console.log(q.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}Gv("done","close a request as finished, with a link to the evidence or the reason","--evidence <link>","a finished request needs --evidence <link> or --reason <text>");Gv("drop","drop a request you no longer want","--reason <text>","");Fo.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").option("--headlines <on|off>","write a headline for a request its agent did not describe (one small model call each)").option("--catch <on|off>","read the reply of each of your turns for a promise or a question to you (one small model call each)").option("--catch-cap <n>","model calls a day the promise catch may make").option("--settle <on|off>","close a quiet request whose handed work all came back done, instead of bringing it back to you").option("--home-closes <on|off>","close a request once its issue or merge request home is merged or closed as completed").option("--plans <on|off>","follow requests of two or more steps as tracked plans").option("--stall-minutes <n>","minutes without progress before a plan step's agent is nudged").option("--max-nudges <n>","nudges per step before it counts as blocked and you are told").option("--approve-kinds <kind,...>",'step kinds you approve once when the plan is made; "none" to clear').option("--plans-off-for <agent,...>",'agents that may not open a plan; "none" to clear').option("--plan-for <work,...>",'kinds of work an agent must plan before it starts (default code); "none" to clear').option("--plan-over <minutes>","work estimated over this many minutes needs a plan (default 30); 0 turns it off").option("--checks <kind,...>",`checks agents may use to close a loop (${Ui.join(", ")}); "none" to turn them all off`).option("--check-every <minutes>","how often each open loop's check runs").option("--auto-resend <on|off>","send a request stopped by a usage limit or a restart back to its agent once, on its own").option("--resend-after <minutes>","minutes after it stopped before it is resent (a limit also waits for its reset)").option("--resend-hold-hours <n>","hours your notice waits for the resend before you are told anyway").option("--flow-zone <zone>","the time zone whose day the flow rate counts by, for example Africa/Tunis").action(async e=>{let t={};try{let u=(y,w)=>{if(w===void 0)return;let $=Number(w);if(!($>0))throw new Error(`${y} must be a positive number`);return $},d=(y,w)=>y===void 0?void 0:y===w?[]:y.split(",").map($=>$.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");t.enabled=e.enabled==="on"}if(t.from=d(e.from,"none"),t.channels=d(e.channels,"all"),t.staleAfterHours=u("--stale-hours",e.staleHours),t.retentionDays=u("--retention-days",e.retentionDays),e.headlines!==void 0){if(e.headlines!=="on"&&e.headlines!=="off")throw new Error("--headlines takes on or off");t.headlines={enabled:e.headlines==="on"}}if(e.catch!==void 0||e.catchCap!==void 0){if(e.catch!==void 0&&e.catch!=="on"&&e.catch!=="off")throw new Error("--catch takes on or off");let y=u("--catch-cap",e.catchCap);if(y!==void 0&&!Number.isInteger(y))throw new Error("--catch-cap must be a whole number");t.catchPromises={...e.catch!==void 0?{enabled:e.catch==="on"}:{},...y!==void 0?{dailyCap:y}:{}}}if(e.settle!==void 0){if(e.settle!=="on"&&e.settle!=="off")throw new Error("--settle takes on or off");t.settleHandedBack=e.settle==="on"}if(e.homeCloses!==void 0){if(e.homeCloses!=="on"&&e.homeCloses!=="off")throw new Error("--home-closes takes on or off");t.homeCloses=e.homeCloses==="on"}let p={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");p.enabled=e.plans==="on"}if(p.stallMinutes=u("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let y=Number(e.maxNudges);if(!Number.isInteger(y)||y<0)throw new Error("--max-nudges must be a whole number, 0 or more");p.maxNudges=y}if(p.approveKinds=d(e.approveKinds,"none"),p.disabledAgents=d(e.plansOffFor,"none"),p.requireForWork=d(e.planFor,"none"),e.planOver!==void 0){let y=Number(e.planOver);if(!(y>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");p.requireOverMinutes=y}Object.values(p).some(y=>y!==void 0)&&(t.plans=p);let f={},g=d(e.checks,"none");if(g){let y=g.filter(w=>!Ui.includes(w));if(y.length)throw new Error(`unknown check ${y.join(", ")}: use ${Ui.join(", ")}`);f.enabled=g}f.checkEveryMinutes=u("--check-every",e.checkEvery),Object.values(f).some(y=>y!==void 0)&&(t.checkers=f);let h={};if(e.autoResend!==void 0){if(e.autoResend!=="on"&&e.autoResend!=="off")throw new Error("--auto-resend takes on or off");h.enabled=e.autoResend==="on"}if(e.resendAfter!==void 0){let y=Number(e.resendAfter);if(!(y>=0))throw new Error("--resend-after must be a number of minutes, 0 or more");h.afterMinutes=y}h.holdMaxHours=u("--resend-hold-hours",e.resendHoldHours),Object.values(h).some(y=>y!==void 0)&&(t.autoResend=h),e.flowZone!==void 0&&(t.flow={timeZone:e.flowZone})}catch(u){console.error(q.red(` ${u.message}`)),process.exitCode=1;return}if(Object.values(t).some(u=>u!==void 0)){let u=await Cf(t);if(!u.success){console.error(q.red(` ${u.error}`)),process.exitCode=1;return}console.log(q.green(" \u2713 saved")+(u.reloaded?q.dim(" (daemon reloaded)"):""))}let o=Pr();console.log(` Requests ${o.enabled?"on":"off"}`),console.log(` Channels ${o.channels.length?o.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${o.from.length?o.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${o.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${o.retentionDays} day(s)`),console.log(` Headlines ${o.headlines?.enabled===!1?"off: titled with the start of your words":"on: written when the agent gave none"}`);let n=o.catchPromises;console.log(` Catch promises ${n?.enabled?`on: each of your turns' reply is read, up to ${n.dailyCap} call(s) a day`:"off"}`),console.log(` Handed work came back ${o.settleHandedBack===!1?"comes back to you when quiet":"closed when quiet, with its link or marked unproven"}`),console.log(` Home closed ${o.homeCloses===!1?"left open":"closes the request: merged, or closed as completed"}`);let s=o.plans??da;console.log(` Plans ${s.enabled?"on":"off"}`),console.log(` Nudge a quiet step after ${s.stallMinutes} minute(s), up to ${s.maxNudges} time(s)`),console.log(` You approve up front ${s.approveKinds.length?s.approveKinds.join(", "):"nothing"}`),console.log(` Plans off for ${s.disabledAgents.length?s.disabledAgents.join(", "):"no agent"}`);let r=s.requireOverMinutes??da.requireOverMinutes,i=s.requireForWork??da.requireForWork;console.log(` Plan before starting ${[i.length?`${i.join(", ")} work`:"",r>0?`work over ${r} minute(s)`:""].filter(Boolean).join("; ")||"never required"}`);let a=o.autoResend??zf;console.log(` Resend once ${a.enabled?`on: after a usage limit resets or a restart, ${a.afterMinutes} minute(s) on; you are told after ${a.holdMaxHours} hour(s) or a second stop`:"off"}`),console.log(` Flow rate counts by ${(o.flow??Nc).timeZone} days`);let l=o.checkers??Wi;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 NI}from"commander";import hr from"chalk";Z();var zv=new NI("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",nd.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(hr.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await pe(r=>{n=fy(r,e,t==="on")});s.success||(console.error(hr.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(hr.green(`\u2713 ${n}`)),s.reloaded&&console.log(hr.dim(" daemon hot-reloaded"))}let o=O().requestStatus.channels.map(n=>n.toLowerCase());for(let n of nd)console.log(` ${n.padEnd(8)} ${o.includes(n)?hr.green("on"):hr.dim("off")}`)});import{Command as aN}from"commander";import yr from"chalk";import Ee from"chalk";import wi from"prompts";import{readFileSync as jI,writeFileSync as _I,existsSync as DI}from"fs";import{resolve as Yv}from"path";var PI=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function MI(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Yu(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Kv(e=".env"){let t=Yv(e);if(!DI(t))return[];let o=jI(t,"utf-8"),n=[];for(let s of o.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let r=s.match(PI);r?n.push({kind:"kv",key:r[1],value:MI(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function LI(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Yu(t.value)}`:t.raw).join(`
|
|
610
610
|
`)+`
|
|
611
|
-
`}function is(e,t,o=".env"){let n=Yv(o),s=Kv(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`})),_I(n,LI(s))}function Ku(e,t=".env"){return Kv(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Xv="https://t.me/BotFather";async function qI(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function FI(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Vv(e={}){console.log(),console.log(Ee.bold(" Connect Telegram")),console.log(),console.log(Ee.dim(` 1. Open ${Xv}`)),console.log(Ee.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Ee.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await wi({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Mo(Xv);let{token:o}=await wi({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:v=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(v.trim())||"That doesn't look like a Telegram token"});o||(console.log(Ee.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await qI(o.trim());n||(console.log(Ee.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Ee.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(Ee.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let 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 wi({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:c.map(x=>({title:x,value:x})),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 wi({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Ee.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;is(f,o.trim()),process.env[f]=o.trim();let g=await pe(v=>{Ge(v,"channels.telegram.enabled",!0),Ge(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let x=js(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),Ge(v,`agents.${u}.mentions`,x))},{configPath:e.configPath});if(g.success||(console.log(Ee.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(Ee.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(Ee.dim(` Token stored in .env as ${f}`)),console.log(Ee.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await wi({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(Ee.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Ee.dim(" Waiting up to 90s..."));let y=await FI(o.trim(),9e4);if(!y){console.log(Ee.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Ee.dim(" agentx config set notifications.destination.channel telegram")),console.log(Ee.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Ee.dim(` agentx config set notifications.destination.accountId ${p}`));return}let w={channel:"telegram",chatId:String(y.chatId),accountId:p},$=[],S=await pe(v=>{Ge(v,"notifications.destination",w),$=Na(v,w)},{configPath:e.configPath});if(!S.success){console.log(Ee.red(` \u2717 failed to save destination: ${S.error}`));return}console.log(Ee.green(" \u2713 Default --notify target set")),console.log(Ee.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Ee.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(Ee.dim(` Schedules that now report here: ${$.join(", ")}`)),S.reloaded&&console.log(Ee.dim(" Daemon hot-reloaded."))}import qe from"chalk";import Xu from"prompts";import{existsSync as Qu,mkdirSync as UI,readdirSync as WI,readFileSync as Qv}from"fs";import{resolve as Vu}from"path";var BI=".agentx/whatsapp-sessions";function JI(){let e=Vu(process.cwd(),".agentx/daemon.pid");if(!Qu(e))return!1;try{let t=parseInt(Qv(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function HI(e){if(!Qu(e))return!1;try{return WI(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function GI(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(qe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(qe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;UI(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let 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(qe.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(qe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(p),t(qe.green(" \u2713 Paired"));try{c.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(qe.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Zv(e={}){if(console.log(),console.log(qe.bold(" Connect WhatsApp")),console.log(),JI()){console.log(qe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(qe.dim(" agentx daemon stop")),console.log();let{cont:c}=await Xu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});c||(console.log(qe.red(" Aborted")),process.exit(1))}let t=e.configPath||Vu(process.cwd(),"agentx.json");Qu(t)||(console.log(qe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Qv(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||BI,s=Vu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(qe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Xu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(qe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(HI(s)&&a){let{keep:c}=await Xu({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(qe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await GI(s,u=>console.log(u))||(console.log(qe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let l=await pe(c=>{Ge(c,"channels.whatsapp.enabled",!0),Ge(c,"channels.whatsapp.sessionDir",n),Ge(c,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});l.success||(console.log(qe.red(` \u2717 ${l.error}`)),process.exit(1)),console.log(),console.log(qe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(qe.dim(` Session: ${n}`)),console.log(qe.dim(" Start the daemon to begin receiving:")),console.log(qe.dim(" agentx daemon start")),console.log(qe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(qe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(qe.dim(" Add routes later with:")),console.log(qe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Ot from"chalk";import zI from"prompts";import{existsSync as YI,readFileSync as KI}from"fs";import{resolve as XI}from"path";async function VI(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function QI(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Uo(e){console.log(Ot.red(` ${e}`)),process.exit(1)}async function as(e){return(await zI(e,{onCancel:()=>Uo("Aborted")}))[e.name]}async function ex(e={}){console.log(),console.log(Ot.bold(" Connect email")),console.log();let t=e.configPath||XI(process.cwd(),"agentx.json");YI(t)||Uo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(KI(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Uo("No agents configured. Run: agentx agent add");let s=e.agent??await as({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(w=>({title:w,value:w}))});o.agents?.[s]||Uo(`No agent "${s}" in ${t}`);let r=(e.address??await as({type:"text",name:"address",message:"Email address customers write to:",validate:w=>/^\S+@\S+\.\S+$/.test(w.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=yy(r),l=e.imapHost??a?.imapHost??await as({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),c=Number(e.imapPort??a?.imapPort??await as({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await as({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await as({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(c)||!Number.isInteger(d))&&Uo("Ports must be numbers.");let p=e.passwordEnv||by(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Uo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Ot.dim(` Gmail needs an app password, not your account password: ${hy}`)),console.log(Ot.dim(" (2-step verification must be on for that page to show.)"))),f=(await as({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Uo("Aborted");let g={agent:s,address:r,imapHost: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 VI(g,f);w&&(console.log(Ot.red("\u2717")),Uo(w)),console.log(Ot.green("\u2713"))}e.passwordEnv||(is(p,f),process.env[p]=f);let h=await pe(w=>{Ge(w,"channels.email.enabled",!0),Ge(w,`channels.email.accounts.${i}`,wy(g))},{configPath:e.configPath});h.success||Uo(`Config save failed: ${h.error}`),console.log(),console.log(Ot.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Ot.dim(` Password stored in .env as ${p}`)),console.log(Ot.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let y=QI(o.agents[s]?.tier,g.allowFrom);y&&console.log(Ot.yellow(` ${y}`)),console.log(g.send==="auto"?Ot.yellow(" Replies are sent as soon as the agent writes them."):Ot.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Ot.dim(" Only mail that arrives from now on is answered.")),console.log(Ot.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as ZI}from"crypto";import Ze from"chalk";import tx from"prompts";var El="agentx-mesh:",Al="//join/";function eN(e){return Buffer.from(e,"utf-8").toString("base64url")}function tN(e){return Buffer.from(e,"base64url").toString("utf-8")}function oN(e){return`${El}${Al}${eN(JSON.stringify(e))}`}function nN(e){if(!e.startsWith(`${El}${Al}`))throw new Error(`Not a mesh invite link \u2014 expected ${El}${Al}\u2026`);let t=e.slice(El.length+Al.length),o=JSON.parse(tN(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function sN(){return ZI(32).toString("hex")}function rN(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function iN(e){return e?.node?.name||e?.node?.id||"node"}async function ox(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ze.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Ku("MESH_TOKEN");i||(i=sN(),is("MESH_TOKEN",i),console.log(Ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||rN(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await tx({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(Ze.red(" Aborted")),process.exit(1)),a=d}let c=await pe(d=>{Ge(d,"mesh.enabled",!0)},{configPath:e.configPath});c.success||(console.log(Ze.red(` \u2717 ${c.error}`)),process.exit(1));let u=oN({url:a,token:i,name:iN(r),version:1});console.log(),console.log(Ze.bold(" Mesh invite")),console.log(),console.log(` ${Ze.cyan(u)}`),console.log(),console.log(Ze.dim(" Run on the other node:")),console.log(Ze.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ze.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function nx(e,t={}){let o;try{o=nN(e)}catch(r){console.log(Ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Ku("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await tx({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ze.red(" Aborted (keeping existing .env)")),process.exit(1))}is("MESH_TOKEN",o.token);let s=await pe(r=>{Ge(r,"mesh.enabled",!0);let i=js(r,"mesh.peers")||[],a=i.findIndex(c=>c.name===o.name),l={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=l:i.push(l),Ge(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ze.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ze.green(" \u2713 Joined mesh")),console.log(Ze.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ze.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ze.dim(" Daemon hot-reloaded.")):console.log(Ze.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Ze.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ze.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ze.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ls=new aN().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ls.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Vv({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ls.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Zv({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});ls.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await ex({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var sx=ls.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");sx.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await ox({url:e.url,configPath:e.config})});sx.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await nx(e,{configPath:t.config})});ls.action(()=>{console.log(),console.log(yr.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${yr.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${yr.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${yr.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${yr.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(yr.dim(" GitLab connect is the next slice.")),console.log()});Z();import{Command as lN}from"commander";import ce from"chalk";var cs=new lN().name("usage").description("token usage analysis and reporting");cs.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}`))}});cs.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}`))}});cs.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?"))}});cs.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 S=r(y),v=w!==null&&S?`${((w-S)/S*100).toFixed(0)}%`:"-";$+=` ${c(S).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()});cs.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-FZBZUK5X.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 cN}from"commander";import Ke from"chalk";import{readFileSync as dN}from"fs";import{resolve as uN}from"path";Z();var fn=new cN().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");fn.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Nm(uN(process.cwd(),".env"))}catch{}let t=gN(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-B6QSOGCC.js");o(t)}catch(t){console.log(Ke.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ke.dim(t.stack)),process.exit(1)}});function gN(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ke.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ke.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
611
|
+
`}function is(e,t,o=".env"){let n=Yv(o),s=Kv(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Yu(t)}`})),_I(n,LI(s))}function Ku(e,t=".env"){return Kv(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Xv="https://t.me/BotFather";async function qI(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function FI(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function Vv(e={}){console.log(),console.log(Ee.bold(" Connect Telegram")),console.log(),console.log(Ee.dim(` 1. Open ${Xv}`)),console.log(Ee.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Ee.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await wi({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Mo(Xv);let{token:o}=await wi({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:v=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(v.trim())||"That doesn't look like a Telegram token"});o||(console.log(Ee.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await qI(o.trim());n||(console.log(Ee.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Ee.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(Ee.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let 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 wi({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:c.map(x=>({title:x,value:x})),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 wi({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Ee.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;is(f,o.trim()),process.env[f]=o.trim();let g=await pe(v=>{Ge(v,"channels.telegram.enabled",!0),Ge(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let x=js(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),Ge(v,`agents.${u}.mentions`,x))},{configPath:e.configPath});if(g.success||(console.log(Ee.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(Ee.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(Ee.dim(` Token stored in .env as ${f}`)),console.log(Ee.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await wi({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(Ee.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Ee.dim(" Waiting up to 90s..."));let y=await FI(o.trim(),9e4);if(!y){console.log(Ee.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Ee.dim(" agentx config set notifications.destination.channel telegram")),console.log(Ee.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Ee.dim(` agentx config set notifications.destination.accountId ${p}`));return}let w={channel:"telegram",chatId:String(y.chatId),accountId:p},$=[],S=await pe(v=>{Ge(v,"notifications.destination",w),$=Na(v,w)},{configPath:e.configPath});if(!S.success){console.log(Ee.red(` \u2717 failed to save destination: ${S.error}`));return}console.log(Ee.green(" \u2713 Default --notify target set")),console.log(Ee.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(Ee.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(Ee.dim(` Schedules that now report here: ${$.join(", ")}`)),S.reloaded&&console.log(Ee.dim(" Daemon hot-reloaded."))}import qe from"chalk";import Xu from"prompts";import{existsSync as Qu,mkdirSync as UI,readdirSync as WI,readFileSync as Qv}from"fs";import{resolve as Vu}from"path";var BI=".agentx/whatsapp-sessions";function JI(){let e=Vu(process.cwd(),".agentx/daemon.pid");if(!Qu(e))return!1;try{let t=parseInt(Qv(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function HI(e){if(!Qu(e))return!1;try{return WI(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function GI(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(qe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(qe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;UI(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let 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(qe.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(qe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(p),t(qe.green(" \u2713 Paired"));try{c.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(qe.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Zv(e={}){if(console.log(),console.log(qe.bold(" Connect WhatsApp")),console.log(),JI()){console.log(qe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(qe.dim(" agentx daemon stop")),console.log();let{cont:c}=await Xu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});c||(console.log(qe.red(" Aborted")),process.exit(1))}let t=e.configPath||Vu(process.cwd(),"agentx.json");Qu(t)||(console.log(qe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Qv(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||BI,s=Vu(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(qe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Xu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(qe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(HI(s)&&a){let{keep:c}=await Xu({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(qe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await GI(s,u=>console.log(u))||(console.log(qe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let l=await pe(c=>{Ge(c,"channels.whatsapp.enabled",!0),Ge(c,"channels.whatsapp.sessionDir",n),Ge(c,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});l.success||(console.log(qe.red(` \u2717 ${l.error}`)),process.exit(1)),console.log(),console.log(qe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(qe.dim(` Session: ${n}`)),console.log(qe.dim(" Start the daemon to begin receiving:")),console.log(qe.dim(" agentx daemon start")),console.log(qe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(qe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(qe.dim(" Add routes later with:")),console.log(qe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Ot from"chalk";import zI from"prompts";import{existsSync as YI,readFileSync as KI}from"fs";import{resolve as XI}from"path";async function VI(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function QI(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Uo(e){console.log(Ot.red(` ${e}`)),process.exit(1)}async function as(e){return(await zI(e,{onCancel:()=>Uo("Aborted")}))[e.name]}async function ex(e={}){console.log(),console.log(Ot.bold(" Connect email")),console.log();let t=e.configPath||XI(process.cwd(),"agentx.json");YI(t)||Uo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(KI(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Uo("No agents configured. Run: agentx agent add");let s=e.agent??await as({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(w=>({title:w,value:w}))});o.agents?.[s]||Uo(`No agent "${s}" in ${t}`);let r=(e.address??await as({type:"text",name:"address",message:"Email address customers write to:",validate:w=>/^\S+@\S+\.\S+$/.test(w.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=yy(r),l=e.imapHost??a?.imapHost??await as({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),c=Number(e.imapPort??a?.imapPort??await as({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await as({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await as({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(c)||!Number.isInteger(d))&&Uo("Ports must be numbers.");let p=e.passwordEnv||by(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Uo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Ot.dim(` Gmail needs an app password, not your account password: ${hy}`)),console.log(Ot.dim(" (2-step verification must be on for that page to show.)"))),f=(await as({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Uo("Aborted");let g={agent:s,address:r,imapHost: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 VI(g,f);w&&(console.log(Ot.red("\u2717")),Uo(w)),console.log(Ot.green("\u2713"))}e.passwordEnv||(is(p,f),process.env[p]=f);let h=await pe(w=>{Ge(w,"channels.email.enabled",!0),Ge(w,`channels.email.accounts.${i}`,wy(g))},{configPath:e.configPath});h.success||Uo(`Config save failed: ${h.error}`),console.log(),console.log(Ot.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Ot.dim(` Password stored in .env as ${p}`)),console.log(Ot.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let y=QI(o.agents[s]?.tier,g.allowFrom);y&&console.log(Ot.yellow(` ${y}`)),console.log(g.send==="auto"?Ot.yellow(" Replies are sent as soon as the agent writes them."):Ot.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Ot.dim(" Only mail that arrives from now on is answered.")),console.log(Ot.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as ZI}from"crypto";import Ze from"chalk";import tx from"prompts";var El="agentx-mesh:",Al="//join/";function eN(e){return Buffer.from(e,"utf-8").toString("base64url")}function tN(e){return Buffer.from(e,"base64url").toString("utf-8")}function oN(e){return`${El}${Al}${eN(JSON.stringify(e))}`}function nN(e){if(!e.startsWith(`${El}${Al}`))throw new Error(`Not a mesh invite link \u2014 expected ${El}${Al}\u2026`);let t=e.slice(El.length+Al.length),o=JSON.parse(tN(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function sN(){return ZI(32).toString("hex")}function rN(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function iN(e){return e?.node?.name||e?.node?.id||"node"}async function ox(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ze.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Ku("MESH_TOKEN");i||(i=sN(),is("MESH_TOKEN",i),console.log(Ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||rN(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await tx({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(Ze.red(" Aborted")),process.exit(1)),a=d}let c=await pe(d=>{Ge(d,"mesh.enabled",!0)},{configPath:e.configPath});c.success||(console.log(Ze.red(` \u2717 ${c.error}`)),process.exit(1));let u=oN({url:a,token:i,name:iN(r),version:1});console.log(),console.log(Ze.bold(" Mesh invite")),console.log(),console.log(` ${Ze.cyan(u)}`),console.log(),console.log(Ze.dim(" Run on the other node:")),console.log(Ze.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ze.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function nx(e,t={}){let o;try{o=nN(e)}catch(r){console.log(Ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Ku("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await tx({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ze.red(" Aborted (keeping existing .env)")),process.exit(1))}is("MESH_TOKEN",o.token);let s=await pe(r=>{Ge(r,"mesh.enabled",!0);let i=js(r,"mesh.peers")||[],a=i.findIndex(c=>c.name===o.name),l={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=l:i.push(l),Ge(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ze.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ze.green(" \u2713 Joined mesh")),console.log(Ze.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ze.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ze.dim(" Daemon hot-reloaded.")):console.log(Ze.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Ze.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ze.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ze.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ls=new aN().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ls.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await Vv({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ls.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await Zv({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});ls.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await ex({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var sx=ls.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");sx.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await ox({url:e.url,configPath:e.config})});sx.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await nx(e,{configPath:t.config})});ls.action(()=>{console.log(),console.log(yr.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${yr.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${yr.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${yr.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${yr.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(yr.dim(" GitLab connect is the next slice.")),console.log()});Z();import{Command as lN}from"commander";import ce from"chalk";var cs=new lN().name("usage").description("token usage analysis and reporting");cs.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}`))}});cs.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}`))}});cs.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?"))}});cs.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 S=r(y),v=w!==null&&S?`${((w-S)/S*100).toFixed(0)}%`:"-";$+=` ${c(S).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()});cs.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-W6CGC2EO.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 cN}from"commander";import Ke from"chalk";import{readFileSync as dN}from"fs";import{resolve as uN}from"path";Z();var fn=new cN().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");fn.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Nm(uN(process.cwd(),".env"))}catch{}let t=gN(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-B6QSOGCC.js");o(t)}catch(t){console.log(Ke.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ke.dim(t.stack)),process.exit(1)}});function gN(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ke.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ke.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
612
612
|
`)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}fn.command("list").description("list configured boards").action(()=>{try{let e=O();if(!e.boards?.length){console.log(Ke.dim(`
|
|
613
613
|
No boards configured.
|
|
614
614
|
`));return}console.log();for(let t of e.boards){console.log(` ${Ke.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(Ke.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(Ke.dim(` primary label: ${t.primaryToolLabel}`)),console.log(Ke.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(Ke.red(` ${e.message}`)),process.exit(1)}});fn.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{bi(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(r=>r.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(r=>r.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(Ke.red(` ${o.message}`)),process.exit(1)}});fn.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,t)=>{try{bi(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=[];if(t.name&&(s.name=t.name,r.push(`name="${t.name}"`)),t.projects){let i=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(i.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:i},r.push(`projects=${i.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,r.push("label cleared")):(s.primaryToolLabel=t.label,r.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,r.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,r.push(`closed-days=${s.closedWindowDays}`)),r.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${r.join(", ")})`})}catch(o){console.log(Ke.red(` ${o.message}`)),process.exit(1)}});var Zu=fn.command("column").description("manage a board's columns (add / remove / edit / list)");Zu.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(dN("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log(Ke.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let r=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${Ke.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${Ke.dim(r)}`)}}catch(t){console.log(Ke.red(` ${t.message}`)),process.exit(1)}});Zu.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,t,o)=>{try{bi(n=>{let r=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!r)throw new Error(`board "${e}" not found`);if(r.columns=r.columns||[],r.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let i={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");i.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");i.mapsToLabel=o.label}return o.accent&&(i.accent=o.accent),r.columns.push(i),`column "${t}" added to board "${e}"`})}catch(n){console.log(Ke.red(` ${n.message}`)),process.exit(1)}});Zu.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{bi(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(i=>i.id!==t),s.columns.length===r)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(Ke.red(` ${o.message}`)),process.exit(1)}});fn.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{bi(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(Ke.red(` ${t.message}`)),process.exit(1)}});function bi(e){let{summary:t,backupPath:o}=Ut(n=>e(n));console.log(Ke.green(`
|
|
@@ -912,7 +912,7 @@ Restart the daemon to activate.
|
|
|
912
912
|
dist/
|
|
913
913
|
*.log
|
|
914
914
|
.env
|
|
915
|
-
`}import{Command as X_}from"commander";import ut from"chalk";import{writeFileSync as V_,mkdirSync as Q_,existsSync as tc,readFileSync as aS,appendFileSync as lS}from"fs";import{resolve as Rr,dirname as uS}from"path";import{homedir as qg}from"os";var gS=new X_().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-
|
|
915
|
+
`}import{Command as X_}from"commander";import ut from"chalk";import{writeFileSync as V_,mkdirSync as Q_,existsSync as tc,readFileSync as aS,appendFileSync as lS}from"fs";import{resolve as Rr,dirname as uS}from"path";import{homedir as qg}from"os";var gS=new X_().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-W6CGC2EO.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=tD(o);break;case"bash":s=iD(o);break;case"fish":s=aD(o);break;default:console.error(ut.red(`unsupported shell: ${n}`)),console.error(ut.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?Rr(String(e.output)):Z_(n);Q_(uS(r),{recursive:!0}),V_(r,s),console.log(ut.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),eD(n,r,!!e.yes)});function Z_(e){let t=qg();switch(e){case"zsh":return Rr(t,".zsh","completions","_agentx");case"bash":return Rr(t,".bash_completion.d","agentx.bash");case"fish":return Rr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function eD(e,t,o){if(e==="zsh"){let n=Rr(qg(),".zshrc"),s=uS(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=tc(n)?aS(n,"utf-8"):"",l=!a.includes(s),c=!/autoload\s+-U\s+compinit/.test(a);if(!l&&!c){console.log(ut.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&tc(n)){let u=["","# agentx completion"];l&&u.push(r),c&&u.push(i),lS(n,u.join(`
|
|
916
916
|
`)+`
|
|
917
917
|
`),console.log(ut.green("\u2713 Patched ~/.zshrc")),console.log(ut.dim("Reload your shell: exec zsh"));return}console.log(ut.dim("Add this to ~/.zshrc if not already present:")),l&&console.log(ut.cyan(` ${r}`)),c&&console.log(ut.cyan(` ${i}`)),console.log(),console.log(ut.dim("Then reload: exec zsh")),console.log(ut.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Rr(qg(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((tc(n)?aS(n,"utf-8"):"").includes(t)){console.log(ut.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&tc(n)){lS(n,`
|
|
918
918
|
# agentx completion
|
|
@@ -928,4 +928,4 @@ ${lD({...t,category:e.category})}`),u&&a.set(c.id,u)}let l=`https://github.com/$
|
|
|
928
928
|
${o.url}`)}catch(t){console.error(Cr.red(` ${t.message}`)),process.exitCode=1}});ji.command("draft <file>").description("turn a draft JSON file ({category, title, fields}) into a pre-filled issue form link; '-' reads stdin").requiredOption("--model <model>","the model that wrote the draft").option("--models <pathOrUrl>","model list to read",Ug).action(async(e,t)=>{try{let o=await Jg(t.models);if(!Wg(t.model,o)){console.log(Bg(t.model,o)),process.exitCode=1;return}let n=e==="-"?await uD():await dD(e,"utf8"),s=JSON.parse(n),{version:r}=await ea(),i=hS({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(Cr.red(` ${o.message}`)),process.exitCode=1}});async function uD(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function V5(){let e=await ea(),t=new gD().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");t.hook("preAction",(o,n)=>{let s=ky(n);vy(s)&&$y("cli",s)});for(let o of[vb,Dw,_w,ls,Ws,yo,Wt,ty,zk,Kk,$o,La,qo,_n,ts,So,Fo,si,zv,pn,Ca,W0,dn,N$,j$,W$,gi,Z$,sk,C$,ak,lk,Ek,Ck,Ok,zt,cs,Y0,Xr,nn,gS,ji])t.addCommand(o);for(let o of wS)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=wS.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,mD(o,74," "),""].join(`
|
|
929
929
|
`)}),t}var wS=[X,$r,Bo,lo,Qr,cr,rt,Wo,fn,es,ps,vr,wn,an,At,er,tl,hl,Qn,yl,wl,M0,F0,Lo,Ei,Jt,By,qn,Ii,Md,$n,xt,Qs,Ld,Jl,To,yg,Jo,eS,Er,tS,G0];function mD(e,t,o){let n=[],s="";for(let r of e)s&&s.length+r.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+r;return s&&n.push(o+s),n.join(`
|
|
930
930
|
`)}export{V5 as buildProgram};
|
|
931
|
-
//# sourceMappingURL=program-
|
|
931
|
+
//# sourceMappingURL=program-W6CGC2EO.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentix-cli",
|
|
3
|
-
"version": "0.226.
|
|
3
|
+
"version": "0.226.4",
|
|
4
4
|
"description": "Put the coding agent you already use on call: it answers in chat and on issues, runs on a schedule, and asks you before anything that matters, on a machine you own. Runs a team of AI agents across Telegram, WhatsApp, GitLab, GitHub, crons, webhooks and mesh tasks, on Claude Code, Codex, OpenCode or any LLM API. Web wizard for operators, CLI for engineers.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
File without changes
|