agentix-cli 0.168.0 → 0.169.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{board-dashboard-ESAX2ZFV.js → board-dashboard-NEYLE6NJ.js} +317 -288
- package/dist/board-dashboard-NEYLE6NJ.js.map +1 -0
- package/dist/{chunk-HRN4WKSJ.js → chunk-6VKWJQOX.js} +3 -3
- package/dist/{chunk-HRN4WKSJ.js.map → chunk-6VKWJQOX.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{program-7W2LJKDN.js → program-URGH65VO.js} +4 -4
- package/dist/web/activity-graph.global.js +12 -12
- package/dist/web/activity-graph.global.js.map +1 -1
- package/package.json +1 -1
- package/dist/board-dashboard-ESAX2ZFV.js.map +0 -1
- /package/dist/{program-7W2LJKDN.js.map → program-URGH65VO.js.map} +0 -0
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-
|
|
2
|
+
import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-URGH65VO.js"),{installCliSignalExit:r}=await import("./signal-exit-WL7G3EEZ.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{Ia as Tt,Ja as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-
|
|
1
|
+
import{Ia as Tt,Ja 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-6VKWJQOX.js";import"./chunk-FEA3XMVU.js";import"./chunk-GTJIKXDB.js";import"./chunk-KWY5IBII.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PIJ6ECBC.js";import"./chunk-EKJG63EJ.js";import"./chunk-VUEQ4SL5.js";import"./chunk-IMLAPB7G.js";import"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import"./chunk-5HLD66CW.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-VD2P4GWU.js";import"./chunk-LQS27HSV.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-A5GYG56I.js";import"./chunk-ZTIOHZIL.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-IS2IWRP7.js";import"./chunk-MNG2AMKZ.js";import"./chunk-RX5O5637.js";import"./chunk-X7UQY7CH.js";import"./chunk-QPABR72X.js";import"./chunk-LXW7H4D4.js";import"./chunk-PYHR4HXO.js";import"./chunk-KP7KDLZ2.js";import{m as lt,n as ct,o as dt,p as mt,q as pt,ta as yt}from"./chunk-E7Y4G3FK.js";import"./chunk-EEM433JK.js";import"./chunk-MEFPXHQJ.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-5PEXL5LD.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-SZDACK6O.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-VJVXEVZ7.js";import{t as ut}from"./chunk-KMPUUH5R.js";import"./chunk-HFSPH5WM.js";import"./chunk-3UOTLMXD.js";import"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-U4PICSLC.js";import{a as ht}from"./chunk-TVGVQABC.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-S34KFBMJ.js";import"./chunk-JTFCU5LH.js";import{f as gt,g as ft}from"./chunk-JKMFMW3E.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-DCJHCUEQ.js";import{j as it,k as rt,l as at}from"./chunk-Z6ZR2ELO.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-QUFIUXMQ.js";import"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-QOYAX2FT.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{jb as tt,lb as st,nb as ot,ub as nt}from"./chunk-NKCS6EZ7.js";import"./chunk-BRK6M6LA.js";import"./chunk-UEEB3UTU.js";import"./chunk-GZIHLADX.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 xf,b as Ii,g as vf}from"./chunk-5QI7XFTA.js";import{n as zc}from"./chunk-U5SJLLXH.js";import{a as $f,b as kf}from"./chunk-YQM6VR6U.js";import{b as bf}from"./chunk-E67Z6OYF.js";import{a as hf,b as yf,d as sr,e as wf}from"./chunk-COMJ7R5T.js";import{d as zp,e as Bc,h as Yp,i as Kp}from"./chunk-CTN4KYE6.js";import{A as Qp,B as Zp,C as ef,D as Jc,E as tf,J as of,K as nf,L as Gc,M as sf,P as lf,Q as df,R as gf,T as Hc,U as uf,W as mf,X as pf,Y as ff,a as Np,b as jp,f as _p,g as Pp,i as Dp,j as Mp,k as Lp,l as qp,m as Fp,n as Up,o as Wp,r as ss,s as rs,t as io,v as Gp,w as Hp,x as Xp,y as Vp}from"./chunk-UF5TWOKL.js";import"./chunk-XVTD6I34.js";import{a as rf,c as af,d as cf}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-MTX4UPNB.js";import{a as Nt}from"./chunk-CBXPIKPJ.js";import{a as Bp,c as Jp}from"./chunk-BRQKV4FC.js";import{a as Uc}from"./chunk-LNY6N73E.js";import"./chunk-AU3VT7BD.js";import{a as yc,b as Ru}from"./chunk-RKPAVWXF.js";import{$ as ip,A as Nm,Aa as Lc,B as Cc,Ba as Ep,C as jm,Ca as Cp,D as _m,Da as Fc,E as Pm,Ea as Op,F as Dm,Fa as Ti,G as Mm,Ga as ns,H as Lm,Ha as Oi,I as ki,Ia as Wc,J as qm,Ja as Ip,K as Tc,L as Fm,M as Um,N as Wm,O as Bm,P as Jm,Q as xi,R as Km,S as Qm,T as Zm,U as ep,V as tp,W as op,X as Ic,Y as np,Z as sp,_ as rp,a as Wu,aa as ap,b as Bu,ba as cp,ca as lp,da as dp,ea as yp,fa as Ai,ga as $o,h as ai,ha as Do,i as zu,ia as es,j as Zs,ja as Ei,k as ci,ka as Ri,l as Ku,la as Mc,m as Vu,ma as wp,n as lm,na as bp,o as dm,oa as $p,p as pi,pa as kp,q as Ac,qa as xp,r as ym,ra as vp,s as Em,sa as ts,t as Rm,ta as os,u as Cm,ua as Sp,v as Tm,va as or,w as $i,wa as Ap,x as Om,xa as ct,y as Im,ya as Ci,z as Rc,za as nr}from"./chunk-
|
|
1
|
+
import{a as xf,b as Ii,g as vf}from"./chunk-5QI7XFTA.js";import{n as zc}from"./chunk-U5SJLLXH.js";import{a as $f,b as kf}from"./chunk-YQM6VR6U.js";import{b as bf}from"./chunk-E67Z6OYF.js";import{a as hf,b as yf,d as sr,e as wf}from"./chunk-COMJ7R5T.js";import{d as zp,e as Bc,h as Yp,i as Kp}from"./chunk-CTN4KYE6.js";import{A as Qp,B as Zp,C as ef,D as Jc,E as tf,J as of,K as nf,L as Gc,M as sf,P as lf,Q as df,R as gf,T as Hc,U as uf,W as mf,X as pf,Y as ff,a as Np,b as jp,f as _p,g as Pp,i as Dp,j as Mp,k as Lp,l as qp,m as Fp,n as Up,o as Wp,r as ss,s as rs,t as io,v as Gp,w as Hp,x as Xp,y as Vp}from"./chunk-UF5TWOKL.js";import"./chunk-XVTD6I34.js";import{a as rf,c as af,d as cf}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-MTX4UPNB.js";import{a as Nt}from"./chunk-CBXPIKPJ.js";import{a as Bp,c as Jp}from"./chunk-BRQKV4FC.js";import{a as Uc}from"./chunk-LNY6N73E.js";import"./chunk-AU3VT7BD.js";import{a as yc,b as Ru}from"./chunk-RKPAVWXF.js";import{$ as ip,A as Nm,Aa as Lc,B as Cc,Ba as Ep,C as jm,Ca as Cp,D as _m,Da as Fc,E as Pm,Ea as Op,F as Dm,Fa as Ti,G as Mm,Ga as ns,H as Lm,Ha as Oi,I as ki,Ia as Wc,J as qm,Ja as Ip,K as Tc,L as Fm,M as Um,N as Wm,O as Bm,P as Jm,Q as xi,R as Km,S as Qm,T as Zm,U as ep,V as tp,W as op,X as Ic,Y as np,Z as sp,_ as rp,a as Wu,aa as ap,b as Bu,ba as cp,ca as lp,da as dp,ea as yp,fa as Ai,ga as $o,h as ai,ha as Do,i as zu,ia as es,j as Zs,ja as Ei,k as ci,ka as Ri,l as Ku,la as Mc,m as Vu,ma as wp,n as lm,na as bp,o as dm,oa as $p,p as pi,pa as kp,q as Ac,qa as xp,r as ym,ra as vp,s as Em,sa as ts,t as Rm,ta as os,u as Cm,ua as Sp,v as Tm,va as or,w as $i,wa as Ap,x as Om,xa as ct,y as Im,ya as Ci,z as Rc,za as nr}from"./chunk-6VKWJQOX.js";import{$a as Si,Da as er,Ga as Nc,Ha as vi,Ia as gp,Kb as ro,Mb as Tp,Pa as Po,Q as vm,Qa as up,Ra as jc,S as wi,T as Sm,Ta as _c,Va as mp,W as Am,Wa as pp,X as bi,Xa as tr,cb as fp,db as hp,ea as Gm,eb as Pc,fa as Hm,ga as zm,ha as Oc,ja as Ym,lb as Dc,v as Xu,vb as Rp,wb as qc}from"./chunk-FEA3XMVU.js";import"./chunk-GTJIKXDB.js";import{a as Ju,c as xc,e as Gu,f as Hu}from"./chunk-KWY5IBII.js";import"./chunk-ZVP6GB4G.js";import{F as gi,G as am,H as cm,a as fc,b as ku,e as xu,f as vu,n as li,o as di,p as Qu,q as Zu,r as em,t as tm,u as om,w as nm,x as sm,y as rm,z as im}from"./chunk-PIJ6ECBC.js";import{a as Xm,b as Vm}from"./chunk-EKJG63EJ.js";import"./chunk-VUEQ4SL5.js";import"./chunk-IMLAPB7G.js";import{c as gm}from"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import{b as Sc}from"./chunk-5HLD66CW.js";import{c as um,e as ui,g as mi}from"./chunk-LQE73AZR.js";import{a as mm,b as pm,c as fm,d as hm}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-VD2P4GWU.js";import{a as wm,b as an,c as bm,d as fi,g as $m,h as km,j as xm,k as Ec,n as hi,o as cn,p as yi}from"./chunk-LQS27HSV.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-A5GYG56I.js";import{a as vc,p as Yu}from"./chunk-ZTIOHZIL.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as It}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-IS2IWRP7.js";import{a as so}from"./chunk-MNG2AMKZ.js";import{a as Pu,b as Du,c as Mu,d as Lu,e as bc,f as qu,g as $c,h as kc,l as Fu,m as Uu}from"./chunk-RX5O5637.js";import"./chunk-X7UQY7CH.js";import{a as hc,d as Su,e as ii}from"./chunk-QPABR72X.js";import{a as Qs,e as Cu,f as Tu,g as wc,i as Ou,j as Iu,l as Nu,m as ju,n as _u}from"./chunk-LXW7H4D4.js";import{b as Zn,e as Eu}from"./chunk-PYHR4HXO.js";import{c as Au}from"./chunk-KP7KDLZ2.js";import{B as uc,C as su,O as _o,U as wu,g as Xg,r as Vg,ta as $u}from"./chunk-E7Y4G3FK.js";import{B as Yn,C as si,D as ri,E as Kn,F as ru,G as No,I as jo,_ as hu,b as zn,na as yu,pa as bu}from"./chunk-EEM433JK.js";import{b as sn}from"./chunk-MEFPXHQJ.js";import"./chunk-5PEXL5LD.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as au}from"./chunk-SZDACK6O.js";import{f as cu,g as lu,h as mc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as gu,f as rn,k as Vn}from"./chunk-VJVXEVZ7.js";import{a as ou,k as du,n as fu}from"./chunk-KMPUUH5R.js";import{a as Rt,b as ue,c as Ye,d as Qn,e as uu}from"./chunk-HFSPH5WM.js";import{a as mu,b as pc,h as pu}from"./chunk-3UOTLMXD.js";import{i as Zg,j as eu}from"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import{a as gc,b as tu}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as nu}from"./chunk-X5C5W3E4.js";import{a as Xn}from"./chunk-GV7S5BAX.js";import{e as iu}from"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import{a as dc}from"./chunk-U4PICSLC.js";import"./chunk-TVGVQABC.js";import{c as Qg}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-S34KFBMJ.js";import"./chunk-JTFCU5LH.js";import{g as Io,i as ni}from"./chunk-JKMFMW3E.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-DCJHCUEQ.js";import{a as sc,b as Sg,c as hx,d as Xr,e as Ag,f as Wg,g as Ax,h as Bg,i as Ex,m as Hn,n as Gg,q as Hg,u as zg,y as no,z as Vs}from"./chunk-Z6ZR2ELO.js";import{a as bo,b as Gn,e as qg,f as Xs}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as oi,b as Jg}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as Oo,j as Yg}from"./chunk-QUFIUXMQ.js";import{n as Kg}from"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-QOYAX2FT.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as oo,b as fx}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{Fa as Dg,Ga as ac,Ia as cc,M as Ng,N as $x,Pa as xx,Qa as lc,S as Vr,Sa as Mg,T as Qr,Ta as vx,W as jg,X as _g,Xa as Lg,Y as Zr,Z as ic,ea as Pg,fa as kx,j as Rg,jb as ei,k as Cg,kb as Ks,l as Tg,lb as C,m as Og,n as Ig,nb as ti,o as wx,ub as ne,x as rc,y as bx}from"./chunk-NKCS6EZ7.js";import"./chunk-BRK6M6LA.js";import{j as bt,r as Jn}from"./chunk-UEEB3UTU.js";import{a as Eg,e as yx}from"./chunk-GZIHLADX.js";import{g as Fg,k as Ug,l as Sx}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Rx}from"commander";var Sf=new Rx().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 Bu({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()});ne();import{Command as Cx}from"commander";import{execFileSync as Ut}from"node:child_process";import{cpSync as Af,existsSync as Xc,mkdirSync as Yc,mkdtempSync as Tx,readdirSync as Ox,rmSync as Ef,writeFileSync as Rf}from"node:fs";import{dirname as Cf,join as lt}from"node:path";import{homedir as Ni,release as Ix,tmpdir as Nx}from"node:os";import{setTimeout as jx}from"node:timers/promises";function ji(){let e=Qu(process.platform,process.arch,Ix());if(e)throw new Error(e)}function _i(){let e=lt(Ni(),"Library/LaunchAgents"),t=[];try{t=Ox(e).filter(tm)}catch{}let o=t.flatMap(n=>{let s=lt(e,n);try{return[{file:s,plist:Ut("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return om(e,o)}function rr(e){return`gui/${process.getuid()}/${e.label}`}async function Kc(e){try{Ut("launchctl",["bootout",rr(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Ut("launchctl",["print",rr(e)],{stdio:"pipe"})}catch{return}await jx(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Tf(e){if(!Xc(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Ut("launchctl",["print",rr(e)],{stdio:"pipe"})}catch{t=!1}t||Ut("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Ut("launchctl",["kickstart",rr(e)],{stdio:"pipe"})}function _x(){let e=im();if(e&&Xc(lt(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var is=new Cx("desktop").description("install and control the macOS desktop assistant");is.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{ji();let t=C(),o=Zu(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=_x(),i=lt(Ni(),"Applications"),{keep:a,remove:c}=_i();if(console.log(`Desktop assistant \u2192 ${lt(i,li)}
|
|
2
2
|
Computer-use helper \u2192 ${lt(i,di)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -547,7 +547,7 @@ People who asked not to be contacted. The sales agent never drafts a message to
|
|
|
547
547
|
Plan ${_.dim(`[${r.state}] by ${r.createdBy}, ${Nn(r.createdAt)}`)}`),Bb(s.steps(e)),console.log(`
|
|
548
548
|
Log`);for(let i of s.events(e))console.log(_.dim(` ${Nn(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});Ko.command("step <id> <step>").description("move a step of a request's plan on: --retry, --skip or --done").option("--retry","hand the step to its agent again, with a fresh count of nudges (approves a message whose card expired)").option("--skip","leave the step out; the plan goes on with the next one").option("--done","mark the step done yourself").option("--note <text>","why, or the evidence for --done").action((e,t,o)=>{let n=["retry","skip","done"].filter(c=>o[c]);if(n.length!==1){console.error(_.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=Or();if(!s)return;let r=Ra();if(!r){process.exitCode=1;return}let i=Number(t),a=qm(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(_.red(` ${a}`)),process.exitCode=1;return}console.log(_.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+_.dim(" (the daemon goes on within a minute)")),Bb(r.steps(e))});function Jb(e,t,o,n){let s=Ko.command(`${e} <id>`).description(t).option(o,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped");e==="done"&&s.option("--reason <text>",'close it by hand without a link, saying why ("checked by hand"); also closes a loop its check cannot verify'),s.action((r,i)=>{let a=Or();if(!a)return;let c=e==="done"?i.evidence??(i.reason?`closed by owner: ${i.reason}`:void 0):i.reason??"dropped by the owner";if(!c){console.error(_.red(` ${n}`)),process.exitCode=1;return}let l=a.get(r);if(!l||l.state==="candidate"){console.error(_.red(` no request "${r}"`)),process.exitCode=1;return}if(!a.close(r,e==="done"?"done":"dropped",c,Date.now())){console.error(_.red(` ${r} is already closed (${Ad[l.state]??l.state})`)),process.exitCode=1;return}console.log(_.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}Jb("done","close a request as finished, with a link to the evidence or the reason","--evidence <link>","a finished request needs --evidence <link> or --reason <text>");Jb("drop","drop a request you no longer want","--reason <text>","");Ko.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").option("--headlines <on|off>","write a headline for a request its agent did not describe (one small model call each)").option("--catch <on|off>","read the reply of each of your turns for a promise or a question to you (one small model call each)").option("--catch-cap <n>","model calls a day the promise catch may make").option("--settle <on|off>","close a quiet request whose handed work all came back done, instead of bringing it back to you").option("--plans <on|off>","follow requests of two or more steps as tracked plans").option("--stall-minutes <n>","minutes without progress before a plan step's agent is nudged").option("--max-nudges <n>","nudges per step before it counts as blocked and you are told").option("--approve-kinds <kind,...>",'step kinds you approve once when the plan is made; "none" to clear').option("--plans-off-for <agent,...>",'agents that may not open a plan; "none" to clear').option("--plan-for <work,...>",'kinds of work an agent must plan before it starts (default code); "none" to clear').option("--plan-over <minutes>","work estimated over this many minutes needs a plan (default 30); 0 turns it off").option("--checks <kind,...>",`checks agents may use to close a loop (${Vr.join(", ")}); "none" to turn them all off`).option("--check-every <minutes>","how often each open loop's check runs").action(async e=>{let t={};try{let l=(u,h)=>{if(h===void 0)return;let y=Number(h);if(!(y>0))throw new Error(`${u} must be a positive number`);return y},g=(u,h)=>u===void 0?void 0:u===h?[]:u.split(",").map(y=>y.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");t.enabled=e.enabled==="on"}if(t.from=g(e.from,"none"),t.channels=g(e.channels,"all"),t.staleAfterHours=l("--stale-hours",e.staleHours),t.retentionDays=l("--retention-days",e.retentionDays),e.headlines!==void 0){if(e.headlines!=="on"&&e.headlines!=="off")throw new Error("--headlines takes on or off");t.headlines={enabled:e.headlines==="on"}}if(e.catch!==void 0||e.catchCap!==void 0){if(e.catch!==void 0&&e.catch!=="on"&&e.catch!=="off")throw new Error("--catch takes on or off");let u=l("--catch-cap",e.catchCap);if(u!==void 0&&!Number.isInteger(u))throw new Error("--catch-cap must be a whole number");t.catchPromises={...e.catch!==void 0?{enabled:e.catch==="on"}:{},...u!==void 0?{dailyCap:u}:{}}}if(e.settle!==void 0){if(e.settle!=="on"&&e.settle!=="off")throw new Error("--settle takes on or off");t.settleHandedBack=e.settle==="on"}let d={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");d.enabled=e.plans==="on"}if(d.stallMinutes=l("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let u=Number(e.maxNudges);if(!Number.isInteger(u)||u<0)throw new Error("--max-nudges must be a whole number, 0 or more");d.maxNudges=u}if(d.approveKinds=g(e.approveKinds,"none"),d.disabledAgents=g(e.plansOffFor,"none"),d.requireForWork=g(e.planFor,"none"),e.planOver!==void 0){let u=Number(e.planOver);if(!(u>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");d.requireOverMinutes=u}Object.values(d).some(u=>u!==void 0)&&(t.plans=d);let f={},p=g(e.checks,"none");if(p){let u=p.filter(h=>!Vr.includes(h));if(u.length)throw new Error(`unknown check ${u.join(", ")}: use ${Vr.join(", ")}`);f.enabled=p}f.checkEveryMinutes=l("--check-every",e.checkEvery),Object.values(f).some(u=>u!==void 0)&&(t.checkers=f)}catch(l){console.error(_.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(t).some(l=>l!==void 0)){let l=await Sm(t);if(!l.success){console.error(_.red(` ${l.error}`)),process.exitCode=1;return}console.log(_.green(" \u2713 saved")+(l.reloaded?_.dim(" (daemon reloaded)"):""))}let o=wi();console.log(` Requests ${o.enabled?"on":"off"}`),console.log(` Channels ${o.channels.length?o.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${o.from.length?o.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${o.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${o.retentionDays} day(s)`),console.log(` Headlines ${o.headlines?.enabled===!1?"off: titled with the start of your words":"on: written when the agent gave none"}`);let n=o.catchPromises;console.log(` Catch promises ${n?.enabled?`on: each of your turns' reply is read, up to ${n.dailyCap} call(s) a day`:"off"}`),console.log(` Handed work came back ${o.settleHandedBack===!1?"comes back to you when quiet":"closed when quiet, with its link or marked unproven"}`);let s=o.plans??ki;console.log(` Plans ${s.enabled?"on":"off"}`),console.log(` Nudge a quiet step after ${s.stallMinutes} minute(s), up to ${s.maxNudges} time(s)`),console.log(` You approve up front ${s.approveKinds.length?s.approveKinds.join(", "):"nothing"}`),console.log(` Plans off for ${s.disabledAgents.length?s.disabledAgents.join(", "):"no agent"}`);let r=s.requireOverMinutes??ki.requireOverMinutes,i=s.requireForWork??ki.requireForWork;console.log(` Plan before starting ${[i.length?`${i.join(", ")} work`:"",r>0?`work over ${r} minute(s)`:""].filter(Boolean).join("; ")||"never required"}`);let a=o.checkers??Qr;console.log(` Loop checks ${a.enabled.length?a.enabled.join(", "):"off"}, every ${a.checkEveryMinutes} minute(s)`);let c=Object.keys(a.repos);console.log(` Repos for git-ancestor ${c.length?c.join(", "):"none (requests.checkers.repos in agentx.json)"}`)});import{Command as PC}from"commander";import Ns from"chalk";ne();var Gb=new PC("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Gc.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(Ns.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await ue(r=>{n=sf(r,e,t==="on")});s.success||(console.error(Ns.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(Ns.green(`\u2713 ${n}`)),s.reloaded&&console.log(Ns.dim(" daemon hot-reloaded"))}let o=C().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Gc)console.log(` ${n.padEnd(8)} ${o.includes(n)?Ns.green("on"):Ns.dim("off")}`)});import{Command as sT}from"commander";import js from"chalk";import ye from"chalk";import Nr from"prompts";import{readFileSync as DC,writeFileSync as MC,existsSync as LC}from"fs";import{resolve as Hb}from"path";var qC=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function FC(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Rd(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function zb(e=".env"){let t=Hb(e);if(!LC(t))return[];let o=DC(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(qC);r?n.push({kind:"kv",key:r[1],value:FC(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function UC(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Rd(t.value)}`:t.raw).join(`
|
|
549
549
|
`)+`
|
|
550
|
-
`}function Ir(e,t,o=".env"){let n=Hb(o),s=zb(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Rd(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Rd(t)}`})),MC(n,UC(s))}function Cd(e,t=".env"){return zb(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Yb="https://t.me/BotFather";async function WC(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 BC(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 Kb(e={}){console.log(),console.log(ye.bold(" Connect Telegram")),console.log(),console.log(ye.dim(` 1. Open ${Yb}`)),console.log(ye.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ye.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Nr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&ko(Yb);let{token:o}=await Nr({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(ye.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await WC(o.trim());n||(console.log(ye.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ye.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(ye.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(ye.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Nr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),g||(console.log(ye.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await Nr({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ye.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Ir(p,o.trim()),process.env[p]=o.trim();let u=await ue(v=>{Ye(v,"channels.telegram.enabled",!0),Ye(v,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let S=Qn(v,`agents.${g}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),Ye(v,`agents.${g}.mentions`,S))},{configPath:e.configPath});if(u.success||(console.log(ye.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(ye.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ye.dim(` Token stored in .env as ${p}`)),console.log(ye.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(ye.dim(" Daemon hot-reloaded.")):console.log(ye.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Nr({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ye.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ye.dim(" Waiting up to 90s..."));let y=await BC(o.trim(),9e4);if(!y){console.log(ye.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ye.dim(" agentx config set notifications.destination.channel telegram")),console.log(ye.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ye.dim(` agentx config set notifications.destination.accountId ${f}`));return}let b={channel:"telegram",chatId:String(y.chatId),accountId:f},$=[],x=await ue(v=>{Ye(v,"notifications.destination",b),$=ka(v,b)},{configPath:e.configPath});if(!x.success){console.log(ye.red(` \u2717 failed to save destination: ${x.error}`));return}console.log(ye.green(" \u2713 Default --notify target set")),console.log(ye.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(ye.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(ye.dim(` Schedules that now report here: ${$.join(", ")}`)),x.reloaded&&console.log(ye.dim(" Daemon hot-reloaded."))}import je from"chalk";import Td from"prompts";import{existsSync as Id,mkdirSync as JC,readdirSync as GC,readFileSync as Xb}from"fs";import{resolve as Od}from"path";var HC=".agentx/whatsapp-sessions";function zC(){let e=Od(process.cwd(),".agentx/daemon.pid");if(!Id(e))return!1;try{let t=parseInt(Xb(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function YC(e){if(!Id(e))return!1;try{return GC(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function KC(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(je.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(je.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;JC(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(g=>{let f=setTimeout(()=>{t(je.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(je.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:u}=await import("qrcode-terminal");u.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(je.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(je.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Vb(e={}){if(console.log(),console.log(je.bold(" Connect WhatsApp")),console.log(),zC()){console.log(je.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(je.dim(" agentx daemon stop")),console.log();let{cont:l}=await Td({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(je.red(" Aborted")),process.exit(1))}let t=e.configPath||Od(process.cwd(),"agentx.json");Id(t)||(console.log(je.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Xb(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||HC,s=Od(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(je.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Td({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(je.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(YC(s)&&a){let{keep:l}=await Td({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(je.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await KC(s,g=>console.log(g))||(console.log(je.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ue(l=>{Ye(l,"channels.whatsapp.enabled",!0),Ye(l,"channels.whatsapp.sessionDir",n),Ye(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(je.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(je.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(je.dim(` Session: ${n}`)),console.log(je.dim(" Start the daemon to begin receiving:")),console.log(je.dim(" agentx daemon start")),console.log(je.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(je.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(je.dim(" Add routes later with:")),console.log(je.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import{randomBytes as XC}from"crypto";import He from"chalk";import Qb from"prompts";var Ca="agentx-mesh:",Ta="//join/";function VC(e){return Buffer.from(e,"utf-8").toString("base64url")}function QC(e){return Buffer.from(e,"base64url").toString("utf-8")}function ZC(e){return`${Ca}${Ta}${VC(JSON.stringify(e))}`}function eT(e){if(!e.startsWith(`${Ca}${Ta}`))throw new Error(`Not a mesh invite link \u2014 expected ${Ca}${Ta}\u2026`);let t=e.slice(Ca.length+Ta.length),o=JSON.parse(QC(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 tT(){return XC(32).toString("hex")}function oT(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function nT(e){return e?.node?.name||e?.node?.id||"node"}async function Zb(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(He.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Cd("MESH_TOKEN");i||(i=tT(),Ir("MESH_TOKEN",i),console.log(He.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||oT(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Qb({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(He.red(" Aborted")),process.exit(1)),a=d}let l=await ue(d=>{Ye(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(He.red(` \u2717 ${l.error}`)),process.exit(1));let g=ZC({url:a,token:i,name:nT(r),version:1});console.log(),console.log(He.bold(" Mesh invite")),console.log(),console.log(` ${He.cyan(g)}`),console.log(),console.log(He.dim(" Run on the other node:")),console.log(He.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(He.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function e$(e,t={}){let o;try{o=eT(e)}catch(r){console.log(He.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Cd("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Qb({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(He.red(" Aborted (keeping existing .env)")),process.exit(1))}Ir("MESH_TOKEN",o.token);let s=await ue(r=>{Ye(r,"mesh.enabled",!0);let i=Qn(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),Ye(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(He.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(He.green(" \u2713 Joined mesh")),console.log(He.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(He.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(He.dim(" Daemon hot-reloaded.")):console.log(He.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(He.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(He.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(He.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var _s=new sT().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");_s.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 Kb({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});_s.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 Vb({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var t$=_s.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");t$.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 Zb({url:e.url,configPath:e.config})});t$.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 e$(e,{configPath:t.config})});_s.action(()=>{console.log(),console.log(js.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${js.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${js.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${js.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${js.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(js.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as rT}from"commander";import se from"chalk";var jn=new rT().name("usage").description("token usage analysis and reporting");jn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=C(),[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(se.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(se.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${se.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: ${se.red(String(s.totalErrors))}`),console.log(),console.log(se.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),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${se.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${se.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${e.message}`))}});jn.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=C(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:se.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(se.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(se.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",u=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?u<60?`resets in ${u} min`:u<48*60?`resets in ${Math.round(u/60)} h`:`resets in ${Math.round(u/1440)} days`:"",y=l.has(d.window)?se.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,y].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(se.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${t.message}`))}});jn.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(se.red(` Script not found: ${s}`)),console.log(se.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(se.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(se.red(" Analysis failed. Is Python 3 installed?"))}});jn.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=u=>/^\d{4}-\d{2}-\d{2}$/.test(u)&&!Number.isNaN(Date.parse(u));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(se.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(u){console.log(se.red(` Cannot read baseline ${e.baseline}: ${u.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=u=>u===null?"-":`$${u.toFixed(u<10?3:2)}`,g=u=>`${(u/1e6).toFixed(1)}M`;console.log(),console.log(se.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(se.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(se.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(u=>[u,a.channels[u],c?.channels[u]]).sort((u,h)=>(h[1]?.cost||0)-(u[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[u,h,y]of p){let b=r(h),$=` ${u.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${g(h?.cacheRead||0).padStart(11)} ${g(h?.cacheCreate||0).padStart(11)} ${g(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l(b).padStart(9)}`;if(c){let x=r(y),v=b!==null&&x?`${((b-x)/x*100).toFixed(0)}%`:"-";$+=` ${l(x).padStart(9)} ${v.padStart(7)}`}console.log($)}console.log(),c&&console.log(se.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(se.dim(` Saved ${e.save}`)),console.log()});jn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y7D5W52I.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-7W2LJKDN.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let u=f?`${f} ${p.name()}`:p.name();c.push(u),l(p,u)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(se.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${se.dim("\xB7")} ${d}`);console.log(),console.log(se.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(se.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(se.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(se.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(se.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(se.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=se.dim(`${r.days}d`);console.log(` ${se.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(se.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as iT}from"commander";import Ue from"chalk";import{readFileSync as aT}from"fs";import{resolve as cT}from"path";ne();var Xo=new iT().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Xo.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{Yg(cT(process.cwd(),".env"))}catch{}let t=lT(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-ESAX2ZFV.js");o(t)}catch(t){console.log(Ue.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ue.dim(t.stack)),process.exit(1)}});function lT(e,t){try{let o=C();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ue.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ue.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
550
|
+
`}function Ir(e,t,o=".env"){let n=Hb(o),s=zb(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Rd(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Rd(t)}`})),MC(n,UC(s))}function Cd(e,t=".env"){return zb(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Yb="https://t.me/BotFather";async function WC(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 BC(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 Kb(e={}){console.log(),console.log(ye.bold(" Connect Telegram")),console.log(),console.log(ye.dim(` 1. Open ${Yb}`)),console.log(ye.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ye.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Nr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&ko(Yb);let{token:o}=await Nr({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(ye.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await WC(o.trim());n||(console.log(ye.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ye.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(ye.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(ye.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Nr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),g||(console.log(ye.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await Nr({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ye.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Ir(p,o.trim()),process.env[p]=o.trim();let u=await ue(v=>{Ye(v,"channels.telegram.enabled",!0),Ye(v,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let S=Qn(v,`agents.${g}.mentions`)||[],k=`@${n.username}`;S.includes(k)||(S.push(k),Ye(v,`agents.${g}.mentions`,S))},{configPath:e.configPath});if(u.success||(console.log(ye.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(ye.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ye.dim(` Token stored in .env as ${p}`)),console.log(ye.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(ye.dim(" Daemon hot-reloaded.")):console.log(ye.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Nr({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ye.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ye.dim(" Waiting up to 90s..."));let y=await BC(o.trim(),9e4);if(!y){console.log(ye.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ye.dim(" agentx config set notifications.destination.channel telegram")),console.log(ye.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ye.dim(` agentx config set notifications.destination.accountId ${f}`));return}let b={channel:"telegram",chatId:String(y.chatId),accountId:f},$=[],x=await ue(v=>{Ye(v,"notifications.destination",b),$=ka(v,b)},{configPath:e.configPath});if(!x.success){console.log(ye.red(` \u2717 failed to save destination: ${x.error}`));return}console.log(ye.green(" \u2713 Default --notify target set")),console.log(ye.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(ye.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(ye.dim(` Schedules that now report here: ${$.join(", ")}`)),x.reloaded&&console.log(ye.dim(" Daemon hot-reloaded."))}import je from"chalk";import Td from"prompts";import{existsSync as Id,mkdirSync as JC,readdirSync as GC,readFileSync as Xb}from"fs";import{resolve as Od}from"path";var HC=".agentx/whatsapp-sessions";function zC(){let e=Od(process.cwd(),".agentx/daemon.pid");if(!Id(e))return!1;try{let t=parseInt(Xb(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function YC(e){if(!Id(e))return!1;try{return GC(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function KC(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(je.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(je.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;JC(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(g=>{let f=setTimeout(()=>{t(je.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(je.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:u}=await import("qrcode-terminal");u.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(je.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(je.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Vb(e={}){if(console.log(),console.log(je.bold(" Connect WhatsApp")),console.log(),zC()){console.log(je.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(je.dim(" agentx daemon stop")),console.log();let{cont:l}=await Td({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(je.red(" Aborted")),process.exit(1))}let t=e.configPath||Od(process.cwd(),"agentx.json");Id(t)||(console.log(je.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Xb(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||HC,s=Od(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(je.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Td({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(je.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(YC(s)&&a){let{keep:l}=await Td({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(je.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await KC(s,g=>console.log(g))||(console.log(je.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ue(l=>{Ye(l,"channels.whatsapp.enabled",!0),Ye(l,"channels.whatsapp.sessionDir",n),Ye(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(je.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(je.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(je.dim(` Session: ${n}`)),console.log(je.dim(" Start the daemon to begin receiving:")),console.log(je.dim(" agentx daemon start")),console.log(je.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(je.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(je.dim(" Add routes later with:")),console.log(je.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import{randomBytes as XC}from"crypto";import He from"chalk";import Qb from"prompts";var Ca="agentx-mesh:",Ta="//join/";function VC(e){return Buffer.from(e,"utf-8").toString("base64url")}function QC(e){return Buffer.from(e,"base64url").toString("utf-8")}function ZC(e){return`${Ca}${Ta}${VC(JSON.stringify(e))}`}function eT(e){if(!e.startsWith(`${Ca}${Ta}`))throw new Error(`Not a mesh invite link \u2014 expected ${Ca}${Ta}\u2026`);let t=e.slice(Ca.length+Ta.length),o=JSON.parse(QC(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 tT(){return XC(32).toString("hex")}function oT(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function nT(e){return e?.node?.name||e?.node?.id||"node"}async function Zb(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(He.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Cd("MESH_TOKEN");i||(i=tT(),Ir("MESH_TOKEN",i),console.log(He.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||oT(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Qb({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(He.red(" Aborted")),process.exit(1)),a=d}let l=await ue(d=>{Ye(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(He.red(` \u2717 ${l.error}`)),process.exit(1));let g=ZC({url:a,token:i,name:nT(r),version:1});console.log(),console.log(He.bold(" Mesh invite")),console.log(),console.log(` ${He.cyan(g)}`),console.log(),console.log(He.dim(" Run on the other node:")),console.log(He.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(He.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function e$(e,t={}){let o;try{o=eT(e)}catch(r){console.log(He.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Cd("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Qb({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(He.red(" Aborted (keeping existing .env)")),process.exit(1))}Ir("MESH_TOKEN",o.token);let s=await ue(r=>{Ye(r,"mesh.enabled",!0);let i=Qn(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),Ye(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(He.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(He.green(" \u2713 Joined mesh")),console.log(He.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(He.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(He.dim(" Daemon hot-reloaded.")):console.log(He.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(He.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(He.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(He.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var _s=new sT().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");_s.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 Kb({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});_s.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 Vb({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var t$=_s.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");t$.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 Zb({url:e.url,configPath:e.config})});t$.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 e$(e,{configPath:t.config})});_s.action(()=>{console.log(),console.log(js.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${js.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${js.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${js.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${js.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(js.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as rT}from"commander";import se from"chalk";var jn=new rT().name("usage").description("token usage analysis and reporting");jn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=C(),[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(se.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(se.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${se.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: ${se.red(String(s.totalErrors))}`),console.log(),console.log(se.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),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${se.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${se.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${e.message}`))}});jn.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=C(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:se.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(se.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(se.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",u=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?u<60?`resets in ${u} min`:u<48*60?`resets in ${Math.round(u/60)} h`:`resets in ${Math.round(u/1440)} days`:"",y=l.has(d.window)?se.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,y].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(se.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${t.message}`))}});jn.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(se.red(` Script not found: ${s}`)),console.log(se.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(se.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(se.red(" Analysis failed. Is Python 3 installed?"))}});jn.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=u=>/^\d{4}-\d{2}-\d{2}$/.test(u)&&!Number.isNaN(Date.parse(u));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(se.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(u){console.log(se.red(` Cannot read baseline ${e.baseline}: ${u.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=u=>u===null?"-":`$${u.toFixed(u<10?3:2)}`,g=u=>`${(u/1e6).toFixed(1)}M`;console.log(),console.log(se.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(se.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(se.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(u=>[u,a.channels[u],c?.channels[u]]).sort((u,h)=>(h[1]?.cost||0)-(u[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[u,h,y]of p){let b=r(h),$=` ${u.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${g(h?.cacheRead||0).padStart(11)} ${g(h?.cacheCreate||0).padStart(11)} ${g(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l(b).padStart(9)}`;if(c){let x=r(y),v=b!==null&&x?`${((b-x)/x*100).toFixed(0)}%`:"-";$+=` ${l(x).padStart(9)} ${v.padStart(7)}`}console.log($)}console.log(),c&&console.log(se.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(se.dim(` Saved ${e.save}`)),console.log()});jn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y7D5W52I.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-URGH65VO.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let u=f?`${f} ${p.name()}`:p.name();c.push(u),l(p,u)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(se.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${se.dim("\xB7")} ${d}`);console.log(),console.log(se.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(se.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(se.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(se.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(se.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(se.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=se.dim(`${r.days}d`);console.log(` ${se.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(se.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as iT}from"commander";import Ue from"chalk";import{readFileSync as aT}from"fs";import{resolve as cT}from"path";ne();var Xo=new iT().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Xo.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{Yg(cT(process.cwd(),".env"))}catch{}let t=lT(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-NEYLE6NJ.js");o(t)}catch(t){console.log(Ue.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Ue.dim(t.stack)),process.exit(1)}});function lT(e,t){try{let o=C();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Ue.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Ue.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
551
551
|
`)),{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}}}}Xo.command("list").description("list configured boards").action(()=>{try{let e=C();if(!e.boards?.length){console.log(Ue.dim(`
|
|
552
552
|
No boards configured.
|
|
553
553
|
`));return}console.log();for(let t of e.boards){console.log(` ${Ue.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(Ue.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(Ue.dim(` primary label: ${t.primaryToolLabel}`)),console.log(Ue.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(Ue.red(` ${e.message}`)),process.exit(1)}});Xo.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{jr(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(Ue.red(` ${o.message}`)),process.exit(1)}});Xo.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{jr(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(Ue.red(` ${o.message}`)),process.exit(1)}});var Nd=Xo.command("column").description("manage a board's columns (add / remove / edit / list)");Nd.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(aT("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(Ue.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(` ${Ue.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${Ue.dim(r)}`)}}catch(t){console.log(Ue.red(` ${t.message}`)),process.exit(1)}});Nd.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{jr(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(Ue.red(` ${n.message}`)),process.exit(1)}});Nd.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{jr(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(Ue.red(` ${o.message}`)),process.exit(1)}});Xo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{jr(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(Ue.red(` ${t.message}`)),process.exit(1)}});function jr(e){let{summary:t,backupPath:o}=Nt(n=>e(n));console.log(Ue.green(`
|
|
@@ -849,7 +849,7 @@ Restart the daemon to activate.
|
|
|
849
849
|
dist/
|
|
850
850
|
*.log
|
|
851
851
|
.env
|
|
852
|
-
`}import{Command as q1}from"commander";import nt from"chalk";import{writeFileSync as F1,mkdirSync as U1,existsSync as ec,readFileSync as ex,appendFileSync as tx}from"fs";import{resolve as Hs,dirname as sx}from"path";import{homedir as yg}from"os";var rx=new q1().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-
|
|
852
|
+
`}import{Command as q1}from"commander";import nt from"chalk";import{writeFileSync as F1,mkdirSync as U1,existsSync as ec,readFileSync as ex,appendFileSync as tx}from"fs";import{resolve as Hs,dirname as sx}from"path";import{homedir as yg}from"os";var rx=new q1().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-URGH65VO.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=J1(o);break;case"bash":s=K1(o);break;case"fish":s=X1(o);break;default:console.error(nt.red(`unsupported shell: ${n}`)),console.error(nt.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?Hs(String(e.output)):W1(n);U1(sx(r),{recursive:!0}),F1(r,s),console.log(nt.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),B1(n,r,!!e.yes)});function W1(e){let t=yg();switch(e){case"zsh":return Hs(t,".zsh","completions","_agentx");case"bash":return Hs(t,".bash_completion.d","agentx.bash");case"fish":return Hs(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function B1(e,t,o){if(e==="zsh"){let n=Hs(yg(),".zshrc"),s=sx(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=ec(n)?ex(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(nt.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&ec(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),tx(n,g.join(`
|
|
853
853
|
`)+`
|
|
854
854
|
`),console.log(nt.green("\u2713 Patched ~/.zshrc")),console.log(nt.dim("Reload your shell: exec zsh"));return}console.log(nt.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(nt.cyan(` ${r}`)),l&&console.log(nt.cyan(` ${i}`)),console.log(),console.log(nt.dim("Then reload: exec zsh")),console.log(nt.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Hs(yg(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((ec(n)?ex(n,"utf-8"):"").includes(t)){console.log(nt.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&ec(n)){tx(n,`
|
|
855
855
|
# agentx completion
|
|
@@ -865,4 +865,4 @@ ${V1({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
|
|
|
865
865
|
${o.url}`)}catch(t){console.error(Ys.red(` ${t.message}`)),process.exitCode=1}});Yr.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",bg).action(async(e,t)=>{try{let o=await xg(t.models);if(!$g(t.model,o)){console.log(kg(t.model,o)),process.exitCode=1;return}let n=e==="-"?await eI():await Z1(e,"utf8"),s=JSON.parse(n),{version:r}=await ai(),i=lx({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(Ys.red(` ${o.message}`)),process.exitCode=1}});async function eI(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function a4(){let e=await ai(),t=new tI().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=af(n);cf(s)&&rf("cli",s)});for(let o of[Dh,fh,ph,_s,is,ao,jt,Jp,gn,Bi,vo,Tn,On,Ao,Ko,Gb,Yo,qi,Pk,Jo,vy,Sy,jy,xr,Jy,Ky,$y,Qy,Zy,hw,$w,kw,Mt,jn,Uk,gr,qo,rx,Yr])t.addCommand(o);for(let o of gx)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=gx.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,oI(o,74," "),""].join(`
|
|
866
866
|
`)}),t}var gx=[H,Ms,Ro,Zt,pr,vs,Qe,Eo,Xo,Rn,Fs,Us,Wo,$t,fs,oa,wa,En,ba,Ok,jk,xo,Fr,_t,Sf,mn,Hr,bl,Zo,St,ms,$l,Ba,ho,Co,zk,Js,Yk,qk];function oI(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(`
|
|
867
867
|
`)}export{a4 as buildProgram};
|
|
868
|
-
//# sourceMappingURL=program-
|
|
868
|
+
//# sourceMappingURL=program-URGH65VO.js.map
|