agentix-cli 0.211.0 → 0.211.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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-YEHUSQFX.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();
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-YIX4NQZV.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-YZEQLJD2.js";import"./chunk-YRBJ4KB7.js";import"./chunk-GTJIKXDB.js";import"./chunk-UYG7UOVQ.js";import"./chunk-W4K3DFAX.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-FLNSBODK.js";import"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-EPIKS3WL.js";import"./chunk-MRIVENBY.js";import"./chunk-GJOKXP5D.js";import"./chunk-A5GYG56I.js";import"./chunk-ZWO36TCN.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-323KMXT4.js";import"./chunk-QPABR72X.js";import"./chunk-IFUAP7UD.js";import"./chunk-KP7KDLZ2.js";import{Ha as yt,q as lt,r as ct,s as dt,t as mt,u as pt}from"./chunk-6BINQY52.js";import"./chunk-MKQI5WL2.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-CUX7BF7B.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-FLDMRYZD.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-IH65GDJR.js";import{u as ut}from"./chunk-JJC2HBWC.js";import"./chunk-Y4BNOZWQ.js";import"./chunk-3UOTLMXD.js";import"./chunk-XVV7ZZ77.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-LIY5CHUV.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-VWTBHLMX.js";import"./chunk-MHRVTFLZ.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-3AHYZLGE.js";import"./chunk-XL7UWG36.js";import"./chunk-MNG2AMKZ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-HPRLRD4P.js";import"./chunk-PYTNMX2D.js";import{a as ht}from"./chunk-6VHORIGB.js";import{f as gt,g as ft}from"./chunk-OAVJMZLF.js";import"./chunk-WPNRDEHW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-YZD6EZMU.js";import{j as it,k as rt,l as at}from"./chunk-LYY7G6LO.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{Nb as tt,Pb as st,Sb as ot,Zb as nt}from"./chunk-GUID2ZA2.js";import"./chunk-KEUW6YLL.js";import"./chunk-N47Y5ADQ.js";import"./chunk-YSCT6DPR.js";import"./chunk-VQRY4IDI.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
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-2FXHWT5U.js";import"./chunk-YRBJ4KB7.js";import"./chunk-GTJIKXDB.js";import"./chunk-UYG7UOVQ.js";import"./chunk-W4K3DFAX.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-FLNSBODK.js";import"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-EPIKS3WL.js";import"./chunk-MRIVENBY.js";import"./chunk-GJOKXP5D.js";import"./chunk-A5GYG56I.js";import"./chunk-ZWO36TCN.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-323KMXT4.js";import"./chunk-QPABR72X.js";import"./chunk-IFUAP7UD.js";import"./chunk-KP7KDLZ2.js";import{Ha as yt,q as lt,r as ct,s as dt,t as mt,u as pt}from"./chunk-6BINQY52.js";import"./chunk-MKQI5WL2.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-CUX7BF7B.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-FLDMRYZD.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-IH65GDJR.js";import{u as ut}from"./chunk-JJC2HBWC.js";import"./chunk-Y4BNOZWQ.js";import"./chunk-3UOTLMXD.js";import"./chunk-XVV7ZZ77.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-LIY5CHUV.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-VWTBHLMX.js";import"./chunk-MHRVTFLZ.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-3AHYZLGE.js";import"./chunk-XL7UWG36.js";import"./chunk-MNG2AMKZ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-HPRLRD4P.js";import"./chunk-PYTNMX2D.js";import{a as ht}from"./chunk-6VHORIGB.js";import{f as gt,g as ft}from"./chunk-OAVJMZLF.js";import"./chunk-WPNRDEHW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-YZD6EZMU.js";import{j as it,k as rt,l as at}from"./chunk-LYY7G6LO.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{Nb as tt,Pb as st,Sb as ot,Zb as nt}from"./chunk-GUID2ZA2.js";import"./chunk-KEUW6YLL.js";import"./chunk-N47Y5ADQ.js";import"./chunk-YSCT6DPR.js";import"./chunk-VQRY4IDI.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
2
2
  `)}
3
3
 
4
4
  ${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
@@ -1,4 +1,4 @@
1
- import{a as tw,b as na,g as ow}from"./chunk-WNE4GRXY.js";import{a as Zh,b as ew}from"./chunk-F3HVONL6.js";import{b as Qh}from"./chunk-XWOXXVVX.js";import{$ as Ih,A as wh,B as kh,C as vh,E as xh,G as Sh,H as Ah,I as Ol,J as Eh,U as Ch,V as Rh,W as Il,X as Th,_ as Oh,aa as Nh,ba as jh,ca as Mh,da as Lh,ea as qh,fa as Fh,g as sh,ga as Uh,h as rh,ha as Wh,ja as Nl,ka as Bh,l as ih,la as Jh,m as ah,na as Hh,o as Is,p as Ns,q as ch,qa as Gh,r as lh,ra as zh,s as dh,sa as Yh,t as uh,u as gh,v as mh,x as uo,z as hh}from"./chunk-QQKPZKQT.js";import{a as _h,c as Ph,d as Dh}from"./chunk-FFOGEFPT.js";import{n as jl}from"./chunk-ISRY3GAD.js";import{a as Kh,b as Xh,d as Tr,e as Vh}from"./chunk-Y65DB3PF.js";import"./chunk-EFGAPAYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as ph,c as fh}from"./chunk-BQIZN5JU.js";import"./chunk-WMZ4TGMR.js";import{d as yh,e as Tl,h as $h,i as bh}from"./chunk-6UI7GJSB.js";import"./chunk-2YDG5CSS.js";import{b as No}from"./chunk-7NQQIDDI.js";import{a as Cl}from"./chunk-LNY6N73E.js";import{a as rp,b as il}from"./chunk-GMP2IB4E.js";import{a as tl,b as Fm}from"./chunk-RKPAVWXF.js";import{$ as Cf,A as gl,Aa as Cr,B as ef,Ba as Vf,C as ml,Ca as mt,D as tf,Da as Zi,E as of,Ea as ea,F as nf,Fa as Rr,G as sf,Ga as Sl,H as rf,Ha as Qf,I as af,Ia as eh,J as pl,Ja as El,K as cf,Ka as oh,L as Gi,La as ta,M as lf,Ma as Os,N as fl,Na as oa,O as df,Oa as Rl,P as uf,Pa as nh,Q as gf,R as mf,S as pf,T as zi,U as $f,V as vf,W as xf,X as Sf,Y as Af,Z as Ef,_ as wl,a as dp,aa as Rf,b as up,ba as Tf,ca as Of,da as If,ea as Nf,fa as jf,ga as _f,h as Di,ha as Pf,i as Es,ia as Df,j as fp,ja as Bf,k as xr,ka as Xi,l as Mi,la as Io,m as wp,ma as Ko,n as $p,na as Cs,o as _p,oa as Vi,p as Pp,pa as Qi,q as Bi,qa as xl,r as ul,ra as Jf,s as Wp,sa as Hf,t as Yp,ta as Gf,u as Kp,ua as zf,v as Xp,va as Yf,w as Vp,wa as Kf,x as Hi,xa as Rs,y as Qp,ya as Ts,z as Zp,za as Xf}from"./chunk-YZEQLJD2.js";import{Bb as Uf,Cb as Wf,Db as kl,Kb as vl,P as Bp,R as Sr,S as Jp,V as Hp,W as Ji,Zb as Zf,_b as Al,ab as Ar,db as yl,eb as Yi,fb as Mf,mb as Yo,mc as lo,nb as Lf,ob as $l,oc as th,pa as ff,qa as hf,qb as bl,ra as wf,sa as hl,sb as qf,tb as Ff,ub as Er,v as yp,va as yf,yb as Ki}from"./chunk-YRBJ4KB7.js";import"./chunk-GTJIKXDB.js";import{a as gp,c as cl,e as mp,f as pp}from"./chunk-UYG7UOVQ.js";import{A as Ep,B as Cp,C as Rp,D as Tp,E as Op,F as Ip,K as Fi,L as Np,M as jp,Q as Gp,R as zp,a as Zc,b as _m,e as Pm,f as Dm,o as bp,s as Li,t as qi,u as kp,v as vp,w as xp,y as Sp,z as Ap}from"./chunk-W4K3DFAX.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as bf,b as kf}from"./chunk-EKJG63EJ.js";import"./chunk-FLNSBODK.js";import{c as Dp}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import{c as dl}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as Mp,e as Ui,g as Wi}from"./chunk-LQE73AZR.js";import{a as Lp,b as qp,c as Fp,d as Up}from"./chunk-2D3RYIDU.js";import{a as Mt}from"./chunk-EPIKS3WL.js";import"./chunk-MRIVENBY.js";import"./chunk-GJOKXP5D.js";import"./chunk-A5GYG56I.js";import{a as ll,p as hp}from"./chunk-ZWO36TCN.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Dt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import{a as Ym,b as Km,c as Xm,d as Vm,e as nl,f as Qm,g as sl,h as rl,l as Zm,m as ep}from"./chunk-RX5O5637.js";import{f as tp,i as op,l as np,m as sp}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{m as ip,n as ap,o as al,p as Pi,q as cp,r as lp}from"./chunk-323KMXT4.js";import{a as el,d as Mm,e as _i}from"./chunk-QPABR72X.js";import{b as As,e as qm}from"./chunk-IFUAP7UD.js";import{c as Lm}from"./chunk-KP7KDLZ2.js";import{Ha as jm,I as Yc,J as pm,X as zo,ba as Tm,ea as Im,fa as Nm,k as sm,v as rm,w as im,x as am}from"./chunk-6BINQY52.js";import{I as bs,J as Ni,K as ji,L as ks,M as hm,N as Ho,P as Go,b as $s,fa as Cm,r as To,s as Kc,t as fm,u as Xc,ua as Rm,w as Oo,wa as Om,x as Ii}from"./chunk-MKQI5WL2.js";import{b as vn}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-CUX7BF7B.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{a as vr,e as Um,f as Wm,g as ol,i as Bm,j as Jm,l as Hm,m as Gm,n as zm}from"./chunk-FLDMRYZD.js";import{f as $m,g as bm,h as Vc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as vm,f as xn,k as xs}from"./chunk-IH65GDJR.js";import{a as gm,l as km,o as Em}from"./chunk-JJC2HBWC.js";import{a as dt,b as me,c as We,d as Ss,e as xm}from"./chunk-Y4BNOZWQ.js";import{a as Sm,b as Qc,h as Am}from"./chunk-3UOTLMXD.js";import"./chunk-XVV7ZZ77.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as mm}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-LIY5CHUV.js";import{a as vs}from"./chunk-GV7S5BAX.js";import{e as wm}from"./chunk-GSX4NK2N.js";import{c as ym}from"./chunk-SZDACK6O.js";import"./chunk-VWTBHLMX.js";import"./chunk-MHRVTFLZ.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as lm,j as dm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as zc,b as um}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as Hc,p as om,v as nm}from"./chunk-3AHYZLGE.js";import{d as Vg,e as kn,f as Qg,g as Ci,j as Zg,k as em,m as tm,n as Jc,r as Ri,s as Ro,t as Ti}from"./chunk-XL7UWG36.js";import{a as co}from"./chunk-MNG2AMKZ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-HPRLRD4P.js";import{a as Gc}from"./chunk-PYTNMX2D.js";import"./chunk-6VHORIGB.js";import{g as Jo,i as Oi}from"./chunk-OAVJMZLF.js";import"./chunk-WPNRDEHW.js";import{c as cm}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-YZD6EZMU.js";import{a as Dc,b as hg,c as $0,d as yi,e as wg,f as Bg,g as O0,h as Jg,i as I0,m as ys,n as Gg,q as zg,u as Yg,y as ao,z as kr}from"./chunk-LYY7G6LO.js";import{a as Co,b as ws,e as Fg,f as br}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Ei,b as Hg}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as Xg}from"./chunk-BYEL7KKR.js";import{h as Bo,j as Kg}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as io,b as y0}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as Eg,B as Sg,C as Ag,Ca as Ng,D as v0,Ea as jg,Fa as _g,M as Lc,N as x0,Nb as Si,Ob as $r,Pb as O,Sb as Ai,Ua as Pg,X as ki,Y as qc,Ya as E0,Zb as te,aa as Cg,ba as S0,f as $i,fb as Dg,g as yg,ga as Rg,gb as bn,ha as A0,ib as Uc,j as Pt,k as Mc,m as $g,ma as vi,n as bi,na as xi,p as b0,pb as Wc,qa as Tg,qb as Bc,sa as Og,sb as Mg,ta as hs,tb as C0,ua as Fc,va as Ig,x as kg,y as vg,z as xg,zb as qg}from"./chunk-GUID2ZA2.js";import"./chunk-KEUW6YLL.js";import{j as nt,r as Wo}from"./chunk-N47Y5ADQ.js";import{a as Lg,c as R0}from"./chunk-YSCT6DPR.js";import{a as bg,e as k0}from"./chunk-VQRY4IDI.js";import{g as Ug,k as Wg,l as T0}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as N0}from"commander";var nw=new N0().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 up({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});te();import{Command as j0}from"commander";import{execFileSync as go}from"node:child_process";import{cpSync as sw,existsSync as Dl,mkdirSync as _l,mkdtempSync as _0,readdirSync as P0,rmSync as rw,writeFileSync as iw}from"node:fs";import{dirname as aw,join as pt}from"node:path";import{homedir as sa,release as D0,tmpdir as M0}from"node:os";import{setTimeout as L0}from"node:timers/promises";function ra(){let e=kp(process.platform,process.arch,D0());if(e)throw new Error(e)}function ia(){let e=pt(sa(),"Library/LaunchAgents"),t=[];try{t=P0(e).filter(Sp)}catch{}let o=t.flatMap(n=>{let s=pt(e,n);try{return[{file:s,plist:go("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Ap(e,o)}function Or(e){return`gui/${process.getuid()}/${e.label}`}async function Pl(e){try{go("launchctl",["bootout",Or(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{go("launchctl",["print",Or(e)],{stdio:"pipe"})}catch{return}await L0(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function cw(e){if(!Dl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{go("launchctl",["print",Or(e)],{stdio:"pipe"})}catch{t=!1}t||go("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),go("launchctl",["kickstart",Or(e)],{stdio:"pipe"})}function q0(){let e=Ip();if(e&&Dl(pt(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 js=new j0("desktop").description("install and control the macOS desktop assistant");js.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=>{ra();let t=O(),o=vp(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=q0(),i=pt(sa(),"Applications"),{keep:a,remove:c}=ia();if(console.log(`Desktop assistant \u2192 ${pt(i,Li)}
1
+ import{a as tw,b as na,g as ow}from"./chunk-WNE4GRXY.js";import{a as Zh,b as ew}from"./chunk-F3HVONL6.js";import{b as Qh}from"./chunk-XWOXXVVX.js";import{$ as Ih,A as wh,B as kh,C as vh,E as xh,G as Sh,H as Ah,I as Ol,J as Eh,U as Ch,V as Rh,W as Il,X as Th,_ as Oh,aa as Nh,ba as jh,ca as Mh,da as Lh,ea as qh,fa as Fh,g as sh,ga as Uh,h as rh,ha as Wh,ja as Nl,ka as Bh,l as ih,la as Jh,m as ah,na as Hh,o as Is,p as Ns,q as ch,qa as Gh,r as lh,ra as zh,s as dh,sa as Yh,t as uh,u as gh,v as mh,x as uo,z as hh}from"./chunk-QQKPZKQT.js";import{a as _h,c as Ph,d as Dh}from"./chunk-FFOGEFPT.js";import{n as jl}from"./chunk-ISRY3GAD.js";import{a as Kh,b as Xh,d as Tr,e as Vh}from"./chunk-Y65DB3PF.js";import"./chunk-EFGAPAYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as ph,c as fh}from"./chunk-BQIZN5JU.js";import"./chunk-WMZ4TGMR.js";import{d as yh,e as Tl,h as $h,i as bh}from"./chunk-6UI7GJSB.js";import"./chunk-2YDG5CSS.js";import{b as No}from"./chunk-7NQQIDDI.js";import{a as Cl}from"./chunk-LNY6N73E.js";import{a as rp,b as il}from"./chunk-GMP2IB4E.js";import{a as tl,b as Fm}from"./chunk-RKPAVWXF.js";import{$ as Cf,A as gl,Aa as Cr,B as ef,Ba as Vf,C as ml,Ca as mt,D as tf,Da as Zi,E as of,Ea as ea,F as nf,Fa as Rr,G as sf,Ga as Sl,H as rf,Ha as Qf,I as af,Ia as eh,J as pl,Ja as El,K as cf,Ka as oh,L as Gi,La as ta,M as lf,Ma as Os,N as fl,Na as oa,O as df,Oa as Rl,P as uf,Pa as nh,Q as gf,R as mf,S as pf,T as zi,U as $f,V as vf,W as xf,X as Sf,Y as Af,Z as Ef,_ as wl,a as dp,aa as Rf,b as up,ba as Tf,ca as Of,da as If,ea as Nf,fa as jf,ga as _f,h as Di,ha as Pf,i as Es,ia as Df,j as fp,ja as Bf,k as xr,ka as Xi,l as Mi,la as Io,m as wp,ma as Ko,n as $p,na as Cs,o as _p,oa as Vi,p as Pp,pa as Qi,q as Bi,qa as xl,r as ul,ra as Jf,s as Wp,sa as Hf,t as Yp,ta as Gf,u as Kp,ua as zf,v as Xp,va as Yf,w as Vp,wa as Kf,x as Hi,xa as Rs,y as Qp,ya as Ts,z as Zp,za as Xf}from"./chunk-2FXHWT5U.js";import{Bb as Uf,Cb as Wf,Db as kl,Kb as vl,P as Bp,R as Sr,S as Jp,V as Hp,W as Ji,Zb as Zf,_b as Al,ab as Ar,db as yl,eb as Yi,fb as Mf,mb as Yo,mc as lo,nb as Lf,ob as $l,oc as th,pa as ff,qa as hf,qb as bl,ra as wf,sa as hl,sb as qf,tb as Ff,ub as Er,v as yp,va as yf,yb as Ki}from"./chunk-YRBJ4KB7.js";import"./chunk-GTJIKXDB.js";import{a as gp,c as cl,e as mp,f as pp}from"./chunk-UYG7UOVQ.js";import{A as Ep,B as Cp,C as Rp,D as Tp,E as Op,F as Ip,K as Fi,L as Np,M as jp,Q as Gp,R as zp,a as Zc,b as _m,e as Pm,f as Dm,o as bp,s as Li,t as qi,u as kp,v as vp,w as xp,y as Sp,z as Ap}from"./chunk-W4K3DFAX.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as bf,b as kf}from"./chunk-EKJG63EJ.js";import"./chunk-FLNSBODK.js";import{c as Dp}from"./chunk-3Q6MRG3P.js";import"./chunk-2VDO2HEK.js";import{c as dl}from"./chunk-2P5NP4H6.js";import"./chunk-B4KQC3DG.js";import{c as Mp,e as Ui,g as Wi}from"./chunk-LQE73AZR.js";import{a as Lp,b as qp,c as Fp,d as Up}from"./chunk-2D3RYIDU.js";import{a as Mt}from"./chunk-EPIKS3WL.js";import"./chunk-MRIVENBY.js";import"./chunk-GJOKXP5D.js";import"./chunk-A5GYG56I.js";import{a as ll,p as hp}from"./chunk-ZWO36TCN.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Dt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import{a as Ym,b as Km,c as Xm,d as Vm,e as nl,f as Qm,g as sl,h as rl,l as Zm,m as ep}from"./chunk-RX5O5637.js";import{f as tp,i as op,l as np,m as sp}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{m as ip,n as ap,o as al,p as Pi,q as cp,r as lp}from"./chunk-323KMXT4.js";import{a as el,d as Mm,e as _i}from"./chunk-QPABR72X.js";import{b as As,e as qm}from"./chunk-IFUAP7UD.js";import{c as Lm}from"./chunk-KP7KDLZ2.js";import{Ha as jm,I as Yc,J as pm,X as zo,ba as Tm,ea as Im,fa as Nm,k as sm,v as rm,w as im,x as am}from"./chunk-6BINQY52.js";import{I as bs,J as Ni,K as ji,L as ks,M as hm,N as Ho,P as Go,b as $s,fa as Cm,r as To,s as Kc,t as fm,u as Xc,ua as Rm,w as Oo,wa as Om,x as Ii}from"./chunk-MKQI5WL2.js";import{b as vn}from"./chunk-MEFPXHQJ.js";import"./chunk-7AB3QUGH.js";import"./chunk-CUX7BF7B.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{a as vr,e as Um,f as Wm,g as ol,i as Bm,j as Jm,l as Hm,m as Gm,n as zm}from"./chunk-FLDMRYZD.js";import{f as $m,g as bm,h as Vc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as vm,f as xn,k as xs}from"./chunk-IH65GDJR.js";import{a as gm,l as km,o as Em}from"./chunk-JJC2HBWC.js";import{a as dt,b as me,c as We,d as Ss,e as xm}from"./chunk-Y4BNOZWQ.js";import{a as Sm,b as Qc,h as Am}from"./chunk-3UOTLMXD.js";import"./chunk-XVV7ZZ77.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as mm}from"./chunk-X5C5W3E4.js";import"./chunk-KWWBDLE6.js";import"./chunk-LIY5CHUV.js";import{a as vs}from"./chunk-GV7S5BAX.js";import{e as wm}from"./chunk-GSX4NK2N.js";import{c as ym}from"./chunk-SZDACK6O.js";import"./chunk-VWTBHLMX.js";import"./chunk-MHRVTFLZ.js";import"./chunk-JTFCU5LH.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import{i as lm,j as dm}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as zc,b as um}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-MYVHVJWZ.js";import{n as Hc,p as om,v as nm}from"./chunk-3AHYZLGE.js";import{d as Vg,e as kn,f as Qg,g as Ci,j as Zg,k as em,m as tm,n as Jc,r as Ri,s as Ro,t as Ti}from"./chunk-XL7UWG36.js";import{a as co}from"./chunk-MNG2AMKZ.js";import"./chunk-LY4G7PCW.js";import"./chunk-DPG6VHPX.js";import"./chunk-BERWTVG2.js";import"./chunk-A7JSRDJL.js";import"./chunk-HPRLRD4P.js";import{a as Gc}from"./chunk-PYTNMX2D.js";import"./chunk-6VHORIGB.js";import{g as Jo,i as Oi}from"./chunk-OAVJMZLF.js";import"./chunk-WPNRDEHW.js";import{c as cm}from"./chunk-OWNQ2FD4.js";import"./chunk-AHWWJ7AF.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-YZD6EZMU.js";import{a as Dc,b as hg,c as $0,d as yi,e as wg,f as Bg,g as O0,h as Jg,i as I0,m as ys,n as Gg,q as zg,u as Yg,y as ao,z as kr}from"./chunk-LYY7G6LO.js";import{a as Co,b as ws,e as Fg,f as br}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as Ei,b as Hg}from"./chunk-MCI3DIWW.js";import"./chunk-7IW25T4K.js";import"./chunk-Q3A5P373.js";import"./chunk-JLBRNYKY.js";import{a as Xg}from"./chunk-BYEL7KKR.js";import{h as Bo,j as Kg}from"./chunk-QUFIUXMQ.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as io,b as y0}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as Eg,B as Sg,C as Ag,Ca as Ng,D as v0,Ea as jg,Fa as _g,M as Lc,N as x0,Nb as Si,Ob as $r,Pb as O,Sb as Ai,Ua as Pg,X as ki,Y as qc,Ya as E0,Zb as te,aa as Cg,ba as S0,f as $i,fb as Dg,g as yg,ga as Rg,gb as bn,ha as A0,ib as Uc,j as Pt,k as Mc,m as $g,ma as vi,n as bi,na as xi,p as b0,pb as Wc,qa as Tg,qb as Bc,sa as Og,sb as Mg,ta as hs,tb as C0,ua as Fc,va as Ig,x as kg,y as vg,z as xg,zb as qg}from"./chunk-GUID2ZA2.js";import"./chunk-KEUW6YLL.js";import{j as nt,r as Wo}from"./chunk-N47Y5ADQ.js";import{a as Lg,c as R0}from"./chunk-YSCT6DPR.js";import{a as bg,e as k0}from"./chunk-VQRY4IDI.js";import{g as Ug,k as Wg,l as T0}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as N0}from"commander";var nw=new N0().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 up({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});te();import{Command as j0}from"commander";import{execFileSync as go}from"node:child_process";import{cpSync as sw,existsSync as Dl,mkdirSync as _l,mkdtempSync as _0,readdirSync as P0,rmSync as rw,writeFileSync as iw}from"node:fs";import{dirname as aw,join as pt}from"node:path";import{homedir as sa,release as D0,tmpdir as M0}from"node:os";import{setTimeout as L0}from"node:timers/promises";function ra(){let e=kp(process.platform,process.arch,D0());if(e)throw new Error(e)}function ia(){let e=pt(sa(),"Library/LaunchAgents"),t=[];try{t=P0(e).filter(Sp)}catch{}let o=t.flatMap(n=>{let s=pt(e,n);try{return[{file:s,plist:go("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Ap(e,o)}function Or(e){return`gui/${process.getuid()}/${e.label}`}async function Pl(e){try{go("launchctl",["bootout",Or(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{go("launchctl",["print",Or(e)],{stdio:"pipe"})}catch{return}await L0(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function cw(e){if(!Dl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{go("launchctl",["print",Or(e)],{stdio:"pipe"})}catch{t=!1}t||go("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),go("launchctl",["kickstart",Or(e)],{stdio:"pipe"})}function q0(){let e=Ip();if(e&&Dl(pt(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 js=new j0("desktop").description("install and control the macOS desktop assistant");js.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=>{ra();let t=O(),o=vp(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=q0(),i=pt(sa(),"Applications"),{keep:a,remove:c}=ia();if(console.log(`Desktop assistant \u2192 ${pt(i,Li)}
2
2
  Computer-use helper \u2192 ${pt(i,qi)}
3
3
  Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -578,7 +578,7 @@ ${oe.text}`));R.delivery.reached.of++,ie&&R.delivery.reached.n++;let j=D[0]??Q[0
578
578
  Seen more than once`));for(let s of n.top)console.log(` ${String(s.count).padStart(5)} ${s.kind.padEnd(24)} ${(s.agentId??"-").padEnd(18)} ${kt.dim(s.detail.slice(0,110))}`)}console.log(kt.dim(`
579
579
  One kind's rows: agentx improve signals --kind <kind> --since ${e.since??"24h"}`))});import{Command as c1}from"commander";import rr from"chalk";te();var Jk=new c1("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Il.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(rr.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await me(r=>{n=Th(r,e,t==="on")});s.success||(console.error(rr.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(rr.green(`\u2713 ${n}`)),s.reloaded&&console.log(rr.dim(" daemon hot-reloaded"))}let o=O().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Il)console.log(` ${n.padEnd(8)} ${o.includes(n)?rr.green("on"):rr.dim("off")}`)});import{Command as M1}from"commander";import ir from"chalk";import Se from"chalk";import ti from"prompts";import{readFileSync as l1,writeFileSync as d1,existsSync as u1}from"fs";import{resolve as Hk}from"path";var g1=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function m1(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 Gk(e=".env"){let t=Hk(e);if(!u1(t))return[];let o=l1(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(g1);r?n.push({kind:"kv",key:r[1],value:m1(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function p1(e){return e.map(t=>t.kind==="kv"?`${t.key}=${yu(t.value)}`:t.raw).join(`
580
580
  `)+`
581
- `}function ts(e,t,o=".env"){let n=Hk(o),s=Gk(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)}`})),d1(n,p1(s))}function $u(e,t=".env"){return Gk(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var zk="https://t.me/BotFather";async function f1(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 h1(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 Yk(e={}){console.log(),console.log(Se.bold(" Connect Telegram")),console.log(),console.log(Se.dim(` 1. Open ${zk}`)),console.log(Se.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Se.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await ti({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&No(zk);let{token:o}=await ti({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(Se.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await f1(o.trim());n||(console.log(Se.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Se.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(Se.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(Se.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await ti({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),u||(console.log(Se.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await ti({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Se.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;ts(f,o.trim()),process.env[f]=o.trim();let g=await me(v=>{We(v,"channels.telegram.enabled",!0),We(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let S=Ss(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),We(v,`agents.${u}.mentions`,S))},{configPath:e.configPath});if(g.success||(console.log(Se.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(Se.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(Se.dim(` Token stored in .env as ${f}`)),console.log(Se.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(Se.dim(" Daemon hot-reloaded.")):console.log(Se.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await ti({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(Se.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Se.dim(" Waiting up to 90s..."));let h=await h1(o.trim(),9e4);if(!h){console.log(Se.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Se.dim(" agentx config set notifications.destination.channel telegram")),console.log(Se.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Se.dim(` agentx config set notifications.destination.accountId ${p}`));return}let y={channel:"telegram",chatId:String(h.chatId),accountId:p},b=[],x=await me(v=>{We(v,"notifications.destination",y),b=pa(v,y)},{configPath:e.configPath});if(!x.success){console.log(Se.red(` \u2717 failed to save destination: ${x.error}`));return}console.log(Se.green(" \u2713 Default --notify target set")),console.log(Se.dim(` Chat: ${h.chatTitle||h.chatId} (from ${h.from})`)),console.log(Se.dim(" From now on, --notify me resolves to this chat.")),b.length&&console.log(Se.dim(` Schedules that now report here: ${b.join(", ")}`)),x.reloaded&&console.log(Se.dim(" Daemon hot-reloaded."))}import Me from"chalk";import bu from"prompts";import{existsSync as vu,mkdirSync as w1,readdirSync as y1,readFileSync as Kk}from"fs";import{resolve as ku}from"path";var $1=".agentx/whatsapp-sessions";function b1(){let e=ku(process.cwd(),".agentx/daemon.pid");if(!vu(e))return!1;try{let t=parseInt(Kk(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function k1(e){if(!vu(e))return!1;try{return y1(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function v1(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Me.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Me.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;w1(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(u=>{let p=setTimeout(()=>{t(Me.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}u(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){t(Me.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(p),t(Me.green(" \u2713 Paired"));try{l.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(Me.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Xk(e={}){if(console.log(),console.log(Me.bold(" Connect WhatsApp")),console.log(),b1()){console.log(Me.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Me.dim(" agentx daemon stop")),console.log();let{cont:l}=await bu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Me.red(" Aborted")),process.exit(1))}let t=e.configPath||ku(process.cwd(),"agentx.json");vu(t)||(console.log(Me.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Kk(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||$1,s=ku(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Me.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await bu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(Me.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(k1(s)&&a){let{keep:l}=await bu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(Me.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await v1(s,u=>console.log(u))||(console.log(Me.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await me(l=>{We(l,"channels.whatsapp.enabled",!0),We(l,"channels.whatsapp.sessionDir",n),We(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Me.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Me.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Me.dim(` Session: ${n}`)),console.log(Me.dim(" Start the daemon to begin receiving:")),console.log(Me.dim(" agentx daemon start")),console.log(Me.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Me.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Me.dim(" Add routes later with:")),console.log(Me.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Rt from"chalk";import x1 from"prompts";import{existsSync as S1,readFileSync as A1}from"fs";import{resolve as E1}from"path";async function C1(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 R1(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 Mo(e){console.log(Rt.red(` ${e}`)),process.exit(1)}async function os(e){return(await x1(e,{onCancel:()=>Mo("Aborted")}))[e.name]}async function Vk(e={}){console.log(),console.log(Rt.bold(" Connect email")),console.log();let t=e.configPath||E1(process.cwd(),"agentx.json");S1(t)||Mo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(A1(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Mo("No agents configured. Run: agentx agent add");let s=e.agent??await os({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(y=>({title:y,value:y}))});o.agents?.[s]||Mo(`No agent "${s}" in ${t}`);let r=(e.address??await os({type:"text",name:"address",message:"Email address customers write to:",validate:y=>/^\S+@\S+\.\S+$/.test(y.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=Ih(r),c=e.imapHost??a?.imapHost??await os({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await os({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await os({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await os({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Mo("Ports must be numbers.");let p=e.passwordEnv||jh(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Mo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Rt.dim(` Gmail needs an app password, not your account password: ${Oh}`)),console.log(Rt.dim(" (2-step verification must be on for that page to show.)"))),f=(await os({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Mo("Aborted");let g={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:p,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let y=await C1(g,f);y&&(console.log(Rt.red("\u2717")),Mo(y)),console.log(Rt.green("\u2713"))}e.passwordEnv||(ts(p,f),process.env[p]=f);let w=await me(y=>{We(y,"channels.email.enabled",!0),We(y,`channels.email.accounts.${i}`,Nh(g))},{configPath:e.configPath});w.success||Mo(`Config save failed: ${w.error}`),console.log(),console.log(Rt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Rt.dim(` Password stored in .env as ${p}`)),console.log(Rt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let h=R1(o.agents[s]?.tier,g.allowFrom);h&&console.log(Rt.yellow(` ${h}`)),console.log(g.send==="auto"?Rt.yellow(" Replies are sent as soon as the agent writes them."):Rt.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Rt.dim(" Only mail that arrives from now on is answered.")),console.log(Rt.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as T1}from"crypto";import Ke from"chalk";import Qk from"prompts";var nc="agentx-mesh:",sc="//join/";function O1(e){return Buffer.from(e,"utf-8").toString("base64url")}function I1(e){return Buffer.from(e,"base64url").toString("utf-8")}function N1(e){return`${nc}${sc}${O1(JSON.stringify(e))}`}function j1(e){if(!e.startsWith(`${nc}${sc}`))throw new Error(`Not a mesh invite link \u2014 expected ${nc}${sc}\u2026`);let t=e.slice(nc.length+sc.length),o=JSON.parse(I1(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 _1(){return T1(32).toString("hex")}function P1(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function D1(e){return e?.node?.name||e?.node?.id||"node"}async function Zk(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ke.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=$u("MESH_TOKEN");i||(i=_1(),ts("MESH_TOKEN",i),console.log(Ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||P1(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Qk({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(Ke.red(" Aborted")),process.exit(1)),a=d}let l=await me(d=>{We(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ke.red(` \u2717 ${l.error}`)),process.exit(1));let u=N1({url:a,token:i,name:D1(r),version:1});console.log(),console.log(Ke.bold(" Mesh invite")),console.log(),console.log(` ${Ke.cyan(u)}`),console.log(),console.log(Ke.dim(" Run on the other node:")),console.log(Ke.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ke.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function ev(e,t={}){let o;try{o=j1(e)}catch(r){console.log(Ke.red(` \u2717 ${r.message}`)),process.exit(1)}let n=$u("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Qk({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ke.red(" Aborted (keeping existing .env)")),process.exit(1))}ts("MESH_TOKEN",o.token);let s=await me(r=>{We(r,"mesh.enabled",!0);let i=Ss(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),We(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ke.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ke.green(" \u2713 Joined mesh")),console.log(Ke.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ke.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ke.dim(" Daemon hot-reloaded.")):console.log(Ke.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Ke.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ke.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ke.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ns=new M1().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ns.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 Yk({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ns.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 Xk({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});ns.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 Vk({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 tv=ns.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");tv.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 Zk({url:e.url,configPath:e.config})});tv.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 ev(e,{configPath:t.config})});ns.action(()=>{console.log(),console.log(ir.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${ir.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${ir.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${ir.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${ir.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(ir.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as L1}from"commander";import le from"chalk";var ss=new L1().name("usage").description("token usage analysis and reporting");ss.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(le.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(le.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${le.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${le.red(String(s.totalErrors))}`),console.log(),console.log(le.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),u=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${le.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${le.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${e.message}`))}});ss.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=O(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(p=>a(p.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:le.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(le.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(le.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let p=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-c)/6e4)),w=d.resetsAt>c?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",h=l.has(d.window)?le.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${p.padEnd(12)} ${[f,w,h].filter(Boolean).join(", ")}`)}console.log();let u=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${u(i.maxPerHour)} in the last hour, ${i.last5h}${u(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(le.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${t.message}`))}});ss.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(le.red(` Script not found: ${s}`)),console.log(le.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(le.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(le.red(" Analysis failed. Is Python 3 installed?"))}});ss.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=g=>/^\d{4}-\d{2}-\d{2}$/.test(g)&&!Number.isNaN(Date.parse(g));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(le.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(le.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=g=>g===null?"-":`$${g.toFixed(g<10?3:2)}`,u=g=>`${(g/1e6).toFixed(1)}M`;console.log(),console.log(le.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(le.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(le.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(g=>[g,a.channels[g],c?.channels[g]]).sort((g,w)=>(w[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,c?.total]);for(let[g,w,h]of f){let y=r(w),b=` ${g.padEnd(14)} ${String(w?.tasks||0).padStart(6)} ${u(w?.cacheRead||0).padStart(11)} ${u(w?.cacheCreate||0).padStart(11)} ${u(w?.output||0).padStart(8)} ${l(w?.cost||0).padStart(10)} ${l(y).padStart(9)}`;if(c){let x=r(h),v=y!==null&&x?`${((y-x)/x*100).toFixed(0)}%`:"-";b+=` ${l(x).padStart(9)} ${v.padStart(7)}`}console.log(b)}console.log(),c&&console.log(le.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(le.dim(` Saved ${e.save}`)),console.log()});ss.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-YEHUSQFX.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();c.push(g),l(f,g)}};l(i,"");let u=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:u},null,2));return}console.log(),console.log(le.bold(` Never used in the last ${e.days} days (${u.length}/${c.length})`)),console.log();for(let d of u)console.log(` ${le.dim("\xB7")} ${d}`);console.log(),console.log(le.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(le.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(le.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(le.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(le.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(le.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=le.dim(`${r.days}d`);console.log(` ${le.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(le.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as q1}from"commander";import He from"chalk";import{readFileSync as F1}from"fs";import{resolve as U1}from"path";te();var un=new q1().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");un.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{Kg(U1(process.cwd(),".env"))}catch{}let t=W1(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-RPZJBHL3.js");o(t)}catch(t){console.log(He.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(He.dim(t.stack)),process.exit(1)}});function W1(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(He.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(He.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
581
+ `}function ts(e,t,o=".env"){let n=Hk(o),s=Gk(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)}`})),d1(n,p1(s))}function $u(e,t=".env"){return Gk(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var zk="https://t.me/BotFather";async function f1(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 h1(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 Yk(e={}){console.log(),console.log(Se.bold(" Connect Telegram")),console.log(),console.log(Se.dim(` 1. Open ${zk}`)),console.log(Se.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(Se.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await ti({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&No(zk);let{token:o}=await ti({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(Se.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await f1(o.trim());n||(console.log(Se.red("\u2717 invalid or revoked")),process.exit(1)),console.log(Se.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(Se.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(Se.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await ti({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),u||(console.log(Se.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||u;d[p]&&d[p].agentBinding!==u&&(p=(await ti({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(Se.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;ts(f,o.trim()),process.env[f]=o.trim();let g=await me(v=>{We(v,"channels.telegram.enabled",!0),We(v,`channels.telegram.accounts.${p}`,{token:`\${${f}}`,agentBinding:u});let S=Ss(v,`agents.${u}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),We(v,`agents.${u}.mentions`,S))},{configPath:e.configPath});if(g.success||(console.log(Se.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(Se.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(Se.dim(` Token stored in .env as ${f}`)),console.log(Se.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(Se.dim(" Daemon hot-reloaded.")):console.log(Se.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await ti({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(Se.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(Se.dim(" Waiting up to 90s..."));let h=await h1(o.trim(),9e4);if(!h){console.log(Se.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(Se.dim(" agentx config set notifications.destination.channel telegram")),console.log(Se.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(Se.dim(` agentx config set notifications.destination.accountId ${p}`));return}let y={channel:"telegram",chatId:String(h.chatId),accountId:p},b=[],x=await me(v=>{We(v,"notifications.destination",y),b=pa(v,y)},{configPath:e.configPath});if(!x.success){console.log(Se.red(` \u2717 failed to save destination: ${x.error}`));return}console.log(Se.green(" \u2713 Default --notify target set")),console.log(Se.dim(` Chat: ${h.chatTitle||h.chatId} (from ${h.from})`)),console.log(Se.dim(" From now on, --notify me resolves to this chat.")),b.length&&console.log(Se.dim(` Schedules that now report here: ${b.join(", ")}`)),x.reloaded&&console.log(Se.dim(" Daemon hot-reloaded."))}import Me from"chalk";import bu from"prompts";import{existsSync as vu,mkdirSync as w1,readdirSync as y1,readFileSync as Kk}from"fs";import{resolve as ku}from"path";var $1=".agentx/whatsapp-sessions";function b1(){let e=ku(process.cwd(),".agentx/daemon.pid");if(!vu(e))return!1;try{let t=parseInt(Kk(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function k1(e){if(!vu(e))return!1;try{return y1(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function v1(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Me.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Me.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;w1(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(u=>{let p=setTimeout(()=>{t(Me.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}u(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){t(Me.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:g}=await import("qrcode-terminal");g.generate(f.qr,{small:!0})}catch{t(` QR: ${f.qr}`)}t("")}if(f.connection==="open"){clearTimeout(p),t(Me.green(" \u2713 Paired"));try{l.end(void 0)}catch{}u(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),t(Me.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Xk(e={}){if(console.log(),console.log(Me.bold(" Connect WhatsApp")),console.log(),b1()){console.log(Me.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Me.dim(" agentx daemon stop")),console.log();let{cont:l}=await bu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Me.red(" Aborted")),process.exit(1))}let t=e.configPath||ku(process.cwd(),"agentx.json");vu(t)||(console.log(Me.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Kk(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||$1,s=ku(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Me.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await bu({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(u=>({title:u,value:u})),initial:0})).agent),i||(console.log(Me.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(k1(s)&&a){let{keep:l}=await bu({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(Me.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await v1(s,u=>console.log(u))||(console.log(Me.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await me(l=>{We(l,"channels.whatsapp.enabled",!0),We(l,"channels.whatsapp.sessionDir",n),We(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Me.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Me.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Me.dim(` Session: ${n}`)),console.log(Me.dim(" Start the daemon to begin receiving:")),console.log(Me.dim(" agentx daemon start")),console.log(Me.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Me.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Me.dim(" Add routes later with:")),console.log(Me.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import Rt from"chalk";import x1 from"prompts";import{existsSync as S1,readFileSync as A1}from"fs";import{resolve as E1}from"path";async function C1(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 R1(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 Mo(e){console.log(Rt.red(` ${e}`)),process.exit(1)}async function os(e){return(await x1(e,{onCancel:()=>Mo("Aborted")}))[e.name]}async function Vk(e={}){console.log(),console.log(Rt.bold(" Connect email")),console.log();let t=e.configPath||E1(process.cwd(),"agentx.json");S1(t)||Mo(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(A1(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Mo("No agents configured. Run: agentx agent add");let s=e.agent??await os({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(y=>({title:y,value:y}))});o.agents?.[s]||Mo(`No agent "${s}" in ${t}`);let r=(e.address??await os({type:"text",name:"address",message:"Email address customers write to:",validate:y=>/^\S+@\S+\.\S+$/.test(y.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=Ih(r),c=e.imapHost??a?.imapHost??await os({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await os({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await os({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await os({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Mo("Ports must be numbers.");let p=e.passwordEnv||jh(i),f=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!f&&Mo(`${e.passwordEnv} is not set in the environment.`),f||(a?.imapHost==="imap.gmail.com"&&(console.log(Rt.dim(` Gmail needs an app password, not your account password: ${Oh}`)),console.log(Rt.dim(" (2-step verification must be on for that page to show.)"))),f=(await os({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),f||Mo("Aborted");let g={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:p,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let y=await C1(g,f);y&&(console.log(Rt.red("\u2717")),Mo(y)),console.log(Rt.green("\u2713"))}e.passwordEnv||(ts(p,f),process.env[p]=f);let w=await me(y=>{We(y,"channels.email.enabled",!0),We(y,`channels.email.accounts.${i}`,Nh(g))},{configPath:e.configPath});w.success||Mo(`Config save failed: ${w.error}`),console.log(),console.log(Rt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Rt.dim(` Password stored in .env as ${p}`)),console.log(Rt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let h=R1(o.agents[s]?.tier,g.allowFrom);h&&console.log(Rt.yellow(` ${h}`)),console.log(g.send==="auto"?Rt.yellow(" Replies are sent as soon as the agent writes them."):Rt.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(Rt.dim(" Only mail that arrives from now on is answered.")),console.log(Rt.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as T1}from"crypto";import Ke from"chalk";import Qk from"prompts";var nc="agentx-mesh:",sc="//join/";function O1(e){return Buffer.from(e,"utf-8").toString("base64url")}function I1(e){return Buffer.from(e,"base64url").toString("utf-8")}function N1(e){return`${nc}${sc}${O1(JSON.stringify(e))}`}function j1(e){if(!e.startsWith(`${nc}${sc}`))throw new Error(`Not a mesh invite link \u2014 expected ${nc}${sc}\u2026`);let t=e.slice(nc.length+sc.length),o=JSON.parse(I1(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 _1(){return T1(32).toString("hex")}function P1(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function D1(e){return e?.node?.name||e?.node?.id||"node"}async function Zk(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Ke.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=$u("MESH_TOKEN");i||(i=_1(),ts("MESH_TOKEN",i),console.log(Ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||P1(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Qk({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(Ke.red(" Aborted")),process.exit(1)),a=d}let l=await me(d=>{We(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ke.red(` \u2717 ${l.error}`)),process.exit(1));let u=N1({url:a,token:i,name:D1(r),version:1});console.log(),console.log(Ke.bold(" Mesh invite")),console.log(),console.log(` ${Ke.cyan(u)}`),console.log(),console.log(Ke.dim(" Run on the other node:")),console.log(Ke.dim(` agentx connect mesh join "${u}"`)),console.log(),console.log(Ke.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function ev(e,t={}){let o;try{o=j1(e)}catch(r){console.log(Ke.red(` \u2717 ${r.message}`)),process.exit(1)}let n=$u("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Qk({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Ke.red(" Aborted (keeping existing .env)")),process.exit(1))}ts("MESH_TOKEN",o.token);let s=await me(r=>{We(r,"mesh.enabled",!0);let i=Ss(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),We(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Ke.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ke.green(" \u2713 Joined mesh")),console.log(Ke.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Ke.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ke.dim(" Daemon hot-reloaded.")):console.log(Ke.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Ke.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Ke.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Ke.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ns=new M1().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ns.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 Yk({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ns.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 Xk({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});ns.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 Vk({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 tv=ns.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");tv.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 Zk({url:e.url,configPath:e.config})});tv.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 ev(e,{configPath:t.config})});ns.action(()=>{console.log(),console.log(ir.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${ir.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${ir.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${ir.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${ir.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(ir.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as L1}from"commander";import le from"chalk";var ss=new L1().name("usage").description("token usage analysis and reporting");ss.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(le.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(le.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${le.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${le.red(String(s.totalErrors))}`),console.log(),console.log(le.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),u=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${le.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${le.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${e.message}`))}});ss.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=O(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(p=>a(p.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:le.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(le.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(le.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let p=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-c)/6e4)),w=d.resetsAt>c?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",h=l.has(d.window)?le.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${p.padEnd(12)} ${[f,w,h].filter(Boolean).join(", ")}`)}console.log();let u=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${u(i.maxPerHour)} in the last hour, ${i.last5h}${u(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(le.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(le.red(" Daemon not running. Start with: agentx daemon start")):console.log(le.red(` ${t.message}`))}});ss.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(le.red(` Script not found: ${s}`)),console.log(le.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(le.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(le.red(" Analysis failed. Is Python 3 installed?"))}});ss.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=g=>/^\d{4}-\d{2}-\d{2}$/.test(g)&&!Number.isNaN(Date.parse(g));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(le.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(le.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=g=>g===null?"-":`$${g.toFixed(g<10?3:2)}`,u=g=>`${(g/1e6).toFixed(1)}M`;console.log(),console.log(le.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(le.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(le.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(g=>[g,a.channels[g],c?.channels[g]]).sort((g,w)=>(w[1]?.cost||0)-(g[1]?.cost||0));f.push(["TOTAL",a.total,c?.total]);for(let[g,w,h]of f){let y=r(w),b=` ${g.padEnd(14)} ${String(w?.tasks||0).padStart(6)} ${u(w?.cacheRead||0).padStart(11)} ${u(w?.cacheCreate||0).padStart(11)} ${u(w?.output||0).padStart(8)} ${l(w?.cost||0).padStart(10)} ${l(y).padStart(9)}`;if(c){let x=r(h),v=y!==null&&x?`${((y-x)/x*100).toFixed(0)}%`:"-";b+=` ${l(x).padStart(9)} ${v.padStart(7)}`}console.log(b)}console.log(),c&&console.log(le.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(le.dim(` Saved ${e.save}`)),console.log()});ss.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-YIX4NQZV.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let f of d.commands??[]){let g=p?`${p} ${f.name()}`:f.name();c.push(g),l(f,g)}};l(i,"");let u=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:u},null,2));return}console.log(),console.log(le.bold(` Never used in the last ${e.days} days (${u.length}/${c.length})`)),console.log();for(let d of u)console.log(` ${le.dim("\xB7")} ${d}`);console.log(),console.log(le.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(le.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(le.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(le.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(le.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(le.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=le.dim(`${r.days}d`);console.log(` ${le.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(le.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as q1}from"commander";import He from"chalk";import{readFileSync as F1}from"fs";import{resolve as U1}from"path";te();var un=new q1().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");un.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{Kg(U1(process.cwd(),".env"))}catch{}let t=W1(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-RPZJBHL3.js");o(t)}catch(t){console.log(He.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(He.dim(t.stack)),process.exit(1)}});function W1(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(He.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(He.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
582
582
  `)),{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}}}}un.command("list").description("list configured boards").action(()=>{try{let e=O();if(!e.boards?.length){console.log(He.dim(`
583
583
  No boards configured.
584
584
  `));return}console.log();for(let t of e.boards){console.log(` ${He.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(He.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(He.dim(` primary label: ${t.primaryToolLabel}`)),console.log(He.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(He.red(` ${e.message}`)),process.exit(1)}});un.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{oi(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(r=>r.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(r=>r.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(He.red(` ${o.message}`)),process.exit(1)}});un.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{oi(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=[];if(t.name&&(s.name=t.name,r.push(`name="${t.name}"`)),t.projects){let i=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(i.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:i},r.push(`projects=${i.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,r.push("label cleared")):(s.primaryToolLabel=t.label,r.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,r.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,r.push(`closed-days=${s.closedWindowDays}`)),r.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${r.join(", ")})`})}catch(o){console.log(He.red(` ${o.message}`)),process.exit(1)}});var xu=un.command("column").description("manage a board's columns (add / remove / edit / list)");xu.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(F1("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log(He.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let r=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${He.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${He.dim(r)}`)}}catch(t){console.log(He.red(` ${t.message}`)),process.exit(1)}});xu.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{oi(n=>{let r=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!r)throw new Error(`board "${e}" not found`);if(r.columns=r.columns||[],r.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let i={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");i.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");i.mapsToLabel=o.label}return o.accent&&(i.accent=o.accent),r.columns.push(i),`column "${t}" added to board "${e}"`})}catch(n){console.log(He.red(` ${n.message}`)),process.exit(1)}});xu.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{oi(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(i=>i.id!==t),s.columns.length===r)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(He.red(` ${o.message}`)),process.exit(1)}});un.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{oi(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(He.red(` ${t.message}`)),process.exit(1)}});function oi(e){let{summary:t,backupPath:o}=Mt(n=>e(n));console.log(He.green(`
@@ -882,7 +882,7 @@ Restart the daemon to activate.
882
882
  dist/
883
883
  *.log
884
884
  .env
885
- `}import{Command as xj}from"commander";import ct from"chalk";import{writeFileSync as Sj,mkdirSync as Aj,existsSync as Nc,readFileSync as n0,appendFileSync as s0}from"fs";import{resolve as hr,dirname as a0}from"path";import{homedir as lg}from"os";var c0=new xj().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-YEHUSQFX.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Rj(o);break;case"bash":s=jj(o);break;case"fish":s=_j(o);break;default:console.error(ct.red(`unsupported shell: ${n}`)),console.error(ct.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?hr(String(e.output)):Ej(n);Aj(a0(r),{recursive:!0}),Sj(r,s),console.log(ct.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),Cj(n,r,!!e.yes)});function Ej(e){let t=lg();switch(e){case"zsh":return hr(t,".zsh","completions","_agentx");case"bash":return hr(t,".bash_completion.d","agentx.bash");case"fish":return hr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Cj(e,t,o){if(e==="zsh"){let n=hr(lg(),".zshrc"),s=a0(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Nc(n)?n0(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(ct.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Nc(n)){let u=["","# agentx completion"];c&&u.push(r),l&&u.push(i),s0(n,u.join(`
885
+ `}import{Command as xj}from"commander";import ct from"chalk";import{writeFileSync as Sj,mkdirSync as Aj,existsSync as Nc,readFileSync as n0,appendFileSync as s0}from"fs";import{resolve as hr,dirname as a0}from"path";import{homedir as lg}from"os";var c0=new xj().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-YIX4NQZV.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Rj(o);break;case"bash":s=jj(o);break;case"fish":s=_j(o);break;default:console.error(ct.red(`unsupported shell: ${n}`)),console.error(ct.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?hr(String(e.output)):Ej(n);Aj(a0(r),{recursive:!0}),Sj(r,s),console.log(ct.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),Cj(n,r,!!e.yes)});function Ej(e){let t=lg();switch(e){case"zsh":return hr(t,".zsh","completions","_agentx");case"bash":return hr(t,".bash_completion.d","agentx.bash");case"fish":return hr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Cj(e,t,o){if(e==="zsh"){let n=hr(lg(),".zshrc"),s=a0(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Nc(n)?n0(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(ct.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Nc(n)){let u=["","# agentx completion"];c&&u.push(r),l&&u.push(i),s0(n,u.join(`
886
886
  `)+`
887
887
  `),console.log(ct.green("\u2713 Patched ~/.zshrc")),console.log(ct.dim("Reload your shell: exec zsh"));return}console.log(ct.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(ct.cyan(` ${r}`)),l&&console.log(ct.cyan(` ${i}`)),console.log(),console.log(ct.dim("Then reload: exec zsh")),console.log(ct.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=hr(lg(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Nc(n)?n0(n,"utf-8"):"").includes(t)){console.log(ct.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&Nc(n)){s0(n,`
888
888
  # agentx completion
@@ -898,4 +898,4 @@ ${Pj({...t,category:e.category})}`),u&&a.set(l.id,u)}let c=`https://github.com/$
898
898
  ${o.url}`)}catch(t){console.error(yr.red(` ${t.message}`)),process.exitCode=1}});hi.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 pg(t.models);if(!gg(t.model,o)){console.log(mg(t.model,o)),process.exitCode=1;return}let n=e==="-"?await Lj():await Mj(e,"utf8"),s=JSON.parse(n),{version:r}=await Di(),i=g0({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(yr.red(` ${o.message}`)),process.exitCode=1}});async function Lj(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function Rz(){let e=await Di(),t=new qj().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=Ph(n);Dh(s)&&_h("cli",s)});for(let o of[Dy,Kw,Yw,ns,js,mo,Lt,fh,zb,Kb,ho,ba,_o,Tn,Xn,bo,Do,wu,Jk,dn,ua,Lx,rn,N$,j$,W$,Kr,Z$,sb,T$,ab,cb,Ab,Tb,Ob,Bt,ss,Jx,Lr,en,c0,hi])t.addCommand(o);for(let o of p0)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=p0.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Fj(o,74," "),""].join(`
899
899
  `)}),t}var p0=[X,lr,qo,no,Fr,Zs,tt,Lo,un,Kn,ls,ur,nn,St,Hs,ja,Ya,zn,Ka,Xa,jx,Dx,jo,ci,Ft,nw,_n,pi,ud,fn,bt,Bs,gd,kc,So,Uu,Fo,Xx,pr,Vx,Wx];function Fj(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(`
900
900
  `)}export{Rz as buildProgram};
901
- //# sourceMappingURL=program-YEHUSQFX.js.map
901
+ //# sourceMappingURL=program-YIX4NQZV.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentix-cli",
3
- "version": "0.211.0",
3
+ "version": "0.211.1",
4
4
  "description": "AI staff for a small company: they find sales, answer clients, write your posts and watch the money, on a machine you own. You approve what matters. Runs a team of AI agents across Telegram, WhatsApp, GitLab, GitHub, crons, webhooks and mesh tasks, on Claude Code, Codex, OpenCode or any LLM API. Web wizard for operators, CLI for engineers.",
5
5
  "license": "MIT",
6
6
  "author": {