agentix-cli 0.194.0 → 0.196.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/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-IDRN5TAM.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-W7ZO7UDB.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{Ma as Tt,Na 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-S42KBXNO.js";import"./chunk-I45E5TLK.js";import"./chunk-GTJIKXDB.js";import"./chunk-XH36J3Z2.js";import"./chunk-ZVP6GB4G.js";import"./chunk-M2E3CNFS.js";import"./chunk-IMLAPB7G.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-LQIF2OHS.js";import"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-BIYEGA7Q.js";import"./chunk-XPZSEDE3.js";import"./chunk-PPUN7YHA.js";import"./chunk-A5GYG56I.js";import"./chunk-FO762MEC.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-6TTGRTDO.js";import"./chunk-MNG2AMKZ.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-UOYIC7XN.js";import"./chunk-QPABR72X.js";import"./chunk-HOZZUN47.js";import"./chunk-AJ5HMDRW.js";import"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{Ca as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-MB5CBY2C.js";import"./chunk-PO2SORKY.js";import"./chunk-MEFPXHQJ.js";import"./chunk-3FZ6WHKX.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-UOIWIVU3.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-GV7S5BAX.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-MC3ZZA5G.js";import"./chunk-KXJRXRSD.js";import"./chunk-3UOTLMXD.js";import"./chunk-VWTBHLMX.js";import"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GSX4NK2N.js";import"./chunk-HPRLRD4P.js";import"./chunk-RW5FKJRE.js";import{a as ht}from"./chunk-ZALVAXQ4.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-PMSL4A5Y.js";import"./chunk-JTFCU5LH.js";import{f as gt,g as ft}from"./chunk-6NQ7KYJH.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-HNZEXUNM.js";import{j as it,k as rt,l as at}from"./chunk-2KYGPVTX.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-2HBEZV7L.js";import"./chunk-A7JSRDJL.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.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{Bb as ot,Ib as nt,xb as tt,zb as st}from"./chunk-P6WSD2UR.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.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{Ma as Tt,Na 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-NT3DGEBE.js";import"./chunk-YWAJNF2A.js";import"./chunk-GTJIKXDB.js";import"./chunk-XH36J3Z2.js";import"./chunk-ZVP6GB4G.js";import"./chunk-M2E3CNFS.js";import"./chunk-IMLAPB7G.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-LQIF2OHS.js";import"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-BIYEGA7Q.js";import"./chunk-XPZSEDE3.js";import"./chunk-PPUN7YHA.js";import"./chunk-A5GYG56I.js";import"./chunk-FO762MEC.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-6TTGRTDO.js";import"./chunk-MNG2AMKZ.js";import"./chunk-RX5O5637.js";import"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import"./chunk-UOYIC7XN.js";import"./chunk-QPABR72X.js";import"./chunk-HOZZUN47.js";import"./chunk-AJ5HMDRW.js";import"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{Ca as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-MB5CBY2C.js";import"./chunk-PO2SORKY.js";import"./chunk-MEFPXHQJ.js";import"./chunk-3FZ6WHKX.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-UOIWIVU3.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-GV7S5BAX.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-MC3ZZA5G.js";import"./chunk-KXJRXRSD.js";import"./chunk-3UOTLMXD.js";import"./chunk-VWTBHLMX.js";import"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GSX4NK2N.js";import"./chunk-HPRLRD4P.js";import"./chunk-RW5FKJRE.js";import{a as ht}from"./chunk-ZALVAXQ4.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-PMSL4A5Y.js";import"./chunk-JTFCU5LH.js";import{f as gt,g as ft}from"./chunk-6NQ7KYJH.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-HNZEXUNM.js";import{j as it,k as rt,l as at}from"./chunk-2KYGPVTX.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-2HBEZV7L.js";import"./chunk-A7JSRDJL.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.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{Bb as ot,Ib as nt,xb as tt,zb as st}from"./chunk-P6WSD2UR.js";import"./chunk-VJ5HC63R.js";import"./chunk-UEEB3UTU.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 Ph,b as Zi,g as Dh}from"./chunk-2GCPSAXQ.js";import{b as Nh}from"./chunk-VX4PSOKU.js";import{$ as Sh,B as th,C as oh,D as ih,E as ah,G as ch,H as lh,I as dh,J as vl,K as uh,P as gh,Q as mh,R as xl,S as ph,V as fh,W as hh,X as wh,Y as yh,Z as vh,_ as xh,ba as Sl,ca as Ah,ea as Eh,fa as Rh,g as Wf,ga as Ch,h as Bf,l as Jf,m as Hf,o as Gf,q as Rs,r as Cs,s as zf,t as Yf,u as Kf,v as Xf,w as Vf,x as Qf,z as co}from"./chunk-OEG476JY.js";import{n as Al}from"./chunk-7L54Z4EH.js";import{a as Th,b as Oh,d as Ar,e as Ih}from"./chunk-F3CMNSON.js";import{a as jh,b as _h}from"./chunk-BOCLWYWL.js";import"./chunk-EFGAPAYZ.js";import{d as nh,e as kl,h as sh,i as rh}from"./chunk-CTN4KYE6.js";import{a as $h,c as bh,d as kh}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as Pt}from"./chunk-PX7PWXBI.js";import{a as Zf,c as eh}from"./chunk-F2FJXKDG.js";import{a as $l}from"./chunk-LNY6N73E.js";import{a as qm,b as Vc}from"./chunk-KE6BF4ZJ.js";import{a as Gc,b as bm}from"./chunk-RKPAVWXF.js";import{$ as mf,A as qp,Aa as ut,B as rl,Ba as Ki,C as Fp,Ca as Xi,D as Up,Da as Sr,E as Wp,Ea as hl,F as Bp,Fa as Df,G as Jp,Ga as Lf,H as Hp,Ha as yl,I as il,Ia as Ff,J as Gp,Ja as Vi,K as Wi,Ka as Es,L as zp,La as Qi,M as al,Ma as bl,N as Yp,Na as Uf,O as Kp,P as Xp,Q as Vp,R as Qp,S as Bi,T as nf,U as af,V as cf,W as lf,X as df,Y as uf,Z as ll,_ as gf,a as Jm,aa as pf,b as Hm,ba as ff,ca as hf,da as wf,ea as yf,fa as $f,ga as bf,h as Ti,ha as Rf,i as Km,ia as Gi,j as $r,ja as Co,k as Oi,ka as Ho,l as Vm,la as xs,m as Zm,ma as zi,n as pp,na as Yi,o as fp,oa as fl,p as Di,pa as Cf,q as ol,qa as Tf,r as vp,ra as Of,s as jp,sa as If,t as _p,ta as Nf,u as Pp,ua as jf,v as Dp,va as Ss,w as Ui,wa as As,x as Mp,xa as _f,y as Lp,ya as xr,z as sl,za as Pf}from"./chunk-S42KBXNO.js";import{$a as vf,Jb as Mf,Kb as wl,Oa as kr,Q as Cp,Ra as dl,S as br,Sa as Ji,T as Tp,Ta as kf,W as Op,X as Fi,Yb as ao,_a as Jo,_b as qf,ab as ul,cb as gl,ea as Zp,eb as xf,fa as ef,fb as Sf,ga as tf,gb as vr,ha as cl,ka as of,kb as Hi,nb as Af,ob as Ef,pb as ml,v as Qm,wb as pl}from"./chunk-I45E5TLK.js";import"./chunk-GTJIKXDB.js";import{a as Gm,c as Zc,e as zm,f as Ym}from"./chunk-XH36J3Z2.js";import"./chunk-ZVP6GB4G.js";import{A as ip,B as ap,C as cp,D as lp,E as dp,F as up,K as ji,L as gp,M as mp,Q as Ip,R as Np,a as Jc,b as pm,e as fm,f as hm,o as ep,s as Ii,t as Ni,u as tp,v as op,w as np,y as sp,z as rp}from"./chunk-M2E3CNFS.js";import"./chunk-IMLAPB7G.js";import"./chunk-VZLIBDLH.js";import{a as sf,b as rf}from"./chunk-EKJG63EJ.js";import"./chunk-LQIF2OHS.js";import{c as hp}from"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import{b as tl}from"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import{c as wp,e as _i,g as Pi}from"./chunk-LQE73AZR.js";import{a as yp,b as $p,c as bp,d as kp}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-BIYEGA7Q.js";import{d as xp,e as bn,f as Sp,g as Mi,j as Ap,k as Ep,m as Rp,n as nl,q as Li,r as Ro,s as qi}from"./chunk-XPZSEDE3.js";import"./chunk-PPUN7YHA.js";import"./chunk-A5GYG56I.js";import{a as el,p as Xm}from"./chunk-FO762MEC.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as _t}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-6TTGRTDO.js";import{a as io}from"./chunk-MNG2AMKZ.js";import{a as Cm,b as Tm,c as Om,d as Im,e as Yc,f as Nm,g as Kc,h as Xc,l as jm,m as _m}from"./chunk-RX5O5637.js";import{f as Pm,i as Dm,l as Mm,m as Lm}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{a as Fm,b as Um,c as Qc,d as Ci,e as Wm,f as Bm}from"./chunk-UOYIC7XN.js";import{a as Hc,d as wm,e as Ri}from"./chunk-QPABR72X.js";import{a as yr,e as km,f as vm,g as zc,i as xm,j as Sm,l as Am,m as Em,n as Rm}from"./chunk-HOZZUN47.js";import{b as vs,e as $m}from"./chunk-AJ5HMDRW.js";import{c as ym}from"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{$ as um,Ca as mm,D as qc,E as Yg,S as Bo,Y as lm,aa as gm,g as Lg,r as qg,s as Fg,t as Ug}from"./chunk-MB5CBY2C.js";import{I as ws,J as Ai,K as Ei,L as ys,M as Xg,N as Uo,P as Wo,b as hs,fa as am,r as Ao,s as Fc,t as Kg,u as Uc,ua as cm,w as Eo,wa as dm,x as Si}from"./chunk-PO2SORKY.js";import{b as yn}from"./chunk-MEFPXHQJ.js";import"./chunk-3FZ6WHKX.js";import"./chunk-UOIWIVU3.js";import"./chunk-SFQUP3BP.js";import{a as $s}from"./chunk-GV7S5BAX.js";import{c as Qg}from"./chunk-SZDACK6O.js";import{f as Zg,g as em,h as Wc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as om,f as $n,k as bs}from"./chunk-VJVXEVZ7.js";import{a as Gg,k as tm,n as im}from"./chunk-MC3ZZA5G.js";import{a as wt,b as me,c as Ue,d as ks,e as nm}from"./chunk-KXJRXRSD.js";import{a as sm,b as Bc,h as rm}from"./chunk-3UOTLMXD.js";import"./chunk-VWTBHLMX.js";import{i as Bg,j as Jg}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as Lc,b as Hg}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as zg}from"./chunk-X5C5W3E4.js";import{e as Vg}from"./chunk-GSX4NK2N.js";import"./chunk-HPRLRD4P.js";import{a as Mc}from"./chunk-RW5FKJRE.js";import"./chunk-ZALVAXQ4.js";import{c as Wg}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-PMSL4A5Y.js";import"./chunk-JTFCU5LH.js";import{g as Fo,i as xi}from"./chunk-6NQ7KYJH.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-HNZEXUNM.js";import{a as Oc,b as ag,c as Vx,d as fi,e as cg,f as Og,g as i0,h as Ig,i as a0,m as fs,n as jg,q as _g,u as Pg,y as ro,z as wr}from"./chunk-2KYGPVTX.js";import{a as So,b as ps,e as Rg,f as hr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as vi,b as Ng}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as qo,j as Dg}from"./chunk-QUFIUXMQ.js";import{n as Mg}from"./chunk-AV7T3SYT.js";import"./chunk-2HBEZV7L.js";import"./chunk-A7JSRDJL.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as so,b as Xx}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as yi,Bb as ki,Fa as xg,G as Nc,H as t0,Ib as te,Ja as n0,Sa as Sg,Ta as wn,V as wg,Va as _c,W as o0,aa as $i,ab as Pc,bb as Dc,c as hi,d as lg,da as yg,db as Ag,e as fn,ea as $g,eb as s0,f as Ic,fa as ms,ga as jc,h as dg,i as wi,j as Qx,jb as Eg,na as bg,pa as kg,qa as vg,r as gg,s as mg,t as pg,v as fg,w as hg,x as e0,xb as bi,yb as fr,zb as O}from"./chunk-P6WSD2UR.js";import"./chunk-VJ5HC63R.js";import{j as dt,r as hn}from"./chunk-UEEB3UTU.js";import{a as ug,e as Zx}from"./chunk-VQRY4IDI.js";import{g as Cg,k as Tg,l as r0}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as c0}from"commander";var Mh=new c0().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 Hm({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 l0}from"commander";import{execFileSync as lo}from"node:child_process";import{cpSync as Lh,existsSync as Cl,mkdirSync as El,mkdtempSync as d0,readdirSync as u0,rmSync as qh,writeFileSync as Fh}from"node:fs";import{dirname as Uh,join as gt}from"node:path";import{homedir as ea,release as g0,tmpdir as m0}from"node:os";import{setTimeout as p0}from"node:timers/promises";function ta(){let e=tp(process.platform,process.arch,g0());if(e)throw new Error(e)}function oa(){let e=gt(ea(),"Library/LaunchAgents"),t=[];try{t=u0(e).filter(sp)}catch{}let o=t.flatMap(n=>{let s=gt(e,n);try{return[{file:s,plist:lo("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return rp(e,o)}function Er(e){return`gui/${process.getuid()}/${e.label}`}async function Rl(e){try{lo("launchctl",["bootout",Er(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{lo("launchctl",["print",Er(e)],{stdio:"pipe"})}catch{return}await p0(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Wh(e){if(!Cl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{lo("launchctl",["print",Er(e)],{stdio:"pipe"})}catch{t=!1}t||lo("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),lo("launchctl",["kickstart",Er(e)],{stdio:"pipe"})}function f0(){let e=up();if(e&&Cl(gt(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 Ts=new l0("desktop").description("install and control the macOS desktop assistant");Ts.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=>{ta();let t=O(),o=op(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=f0(),i=gt(ea(),"Applications"),{keep:a,remove:c}=oa();if(console.log(`Desktop assistant \u2192 ${gt(i,Ii)}
1
+ import{a as Ph,b as Zi,g as Dh}from"./chunk-2GCPSAXQ.js";import{b as Nh}from"./chunk-VX4PSOKU.js";import{$ as Sh,B as th,C as oh,D as ih,E as ah,G as ch,H as lh,I as dh,J as vl,K as uh,P as gh,Q as mh,R as xl,S as ph,V as fh,W as hh,X as wh,Y as yh,Z as vh,_ as xh,ba as Sl,ca as Ah,ea as Eh,fa as Rh,g as Wf,ga as Ch,h as Bf,l as Jf,m as Hf,o as Gf,q as Rs,r as Cs,s as zf,t as Yf,u as Kf,v as Xf,w as Vf,x as Qf,z as co}from"./chunk-V7FZBETJ.js";import{n as Al}from"./chunk-7L54Z4EH.js";import{a as Th,b as Oh,d as Ar,e as Ih}from"./chunk-F3CMNSON.js";import{a as jh,b as _h}from"./chunk-BOCLWYWL.js";import"./chunk-EFGAPAYZ.js";import{d as nh,e as kl,h as sh,i as rh}from"./chunk-CTN4KYE6.js";import{a as $h,c as bh,d as kh}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as Pt}from"./chunk-PX7PWXBI.js";import{a as Zf,c as eh}from"./chunk-F2FJXKDG.js";import{a as $l}from"./chunk-LNY6N73E.js";import{a as qm,b as Vc}from"./chunk-KE6BF4ZJ.js";import{a as Gc,b as bm}from"./chunk-RKPAVWXF.js";import{$ as mf,A as qp,Aa as ut,B as rl,Ba as Ki,C as Fp,Ca as Xi,D as Up,Da as Sr,E as Wp,Ea as hl,F as Bp,Fa as Df,G as Jp,Ga as Lf,H as Hp,Ha as yl,I as il,Ia as Ff,J as Gp,Ja as Vi,K as Wi,Ka as Es,L as zp,La as Qi,M as al,Ma as bl,N as Yp,Na as Uf,O as Kp,P as Xp,Q as Vp,R as Qp,S as Bi,T as nf,U as af,V as cf,W as lf,X as df,Y as uf,Z as ll,_ as gf,a as Jm,aa as pf,b as Hm,ba as ff,ca as hf,da as wf,ea as yf,fa as $f,ga as bf,h as Ti,ha as Rf,i as Km,ia as Gi,j as $r,ja as Co,k as Oi,ka as Ho,l as Vm,la as xs,m as Zm,ma as zi,n as pp,na as Yi,o as fp,oa as fl,p as Di,pa as Cf,q as ol,qa as Tf,r as vp,ra as Of,s as jp,sa as If,t as _p,ta as Nf,u as Pp,ua as jf,v as Dp,va as Ss,w as Ui,wa as As,x as Mp,xa as _f,y as Lp,ya as xr,z as sl,za as Pf}from"./chunk-NT3DGEBE.js";import{$a as vf,Jb as Mf,Kb as wl,Oa as kr,Q as Cp,Ra as dl,S as br,Sa as Ji,T as Tp,Ta as kf,W as Op,X as Fi,Yb as ao,_a as Jo,_b as qf,ab as ul,cb as gl,ea as Zp,eb as xf,fa as ef,fb as Sf,ga as tf,gb as vr,ha as cl,ka as of,kb as Hi,nb as Af,ob as Ef,pb as ml,v as Qm,wb as pl}from"./chunk-YWAJNF2A.js";import"./chunk-GTJIKXDB.js";import{a as Gm,c as Zc,e as zm,f as Ym}from"./chunk-XH36J3Z2.js";import"./chunk-ZVP6GB4G.js";import{A as ip,B as ap,C as cp,D as lp,E as dp,F as up,K as ji,L as gp,M as mp,Q as Ip,R as Np,a as Jc,b as pm,e as fm,f as hm,o as ep,s as Ii,t as Ni,u as tp,v as op,w as np,y as sp,z as rp}from"./chunk-M2E3CNFS.js";import"./chunk-IMLAPB7G.js";import"./chunk-VZLIBDLH.js";import{a as sf,b as rf}from"./chunk-EKJG63EJ.js";import"./chunk-LQIF2OHS.js";import{c as hp}from"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import{b as tl}from"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import{c as wp,e as _i,g as Pi}from"./chunk-LQE73AZR.js";import{a as yp,b as $p,c as bp,d as kp}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-BIYEGA7Q.js";import{d as xp,e as bn,f as Sp,g as Mi,j as Ap,k as Ep,m as Rp,n as nl,q as Li,r as Ro,s as qi}from"./chunk-XPZSEDE3.js";import"./chunk-PPUN7YHA.js";import"./chunk-A5GYG56I.js";import{a as el,p as Xm}from"./chunk-FO762MEC.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as _t}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import"./chunk-6TTGRTDO.js";import{a as io}from"./chunk-MNG2AMKZ.js";import{a as Cm,b as Tm,c as Om,d as Im,e as Yc,f as Nm,g as Kc,h as Xc,l as jm,m as _m}from"./chunk-RX5O5637.js";import{f as Pm,i as Dm,l as Mm,m as Lm}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{a as Fm,b as Um,c as Qc,d as Ci,e as Wm,f as Bm}from"./chunk-UOYIC7XN.js";import{a as Hc,d as wm,e as Ri}from"./chunk-QPABR72X.js";import{a as yr,e as km,f as vm,g as zc,i as xm,j as Sm,l as Am,m as Em,n as Rm}from"./chunk-HOZZUN47.js";import{b as vs,e as $m}from"./chunk-AJ5HMDRW.js";import{c as ym}from"./chunk-KP7KDLZ2.js";import"./chunk-XVV7ZZ77.js";import{$ as um,Ca as mm,D as qc,E as Yg,S as Bo,Y as lm,aa as gm,g as Lg,r as qg,s as Fg,t as Ug}from"./chunk-MB5CBY2C.js";import{I as ws,J as Ai,K as Ei,L as ys,M as Xg,N as Uo,P as Wo,b as hs,fa as am,r as Ao,s as Fc,t as Kg,u as Uc,ua as cm,w as Eo,wa as dm,x as Si}from"./chunk-PO2SORKY.js";import{b as yn}from"./chunk-MEFPXHQJ.js";import"./chunk-3FZ6WHKX.js";import"./chunk-UOIWIVU3.js";import"./chunk-SFQUP3BP.js";import{a as $s}from"./chunk-GV7S5BAX.js";import{c as Qg}from"./chunk-SZDACK6O.js";import{f as Zg,g as em,h as Wc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as om,f as $n,k as bs}from"./chunk-VJVXEVZ7.js";import{a as Gg,k as tm,n as im}from"./chunk-MC3ZZA5G.js";import{a as wt,b as me,c as Ue,d as ks,e as nm}from"./chunk-KXJRXRSD.js";import{a as sm,b as Bc,h as rm}from"./chunk-3UOTLMXD.js";import"./chunk-VWTBHLMX.js";import{i as Bg,j as Jg}from"./chunk-BE64IJWM.js";import"./chunk-5ONH4ITT.js";import{a as Lc,b as Hg}from"./chunk-JRAG37V5.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as zg}from"./chunk-X5C5W3E4.js";import{e as Vg}from"./chunk-GSX4NK2N.js";import"./chunk-HPRLRD4P.js";import{a as Mc}from"./chunk-RW5FKJRE.js";import"./chunk-ZALVAXQ4.js";import{c as Wg}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-PMSL4A5Y.js";import"./chunk-JTFCU5LH.js";import{g as Fo,i as xi}from"./chunk-6NQ7KYJH.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-HNZEXUNM.js";import{a as Oc,b as ag,c as Vx,d as fi,e as cg,f as Og,g as i0,h as Ig,i as a0,m as fs,n as jg,q as _g,u as Pg,y as ro,z as wr}from"./chunk-2KYGPVTX.js";import{a as So,b as ps,e as Rg,f as hr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as vi,b as Ng}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as qo,j as Dg}from"./chunk-QUFIUXMQ.js";import{n as Mg}from"./chunk-AV7T3SYT.js";import"./chunk-2HBEZV7L.js";import"./chunk-A7JSRDJL.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as so,b as Xx}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as yi,Bb as ki,Fa as xg,G as Nc,H as t0,Ib as te,Ja as n0,Sa as Sg,Ta as wn,V as wg,Va as _c,W as o0,aa as $i,ab as Pc,bb as Dc,c as hi,d as lg,da as yg,db as Ag,e as fn,ea as $g,eb as s0,f as Ic,fa as ms,ga as jc,h as dg,i as wi,j as Qx,jb as Eg,na as bg,pa as kg,qa as vg,r as gg,s as mg,t as pg,v as fg,w as hg,x as e0,xb as bi,yb as fr,zb as O}from"./chunk-P6WSD2UR.js";import"./chunk-VJ5HC63R.js";import{j as dt,r as hn}from"./chunk-UEEB3UTU.js";import{a as ug,e as Zx}from"./chunk-VQRY4IDI.js";import{g as Cg,k as Tg,l as r0}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as c0}from"commander";var Mh=new c0().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 Hm({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 l0}from"commander";import{execFileSync as lo}from"node:child_process";import{cpSync as Lh,existsSync as Cl,mkdirSync as El,mkdtempSync as d0,readdirSync as u0,rmSync as qh,writeFileSync as Fh}from"node:fs";import{dirname as Uh,join as gt}from"node:path";import{homedir as ea,release as g0,tmpdir as m0}from"node:os";import{setTimeout as p0}from"node:timers/promises";function ta(){let e=tp(process.platform,process.arch,g0());if(e)throw new Error(e)}function oa(){let e=gt(ea(),"Library/LaunchAgents"),t=[];try{t=u0(e).filter(sp)}catch{}let o=t.flatMap(n=>{let s=gt(e,n);try{return[{file:s,plist:lo("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return rp(e,o)}function Er(e){return`gui/${process.getuid()}/${e.label}`}async function Rl(e){try{lo("launchctl",["bootout",Er(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{lo("launchctl",["print",Er(e)],{stdio:"pipe"})}catch{return}await p0(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Wh(e){if(!Cl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{lo("launchctl",["print",Er(e)],{stdio:"pipe"})}catch{t=!1}t||lo("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),lo("launchctl",["kickstart",Er(e)],{stdio:"pipe"})}function f0(){let e=up();if(e&&Cl(gt(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 Ts=new l0("desktop").description("install and control the macOS desktop assistant");Ts.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=>{ta();let t=O(),o=op(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=f0(),i=gt(ea(),"Applications"),{keep:a,remove:c}=oa();if(console.log(`Desktop assistant \u2192 ${gt(i,Ii)}
2
2
  Computer-use helper \u2192 ${gt(i,Ni)}
3
3
  Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -566,7 +566,7 @@ ${oe.text}`));T.delivery.reached.of++,ie&&T.delivery.reached.n++;let j=P[0]??Q[0
566
566
  Plan ${L.dim(`[${r.state}] by ${r.createdBy}, ${Vn(r.createdAt)}`)}`),vk(s.steps(e)),console.log(`
567
567
  Log`);for(let i of s.events(e))console.log(L.dim(` ${Vn(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});jo.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(L.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=er();if(!s)return;let r=Za();if(!r){process.exitCode=1;return}let i=Number(t),a=zp(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(L.red(` ${a}`)),process.exitCode=1;return}console.log(L.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+L.dim(" (the daemon goes on within a minute)")),vk(r.steps(e))});function xk(e,t,o,n){let s=jo.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=er();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(L.red(` ${n}`)),process.exitCode=1;return}let l=a.get(r);if(!l||l.state==="candidate"){console.error(L.red(` no request "${r}"`)),process.exitCode=1;return}if(!a.close(r,e==="done"?"done":"dropped",c,Date.now())){console.error(L.red(` ${r} is already closed (${au[l.state]??l.state})`)),process.exitCode=1;return}console.log(L.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}xk("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>");xk("drop","drop a request you no longer want","--reason <text>","");jo.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").option("--headlines <on|off>","write a headline for a request its agent did not describe (one small model call each)").option("--catch <on|off>","read the reply of each of your turns for a promise or a question to you (one small model call each)").option("--catch-cap <n>","model calls a day the promise catch may make").option("--settle <on|off>","close a quiet request whose handed work all came back done, instead of bringing it back to you").option("--home-closes <on|off>","close a request once its issue or merge request home is merged or closed as completed").option("--plans <on|off>","follow requests of two or more steps as tracked plans").option("--stall-minutes <n>","minutes without progress before a plan step's agent is nudged").option("--max-nudges <n>","nudges per step before it counts as blocked and you are told").option("--approve-kinds <kind,...>",'step kinds you approve once when the plan is made; "none" to clear').option("--plans-off-for <agent,...>",'agents that may not open a plan; "none" to clear').option("--plan-for <work,...>",'kinds of work an agent must plan before it starts (default code); "none" to clear').option("--plan-over <minutes>","work estimated over this many minutes needs a plan (default 30); 0 turns it off").option("--checks <kind,...>",`checks agents may use to close a loop (${yi.join(", ")}); "none" to turn them all off`).option("--check-every <minutes>","how often each open loop's check runs").option("--auto-resend <on|off>","send a request stopped by a usage limit or a restart back to its agent once, on its own").option("--resend-after <minutes>","minutes after it stopped before it is resent (a limit also waits for its reset)").option("--resend-hold-hours <n>","hours your notice waits for the resend before you are told anyway").option("--flow-zone <zone>","the time zone whose day the flow rate counts by, for example Africa/Tunis").action(async e=>{let t={};try{let u=(w,y)=>{if(y===void 0)return;let b=Number(y);if(!(b>0))throw new Error(`${w} must be a positive number`);return b},d=(w,y)=>w===void 0?void 0:w===y?[]:w.split(",").map(b=>b.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");t.enabled=e.enabled==="on"}if(t.from=d(e.from,"none"),t.channels=d(e.channels,"all"),t.staleAfterHours=u("--stale-hours",e.staleHours),t.retentionDays=u("--retention-days",e.retentionDays),e.headlines!==void 0){if(e.headlines!=="on"&&e.headlines!=="off")throw new Error("--headlines takes on or off");t.headlines={enabled:e.headlines==="on"}}if(e.catch!==void 0||e.catchCap!==void 0){if(e.catch!==void 0&&e.catch!=="on"&&e.catch!=="off")throw new Error("--catch takes on or off");let w=u("--catch-cap",e.catchCap);if(w!==void 0&&!Number.isInteger(w))throw new Error("--catch-cap must be a whole number");t.catchPromises={...e.catch!==void 0?{enabled:e.catch==="on"}:{},...w!==void 0?{dailyCap:w}:{}}}if(e.settle!==void 0){if(e.settle!=="on"&&e.settle!=="off")throw new Error("--settle takes on or off");t.settleHandedBack=e.settle==="on"}if(e.homeCloses!==void 0){if(e.homeCloses!=="on"&&e.homeCloses!=="off")throw new Error("--home-closes takes on or off");t.homeCloses=e.homeCloses==="on"}let f={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");f.enabled=e.plans==="on"}if(f.stallMinutes=u("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let w=Number(e.maxNudges);if(!Number.isInteger(w)||w<0)throw new Error("--max-nudges must be a whole number, 0 or more");f.maxNudges=w}if(f.approveKinds=d(e.approveKinds,"none"),f.disabledAgents=d(e.plansOffFor,"none"),f.requireForWork=d(e.planFor,"none"),e.planOver!==void 0){let w=Number(e.planOver);if(!(w>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");f.requireOverMinutes=w}Object.values(f).some(w=>w!==void 0)&&(t.plans=f);let p={},g=d(e.checks,"none");if(g){let w=g.filter(y=>!yi.includes(y));if(w.length)throw new Error(`unknown check ${w.join(", ")}: use ${yi.join(", ")}`);p.enabled=g}p.checkEveryMinutes=u("--check-every",e.checkEvery),Object.values(p).some(w=>w!==void 0)&&(t.checkers=p);let h={};if(e.autoResend!==void 0){if(e.autoResend!=="on"&&e.autoResend!=="off")throw new Error("--auto-resend takes on or off");h.enabled=e.autoResend==="on"}if(e.resendAfter!==void 0){let w=Number(e.resendAfter);if(!(w>=0))throw new Error("--resend-after must be a number of minutes, 0 or more");h.afterMinutes=w}h.holdMaxHours=u("--resend-hold-hours",e.resendHoldHours),Object.values(h).some(w=>w!==void 0)&&(t.autoResend=h),e.flowZone!==void 0&&(t.flow={timeZone:e.flowZone})}catch(u){console.error(L.red(` ${u.message}`)),process.exitCode=1;return}if(Object.values(t).some(u=>u!==void 0)){let u=await Tp(t);if(!u.success){console.error(L.red(` ${u.error}`)),process.exitCode=1;return}console.log(L.green(" \u2713 saved")+(u.reloaded?L.dim(" (daemon reloaded)"):""))}let o=br();console.log(` Requests ${o.enabled?"on":"off"}`),console.log(` Channels ${o.channels.length?o.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${o.from.length?o.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${o.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${o.retentionDays} day(s)`),console.log(` Headlines ${o.headlines?.enabled===!1?"off: titled with the start of your words":"on: written when the agent gave none"}`);let n=o.catchPromises;console.log(` Catch promises ${n?.enabled?`on: each of your turns' reply is read, up to ${n.dailyCap} call(s) a day`:"off"}`),console.log(` Handed work came back ${o.settleHandedBack===!1?"comes back to you when quiet":"closed when quiet, with its link or marked unproven"}`),console.log(` Home closed ${o.homeCloses===!1?"left open":"closes the request: merged, or closed as completed"}`);let s=o.plans??Wi;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??Wi.requireOverMinutes,i=s.requireForWork??Wi.requireForWork;console.log(` Plan before starting ${[i.length?`${i.join(", ")} work`:"",r>0?`work over ${r} minute(s)`:""].filter(Boolean).join("; ")||"never required"}`);let a=o.autoResend??Gp;console.log(` Resend once ${a.enabled?`on: after a usage limit resets or a restart, ${a.afterMinutes} minute(s) on; you are told after ${a.holdMaxHours} hour(s) or a second stop`:"off"}`),console.log(` Flow rate counts by ${(o.flow??Qc).timeZone} days`);let c=o.checkers??$i;console.log(` Loop checks ${c.enabled.length?c.enabled.join(", "):"off"}, every ${c.checkEveryMinutes} minute(s)`);let l=Object.keys(c.repos);console.log(` Repos for git-ancestor ${l.length?l.join(", "):"none (requests.checkers.repos in agentx.json)"}`)});import{Command as jO}from"commander";import tr from"chalk";te();var Sk=new jO("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",xl.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(tr.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await me(r=>{n=ph(r,e,t==="on")});s.success||(console.error(tr.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(tr.green(`\u2713 ${n}`)),s.reloaded&&console.log(tr.dim(" daemon hot-reloaded"))}let o=O().requestStatus.channels.map(n=>n.toLowerCase());for(let n of xl)console.log(` ${n.padEnd(8)} ${o.includes(n)?tr.green("on"):tr.dim("off")}`)});import{Command as c1}from"commander";import or from"chalk";import ve from"chalk";import Vr from"prompts";import{readFileSync as _O,writeFileSync as PO,existsSync as DO}from"fs";import{resolve as Ak}from"path";var MO=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function LO(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function lu(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Ek(e=".env"){let t=Ak(e);if(!DO(t))return[];let o=_O(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(MO);r?n.push({kind:"kv",key:r[1],value:LO(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function qO(e){return e.map(t=>t.kind==="kv"?`${t.key}=${lu(t.value)}`:t.raw).join(`
568
568
  `)+`
569
- `}function Qn(e,t,o=".env"){let n=Ak(o),s=Ek(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${lu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${lu(t)}`})),PO(n,qO(s))}function du(e,t=".env"){return Ek(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Rk="https://t.me/BotFather";async function FO(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 UO(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 Ck(e={}){console.log(),console.log(ve.bold(" Connect Telegram")),console.log(),console.log(ve.dim(` 1. Open ${Rk}`)),console.log(ve.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ve.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Vr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&To(Rk);let{token:o}=await Vr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:S=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(S.trim())||"That doesn't look like a Telegram token"});o||(console.log(ve.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await FO(o.trim());n||(console.log(ve.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ve.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(ve.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(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await Vr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),u||(console.log(ve.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||u;d[f]&&d[f].agentBinding!==u&&(f=(await Vr({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ve.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Qn(p,o.trim()),process.env[p]=o.trim();let g=await me(S=>{Ue(S,"channels.telegram.enabled",!0),Ue(S,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:u});let x=ks(S,`agents.${u}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),Ue(S,`agents.${u}.mentions`,x))},{configPath:e.configPath});if(g.success||(console.log(ve.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(ve.dim(` Token stored in .env as ${p}`)),console.log(ve.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(ve.dim(" Daemon hot-reloaded.")):console.log(ve.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Vr({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(ve.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ve.dim(" Waiting up to 90s..."));let w=await UO(o.trim(),9e4);if(!w){console.log(ve.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ve.dim(" agentx config set notifications.destination.channel telegram")),console.log(ve.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ve.dim(` agentx config set notifications.destination.accountId ${f}`));return}let y={channel:"telegram",chatId:String(w.chatId),accountId:f},b=[],v=await me(S=>{Ue(S,"notifications.destination",y),b=da(S,y)},{configPath:e.configPath});if(!v.success){console.log(ve.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(ve.green(" \u2713 Default --notify target set")),console.log(ve.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ve.dim(" From now on, --notify me resolves to this chat.")),b.length&&console.log(ve.dim(` Schedules that now report here: ${b.join(", ")}`)),v.reloaded&&console.log(ve.dim(" Daemon hot-reloaded."))}import Me from"chalk";import uu from"prompts";import{existsSync as mu,mkdirSync as WO,readdirSync as BO,readFileSync as Tk}from"fs";import{resolve as gu}from"path";var JO=".agentx/whatsapp-sessions";function HO(){let e=gu(process.cwd(),".agentx/daemon.pid");if(!mu(e))return!1;try{let t=parseInt(Tk(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function GO(e){if(!mu(e))return!1;try{return BO(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function zO(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;WO(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 f=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 p=>{if(p.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(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Me.green(" \u2713 Paired"));try{l.end(void 0)}catch{}u(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Me.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Ok(e={}){if(console.log(),console.log(Me.bold(" Connect WhatsApp")),console.log(),HO()){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 uu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Me.red(" Aborted")),process.exit(1))}let t=e.configPath||gu(process.cwd(),"agentx.json");mu(t)||(console.log(Me.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Tk(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||JO,s=gu(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 uu({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(GO(s)&&a){let{keep:l}=await uu({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 zO(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=>{Ue(l,"channels.whatsapp.enabled",!0),Ue(l,"channels.whatsapp.sessionDir",n),Ue(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 YO from"prompts";import{existsSync as KO,readFileSync as XO}from"fs";import{resolve as VO}from"path";async function QO(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 ZO(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 _o(e){console.log(Rt.red(` ${e}`)),process.exit(1)}async function Zn(e){return(await YO(e,{onCancel:()=>_o("Aborted")}))[e.name]}async function Ik(e={}){console.log(),console.log(Rt.bold(" Connect email")),console.log();let t=e.configPath||VO(process.cwd(),"agentx.json");KO(t)||_o(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(XO(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&_o("No agents configured. Run: agentx agent add");let s=e.agent??await Zn({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(y=>({title:y,value:y}))});o.agents?.[s]||_o(`No agent "${s}" in ${t}`);let r=(e.address??await Zn({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=hh(r),c=e.imapHost??a?.imapHost??await Zn({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await Zn({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await Zn({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await Zn({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&_o("Ports must be numbers.");let f=e.passwordEnv||yh(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&_o(`${e.passwordEnv} is not set in the environment.`),p||(a?.imapHost==="imap.gmail.com"&&(console.log(Rt.dim(` Gmail needs an app password, not your account password: ${fh}`)),console.log(Rt.dim(" (2-step verification must be on for that page to show.)"))),p=(await Zn({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||_o("Aborted");let g={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:f,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 QO(g,p);y&&(console.log(Rt.red("\u2717")),_o(y)),console.log(Rt.green("\u2713"))}e.passwordEnv||(Qn(f,p),process.env[f]=p);let h=await me(y=>{Ue(y,"channels.email.enabled",!0),Ue(y,`channels.email.accounts.${i}`,wh(g))},{configPath:e.configPath});h.success||_o(`Config save failed: ${h.error}`),console.log(),console.log(Rt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Rt.dim(` Password stored in .env as ${f}`)),console.log(Rt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let w=ZO(o.agents[s]?.tier,g.allowFrom);w&&console.log(Rt.yellow(` ${w}`)),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 e1}from"crypto";import Ke from"chalk";import Nk from"prompts";var ec="agentx-mesh:",tc="//join/";function t1(e){return Buffer.from(e,"utf-8").toString("base64url")}function o1(e){return Buffer.from(e,"base64url").toString("utf-8")}function n1(e){return`${ec}${tc}${t1(JSON.stringify(e))}`}function s1(e){if(!e.startsWith(`${ec}${tc}`))throw new Error(`Not a mesh invite link \u2014 expected ${ec}${tc}\u2026`);let t=e.slice(ec.length+tc.length),o=JSON.parse(o1(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 r1(){return e1(32).toString("hex")}function i1(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function a1(e){return e?.node?.name||e?.node?.id||"node"}async function jk(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=du("MESH_TOKEN");i||(i=r1(),Qn("MESH_TOKEN",i),console.log(Ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||i1(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Nk({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(Ke.red(" Aborted")),process.exit(1)),a=d}let l=await me(d=>{Ue(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:a1(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 _k(e,t={}){let o;try{o=s1(e)}catch(r){console.log(Ke.red(` \u2717 ${r.message}`)),process.exit(1)}let n=du("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Nk({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))}Qn("MESH_TOKEN",o.token);let s=await me(r=>{Ue(r,"mesh.enabled",!0);let i=ks(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),Ue(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 es=new c1().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");es.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 Ck({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});es.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 Ok({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});es.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 Ik({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 Pk=es.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Pk.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 jk({url:e.url,configPath:e.config})});Pk.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 _k(e,{configPath:t.config})});es.action(()=>{console.log(),console.log(or.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${or.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${or.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${or.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${or.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(or.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as l1}from"commander";import ce from"chalk";var ts=new l1().name("usage").description("token usage analysis and reporting");ts.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(ce.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ce.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${ce.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${ce.red(String(s.totalErrors))}`),console.log(),console.log(ce.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,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(` ${ce.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ce.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${e.message}`))}});ts.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(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:ce.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(ce.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(ce.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",w=l.has(d.window)?ce.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,w].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(ce.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${t.message}`))}});ts.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(ce.red(` Script not found: ${s}`)),console.log(ce.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ce.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ce.red(" Analysis failed. Is Python 3 installed?"))}});ts.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=g=>/^\d{4}-\d{2}-\d{2}$/.test(g)&&!Number.isNaN(Date.parse(g));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(ce.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(ce.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(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(ce.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(ce.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(ce.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(g=>[g,a.channels[g],c?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[g,h,w]of p){let y=r(h),b=` ${g.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${u(h?.cacheRead||0).padStart(11)} ${u(h?.cacheCreate||0).padStart(11)} ${u(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l(y).padStart(9)}`;if(c){let v=r(w),S=y!==null&&v?`${((y-v)/v*100).toFixed(0)}%`:"-";b+=` ${l(v).padStart(9)} ${S.padStart(7)}`}console.log(b)}console.log(),c&&console.log(ce.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(ce.dim(` Saved ${e.save}`)),console.log()});ts.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-IDRN5TAM.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 g=f?`${f} ${p.name()}`:p.name();c.push(g),l(p,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(ce.bold(` Never used in the last ${e.days} days (${u.length}/${c.length})`)),console.log();for(let d of u)console.log(` ${ce.dim("\xB7")} ${d}`);console.log(),console.log(ce.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ce.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(ce.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ce.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ce.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(ce.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=ce.dim(`${r.days}d`);console.log(` ${ce.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(ce.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as d1}from"commander";import Je from"chalk";import{readFileSync as u1}from"fs";import{resolve as g1}from"path";te();var rn=new d1().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");rn.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{Dg(g1(process.cwd(),".env"))}catch{}let t=m1(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-YCRGMNAT.js");o(t)}catch(t){console.log(Je.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Je.dim(t.stack)),process.exit(1)}});function m1(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Je.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Je.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
569
+ `}function Qn(e,t,o=".env"){let n=Ak(o),s=Ek(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${lu(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${lu(t)}`})),PO(n,qO(s))}function du(e,t=".env"){return Ek(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Rk="https://t.me/BotFather";async function FO(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 UO(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 Ck(e={}){console.log(),console.log(ve.bold(" Connect Telegram")),console.log(),console.log(ve.dim(` 1. Open ${Rk}`)),console.log(ve.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ve.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Vr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&To(Rk);let{token:o}=await Vr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:S=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(S.trim())||"That doesn't look like a Telegram token"});o||(console.log(ve.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await FO(o.trim());n||(console.log(ve.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ve.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(ve.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(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let u=e.agent;u||(u=(await Vr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),u||(console.log(ve.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||u;d[f]&&d[f].agentBinding!==u&&(f=(await Vr({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${u}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ve.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Qn(p,o.trim()),process.env[p]=o.trim();let g=await me(S=>{Ue(S,"channels.telegram.enabled",!0),Ue(S,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:u});let x=ks(S,`agents.${u}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),Ue(S,`agents.${u}.mentions`,x))},{configPath:e.configPath});if(g.success||(console.log(ve.red(` \u2717 ${g.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 Bot @${n.username} bound to agent "${u}"`)),console.log(ve.dim(` Token stored in .env as ${p}`)),console.log(ve.dim(` Mentions updated to include @${n.username}`)),g.reloaded?console.log(ve.dim(" Daemon hot-reloaded.")):console.log(ve.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Vr({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(ve.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ve.dim(" Waiting up to 90s..."));let w=await UO(o.trim(),9e4);if(!w){console.log(ve.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ve.dim(" agentx config set notifications.destination.channel telegram")),console.log(ve.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ve.dim(` agentx config set notifications.destination.accountId ${f}`));return}let y={channel:"telegram",chatId:String(w.chatId),accountId:f},b=[],v=await me(S=>{Ue(S,"notifications.destination",y),b=da(S,y)},{configPath:e.configPath});if(!v.success){console.log(ve.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(ve.green(" \u2713 Default --notify target set")),console.log(ve.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ve.dim(" From now on, --notify me resolves to this chat.")),b.length&&console.log(ve.dim(` Schedules that now report here: ${b.join(", ")}`)),v.reloaded&&console.log(ve.dim(" Daemon hot-reloaded."))}import Me from"chalk";import uu from"prompts";import{existsSync as mu,mkdirSync as WO,readdirSync as BO,readFileSync as Tk}from"fs";import{resolve as gu}from"path";var JO=".agentx/whatsapp-sessions";function HO(){let e=gu(process.cwd(),".agentx/daemon.pid");if(!mu(e))return!1;try{let t=parseInt(Tk(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function GO(e){if(!mu(e))return!1;try{return BO(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function zO(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;WO(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 f=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 p=>{if(p.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(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Me.green(" \u2713 Paired"));try{l.end(void 0)}catch{}u(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Me.red(" \u2717 Authorization failed \u2014 rescan required")),u(!1))})})}async function Ok(e={}){if(console.log(),console.log(Me.bold(" Connect WhatsApp")),console.log(),HO()){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 uu({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Me.red(" Aborted")),process.exit(1))}let t=e.configPath||gu(process.cwd(),"agentx.json");mu(t)||(console.log(Me.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Tk(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||JO,s=gu(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 uu({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(GO(s)&&a){let{keep:l}=await uu({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 zO(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=>{Ue(l,"channels.whatsapp.enabled",!0),Ue(l,"channels.whatsapp.sessionDir",n),Ue(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 YO from"prompts";import{existsSync as KO,readFileSync as XO}from"fs";import{resolve as VO}from"path";async function QO(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 ZO(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 _o(e){console.log(Rt.red(` ${e}`)),process.exit(1)}async function Zn(e){return(await YO(e,{onCancel:()=>_o("Aborted")}))[e.name]}async function Ik(e={}){console.log(),console.log(Rt.bold(" Connect email")),console.log();let t=e.configPath||VO(process.cwd(),"agentx.json");KO(t)||_o(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(XO(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&_o("No agents configured. Run: agentx agent add");let s=e.agent??await Zn({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(y=>({title:y,value:y}))});o.agents?.[s]||_o(`No agent "${s}" in ${t}`);let r=(e.address??await Zn({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=hh(r),c=e.imapHost??a?.imapHost??await Zn({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await Zn({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),u=e.smtpHost??a?.smtpHost??await Zn({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await Zn({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&_o("Ports must be numbers.");let f=e.passwordEnv||yh(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&_o(`${e.passwordEnv} is not set in the environment.`),p||(a?.imapHost==="imap.gmail.com"&&(console.log(Rt.dim(` Gmail needs an app password, not your account password: ${fh}`)),console.log(Rt.dim(" (2-step verification must be on for that page to show.)"))),p=(await Zn({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||_o("Aborted");let g={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:u,smtpPort:d,user:e.user,passwordEnv:f,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 QO(g,p);y&&(console.log(Rt.red("\u2717")),_o(y)),console.log(Rt.green("\u2713"))}e.passwordEnv||(Qn(f,p),process.env[f]=p);let h=await me(y=>{Ue(y,"channels.email.enabled",!0),Ue(y,`channels.email.accounts.${i}`,wh(g))},{configPath:e.configPath});h.success||_o(`Config save failed: ${h.error}`),console.log(),console.log(Rt.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(Rt.dim(` Password stored in .env as ${f}`)),console.log(Rt.dim(` Who may write: ${g.allowFrom.join(", ")}${g.allowFrom.includes("*")?" (anyone)":""}`));let w=ZO(o.agents[s]?.tier,g.allowFrom);w&&console.log(Rt.yellow(` ${w}`)),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 e1}from"crypto";import Ke from"chalk";import Nk from"prompts";var ec="agentx-mesh:",tc="//join/";function t1(e){return Buffer.from(e,"utf-8").toString("base64url")}function o1(e){return Buffer.from(e,"base64url").toString("utf-8")}function n1(e){return`${ec}${tc}${t1(JSON.stringify(e))}`}function s1(e){if(!e.startsWith(`${ec}${tc}`))throw new Error(`Not a mesh invite link \u2014 expected ${ec}${tc}\u2026`);let t=e.slice(ec.length+tc.length),o=JSON.parse(o1(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 r1(){return e1(32).toString("hex")}function i1(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function a1(e){return e?.node?.name||e?.node?.id||"node"}async function jk(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=du("MESH_TOKEN");i||(i=r1(),Qn("MESH_TOKEN",i),console.log(Ke.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||i1(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Nk({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(Ke.red(" Aborted")),process.exit(1)),a=d}let l=await me(d=>{Ue(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:a1(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 _k(e,t={}){let o;try{o=s1(e)}catch(r){console.log(Ke.red(` \u2717 ${r.message}`)),process.exit(1)}let n=du("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Nk({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))}Qn("MESH_TOKEN",o.token);let s=await me(r=>{Ue(r,"mesh.enabled",!0);let i=ks(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),Ue(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 es=new c1().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");es.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 Ck({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});es.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 Ok({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});es.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 Ik({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 Pk=es.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Pk.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 jk({url:e.url,configPath:e.config})});Pk.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 _k(e,{configPath:t.config})});es.action(()=>{console.log(),console.log(or.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${or.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${or.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${or.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${or.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(or.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as l1}from"commander";import ce from"chalk";var ts=new l1().name("usage").description("token usage analysis and reporting");ts.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(ce.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ce.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${ce.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${ce.red(String(s.totalErrors))}`),console.log(),console.log(ce.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,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(` ${ce.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ce.dim(u)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${e.message}`))}});ts.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(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:ce.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(ce.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(ce.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",g=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?g<60?`resets in ${g} min`:g<48*60?`resets in ${Math.round(g/60)} h`:`resets in ${Math.round(g/1440)} days`:"",w=l.has(d.window)?ce.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,w].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(ce.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(ce.red(" Daemon not running. Start with: agentx daemon start")):console.log(ce.red(` ${t.message}`))}});ts.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(ce.red(` Script not found: ${s}`)),console.log(ce.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ce.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ce.red(" Analysis failed. Is Python 3 installed?"))}});ts.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=g=>/^\d{4}-\d{2}-\d{2}$/.test(g)&&!Number.isNaN(Date.parse(g));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(ce.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(g){console.log(ce.red(` Cannot read baseline ${e.baseline}: ${g.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(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(ce.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(ce.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(ce.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(g=>[g,a.channels[g],c?.channels[g]]).sort((g,h)=>(h[1]?.cost||0)-(g[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[g,h,w]of p){let y=r(h),b=` ${g.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${u(h?.cacheRead||0).padStart(11)} ${u(h?.cacheCreate||0).padStart(11)} ${u(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l(y).padStart(9)}`;if(c){let v=r(w),S=y!==null&&v?`${((y-v)/v*100).toFixed(0)}%`:"-";b+=` ${l(v).padStart(9)} ${S.padStart(7)}`}console.log(b)}console.log(),c&&console.log(ce.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(ce.dim(` Saved ${e.save}`)),console.log()});ts.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-W7ZO7UDB.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 g=f?`${f} ${p.name()}`:p.name();c.push(g),l(p,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(ce.bold(` Never used in the last ${e.days} days (${u.length}/${c.length})`)),console.log();for(let d of u)console.log(` ${ce.dim("\xB7")} ${d}`);console.log(),console.log(ce.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ce.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(ce.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ce.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ce.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(ce.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=ce.dim(`${r.days}d`);console.log(` ${ce.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(ce.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as d1}from"commander";import Je from"chalk";import{readFileSync as u1}from"fs";import{resolve as g1}from"path";te();var rn=new d1().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");rn.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{Dg(g1(process.cwd(),".env"))}catch{}let t=m1(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-Y2X7GNAS.js");o(t)}catch(t){console.log(Je.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Je.dim(t.stack)),process.exit(1)}});function m1(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Je.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Je.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
570
570
  `)),{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}}}}rn.command("list").description("list configured boards").action(()=>{try{let e=O();if(!e.boards?.length){console.log(Je.dim(`
571
571
  No boards configured.
572
572
  `));return}console.log();for(let t of e.boards){console.log(` ${Je.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(Je.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(Je.dim(` primary label: ${t.primaryToolLabel}`)),console.log(Je.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(Je.red(` ${e.message}`)),process.exit(1)}});rn.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{Qr(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(Je.red(` ${o.message}`)),process.exit(1)}});rn.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{Qr(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(Je.red(` ${o.message}`)),process.exit(1)}});var pu=rn.command("column").description("manage a board's columns (add / remove / edit / list)");pu.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(u1("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(Je.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(` ${Je.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${Je.dim(r)}`)}}catch(t){console.log(Je.red(` ${t.message}`)),process.exit(1)}});pu.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{Qr(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(Je.red(` ${n.message}`)),process.exit(1)}});pu.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Qr(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(Je.red(` ${o.message}`)),process.exit(1)}});rn.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Qr(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(Je.red(` ${t.message}`)),process.exit(1)}});function Qr(e){let{summary:t,backupPath:o}=Pt(n=>e(n));console.log(Je.green(`
@@ -868,7 +868,7 @@ Restart the daemon to activate.
868
868
  dist/
869
869
  *.log
870
870
  .env
871
- `}import{Command as JN}from"commander";import it from"chalk";import{writeFileSync as HN,mkdirSync as GN,existsSync as Ec,readFileSync as Px,appendFileSync as Dx}from"fs";import{resolve as gr,dirname as qx}from"path";import{homedir as eg}from"os";var Fx=new JN().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-IDRN5TAM.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=KN(o);break;case"bash":s=ej(o);break;case"fish":s=tj(o);break;default:console.error(it.red(`unsupported shell: ${n}`)),console.error(it.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?gr(String(e.output)):zN(n);GN(qx(r),{recursive:!0}),HN(r,s),console.log(it.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),YN(n,r,!!e.yes)});function zN(e){let t=eg();switch(e){case"zsh":return gr(t,".zsh","completions","_agentx");case"bash":return gr(t,".bash_completion.d","agentx.bash");case"fish":return gr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function YN(e,t,o){if(e==="zsh"){let n=gr(eg(),".zshrc"),s=qx(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Ec(n)?Px(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(it.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Ec(n)){let u=["","# agentx completion"];c&&u.push(r),l&&u.push(i),Dx(n,u.join(`
871
+ `}import{Command as JN}from"commander";import it from"chalk";import{writeFileSync as HN,mkdirSync as GN,existsSync as Ec,readFileSync as Px,appendFileSync as Dx}from"fs";import{resolve as gr,dirname as qx}from"path";import{homedir as eg}from"os";var Fx=new JN().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-W7ZO7UDB.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=KN(o);break;case"bash":s=ej(o);break;case"fish":s=tj(o);break;default:console.error(it.red(`unsupported shell: ${n}`)),console.error(it.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?gr(String(e.output)):zN(n);GN(qx(r),{recursive:!0}),HN(r,s),console.log(it.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),YN(n,r,!!e.yes)});function zN(e){let t=eg();switch(e){case"zsh":return gr(t,".zsh","completions","_agentx");case"bash":return gr(t,".bash_completion.d","agentx.bash");case"fish":return gr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function YN(e,t,o){if(e==="zsh"){let n=gr(eg(),".zshrc"),s=qx(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Ec(n)?Px(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(it.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Ec(n)){let u=["","# agentx completion"];c&&u.push(r),l&&u.push(i),Dx(n,u.join(`
872
872
  `)+`
873
873
  `),console.log(it.green("\u2713 Patched ~/.zshrc")),console.log(it.dim("Reload your shell: exec zsh"));return}console.log(it.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(it.cyan(` ${r}`)),l&&console.log(it.cyan(` ${i}`)),console.log(),console.log(it.dim("Then reload: exec zsh")),console.log(it.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=gr(eg(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Ec(n)?Px(n,"utf-8"):"").includes(t)){console.log(it.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&Ec(n)){Dx(n,`
874
874
  # agentx completion
@@ -884,4 +884,4 @@ ${oj({...t,category:e.category})}`),u&&a.set(l.id,u)}let c=`https://github.com/$
884
884
  ${o.url}`)}catch(t){console.error(pr.red(` ${t.message}`)),process.exitCode=1}});mi.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",og).action(async(e,t)=>{try{let o=await rg(t.models);if(!ng(t.model,o)){console.log(sg(t.model,o)),process.exitCode=1;return}let n=e==="-"?await rj():await sj(e,"utf8"),s=JSON.parse(n),{version:r}=await Ti(),i=Jx({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(pr.red(` ${o.message}`)),process.exitCode=1}});async function rj(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function Tz(){let e=await Ti(),t=new ij().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=bh(n);kh(s)&&$h("cli",s)});for(let o of[wy,Ow,Tw,es,Ts,uo,Dt,eh,Rb,Tb,po,ha,Io,En,zn,yo,jo,Sk,sn,aa,hx,en,g$,m$,v$,Hr,j$,L$,l$,U$,W$,rb,lb,db,Ut,ts,vx,_r,Ko,Fx,mi])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):`,aj(o,74," "),""].join(`
885
885
  `)}),t}var Gx=[X,rr,Do,to,Mr,Ks,tt,Po,rn,Gn,is,ar,Qo,xt,Us,Ta,Ha,Jn,Ga,za,ux,px,Oo,ri,Lt,Mh,In,ui,nd,dn,bt,qs,sd,fc,ko,Mo,Cx,dr,Tx,bx];function aj(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(`
886
886
  `)}export{Tz as buildProgram};
887
- //# sourceMappingURL=program-IDRN5TAM.js.map
887
+ //# sourceMappingURL=program-W7ZO7UDB.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentix-cli",
3
- "version": "0.194.0",
3
+ "version": "0.196.0",
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": {