agentix-cli 0.108.0 → 0.110.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.
@@ -1,4 +1,4 @@
1
- import{a as rd,b as Ds,g as ad}from"./chunk-CJR26JUI.js";import{a as Jl,c as Hl}from"./chunk-NIW75USA.js";import{A as id,a as so,b as Bl,f as Ut,g as Gl,h as zl,i as Yl,j as Vl,l as Xl,m as Kl,r as Ql,s as Zl,t as sr,u as ed,x as ir,y as sd}from"./chunk-SFPMS55Z.js";import{a as od,c as td,d as nd}from"./chunk-UVMCAZL7.js";import"./chunk-N7HKIMMR.js";import{a as Bi,b as hc}from"./chunk-RKPAVWXF.js";import{$ as Rn,A as ul,B as fl,C as hl,D as yl,E as wl,F as $l,G as bl,H as Tl,I as Os,J as Co,K as Bo,L as Pt,M as Cs,N as Is,O as Qi,P as jl,Q as Ol,R as Cl,S as Il,T as Nl,U as Rl,V as Mt,W as Lt,X as _l,Y as Dl,Z as Le,_ as Ns,a as Sc,aa as Zi,b as Ec,ba as Pl,ca as ql,da as tr,ea as Fl,fa as Rs,ga as qt,h as ws,ha as _s,i as Oc,ia as nr,j as Cn,ja as Wl,k as $s,l as Nc,m as Rc,n as Hc,o as Gc,p as Es,q as Hi,r as Qc,s as il,t as rl,u as ll,v as dl,w as gl,x as ml,y as pl,z as zi}from"./chunk-GCE7T5QL.js";import{$a as Ul,A as As,C as sl,Ia as Ml,Ja as er,Ka as Ll,La as or,R as In,U as Yi,V as Ts,W as kl,Za as ko,ba as Wo,ca as vl,da as Vi,fa as Xi,ha as xl,ia as Sl,ja as Nn,na as js,qa as El,ra as Al,sa as Ki,w as Gi,x as tl,z as nl}from"./chunk-FHI5WPFO.js";import{a as Ac,d as Tc,e as jc}from"./chunk-BG6SOGKT.js";import{a as bs,b as ks,c as _c,d as Dc,e as Pc,g as Mc,h as Lc,j as qc,k as Uc,l as Fc,m as Wc,p as vs,s as Bc,t as Jc}from"./chunk-S2GAEH2F.js";import"./chunk-GTJIKXDB.js";import"./chunk-DG5I6PPM.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as al,b as cl}from"./chunk-EKJG63EJ.js";import{a as Cc,p as Ic}from"./chunk-5O6PIO7F.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as no}from"./chunk-ACFQBLPX.js";import{c as zc,e as xs,g as Ss}from"./chunk-LQE73AZR.js";import{a as Yc,b as Vc,c as Xc,d as Kc}from"./chunk-2D3RYIDU.js";import"./chunk-3Z5P2CWS.js";import{a as Zc,e as el,g as ol}from"./chunk-E5OV6RTG.js";import{L as Fo,R as gc,aa as pc,g as Va,r as Xa,y as Ui,z as ec}from"./chunk-LH54FH7J.js";import{b as Ct,g as Nt,h as hs,i as ys,j as Rt,k as oc,l as at,m as jn,u as mc}from"./chunk-2VGYRETU.js";import{e as ac,f as Wi,k as cc}from"./chunk-GLQLCBJS.js";import{b as It}from"./chunk-6W74CHNW.js";import"./chunk-KBYZTCHO.js";import"./chunk-SFQUP3BP.js";import{b as On}from"./chunk-LLNPKE7H.js";import{a as uc,b as fc}from"./chunk-SHEUCITK.js";import"./chunk-Y4CYQV7G.js";import{a as Ji,e as yc,f as wc,h as $c,i as bc,k as kc,l as vc,m as xc}from"./chunk-S4NZUPIN.js";import{a as _t}from"./chunk-GV7S5BAX.js";import{c as nc}from"./chunk-SZDACK6O.js";import{f as sc,g as ic,h as Fi}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as Qa,k as rc}from"./chunk-QQAZ6EJP.js";import{a as lc,b as re,c as Ie,d as Dt,e as dc}from"./chunk-6F2E5NQA.js";import"./chunk-VWTBHLMX.js";import{a as Li}from"./chunk-BFOB6ERR.js";import"./chunk-CJL5OPNQ.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import{a as qi,b as Ka}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Za}from"./chunk-X5C5W3E4.js";import{e as tc}from"./chunk-GSX4NK2N.js";import"./chunk-J32LSOBJ.js";import"./chunk-MYVHVJWZ.js";import{n as Ya}from"./chunk-UDJAODAB.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-BZKGQMU2.js";import{g as Uo,i as fs}from"./chunk-QFP4YZII.js";import"./chunk-WPNRDEHW.js";import{b as Ot,d as za}from"./chunk-2GIDVZ4H.js";import{a as Di,b as ja,c as Bp,d as ms,e as Oa,f as Fa,g as Yp,h as Wa,i as Vp,m as jt,n as Ja,o as Ha,s as Ga,v as bo,w as Tn}from"./chunk-UTV4DRAW.js";import{a as Oo,b as Tt,e as La,f as An}from"./chunk-72SZI2UW.js";import{a as Ba,b as Xp}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-5MUJZODV.js";import{a as jo,b as Wp}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{A as Hp,N as Pi,P as Mi,W as Gp,fa as Pa,ga as Ma,h as Ca,ha as T,i as Ia,ia as us,j as Na,k as Ra,ka as te,l as _a,m as Jp,z as Da}from"./chunk-D7M4WQFU.js";import{a as qo,i as ps}from"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as qa,k as Ua,l as zp}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Kp}from"commander";var cd=new Kp().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 Ec({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 Qp}from"commander";import{execFileSync as ao}from"node:child_process";import{cpSync as ld,existsSync as cr,mkdirSync as rr,mkdtempSync as Zp,readdirSync as eu,rmSync as dd,writeFileSync as gd}from"node:fs";import{dirname as md,join as qe}from"node:path";import{homedir as Ps,release as ou,tmpdir as tu}from"node:os";import{setTimeout as nu}from"node:timers/promises";function Ms(){let e=_c(process.platform,process.arch,ou());if(e)throw new Error(e)}function Ls(){let e=qe(Ps(),"Library/LaunchAgents"),o=[];try{o=eu(e).filter(Mc)}catch{}let t=o.flatMap(n=>{let s=qe(e,n);try{return[{file:s,plist:ao("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Lc(e,t)}function _n(e){return`gui/${process.getuid()}/${e.label}`}async function ar(e){try{ao("launchctl",["bootout",_n(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{ao("launchctl",["print",_n(e)],{stdio:"pipe"})}catch{return}await nu(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function pd(e){if(!cr(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{ao("launchctl",["print",_n(e)],{stdio:"pipe"})}catch{o=!1}o||ao("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ao("launchctl",["kickstart",_n(e)],{stdio:"pipe"})}function su(){let e=Wc();if(e&&cr(qe(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 Ft=new Qp("desktop").description("install and control the macOS desktop assistant");Ft.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=>{Ms();let o=T(),t=Dc(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=su(),r=qe(Ps(),"Applications"),{keep:a,remove:c}=Ls();if(console.log(`Desktop assistant \u2192 ${qe(r,bs)}
1
+ import{a as rd,b as Ds,g as ad}from"./chunk-CJR26JUI.js";import{a as Jl,c as Hl}from"./chunk-NIW75USA.js";import{A as id,a as so,b as Bl,f as Ut,g as Gl,h as zl,i as Yl,j as Vl,l as Xl,m as Kl,r as Ql,s as Zl,t as sr,u as ed,x as ir,y as sd}from"./chunk-SFPMS55Z.js";import{a as od,c as td,d as nd}from"./chunk-UVMCAZL7.js";import"./chunk-N7HKIMMR.js";import{a as Bi,b as hc}from"./chunk-RKPAVWXF.js";import{$ as Rn,A as ul,B as fl,C as hl,D as yl,E as wl,F as $l,G as bl,H as Tl,I as Os,J as Co,K as Bo,L as Pt,M as Cs,N as Is,O as Qi,P as jl,Q as Ol,R as Cl,S as Il,T as Nl,U as Rl,V as Mt,W as Lt,X as _l,Y as Dl,Z as Le,_ as Ns,a as Sc,aa as Zi,b as Ec,ba as Pl,ca as ql,da as tr,ea as Fl,fa as Rs,ga as qt,h as ws,ha as _s,i as Oc,ia as nr,j as Cn,ja as Wl,k as $s,l as Nc,m as Rc,n as Hc,o as Gc,p as Es,q as Hi,r as Qc,s as il,t as rl,u as ll,v as dl,w as gl,x as ml,y as pl,z as zi}from"./chunk-EC6DKMR5.js";import{$a as Ul,A as As,C as sl,Ia as Ml,Ja as er,Ka as Ll,La as or,R as In,U as Yi,V as Ts,W as kl,Za as ko,ba as Wo,ca as vl,da as Vi,fa as Xi,ha as xl,ia as Sl,ja as Nn,na as js,qa as El,ra as Al,sa as Ki,w as Gi,x as tl,z as nl}from"./chunk-FHI5WPFO.js";import{a as Ac,d as Tc,e as jc}from"./chunk-BG6SOGKT.js";import{a as bs,b as ks,c as _c,d as Dc,e as Pc,g as Mc,h as Lc,j as qc,k as Uc,l as Fc,m as Wc,p as vs,s as Bc,t as Jc}from"./chunk-S2GAEH2F.js";import"./chunk-GTJIKXDB.js";import"./chunk-DG5I6PPM.js";import"./chunk-ZVP6GB4G.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as al,b as cl}from"./chunk-EKJG63EJ.js";import{a as Cc,p as Ic}from"./chunk-5O6PIO7F.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as no}from"./chunk-ACFQBLPX.js";import{c as zc,e as xs,g as Ss}from"./chunk-LQE73AZR.js";import{a as Yc,b as Vc,c as Xc,d as Kc}from"./chunk-2D3RYIDU.js";import"./chunk-3Z5P2CWS.js";import{a as Zc,e as el,g as ol}from"./chunk-E5OV6RTG.js";import{L as Fo,R as gc,aa as pc,g as Va,r as Xa,y as Ui,z as ec}from"./chunk-3TY6YJHO.js";import{b as Ct,g as Nt,h as hs,i as ys,j as Rt,k as oc,l as at,m as jn,u as mc}from"./chunk-2VGYRETU.js";import{e as ac,f as Wi,k as cc}from"./chunk-GLQLCBJS.js";import{b as It}from"./chunk-6W74CHNW.js";import"./chunk-4UCDWEC4.js";import"./chunk-SFQUP3BP.js";import{b as On}from"./chunk-LLNPKE7H.js";import{a as uc,b as fc}from"./chunk-SHEUCITK.js";import"./chunk-Y4CYQV7G.js";import{a as Ji,e as yc,f as wc,h as $c,i as bc,k as kc,l as vc,m as xc}from"./chunk-S4NZUPIN.js";import{a as _t}from"./chunk-GV7S5BAX.js";import{c as nc}from"./chunk-SZDACK6O.js";import{f as sc,g as ic,h as Fi}from"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as Qa,k as rc}from"./chunk-QQAZ6EJP.js";import{a as lc,b as re,c as Ie,d as Dt,e as dc}from"./chunk-6F2E5NQA.js";import"./chunk-VWTBHLMX.js";import{a as Li}from"./chunk-BFOB6ERR.js";import"./chunk-CJL5OPNQ.js";import"./chunk-36AXN6ZB.js";import"./chunk-KA2UIZXG.js";import{a as qi,b as Ka}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Za}from"./chunk-X5C5W3E4.js";import{e as tc}from"./chunk-GSX4NK2N.js";import"./chunk-J32LSOBJ.js";import"./chunk-MYVHVJWZ.js";import{n as Ya}from"./chunk-UDJAODAB.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-BZKGQMU2.js";import{g as Uo,i as fs}from"./chunk-QFP4YZII.js";import"./chunk-WPNRDEHW.js";import{b as Ot,d as za}from"./chunk-2GIDVZ4H.js";import{a as Di,b as ja,c as Bp,d as ms,e as Oa,f as Fa,g as Yp,h as Wa,i as Vp,m as jt,n as Ja,o as Ha,s as Ga,v as bo,w as Tn}from"./chunk-UTV4DRAW.js";import{a as Oo,b as Tt,e as La,f as An}from"./chunk-72SZI2UW.js";import{a as Ba,b as Xp}from"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-5MUJZODV.js";import{a as jo,b as Wp}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{A as Hp,N as Pi,P as Mi,W as Gp,fa as Pa,ga as Ma,h as Ca,ha as T,i as Ia,ia as us,j as Na,k as Ra,ka as te,l as _a,m as Jp,z as Da}from"./chunk-D7M4WQFU.js";import{a as qo,i as ps}from"./chunk-RJ7DASOU.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import{g as qa,k as Ua,l as zp}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Kp}from"commander";var cd=new Kp().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 Ec({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 Qp}from"commander";import{execFileSync as ao}from"node:child_process";import{cpSync as ld,existsSync as cr,mkdirSync as rr,mkdtempSync as Zp,readdirSync as eu,rmSync as dd,writeFileSync as gd}from"node:fs";import{dirname as md,join as qe}from"node:path";import{homedir as Ps,release as ou,tmpdir as tu}from"node:os";import{setTimeout as nu}from"node:timers/promises";function Ms(){let e=_c(process.platform,process.arch,ou());if(e)throw new Error(e)}function Ls(){let e=qe(Ps(),"Library/LaunchAgents"),o=[];try{o=eu(e).filter(Mc)}catch{}let t=o.flatMap(n=>{let s=qe(e,n);try{return[{file:s,plist:ao("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Lc(e,t)}function _n(e){return`gui/${process.getuid()}/${e.label}`}async function ar(e){try{ao("launchctl",["bootout",_n(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{ao("launchctl",["print",_n(e)],{stdio:"pipe"})}catch{return}await nu(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function pd(e){if(!cr(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{ao("launchctl",["print",_n(e)],{stdio:"pipe"})}catch{o=!1}o||ao("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),ao("launchctl",["kickstart",_n(e)],{stdio:"pipe"})}function su(){let e=Wc();if(e&&cr(qe(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 Ft=new Qp("desktop").description("install and control the macOS desktop assistant");Ft.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=>{Ms();let o=T(),t=Dc(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=su(),r=qe(Ps(),"Applications"),{keep:a,remove:c}=Ls();if(console.log(`Desktop assistant \u2192 ${qe(r,bs)}
2
2
  Computer-use helper \u2192 ${qe(r,ks)}
3
3
  Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
4
4
  Daemon \u2192 ${s}
@@ -448,7 +448,7 @@ return aid ?? null`}function ey(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
448
448
  Latest runs (${s.length})`),s.length===0&&console.log(z.dim(" nothing recorded yet"));for(let r of s){let a=r.status==="ok"?z.green("ok"):r.status==="in-flight"?z.yellow("running"):z.red(r.status);console.log(` ${z.dim(hm(r.startedAt))} ${(r.channel??"?").padEnd(9)} ${r.agentId} ${a} ${ym(r.messagePreview)}`)}console.log()});ps();Hp();import{Command as cw}from"commander";import{existsSync as lw}from"fs";import ye from"chalk";var rn=new cw("requests").description("what you asked agents for that is not finished, oldest first"),vm={in_progress:"in progress",waiting_owner:"waiting on you",waiting_other:"waiting on another agent",needs_attention:"needs attention",done:"done",declined:"declined",dropped:"dropped"};function zr(){if(!lw(lc()))return console.error(ye.red(" no agentx.json here: run this from the install folder, the one that holds agentx.json")),process.exitCode=1,null;let e=qo();return e?new Da(e):(process.exitCode=1,null)}var gi=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function xm(e){let o=e.state==="needs_attention"?ye.red:e.state==="waiting_owner"?ye.yellow:ye.dim;console.log(` ${ye.cyan(e.id)} ${o(`[${vm[e.state]??e.state}]`)} ${ye.dim(`${gi(e.createdAt)} \xB7 ${e.channel} \xB7 ${e.agentId}`)}`),console.log(` ${e.text.replace(/\s+/g," ").trim().slice(0,240)}`),e.state==="waiting_owner"&&e.question&&console.log(ye.yellow(` Question: ${e.question}`)),e.state==="needs_attention"&&e.attentionReason&&console.log(ye.red(` ${e.attentionReason}`)),e.evidence&&console.log(ye.green(` Evidence: ${e.evidence}`)),e.closeReason&&console.log(ye.dim(` Reason: ${e.closeReason}`))}rn.command("list",{isDefault:!0}).alias("ls").description("open requests, oldest first").option("--json","machine-readable output").action(e=>{let o=zr();if(!o)return;let t=o.listOpen();if(e.json){console.log(JSON.stringify(t,null,2));return}if(Gi().enabled||console.log(ye.dim(" requests are off: turn them on with `agentx requests settings --enabled on`")),t.length===0){console.log(ye.dim(" no open requests"));return}for(let n of t)xm(n);console.log(ye.dim(`
449
449
  ${t.length} open. Close one: agentx requests done <id> --evidence <link> \xB7 agentx requests drop <id>`))});rn.command("show <id>").description("one request and the runs, delegations and cards linked to it").action(e=>{let o=zr();if(!o)return;let t=o.get(e);if(!t||t.state==="candidate"){console.error(ye.red(` no request "${e}"`)),process.exitCode=1;return}xm(t),console.log(ye.dim(` Last activity ${gi(t.updatedAt)}${t.closedAt?` \xB7 closed ${gi(t.closedAt)}`:""}`));for(let n of o.links(e))console.log(ye.dim(` ${n.kind} ${n.ref} (${gi(n.at)})`))});function Sm(e,o,t,n){rn.command(`${e} <id>`).description(o).option(t,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped").action((s,i)=>{let r=zr();if(!r)return;let a=e==="done"?i.evidence:i.reason??"dropped by the owner";if(!a){console.error(ye.red(` ${n}`)),process.exitCode=1;return}let c=r.get(s);if(!c||c.state==="candidate"){console.error(ye.red(` no request "${s}"`)),process.exitCode=1;return}if(!r.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(ye.red(` ${s} is already closed (${vm[c.state]??c.state})`)),process.exitCode=1;return}console.log(ye.green(` \u2713 ${s} ${e==="done"?"closed as done":"dropped"}`))})}Sm("done","close a request as finished, with a link to the evidence","--evidence <link>","a finished request needs --evidence <link>");Sm("drop","drop a request you no longer want","--reason <text>","");rn.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").action(async e=>{let o={};try{let n=(i,r)=>{if(r===void 0)return;let a=Number(r);if(!(a>0))throw new Error(`${i} must be a positive number`);return a},s=(i,r)=>i===void 0?void 0:i===r?[]:i.split(",").map(a=>a.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");o.enabled=e.enabled==="on"}o.from=s(e.from,"none"),o.channels=s(e.channels,"all"),o.staleAfterHours=n("--stale-hours",e.staleHours),o.retentionDays=n("--retention-days",e.retentionDays)}catch(n){console.error(ye.red(` ${n.message}`)),process.exitCode=1;return}if(Object.values(o).some(n=>n!==void 0)){let n=await tl(o);if(!n.success){console.error(ye.red(` ${n.error}`)),process.exitCode=1;return}console.log(ye.green(" \u2713 saved")+(n.reloaded?ye.dim(" (daemon reloaded)"):""))}let t=Gi();console.log(` Requests ${t.enabled?"on":"off"}`),console.log(` Channels ${t.channels.length?t.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${t.from.length?t.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${t.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${t.retentionDays} day(s)`)});import{Command as dw}from"commander";import an from"chalk";te();var Em=new dw("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",sr.join(" or ")).argument("[state]","on or off").action(async(e,o)=>{if(e!==void 0){o!=="on"&&o!=="off"&&(console.error(an.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await re(i=>{n=ed(i,e,o==="on")});s.success||(console.error(an.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(an.green(`\u2713 ${n}`)),s.reloaded&&console.log(an.dim(" daemon hot-reloaded"))}let t=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of sr)console.log(` ${n.padEnd(8)} ${t.includes(n)?an.green("on"):an.dim("off")}`)});import{Command as Rw}from"commander";import cn from"chalk";import ce from"chalk";import Zn from"prompts";import{readFileSync as gw,writeFileSync as mw,existsSync as pw}from"fs";import{resolve as Am}from"path";var uw=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function fw(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Yr(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Tm(e=".env"){let o=Am(e);if(!pw(o))return[];let t=gw(o,"utf-8"),n=[];for(let s of t.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 i=s.match(uw);i?n.push({kind:"kv",key:i[1],value:fw(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function hw(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Yr(o.value)}`:o.raw).join(`
450
450
  `)+`
451
- `}function Qn(e,o,t=".env"){let n=Am(t),s=Tm(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Yr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Yr(o)}`})),mw(n,hw(s))}function Vr(e,o=".env"){return Tm(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var jm="https://t.me/BotFather";async function yw(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function ww(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.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 Om(e={}){console.log(),console.log(ce.bold(" Connect Telegram")),console.log(),console.log(ce.dim(` 1. Open ${jm}`)),console.log(ce.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ce.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await Zn({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&&dt(jm);let{token:t}=await Zn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:k=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(k.trim())||"That doesn't look like a Telegram token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await yw(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ce.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ce.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(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Zn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ce.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Zn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ce.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Qn(f,t.trim()),process.env[f]=t.trim();let p=await re(k=>{Ie(k,"channels.telegram.enabled",!0),Ie(k,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=Dt(k,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(k,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ce.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ce.dim(` Token stored in .env as ${f}`)),console.log(ce.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Zn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(ce.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ce.dim(" Waiting up to 90s..."));let w=await ww(t.trim(),9e4);if(!w){console.log(ce.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ce.dim(" agentx config set notifications.destination.channel telegram")),console.log(ce.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ce.dim(` agentx config set notifications.destination.accountId ${u}`));return}let b=await re(k=>{Ie(k,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!b.success){console.log(ce.red(` \u2717 failed to save destination: ${b.error}`));return}console.log(ce.green(" \u2713 Default --notify target set")),console.log(ce.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ce.dim(" From now on, --notify me resolves to this chat.")),b.reloaded&&console.log(ce.dim(" Daemon hot-reloaded."))}import ve from"chalk";import Xr from"prompts";import{existsSync as Qr,mkdirSync as $w,readdirSync as bw,readFileSync as Cm}from"fs";import{resolve as Kr}from"path";var kw=".agentx/whatsapp-sessions";function vw(){let e=Kr(process.cwd(),".agentx/daemon.pid");if(!Qr(e))return!1;try{let o=parseInt(Cm(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function xw(e){if(!Qr(e))return!1;try{return bw(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Sw(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ve.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ve.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;$w(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ve.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ve.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ve.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ve.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Im(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),vw()){console.log(ve.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ve.dim(" agentx daemon stop")),console.log();let{cont:l}=await Xr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||Kr(process.cwd(),"agentx.json");Qr(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Cm(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||kw,s=Kr(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Xr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ve.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(xw(s)&&a){let{keep:l}=await Xr({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(ve.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Sw(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{Ie(l,"channels.whatsapp.enabled",!0),Ie(l,"channels.whatsapp.sessionDir",n),Ie(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ve.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ve.dim(` Session: ${n}`)),console.log(ve.dim(" Start the daemon to begin receiving:")),console.log(ve.dim(" agentx daemon start")),console.log(ve.dim(" Add routes later with:")),console.log(ve.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Ew}from"crypto";import je from"chalk";import Nm from"prompts";var mi="agentx-mesh:",pi="//join/";function Aw(e){return Buffer.from(e,"utf-8").toString("base64url")}function Tw(e){return Buffer.from(e,"base64url").toString("utf-8")}function jw(e){return`${mi}${pi}${Aw(JSON.stringify(e))}`}function Ow(e){if(!e.startsWith(`${mi}${pi}`))throw new Error(`Not a mesh invite link \u2014 expected ${mi}${pi}\u2026`);let o=e.slice(mi.length+pi.length),t=JSON.parse(Tw(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Cw(){return Ew(32).toString("hex")}function Iw(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Nw(e){return e?.node?.name||e?.node?.id||"node"}async function Rm(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Vr("MESH_TOKEN");r||(r=Cw(),Qn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Iw(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Nm({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:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(je.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=jw({url:a,token:r,name:Nw(i),version:1});console.log(),console.log(je.bold(" Mesh invite")),console.log(),console.log(` ${je.cyan(g)}`),console.log(),console.log(je.dim(" Run on the other node:")),console.log(je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function _m(e,o={}){let t;try{t=Ow(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Vr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Nm({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(je.red(" Aborted (keeping existing .env)")),process.exit(1))}Qn("MESH_TOKEN",t.token);let s=await re(i=>{Ie(i,"mesh.enabled",!0);let r=Dt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ie(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(je.green(" \u2713 Joined mesh")),console.log(je.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(je.dim(" Daemon hot-reloaded.")):console.log(je.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(je.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(je.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(je.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ln=new Rw().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ln.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 Om({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ln.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 Im({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Dm=ln.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Dm.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 Rm({url:e.url,configPath:e.config})});Dm.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await _m(e,{configPath:o.config})});ln.action(()=>{console.log(),console.log(cn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${cn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${cn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${cn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${cn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(cn.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as _w}from"commander";import X from"chalk";var kt=new _w().name("usage").description("token usage analysis and reporting");kt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(X.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(X.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${X.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${X.red(String(s.totalErrors))}`),console.log(),console.log(X.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${X.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${X.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(X.red(" Daemon not running. Start with: agentx daemon start")):console.log(X.red(` ${e.message}`))}});kt.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 o=T(),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}`,i=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)throw new Error(`Daemon answered ${i.status}. It may be older than this command; restart it.`);let r=await i.json();if(e.json){console.log(JSON.stringify(r,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=r.lifted.map(u=>a(u.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:X.dim(" No hold to lift.")),console.log();return}let c=r.now,l=new Set(r.holds.map(d=>d.window));console.log(X.bold(" Claude plan (as Claude Code last reported it)")),console.log(),r.provider.length===0&&console.log(X.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of r.provider){let u=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?X.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${u.padEnd(12)} ${[f,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${r.lastHour}${g(r.maxPerHour)} in the last hour, ${r.last5h}${g(r.maxPer5h)} in the last 5 hours`),l.size&&console.log(X.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(o){o.cause?.code==="ECONNREFUSED"?console.log(X.red(" Daemon not running. Start with: agentx daemon start")):console.log(X.red(` ${o.message}`))}});kt.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:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(X.red(` Script not found: ${s}`)),console.log(X.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(X.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(X.red(" Analysis failed. Is Python 3 installed?"))}});kt.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:o,writeFileSync:t}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-W7DFDEFN.js"),{channelCosts:s,costPerTask:i}=await import("./usage-channels-KBLEC4NE.js"),r=p=>/^\d{4}-\d{2}-\d{2}$/.test(p)&&!Number.isNaN(Date.parse(p));if(!r(e.from)||!r(e.to)||e.from>e.to){console.log(X.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&&t(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(o(e.baseline,"utf-8"))}catch(p){console.log(X.red(` Cannot read baseline ${e.baseline}: ${p.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=p=>p===null?"-":`$${p.toFixed(p<10?3:2)}`,g=p=>`${(p/1e6).toFixed(1)}M`;console.log(),console.log(X.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(X.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(X.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(p=>[p,a.channels[p],c?.channels[p]]).sort((p,y)=>(y[1]?.cost||0)-(p[1]?.cost||0));f.push(["TOTAL",a.total,c?.total]);for(let[p,y,w]of f){let b=i(y),k=` ${p.padEnd(14)} ${String(y?.tasks||0).padStart(6)} ${g(y?.cacheRead||0).padStart(11)} ${g(y?.cacheCreate||0).padStart(11)} ${g(y?.output||0).padStart(8)} ${l(y?.cost||0).padStart(10)} ${l(b).padStart(9)}`;if(c){let $=i(w),E=b!==null&&$?`${((b-$)/$*100).toFixed(0)}%`:"-";k+=` ${l($).padStart(9)} ${E.padStart(7)}`}console.log(k)}console.log(),c&&console.log(X.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(X.dim(` Saved ${e.save}`)),console.log()});kt.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:o}=await import("./surface-usage-CH3SHO77.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-LSQMLS6W.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(X.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${X.dim("\xB7")} ${d}`);console.log(),console.log(X.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(X.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(X.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(X.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(X.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(X.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=X.dim(`${i.days}d`);console.log(` ${X.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(X.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Dw}from"commander";import xe from"chalk";import{readFileSync as Pw}from"fs";import{resolve as Mw}from"path";te();var ot=new Dw().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");ot.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{za(Mw(process.cwd(),".env"))}catch{}let o=Lw(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-2X4OKKOM.js");t(o)}catch(o){console.log(xe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(xe.dim(o.stack)),process.exit(1)}});function Lw(e,o){try{let t=T();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(xe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(xe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
451
+ `}function Qn(e,o,t=".env"){let n=Am(t),s=Tm(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Yr(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Yr(o)}`})),mw(n,hw(s))}function Vr(e,o=".env"){return Tm(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var jm="https://t.me/BotFather";async function yw(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function ww(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.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 Om(e={}){console.log(),console.log(ce.bold(" Connect Telegram")),console.log(),console.log(ce.dim(` 1. Open ${jm}`)),console.log(ce.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ce.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:o}=await Zn({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});o&&dt(jm);let{token:t}=await Zn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:k=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(k.trim())||"That doesn't look like a Telegram token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await yw(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ce.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(ce.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(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Zn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map($=>({title:$,value:$})),initial:0})).agent),g||(console.log(ce.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Zn({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ce.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Qn(f,t.trim()),process.env[f]=t.trim();let p=await re(k=>{Ie(k,"channels.telegram.enabled",!0),Ie(k,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let $=Dt(k,`agents.${g}.mentions`)||[],E=`@${n.username}`;$.includes(E)||($.push(E),Ie(k,`agents.${g}.mentions`,$))},{configPath:e.configPath});if(p.success||(console.log(ce.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ce.dim(` Token stored in .env as ${f}`)),console.log(ce.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Zn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(ce.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ce.dim(" Waiting up to 90s..."));let w=await ww(t.trim(),9e4);if(!w){console.log(ce.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ce.dim(" agentx config set notifications.destination.channel telegram")),console.log(ce.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ce.dim(` agentx config set notifications.destination.accountId ${u}`));return}let b=await re(k=>{Ie(k,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:u})},{configPath:e.configPath});if(!b.success){console.log(ce.red(` \u2717 failed to save destination: ${b.error}`));return}console.log(ce.green(" \u2713 Default --notify target set")),console.log(ce.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ce.dim(" From now on, --notify me resolves to this chat.")),b.reloaded&&console.log(ce.dim(" Daemon hot-reloaded."))}import ve from"chalk";import Xr from"prompts";import{existsSync as Qr,mkdirSync as $w,readdirSync as bw,readFileSync as Cm}from"fs";import{resolve as Kr}from"path";var kw=".agentx/whatsapp-sessions";function vw(){let e=Kr(process.cwd(),".agentx/daemon.pid");if(!Qr(e))return!1;try{let o=parseInt(Cm(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function xw(e){if(!Qr(e))return!1;try{return bw(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Sw(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ve.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ve.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;$w(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ve.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ve.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ve.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ve.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Im(e={}){if(console.log(),console.log(ve.bold(" Connect WhatsApp")),console.log(),vw()){console.log(ve.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ve.dim(" agentx daemon stop")),console.log();let{cont:l}=await Xr({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ve.red(" Aborted")),process.exit(1))}let o=e.configPath||Kr(process.cwd(),"agentx.json");Qr(o)||(console.log(ve.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Cm(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||kw,s=Kr(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ve.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Xr({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ve.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(xw(s)&&a){let{keep:l}=await Xr({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(ve.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Sw(s,g=>console.log(g))||(console.log(ve.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{Ie(l,"channels.whatsapp.enabled",!0),Ie(l,"channels.whatsapp.sessionDir",n),Ie(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ve.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ve.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ve.dim(` Session: ${n}`)),console.log(ve.dim(" Start the daemon to begin receiving:")),console.log(ve.dim(" agentx daemon start")),console.log(ve.dim(" Add routes later with:")),console.log(ve.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Ew}from"crypto";import je from"chalk";import Nm from"prompts";var mi="agentx-mesh:",pi="//join/";function Aw(e){return Buffer.from(e,"utf-8").toString("base64url")}function Tw(e){return Buffer.from(e,"base64url").toString("utf-8")}function jw(e){return`${mi}${pi}${Aw(JSON.stringify(e))}`}function Ow(e){if(!e.startsWith(`${mi}${pi}`))throw new Error(`Not a mesh invite link \u2014 expected ${mi}${pi}\u2026`);let o=e.slice(mi.length+pi.length),t=JSON.parse(Tw(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function Cw(){return Ew(32).toString("hex")}function Iw(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Nw(e){return e?.node?.name||e?.node?.id||"node"}async function Rm(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(je.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Vr("MESH_TOKEN");r||(r=Cw(),Qn("MESH_TOKEN",r),console.log(je.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Iw(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Nm({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:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(je.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{Ie(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(je.red(` \u2717 ${l.error}`)),process.exit(1));let g=jw({url:a,token:r,name:Nw(i),version:1});console.log(),console.log(je.bold(" Mesh invite")),console.log(),console.log(` ${je.cyan(g)}`),console.log(),console.log(je.dim(" Run on the other node:")),console.log(je.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(je.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function _m(e,o={}){let t;try{t=Ow(e)}catch(i){console.log(je.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Vr("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Nm({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(je.red(" Aborted (keeping existing .env)")),process.exit(1))}Qn("MESH_TOKEN",t.token);let s=await re(i=>{Ie(i,"mesh.enabled",!0);let r=Dt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ie(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(je.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(je.green(" \u2713 Joined mesh")),console.log(je.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(je.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(je.dim(" Daemon hot-reloaded.")):console.log(je.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(je.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(je.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(je.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ln=new Rw().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ln.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 Om({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ln.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 Im({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Dm=ln.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Dm.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 Rm({url:e.url,configPath:e.config})});Dm.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await _m(e,{configPath:o.config})});ln.action(()=>{console.log(),console.log(cn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${cn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${cn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${cn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${cn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(cn.dim(" GitLab connect is the next slice.")),console.log()});te();import{Command as _w}from"commander";import X from"chalk";var kt=new _w().name("usage").description("token usage analysis and reporting");kt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(X.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(X.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${X.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${X.red(String(s.totalErrors))}`),console.log(),console.log(X.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${X.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${X.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(X.red(" Daemon not running. Start with: agentx daemon start")):console.log(X.red(` ${e.message}`))}});kt.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 o=T(),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}`,i=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)throw new Error(`Daemon answered ${i.status}. It may be older than this command; restart it.`);let r=await i.json();if(e.json){console.log(JSON.stringify(r,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=r.lifted.map(u=>a(u.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:X.dim(" No hold to lift.")),console.log();return}let c=r.now,l=new Set(r.holds.map(d=>d.window));console.log(X.bold(" Claude plan (as Claude Code last reported it)")),console.log(),r.provider.length===0&&console.log(X.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of r.provider){let u=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,f=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",p=Math.max(1,Math.round((d.resetsAt-c)/6e4)),y=d.resetsAt>c?p<60?`resets in ${p} min`:p<48*60?`resets in ${Math.round(p/60)} h`:`resets in ${Math.round(p/1440)} days`:"",w=l.has(d.window)?X.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${u.padEnd(12)} ${[f,y,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${r.lastHour}${g(r.maxPerHour)} in the last hour, ${r.last5h}${g(r.maxPer5h)} in the last 5 hours`),l.size&&console.log(X.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(o){o.cause?.code==="ECONNREFUSED"?console.log(X.red(" Daemon not running. Start with: agentx daemon start")):console.log(X.red(` ${o.message}`))}});kt.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:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(X.red(` Script not found: ${s}`)),console.log(X.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(X.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(X.red(" Analysis failed. Is Python 3 installed?"))}});kt.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:o,writeFileSync:t}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-W7DFDEFN.js"),{channelCosts:s,costPerTask:i}=await import("./usage-channels-KBLEC4NE.js"),r=p=>/^\d{4}-\d{2}-\d{2}$/.test(p)&&!Number.isNaN(Date.parse(p));if(!r(e.from)||!r(e.to)||e.from>e.to){console.log(X.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&&t(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(o(e.baseline,"utf-8"))}catch(p){console.log(X.red(` Cannot read baseline ${e.baseline}: ${p.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=p=>p===null?"-":`$${p.toFixed(p<10?3:2)}`,g=p=>`${(p/1e6).toFixed(1)}M`;console.log(),console.log(X.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(X.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(X.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let f=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(p=>[p,a.channels[p],c?.channels[p]]).sort((p,y)=>(y[1]?.cost||0)-(p[1]?.cost||0));f.push(["TOTAL",a.total,c?.total]);for(let[p,y,w]of f){let b=i(y),k=` ${p.padEnd(14)} ${String(y?.tasks||0).padStart(6)} ${g(y?.cacheRead||0).padStart(11)} ${g(y?.cacheCreate||0).padStart(11)} ${g(y?.output||0).padStart(8)} ${l(y?.cost||0).padStart(10)} ${l(b).padStart(9)}`;if(c){let $=i(w),E=b!==null&&$?`${((b-$)/$*100).toFixed(0)}%`:"-";k+=` ${l($).padStart(9)} ${E.padStart(7)}`}console.log(k)}console.log(),c&&console.log(X.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(X.dim(` Saved ${e.save}`)),console.log()});kt.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:o}=await import("./surface-usage-CH3SHO77.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-V2JEVJAD.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(X.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${X.dim("\xB7")} ${d}`);console.log(),console.log(X.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(X.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(X.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(X.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(X.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(X.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=X.dim(`${i.days}d`);console.log(` ${X.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(X.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Dw}from"commander";import xe from"chalk";import{readFileSync as Pw}from"fs";import{resolve as Mw}from"path";te();var ot=new Dw().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");ot.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{za(Mw(process.cwd(),".env"))}catch{}let o=Lw(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-SAYBNLZW.js");t(o)}catch(o){console.log(xe.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(xe.dim(o.stack)),process.exit(1)}});function Lw(e,o){try{let t=T();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(xe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(xe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
452
452
  `)),{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:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}ot.command("list").description("list configured boards").action(()=>{try{let e=T();if(!e.boards?.length){console.log(xe.dim(`
453
453
  No boards configured.
454
454
  `));return}console.log();for(let o of e.boards){console.log(` ${xe.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(xe.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(xe.dim(` primary label: ${o.primaryToolLabel}`)),console.log(xe.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(xe.red(` ${e.message}`)),process.exit(1)}});ot.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,o)=>{try{es(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});ot.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,o)=>{try{es(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});var Zr=ot.command("column").description("manage a board's columns (add / remove / edit / list)");Zr.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(Pw("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(xe.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${xe.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${xe.dim(i)}`)}}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});Zr.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,o,t)=>{try{es(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(xe.red(` ${n.message}`)),process.exit(1)}});Zr.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{es(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(xe.red(` ${t.message}`)),process.exit(1)}});ot.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{es(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(xe.red(` ${o.message}`)),process.exit(1)}});function es(e){let{summary:o,backupPath:t}=so(n=>e(n));console.log(xe.green(`
@@ -604,7 +604,7 @@ ${e.persona}
604
604
  `),Oi(Be(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=o.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:t})),i={node:{id:e.id,name:e.name,bind:`127.0.0.1:${e.port}`,defaultAgent:e.agentId},dashboard:{enabled:!0,port:e.port+10,bind:"127.0.0.1",daemonUrl:`http://127.0.0.1:${e.port}`},providers:{demo:{apiKey:"demo-mode"}},agents:{[e.agentId]:{name:e.agentName,description:e.persona,workspace:"./workspaces/"+e.agentId,tier:"orchestrator",provider:"demo",mentions:[`@${e.agentId}`,e.agentId],maxConcurrent:2,systemPrompt:e.persona}},mesh:{enabled:!0,peers:s,discovery:"static",healthCheck:{interval:3,timeout:5}},workflows:{enabled:!0}};Oi(Be(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function ua(e,o,t){let n=Date.now();for(;Date.now()-n<t;){try{if(await o())return}catch{}await new Promise(s=>setTimeout(s,250))}throw new Error(`Timed out waiting for ${e} (${t/1e3}s) \u2014 raise it with --startup-timeout <seconds>`)}function fa(e){return fetch(e,{signal:AbortSignal.timeout(5e3)})}async function ha(e,o,t){let n=await fetch(`http://127.0.0.1:${e}${o}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${o} HTTP ${n.status}`);return s}function ji(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
605
605
  `).join(`
606
606
  `)}`)}var Sp=new nb().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").option("--startup-timeout <seconds>","seconds each startup step may take (default: 60, longer when the machine is loaded)").action(async e=>{let o=parseInt(e.basePort,10),t=ab(process.cwd(),".agentx-demo"),n;try{n=$p({flag:e.startupTimeout,env:process.env.AGENTX_DEMO_STARTUP_TIMEOUT,config:wp(process.cwd())})}catch(y){console.error(ge.red(y.message)),process.exit(1)}let s=n.seconds*1e3,i=db(t,o),r=Be(t,"mesh-token"),a=!!e.reuse&&Ti(r)&&Ti(Be(i[0].dir,"agentx.json")),c=a?ib(r,"utf8").trim():cb(24).toString("hex"),l=e.keep||e.reuse,g=[],d=process.argv[1];if((!d||!Ti(d))&&(console.error(ge.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!a){if(Ti(t))for(let y of rb(t))kp(Be(t,y),{recursive:!0,force:!0});for(let y of i)gb(y,i,c);Oi(r,c+`
607
- `,{mode:384})}console.log(),console.log(ge.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ge.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ge.dim(" Run `agentx setup` to wire real agents.\n")),console.log(ge.dim(` Startup limit: ${n.seconds}s per step (${n.source})`));let u=!1,f=y=>{if(!u){u=!0;for(let w of g)try{w.kill("SIGTERM")}catch{}setTimeout(()=>{if(!l)try{kp(t,{recursive:!0,force:!0})}catch{}process.exit(y)},800)}};process.on("SIGINT",()=>f(0)),process.on("SIGTERM",()=>f(0));let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD,delete p.OPENAI_API_KEY,delete p.DEEPSEEK_API_KEY,p.INTENT_LEDGER_MODE||="shadow";try{for(let $ of i){let E=vp(Be($.dir,"daemon.log"),"a"),S=bp(process.execPath,[d,"daemon","start","-c",Be($.dir,"agentx.json")],{cwd:$.dir,env:{...p,MESH_TOKEN:c,AGENTX_DEMO_SCRIPT:Be($.dir,"demo-script.json")},stdio:["ignore",E,E]});g.push(S),console.log(ge.dim(` \u25B8 ${$.name} starting on 127.0.0.1:${$.port} (log: ${Be($.dir,"daemon.log")})`))}let y=$=>ua(`${$.name} /health`,async()=>(await fa(`http://127.0.0.1:${$.port}/health`)).ok,s);await y(i[0]);let w=i[0].port+10;{let $=vp(Be(i[0].dir,"board.log"),"a"),E=bp(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:i[0].dir,env:{...p,MESH_TOKEN:c},stdio:["ignore",$,$]});g.push(E)}for(let $ of i.slice(1))await y($);console.log(ge.green(" \u2713 three daemons up")),await ua("dashboard /live",async()=>(await fa(`http://127.0.0.1:${w}/live`)).ok,s),console.log(ge.green(" \u2713 dashboard up")),await ua("mesh discovery (laptop sees both peers)",async()=>((await(await fa(`http://127.0.0.1:${i[0].port}/health`)).json()).mesh||[]).filter(v=>v.healthy&&v.skills?.length).length>=2,s),console.log(ge.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let b=`http://127.0.0.1:${w}/live`;console.log(),console.log(` Dashboard: ${ge.cyan(b)} (all three nodes via the mesh)`),console.log(ge.dim(` Daemon APIs: ${i.map($=>`127.0.0.1:${$.port}`).join(" \xB7 ")}`)),e.open!==!1&&dt(b);let k=async()=>{console.log(),console.log(ge.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),ji("You \u2192 @cx (laptop-paris)",xp,ge.cyan);let $=await ha(i[0].port,"/task",{agent:"cx",message:xp});ji("@cx (laptop-paris)",$.content||"(no content)",ge.green),console.log(),console.log(ge.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let E=await ha(i[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:lb}),S=typeof E.messageId=="string"?E.messageId:E.content||"(no reply)";ji("@builder (vps-nyc)",S,ge.yellow);let v=await ha(i[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${S}`});ji("@cx (laptop-paris)",v.content||"(no content)",ge.green),console.log(),console.log(ge.dim(` Inspect the run: ${b} \xB7 ledger rows on each node record every dispatch`)),console.log(ge.dim(` Worth your time? A star helps others find it: ${ge.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(a?console.log(ge.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await k(),e.once){console.log(),console.log(ge.dim(" --once: shutting down.")),f(0);return}console.log(),console.log(ge.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{k().catch($=>console.error(ge.red(` Replay failed: ${$.message}`)))}),process.stdin.resume()}catch(y){console.error(),console.error(ge.red(` Demo failed: ${y.message}`)),console.error(ge.dim(` Node logs: ${i.map(w=>Be(w.dir,"daemon.log")).join(", ")}`)),f(1)}});import{Command as mb}from"commander";import{randomUUID as pb}from"crypto";import{readFileSync as ub}from"fs";import{resolve as fb}from"path";te();var Ep=new mb().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").option("--channel <name>","channel name the task runs under, as a channel adapter would set it","exec").option("--chat-id <id>","chat id for the session (default: a fresh one), so repeated runs share a history").option("--profile <full|lean>","session profile for this run's channel, overriding session.profileByChannel").action(async(e,o)=>{let t=(e??ub(0,"utf8")).trim();t||ya("no task given (pass it as an argument or on stdin)");let n=T(o.config?fb(o.config):void 0),s=n.agents[o.agent];s||ya(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`),o.profile!==void 0&&o.profile!=="full"&&o.profile!=="lean"&&ya(`--profile must be full or lean, not "${o.profile}"`),o.profile&&(n.session.profileByChannel={...n.session.profileByChannel,[o.channel]:o.profile});let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";Ya(o.agent,s,l,i)}let r=new pc(n,i);try{let l=new fl(n);l.build(),r.setLandscape(l)}catch(l){i(`no landscape: ${l?.message??l}`)}let a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:o.channel,chatId:o.chatId||`exec-${pb()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
607
+ `,{mode:384})}console.log(),console.log(ge.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ge.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ge.dim(" Run `agentx setup` to wire real agents.\n")),console.log(ge.dim(` Startup limit: ${n.seconds}s per step (${n.source})`));let u=!1,f=y=>{if(!u){u=!0;for(let w of g)try{w.kill("SIGTERM")}catch{}setTimeout(()=>{if(!l)try{kp(t,{recursive:!0,force:!0})}catch{}process.exit(y)},800)}};process.on("SIGINT",()=>f(0)),process.on("SIGTERM",()=>f(0));let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD,delete p.OPENAI_API_KEY,delete p.DEEPSEEK_API_KEY,p.INTENT_LEDGER_MODE||="shadow";try{for(let $ of i){let E=vp(Be($.dir,"daemon.log"),"a"),S=bp(process.execPath,[d,"daemon","start","-c",Be($.dir,"agentx.json")],{cwd:$.dir,env:{...p,MESH_TOKEN:c,AGENTX_DEMO_SCRIPT:Be($.dir,"demo-script.json")},stdio:["ignore",E,E]});g.push(S),console.log(ge.dim(` \u25B8 ${$.name} starting on 127.0.0.1:${$.port} (log: ${Be($.dir,"daemon.log")})`))}let y=$=>ua(`${$.name} /health`,async()=>(await fa(`http://127.0.0.1:${$.port}/health`)).ok,s);await y(i[0]);let w=i[0].port+10;{let $=vp(Be(i[0].dir,"board.log"),"a"),E=bp(process.execPath,[d,"board","serve","--bind",e.bind],{cwd:i[0].dir,env:{...p,MESH_TOKEN:c},stdio:["ignore",$,$]});g.push(E)}for(let $ of i.slice(1))await y($);console.log(ge.green(" \u2713 three daemons up")),await ua("dashboard /live",async()=>(await fa(`http://127.0.0.1:${w}/live`)).ok,s),console.log(ge.green(" \u2713 dashboard up")),await ua("mesh discovery (laptop sees both peers)",async()=>((await(await fa(`http://127.0.0.1:${i[0].port}/health`)).json()).mesh||[]).filter(v=>v.healthy&&v.skills?.length).length>=2,s),console.log(ge.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let b=`http://127.0.0.1:${w}/live`;console.log(),console.log(` Dashboard: ${ge.cyan(b)} (all three nodes via the mesh)`),console.log(ge.dim(` Daemon APIs: ${i.map($=>`127.0.0.1:${$.port}`).join(" \xB7 ")}`)),e.open!==!1&&dt(b);let k=async()=>{console.log(),console.log(ge.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),ji("You \u2192 @cx (laptop-paris)",xp,ge.cyan);let $=await ha(i[0].port,"/task",{agent:"cx",message:xp});ji("@cx (laptop-paris)",$.content||"(no content)",ge.green),console.log(),console.log(ge.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let E=await ha(i[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:lb}),S=typeof E.messageId=="string"?E.messageId:E.content||"(no reply)";ji("@builder (vps-nyc)",S,ge.yellow);let v=await ha(i[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${S}`});ji("@cx (laptop-paris)",v.content||"(no content)",ge.green),console.log(),console.log(ge.dim(` Inspect the run: ${b} \xB7 ledger rows on each node record every dispatch`)),console.log(ge.dim(` Worth your time? A star helps others find it: ${ge.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(a?console.log(ge.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await k(),e.once){console.log(),console.log(ge.dim(" --once: shutting down.")),f(0);return}console.log(),console.log(ge.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{k().catch($=>console.error(ge.red(` Replay failed: ${$.message}`)))}),process.stdin.resume()}catch(y){console.error(),console.error(ge.red(` Demo failed: ${y.message}`)),console.error(ge.dim(` Node logs: ${i.map(w=>Be(w.dir,"daemon.log")).join(", ")}`)),f(1)}});import{Command as mb}from"commander";import{randomUUID as pb}from"crypto";import{readFileSync as ub}from"fs";import{resolve as fb}from"path";te();var Ep=new mb().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").option("--channel <name>","channel name the task runs under, as a channel adapter would set it","exec").option("--chat-id <id>","chat id for the session (default: a fresh one), so repeated runs share a history").option("--profile <full|lean>","session profile for this run's channel, overriding session.profileByChannel").action(async(e,o)=>{let t=(e??ub(0,"utf8")).trim();t||ya("no task given (pass it as an argument or on stdin)");let n=T(o.config?fb(o.config):void 0),s=n.agents[o.agent];s||ya(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`),o.profile!==void 0&&o.profile!=="full"&&o.profile!=="lean"&&ya(`--profile must be full or lean, not "${o.profile}"`),o.profile&&(n.session.profileByChannel={...n.session.profileByChannel,[o.channel]:o.profile});let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";Ya(o.agent,s,l,i)}let r=new pc(n,i);try{let l=new fl(n);l.build(),r.setLandscape(l)}catch(l){i(`no landscape: ${l?.message??l}`)}let a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:o.channel,chatId:o.chatId||`exec-${pb()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,costUsd:c.costUsd,billedModel:c.billedModel,durationMs:Date.now()-a})+`
608
608
  `):c.error?console.error(c.error):process.stdout.write(c.content+`
609
609
  `),process.exit(c.error?1:0)});function ya(e){console.error(`agentx exec: ${e}`),process.exit(1)}te();import{Command as yb}from"commander";import De from"chalk";import{Command as hb}from"commander";import _e from"chalk";te();ps();var At=new hb("triage").description("route messages from watched WhatsApp chats to an agent (needs `wacli sync --webhook`)");async function rs(e){let o="",t=await re(n=>{n.whatsappTriage=n.whatsappTriage&&typeof n.whatsappTriage=="object"?n.whatsappTriage:{},n.whatsappTriage.rules=Array.isArray(n.whatsappTriage.rules)?n.whatsappTriage.rules:[],o=e(n.whatsappTriage,n)});t.success||(console.error(_e.red(`\u2717 ${t.error}`)),process.exit(1)),console.log(_e.green(`\u2713 ${o}`)),t.reloaded&&console.log(_e.dim(" daemon hot-reloaded"))}function Tp(e,o){let t=e.rules.find(n=>n.id===o);if(!t)throw new Error(`No watch rule "${o}". See \`agentx whatsapp triage status\`.`);return t}var Ap=(e,o=[])=>[...o,e];At.command("status").description("show triage settings and watch rules").action(()=>{let e=T().whatsappTriage,o=!!process.env[e.secretEnv];console.log(),console.log(` WhatsApp triage: ${e.enabled?_e.green("on"):_e.yellow("off")}`),console.log(` Webhook secret (${e.secretEnv}): ${o?_e.green("set in this shell"):_e.yellow("not set in this shell; the daemon needs it too")}`),console.log(` Batch: ${e.batchSeconds} s \xB7 auto-acknowledge allowed: ${e.allowAutoAck?"yes":"no"}`),console.log(),e.rules.length===0&&console.log(_e.dim(" no watch rules yet: agentx whatsapp triage rule add <id> --agent <agent> --chat <number or JID>"));for(let t of e.rules){let n=t.quietHours?` \xB7 quiet ${t.quietHours.start}\u2013${t.quietHours.end}`:"";console.log(` ${t.enabled?_e.green("\u25CF"):_e.dim("\u25CB")} ${_e.bold(t.id)} \u2192 ${t.agent}${n}${t.autoAck?" \xB7 autoAck":""}`),t.chats.length&&console.log(_e.dim(` chats: ${t.chats.join(", ")}`)),t.senders.length&&console.log(_e.dim(` senders: ${t.senders.join(", ")}`))}console.log()});At.command("on").description("turn triage on").action(()=>rs(e=>(e.enabled=!0,"WhatsApp triage is on")));At.command("off").description("turn triage off").action(()=>rs(e=>(e.enabled=!1,"WhatsApp triage is off")));At.command("log").description("the latest triage results").option("--limit <n>","how many","20").action(e=>{let o=qo();o||(console.error(_e.red("\u2717 can't open .agentx/db.sqlite here; run this from the AgentX folder")),process.exit(1));let t=new Tl(o).recent(Math.max(1,Number(e.limit)||20));if(t.length===0){console.log(_e.dim(" nothing triaged yet"));return}for(let n of t){let s=new Date(n.at).toISOString().slice(0,16).replace("T"," "),i=n.error?_e.red(n.error):`${_e.cyan(n.triage??"?")} ${n.summary}`;console.log(` ${_e.dim(s)} ${n.ruleId} ${n.chatName??n.chat} (${n.messages}) ${i}${n.draftId?_e.dim(` draft whatsapp:${n.draftId}`):""}`)}});var wa=At.command("rule").description("add, remove, enable or disable a watch rule");wa.command("add <id>").description("watch a chat (or people) and send its messages to an agent").requiredOption("--agent <agent>","the agent that triages").option("--chat <jid>","a chat to watch: phone number, contact JID or group JID (repeatable)",Ap).option("--sender <jid>","only messages from this person (repeatable)",Ap).option("--prompt <text>","extra instructions for the agent").option("--quiet <range>","no notifications in this window, e.g. 22:00-07:00").option("--auto-ack","send short acknowledgements without asking (also needs allowAutoAck)").action((e,o)=>rs((t,n)=>{if(!n.agents?.[o.agent])throw new Error(`No agent "${o.agent}" on this computer.`);if(t.rules.some(i=>i.id===e))throw new Error(`Watch rule "${e}" already exists.`);let s={id:e,agent:o.agent,chats:o.chat??[],senders:o.sender??[]};if(o.prompt&&(s.prompt=o.prompt),o.quiet){let i=String(o.quiet).match(/^(\d{2}:\d{2})-(\d{2}:\d{2})$/);if(!i)throw new Error("--quiet looks like 22:00-07:00");s.quietHours={start:i[1],end:i[2]}}return o.autoAck&&(s.autoAck=!0),t.rules.push(s),`added watch rule "${e}" \u2192 ${o.agent}`}));wa.command("remove <id>").description("delete a watch rule").action(e=>rs(o=>(Tp(o,e),o.rules=o.rules.filter(t=>t.id!==e),`removed watch rule "${e}"`)));for(let[e,o]of[["enable",!0],["disable",!1]])wa.command(`${e} <id>`).description(`${e} a watch rule`).action(t=>rs(n=>(Tp(n,t).enabled=o,`watch rule "${t}" ${o?"enabled":"disabled"}`)));var Mo=new yb().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Mo.addCommand(At);Mo.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let t=(await as("/whatsapp/chats")).chats??[];if(e.group&&(t=t.filter(n=>n.isGroup)),e.dm&&(t=t.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(De.dim(" no chats cached yet"));return}console.log(),console.log(De.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?De.cyan("group"):De.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${De.dim(n.jid.padEnd(40))} ${De.dim(i)}`)}console.log()}catch(o){bn(o)}});Mo.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let t=(await as("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(De.dim(" no contacts cached yet"));return}console.log(),console.log(De.bold(` ${t.length} contact${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=(n.name||n.pushName||n.phone||n.jid).padEnd(30),i=n.phone?`+${n.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${De.dim(i)} ${De.dim(n.jid)}`)}console.log()}catch(o){bn(o)}});Mo.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let o={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(o.agent=e.agent);let t=await ba("/whatsapp/ingest",o);$a(t,!!e.dryRun)}catch(o){bn(o)}});Mo.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};o.agent&&(t.agent=o.agent);let n=await ba("/whatsapp/ingest",t);$a(n,!!o.dryRun)}catch(t){bn(t)}});Mo.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e};o.agent&&(t.agent=o.agent),o.messages&&(t.forceMode="messages");let n=await ba("/whatsapp/ingest",t);$a(n,!!o.dryRun)}catch(t){bn(t)}});Mo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await as("/whatsapp/state"),o=await as("/whatsapp/chats"),t=await as("/whatsapp/contacts");console.log(),console.log(De.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${o.chats?.length??0}`),console.log(` cached contacts: ${t.contacts?.length??0}`),console.log()}catch(e){bn(e)}});function $a(e,o){if(console.log(),console.log(De.bold(o?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(De.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(De.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(De.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(De.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(De.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function jp(){try{let e=T(),[o,t]=e.node.bind.split(":");return`http://${o||"127.0.0.1"}:${t||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function as(e){let o=await fetch(`${jp()}${e}`,{signal:AbortSignal.timeout(1e4)}),t=await o.json().catch(()=>({}));if(!o.ok)throw new Error(t.error||`HTTP ${o.status}`);return t}async function ba(e,o){let t=await fetch(`${jp()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(6e5)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);return n}function bn(e){console.error(De.red(` ${e.message||e}`)),process.exit(1)}te();import{Command as wb}from"commander";import ue from"chalk";import{existsSync as $b,mkdirSync as Op,writeFileSync as cs}from"fs";import{join as kn,resolve as bb}from"path";var ls=new wb().name("plugin").description("manage agentx plugins (Move B)");ls.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=T().plugins??[];if(console.log(),o.length===0){console.log(ue.dim(" No plugins configured.")),console.log(ue.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(ue.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${ue.cyan(t)}`);console.log(),console.log(ue.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(ue.red(` ${e.message}`)),process.exitCode=1}});ls.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,o)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(ue.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let t=e.startsWith("@")?e.split("/")[1]:e,n=bb(o.cwd,t);$b(n)&&!o.force&&(console.log(ue.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Op(n,{recursive:!0}),Op(kn(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;cs(kn(n,"package.json"),Sb(e,s)),cs(kn(n,"tsconfig.json"),Eb()),cs(kn(n,"src/index.ts"),Ab(e)),cs(kn(n,"README.md"),Tb(e,s)),cs(kn(n,".gitignore"),jb()),console.log(),console.log(ue.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(ue.bold(" Next steps:")),console.log(ue.dim(` cd ${t}`)),console.log(ue.dim(" pnpm install")),console.log(ue.dim(" pnpm build")),console.log(ue.dim(" pnpm link --global # for local testing")),console.log(ue.dim(" # then in your agentx project:")),console.log(ue.dim(` pnpm link --global ${e}`)),console.log(ue.dim(` agentx config set plugins[0] "${e}"`)),console.log(ue.dim(" agentx plugin doctor")),console.log()});ls.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=T().plugins??[];if(console.log(),o.length===0){console.log(ue.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await kb(n);s.kind==="ok"?console.log(` ${ue.green("\u2713")} ${ue.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${ue.red("\u2717")} ${ue.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(ue.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(ue.red(` ${e.message}`)),process.exitCode=1}});async function kb(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=vb(o);if(!xb(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=rl.safeParse(t.manifest);return n.success?{kind:"ok",manifestName:n.data.name,manifestVersion:n.data.version}:{kind:"fail",reason:`manifest invalid: ${n.error.issues.map(i=>i.message).join("; ")}`}}function vb(e){if(e==null||typeof e!="object")return e;let o=e;if(o.default&&typeof o.default=="object"){let t=o.default;if(t.manifest&&typeof t.setup=="function")return t;if(t.default&&typeof t.default=="object"){let n=t.default;if(n.manifest&&typeof n.setup=="function")return n}}return o.manifest&&typeof o.setup=="function"?o:o.default??o}function xb(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Sb(e,o){return JSON.stringify({name:e,version:"0.1.0",description:o,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
610
610
  `}function Eb(){return JSON.stringify({compilerOptions:{target:"es2020",module:"commonjs",lib:["es2020"],declaration:!0,outDir:"dist",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node"},include:["src/**/*.ts"]},null,2)+`
@@ -675,7 +675,7 @@ Restart the daemon to activate.
675
675
  dist/
676
676
  *.log
677
677
  .env
678
- `}import{Command as Ob}from"commander";import Pe from"chalk";import{writeFileSync as Cb,mkdirSync as Ib,existsSync as Ci,readFileSync as Cp,appendFileSync as Ip}from"fs";import{resolve as vn,dirname as _p}from"path";import{homedir as va}from"os";var Dp=new Ob().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:o}=await import("./program-LSQMLS6W.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=_b(t);break;case"bash":s=qb(t);break;case"fish":s=Ub(t);break;default:console.error(Pe.red(`unsupported shell: ${n}`)),console.error(Pe.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?vn(String(e.output)):Nb(n);Ib(_p(i),{recursive:!0}),Cb(i,s),console.log(Pe.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Rb(n,i,!!e.yes)});function Nb(e){let o=va();switch(e){case"zsh":return vn(o,".zsh","completions","_agentx");case"bash":return vn(o,".bash_completion.d","agentx.bash");case"fish":return vn(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Rb(e,o,t){if(e==="zsh"){let n=vn(va(),".zshrc"),s=_p(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ci(n)?Cp(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Pe.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ci(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Ip(n,g.join(`
678
+ `}import{Command as Ob}from"commander";import Pe from"chalk";import{writeFileSync as Cb,mkdirSync as Ib,existsSync as Ci,readFileSync as Cp,appendFileSync as Ip}from"fs";import{resolve as vn,dirname as _p}from"path";import{homedir as va}from"os";var Dp=new Ob().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:o}=await import("./program-V2JEVJAD.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=_b(t);break;case"bash":s=qb(t);break;case"fish":s=Ub(t);break;default:console.error(Pe.red(`unsupported shell: ${n}`)),console.error(Pe.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?vn(String(e.output)):Nb(n);Ib(_p(i),{recursive:!0}),Cb(i,s),console.log(Pe.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Rb(n,i,!!e.yes)});function Nb(e){let o=va();switch(e){case"zsh":return vn(o,".zsh","completions","_agentx");case"bash":return vn(o,".bash_completion.d","agentx.bash");case"fish":return vn(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Rb(e,o,t){if(e==="zsh"){let n=vn(va(),".zshrc"),s=_p(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ci(n)?Cp(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Pe.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ci(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Ip(n,g.join(`
679
679
  `)+`
680
680
  `),console.log(Pe.green("\u2713 Patched ~/.zshrc")),console.log(Pe.dim("Reload your shell: exec zsh"));return}console.log(Pe.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Pe.cyan(` ${i}`)),l&&console.log(Pe.cyan(` ${r}`)),console.log(),console.log(Pe.dim("Then reload: exec zsh")),console.log(Pe.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=vn(va(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Ci(n)?Cp(n,"utf-8"):"").includes(o)){console.log(Pe.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Ci(n)){Ip(n,`
681
681
  # agentx completion
@@ -691,4 +691,4 @@ ${Fb({...o,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
691
691
  ${t.url}`)}catch(o){console.error(Sn.red(` ${o.message}`)),process.exitCode=1}});gs.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",Sa).action(async(e,o)=>{try{let t=await Ta(o.models);if(!Ea(o.model,t)){console.log(Aa(o.model,t)),process.exitCode=1;return}let n=e==="-"?await Jb():await Bb(e,"utf8"),s=JSON.parse(n),{version:i}=await ws(),r=qp({...s,fields:s.fields??{}},{model:o.model,version:i??"unknown"});console.log(r)}catch(t){console.error(Sn.red(` ${t.message}`)),process.exitCode=1}});async function Jb(){let e=[];for await(let o of process.stdin)e.push(o);return Buffer.concat(e).toString("utf8")}async function vI(){let e=await ws(),o=new Hb().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");o.hook("preAction",(t,n)=>{let s=td(n);nd(s)&&od("cli",s)});for(let t of[Rd,Nd,ln,Ft,Jt,co,Hl,gt,Js,No,_o,rn,Em,et,Bs,lp,Ko,ng,sg,pg,Yn,Sg,jg,og,Ig,Ng,Vg,Zg,em,Ao,kt,up,qn,Go,Dp,gs])o.addCommand(t);for(let t of Fp)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Fp.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Gb(t,74," "),""].join(`
692
692
  `)}),o}var Fp=[ne,mn,st,$o,Wn,tn,Qe,Po,ot,bt,hn,yn,Vo,ze,Yt,li,rp,ap,Io,io,cd,pt,ls,br,nt,oo,Gt,kr,xi,To,Mo,Sp,Ep,pp];function Gb(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
693
693
  `)}export{vI as buildProgram};
694
- //# sourceMappingURL=program-LSQMLS6W.js.map
694
+ //# sourceMappingURL=program-V2JEVJAD.js.map