agentix-cli 0.185.0 → 0.185.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{board-dashboard-TCZ3RAQR.js → board-dashboard-BIERRXDD.js} +12 -8
- package/dist/{board-dashboard-TCZ3RAQR.js.map → board-dashboard-BIERRXDD.js.map} +1 -1
- package/dist/{chunk-JJ7FHH53.js → chunk-BIYEGA7Q.js} +2 -2
- package/dist/{chunk-LZVQ4N2Z.js → chunk-BXTSO66H.js} +2 -2
- package/dist/{chunk-Z5DHUJIL.js → chunk-MYFTR4NH.js} +2 -2
- package/dist/{chunk-P7K5ZQVT.js → chunk-TAZIS2VP.js} +2 -2
- package/dist/{chunk-2HZXLYWQ.js → chunk-UXWG4DMD.js} +3 -3
- package/dist/{chunk-BLWVMGSJ.js → chunk-XPZSEDE3.js} +1 -1
- package/dist/chunk-XPZSEDE3.js.map +1 -0
- package/dist/{chunk-DSIPKP2D.js → chunk-ZRC2ZHHE.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{doctor-DKW3EP3O.js → doctor-NPHNPYHR.js} +2 -2
- package/dist/{grants-COGXFWO3.js → grants-3UVDASRI.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/{program-2DFU4DCC.js → program-GQ3YWR5W.js} +5 -5
- package/package.json +1 -1
- package/dist/chunk-BLWVMGSJ.js.map +0 -1
- /package/dist/{chunk-JJ7FHH53.js.map → chunk-BIYEGA7Q.js.map} +0 -0
- /package/dist/{chunk-LZVQ4N2Z.js.map → chunk-BXTSO66H.js.map} +0 -0
- /package/dist/{chunk-Z5DHUJIL.js.map → chunk-MYFTR4NH.js.map} +0 -0
- /package/dist/{chunk-P7K5ZQVT.js.map → chunk-TAZIS2VP.js.map} +0 -0
- /package/dist/{chunk-2HZXLYWQ.js.map → chunk-UXWG4DMD.js.map} +0 -0
- /package/dist/{chunk-DSIPKP2D.js.map → chunk-ZRC2ZHHE.js.map} +0 -0
- /package/dist/{doctor-DKW3EP3O.js.map → doctor-NPHNPYHR.js.map} +0 -0
- /package/dist/{grants-COGXFWO3.js.map → grants-3UVDASRI.js.map} +0 -0
- /package/dist/{program-2DFU4DCC.js.map → program-GQ3YWR5W.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ch,b as zi,g as lh}from"./chunk-GSQ2RCOZ.js";import{b as rh}from"./chunk-7EMPPP3E.js";import{$ as Bf,A as xf,B as Sf,C as Af,E as co,G as Tf,H as Cf,I as jf,J as Pf,L as _f,M as Df,N as Mf,O as ul,P as Lf,U as qf,V as Ff,W as ml,X as Uf,_ as Wf,aa as Jf,ba as Hf,ca as Kf,da as Xf,ea as Vf,ga as pl,ha as Qf,ja as Zf,ka as eh,l as ff,la as th,m as hf,q as wf,r as yf,t as bf,v as ks,w as vs,x as $f,y as kf,z as vf}from"./chunk-
|
|
1
|
+
import{a as ch,b as zi,g as lh}from"./chunk-GSQ2RCOZ.js";import{b as rh}from"./chunk-7EMPPP3E.js";import{$ as Bf,A as xf,B as Sf,C as Af,E as co,G as Tf,H as Cf,I as jf,J as Pf,L as _f,M as Df,N as Mf,O as ul,P as Lf,U as qf,V as Ff,W as ml,X as Uf,_ as Wf,aa as Jf,ba as Hf,ca as Kf,da as Xf,ea as Vf,ga as pl,ha as Qf,ja as Zf,ka as eh,l as ff,la as th,m as hf,q as wf,r as yf,t as bf,v as ks,w as vs,x as $f,y as kf,z as vf}from"./chunk-TAZIS2VP.js";import{n as fl}from"./chunk-YTS54UZ5.js";import{a as oh,b as nh,d as yr,e as sh}from"./chunk-OJ53ATNN.js";import{a as ih,b as ah}from"./chunk-PN42ECV3.js";import"./chunk-EFGAPAYZ.js";import{d as Of,e as gl,h as If,i as Nf}from"./chunk-CTN4KYE6.js";import{a as Gf,c as zf,d as Yf}from"./chunk-TADIDWYZ.js";import"./chunk-QAWKN2N4.js";import"./chunk-DODL5POT.js";import{a as jt}from"./chunk-A4PW7EIK.js";import{a as Ef,c as Rf}from"./chunk-MYFTR4NH.js";import{a as ll}from"./chunk-LNY6N73E.js";import{a as km,b as Bc}from"./chunk-CZMVJP7O.js";import{a as Lc,b as om}from"./chunk-RKPAVWXF.js";import{$ as Wp,A as pp,Aa as il,B as Xc,Ba as lf,C as fp,Ca as gf,D as hp,Da as cl,E as wp,Ea as mf,F as yp,Fa as Hi,G as bp,Ga as $s,H as $p,Ha as Gi,I as Mi,Ia as dl,J as kp,Ja as pf,K as Vc,L as vp,M as xp,N as Sp,O as Ap,P as Ep,Q as Li,R as Ip,S as Pp,T as _p,U as Dp,V as Mp,W as Lp,X as Zc,Y as qp,Z as Fp,_ as Up,a as vm,aa as Bp,b as xm,ba as Jp,ca as Hp,da as Gp,ea as Zp,fa as Ui,ga as Eo,h as xi,ha as Wo,i as Rm,ia as ws,j as mr,ja as Wi,k as Si,ka as Bi,l as Cm,la as rl,m as Im,ma as ef,n as Bm,na as tf,o as Jm,oa as of,p as Oi,pa as nf,q as zc,qa as sf,r as Vm,ra as rf,s as cp,sa as ys,t as lp,ta as bs,u as dp,ua as af,v as gp,va as hr,w as Di,wa as cf,x as up,xa as lt,y as mp,ya as Ji,z as Kc,za as wr}from"./chunk-UXWG4DMD.js";import{$a as Yp,Gb as df,Hb as al,Oa as pr,Q as np,Ra as el,S as Pi,Sa as qi,T as sp,Ta as zp,Vb as ao,W as rp,X as _i,Xb as uf,_a as Uo,ab as tl,cb as ol,ea as Rp,eb as Kp,fa as Tp,fb as Xp,ga as Cp,gb as fr,ha as Qc,ka as Op,kb as Fi,nb as Vp,ob as Qp,pb as nl,v as Om,wb as sl}from"./chunk-BXTSO66H.js";import"./chunk-GTJIKXDB.js";import{a as Sm,c as Jc,e as Am,f as Em}from"./chunk-NBWSZ53L.js";import"./chunk-ZVP6GB4G.js";import{F as Ri,G as Um,H as Wm,L as ip,M as ap,a as Dc,b as Xu,e as Vu,f as Qu,n as Ai,o as Ei,p as Nm,q as jm,r as Pm,t as _m,u as Dm,w as Mm,x as Lm,y as qm,z as Fm}from"./chunk-ZRC2ZHHE.js";import"./chunk-IMLAPB7G.js";import"./chunk-VZLIBDLH.js";import{a as Np,b as jp}from"./chunk-EKJG63EJ.js";import"./chunk-NHW4IY6N.js";import{c as Hm}from"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import{b as Gc}from"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import{c as Gm,e as Ti,g as Ci}from"./chunk-LQE73AZR.js";import{a as zm,b as Ym,c as Km,d as Xm}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-BIYEGA7Q.js";import{d as Qm,e as hn,f as Zm,g as Ii,j as ep,k as tp,m as op,n as Yc,q as Ni,r as Ao,s as ji}from"./chunk-XPZSEDE3.js";import"./chunk-PPUN7YHA.js";import"./chunk-A5GYG56I.js";import{a as Hc,p as Tm}from"./chunk-2V6ZGE74.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as Nt}from"./chunk-UKUH662W.js";import"./chunk-JWDJMFU6.js";import{a as io}from"./chunk-MNG2AMKZ.js";import{a as dm,b as gm,c as um,d as mm,e as Fc,f as pm,g as Uc,h as Wc,l as fm,m as hm}from"./chunk-RX5O5637.js";import{f as wm,i as ym,l as bm,m as $m}from"./chunk-5ELIX7BQ.js";import"./chunk-X7UQY7CH.js";import{a as Mc,d as Zu,e as vi}from"./chunk-QPABR72X.js";import{a as ur,e as nm,f as sm,g as qc,i as rm,j as im,l as am,m as cm,n as lm}from"./chunk-V4IOGISL.js";import{b as hs,e as tm}from"./chunk-AJ5HMDRW.js";import{c as em}from"./chunk-KP7KDLZ2.js";import{B as Ic,C as Ou,O as Fo,U as Hu,X as zu,Y as Yu,g as vu,r as xu,ya as Ku}from"./chunk-UASRZKZQ.js";import{I as gs,J as $i,K as ki,L as us,M as Nu,N as Lo,P as qo,b as ds,fa as Bu,r as xo,s as Nc,t as Iu,u as jc,ua as Ju,w as So,wa as Gu,x as bi}from"./chunk-2GIYVYIM.js";import{b as pn}from"./chunk-MEFPXHQJ.js";import"./chunk-2LTZUZJU.js";import"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import{c as Pu}from"./chunk-SZDACK6O.js";import{f as _u,g as Du,h as Pc}from"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{e as Lu,f as fn,k as ps}from"./chunk-VJVXEVZ7.js";import{a as Tu,k as Mu,n as Wu}from"./chunk-RTIGD4NG.js";import{a as Tt,b as de,c as qe,d as fs,e as qu}from"./chunk-NS2HSAHF.js";import{a as Fu,b as _c,h as Uu}from"./chunk-3UOTLMXD.js";import{i as Au,j as Eu}from"./chunk-BE64IJWM.js";import"./chunk-PE5V2LI7.js";import{a as Oc,b as Ru}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Cu}from"./chunk-X5C5W3E4.js";import{a as ms}from"./chunk-GV7S5BAX.js";import{e as ju}from"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import{a as Cc}from"./chunk-FJMTCU4S.js";import"./chunk-BITVUKT7.js";import{c as Su}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-V6QFBL6F.js";import"./chunk-JTFCU5LH.js";import{g as Mo,i as yi}from"./chunk-56F5UTTA.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-R2KSORSK.js";import{a as xc,b as zg,c as mx,d as li,e as Yg,f as pu,g as vx,h as fu,i as xx,m as ls,n as wu,q as yu,u as bu,y as ro,z as gr}from"./chunk-LR4QUAJT.js";import{a as vo,b as cs,e as gu,f as dr}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as wi,b as hu}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{h as Do,j as $u}from"./chunk-QUFIUXMQ.js";import{n as ku}from"./chunk-AV7T3SYT.js";import"./chunk-LE3BXIUF.js";import"./chunk-BERWTVG2.js";import"./chunk-AHWWJ7AF.js";import"./chunk-OSH2PEBH.js";import"./chunk-DCIYOPJF.js";import{a as so,b as ux}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{$ as mi,$a as Tc,F as Ac,G as wx,Gb as oe,Qa as au,Ra as cr,Ta as Rc,U as nu,V as yx,_ as ui,_a as cu,bb as lu,c as di,ca as su,cb as $x,d as Kg,da as ru,e as mn,ea as pi,f as Sc,fa as Ec,h as Xg,hb as du,i as gi,j as px,oa as iu,pa as bx,r as Qg,s as Zg,t as eu,u as tu,v as ou,vb as fi,w as hx,wb as lr,xb as T,zb as hi}from"./chunk-BZJF7DJR.js";import"./chunk-VJ5HC63R.js";import{j as $t,r as as}from"./chunk-UEEB3UTU.js";import{a as Vg,e as fx}from"./chunk-VQRY4IDI.js";import{g as uu,k as mu,l as kx}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as Sx}from"commander";var dh=new Sx().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 xm({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()});oe();import{Command as Ax}from"commander";import{execFileSync as Bt}from"node:child_process";import{cpSync as gh,existsSync as yl,mkdirSync as hl,mkdtempSync as Ex,readdirSync as Rx,rmSync as uh,writeFileSync as mh}from"node:fs";import{dirname as ph,join as dt}from"node:path";import{homedir as Yi,release as Tx,tmpdir as Cx}from"node:os";import{setTimeout as Ox}from"node:timers/promises";function Ki(){let e=Nm(process.platform,process.arch,Tx());if(e)throw new Error(e)}function Xi(){let e=dt(Yi(),"Library/LaunchAgents"),t=[];try{t=Rx(e).filter(_m)}catch{}let o=t.flatMap(n=>{let s=dt(e,n);try{return[{file:s,plist:Bt("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return Dm(e,o)}function br(e){return`gui/${process.getuid()}/${e.label}`}async function wl(e){try{Bt("launchctl",["bootout",br(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Bt("launchctl",["print",br(e)],{stdio:"pipe"})}catch{return}await Ox(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function fh(e){if(!yl(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Bt("launchctl",["print",br(e)],{stdio:"pipe"})}catch{t=!1}t||Bt("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Bt("launchctl",["kickstart",br(e)],{stdio:"pipe"})}function Ix(){let e=Fm();if(e&&yl(dt(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 xs=new Ax("desktop").description("install and control the macOS desktop assistant");xs.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=>{Ki();let t=T(),o=jm(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=Ix(),i=dt(Yi(),"Applications"),{keep:a,remove:c}=Xi();if(console.log(`Desktop assistant \u2192 ${dt(i,Ai)}
|
|
2
2
|
Computer-use helper \u2192 ${dt(i,Ei)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -65,7 +65,7 @@ Remove them first (agentx agent remove <id>, agentx schedule remove <id>), choos
|
|
|
65
65
|
`)[0]}. Run this from the folder that holds agentx.json.`),!1}let n=e==="agent"?!!o.agents?.[t]:t===cr||(o.people??[]).some(s=>s.id===t);return n||An(e==="agent"?`No agent "${t}" in agentx.json.`:`No person "${t}" in agentx.json: agentx people list`),n}async function Vw(e,t,o){if(Xw(e,t))try{await bm(process.cwd(),e,t,km(o)),console.log(Sn.green(` \u2713 picture set for ${e} "${t}". Pages show it on their next load.`))}catch(n){if(n instanceof wm){An(n.message);return}throw n}}function Qw(e,t){Xw(e,t)&&console.log($m(process.cwd(),e,t)?Sn.green(` \u2713 picture removed for ${e} "${t}"; the initials show again.`):Sn.dim(` ${e} "${t}" has no picture.`))}function Jl(e){let t=e.agent?.trim()||So();return t||An("Say which agent: --agent <id>"),t}function Zw(){let e=new Kw("picture").description("an agent's profile picture: set, remove or show (an agent may set its own)");return e.command("set <file>").description("set the picture from a PNG, JPEG or WebP file (1 MB at most); it is cut to a square, metadata dropped").option("--agent <id>","which agent (default: the agent running this command)").action(async(t,o)=>{if(So()){let s=await Bc(t,o.agent?.trim(),{daemonUrl:Yw()});return s.ok?console.log(Sn.green(` \u2713 ${s.message}`)):An(s.message)}let n=Jl(o);n&&await Vw("agent",n,t)}),e.command("remove").alias("rm").description("remove the picture: the initials show again").option("--agent <id>","which agent (default: the agent running this command)").action(async t=>{if(So()){let n=await Bc(null,t.agent?.trim(),{daemonUrl:Yw()});return n.ok?console.log(Sn.green(` \u2713 ${n.message}`)):An(n.message)}let o=Jl(t);o&&Qw("agent",o)}),e.command("show").description("say whether the agent has a picture").option("--agent <id>","which agent (default: the agent running this command)").action(t=>{let o=Jl(t);if(!o)return;let n=ym(process.cwd(),"agent",o);console.log(n?` ${o}: picture set (.agentx/pictures/agent/${o}.${n}.webp)`:Sn.dim(` ${o}: no picture, the initials show`))}),e}function ey(){let e=new Kw("picture").description("a person's profile picture: set or remove (the owner only)"),t=()=>{let o=So();return o&&An(`Only the owner sets a person's picture; agent "${o}" asked.`),!o};return e.command("set <id> <file>").description("set the picture from a PNG, JPEG or WebP file (1 MB at most); it is cut to a square, metadata dropped").action(async(o,n)=>{t()&&await Vw("person",o,n)}),e.command("remove <id>").alias("rm").description("remove the picture: the initials show again").action(o=>{t()&&Qw("person",o)}),e}function Re(){let e=ie(process.cwd(),"agentx.json");if(!Je(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ho(e,"utf-8"))}function ft(e){return de(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(y.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(y.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(y.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var mo=new uo().name("agent").description("manage agents \u2014 add, list, remove, pause, resume");mo.command("list").alias("ls").description("list configured agents").action(()=>{let e=Re();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${y.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(y.dim(` workspace: ${o.workspace}`)),n&&console.log(y.dim(` mentions: ${n}`))}console.log()});mo.command("add").description("add a new agent interactively").action(async()=>{let e=Re(),t=await at([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:g=>/^[a-z0-9-]+$/.test(g)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:ie(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!t.id)return;let o=t.workspace.endsWith(t.id)?t.workspace:Jo(t.workspace,t.id);go(ie(o,".claude/skills"),{recursive:!0});let n={name:t.name,workspace:o,tier:t.tier,model:t.model,mentions:t.mentions?.map(g=>g.trim()).filter(Boolean)||[],maxConcurrent:t.maxConcurrent,systemPrompt:t.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-HAV4CQV7.js"),r=s(t.id,n,"19900",(...g)=>{console.log(y.dim(` ${g.join(" ")}`))}),i=ie(process.cwd(),"src/wiki/SKILL.md"),a=ie(jS(PS(import.meta.url)),"../wiki/SKILL.md"),c=Je(i)?i:a;Je(c)&&(go(ie(o,".claude/skills/wiki"),{recursive:!0}),Hl(c,ie(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await ft(e),console.log(y.green(`
|
|
66
66
|
Agent "${t.id}" added`)),console.log(y.dim(` Workspace: ${o}`)),console.log(y.dim(` Created: ${r.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`));let l=bi(xo(),[t.id]);l&&console.log(y.yellow(` Created by agent "${l}": it starts once the owner approves it (agentx approvals approve agent:${t.id}).`)),console.log()});mo.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=Re();if(!t.agents?.[e]){console.log(y.red(` Agent "${e}" not found`));return}delete t.agents[e],await ft(t),jc(xo(),e),console.log(y.green(` Agent "${e}" removed from config (workspace preserved)`))});mo.addCommand(Zw());function ty(e){let t=So();return t?(console.log(y.red(` Only the owner can ${e}; agent "${t}" asked. Ask the owner, or raise a card.`)),process.exitCode=1,!1):!0}mo.command("pause <id>").description("pause an agent: it starts no run until resumed (applies at once)").action(e=>{if(ty("pause an agent")){if(!Re().agents?.[e]){console.log(y.red(` Agent "${e}" not found`)),process.exitCode=1;return}if(Nc(xo())[e]?.kind==="approval"){console.log(y.yellow(` "${e}" waits for your approval and does not run yet: agentx approvals list`));return}Iu(xo(),e,"paused","the owner"),console.log(y.green(` "${e}" paused. Messages and schedules for it are refused until you run: agentx agent resume ${e}`))}});mo.command("resume <id>").description("resume a paused agent").action(e=>{if(!ty("resume an agent"))return;let t=Nc(xo())[e];if(t?.kind==="approval"){console.log(y.yellow(` "${e}" was created by ${t.by} and waits for your approval: agentx approvals approve agent:${e}`));return}console.log(jc(xo(),e,"paused")?y.green(` "${e}" resumed`):y.dim(` "${e}" was not paused`))});mo.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,t)=>{let o=Re(),n=o.agents?.[e];if(n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log(y.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):y.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":y.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||y.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(t.intents!==void 0&&(t.intents==="-"||t.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(t.intents).split(",").map(r=>r.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),t.maxDelegationDepth!==void 0){let r=parseInt(t.maxDelegationDepth,10);(!Number.isFinite(r)||r<0||r>50)&&(console.log(y.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=r,s.push(`maxDelegationDepth=${r}`)}if(t.contextReferences!==void 0){let r=String(t.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(r)||(console.log(y.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=r==="true"||r==="on"||r==="1",s.push(`contextReferences=${n.contextReferences}`)}if(t.contextStrategy!==void 0&&(t.contextStrategy==="-"||t.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(t.contextStrategy)?(n.contextStrategy=t.contextStrategy,s.push(`contextStrategy=${t.contextStrategy}`)):(console.log(y.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),t.maxExecutionMinutes!==void 0){let r=parseInt(t.maxExecutionMinutes,10);(!Number.isFinite(r)||r<1||r>240)&&(console.log(y.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=r,s.push(`maxExecutionMinutes=${r}`)}s.length===0&&(console.log(y.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await ft(o),console.log(y.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(y.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Cr=new uo().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Cr.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,t)=>{let n=Re().agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(t.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(y.dim(`
|
|
67
67
|
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
68
|
-
`));return}console.log(),console.log(y.bold(` ${e}`));for(let r of s){let i=r.enabled!==!1,a=[],c=r.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?y.green(`${g}:${d}=set`):y.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(y.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(y.dim(`sessionDir:${d}`));let l=Object.entries(r.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${i?y.cyan(r.kind.padEnd(14)):y.dim(r.kind.padEnd(14))} ${y.bold(r.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${y.dim(l)}`),i||console.log(` ${y.dim("(disabled)")}`)}console.log()});Cr.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,t)=>{let o=Re();o.agents?.[e]||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-RHCIE7VE.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await at({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(p=>({title:p,value:p}))})).kind||"").trim()),r||(console.log(y.red(" --kind is required")),process.exit(1));let i=String(t.label||"").trim();!i&&n&&(i=((await at({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),i||(console.log(y.red(" --label is required")),process.exit(1));let a=String(t.tokenEnv||"").trim(),c=String(t.auth||"").trim(),l=String(t.sessionDir||"").trim();if(!a&&!c&&!l&&n){let f=await at({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});f.scheme==="tokenEnv"?a=((await at({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():f.scheme==="keyring"?c="keyring":f.scheme==="sessionDir"&&(l=((await at({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${r}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(t.metadata)for(let f of String(t.metadata).split(",")){let[p,...u]=f.split("=");p&&(g[p.trim()]=u.join("=").trim())}else if(n){let f=await at({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(f.metadata)for(let p of String(f.metadata).split(",")){let[u,...h]=p.split("=");u&&(g[u.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(y.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(y.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),o.agents[e].integrations=o.agents[e].integrations??[],o.agents[e].integrations.find(f=>f.kind===r&&f.label===i)&&(console.log(y.red(` Integration (${r}, ${i}) already exists on ${e}`)),process.exit(1)),o.agents[e].integrations.push({kind:r,label:i,credentials:d,metadata:g,enabled:!0}),await ft(o),console.log(y.green(` \u2713 ${e}: added ${r} integration "${i}"`)),a&&!process.env[a]&&console.log(y.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Cr.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=Re(),n=o.agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[r,i]=t.includes(":")?t.split(":",2):[t,""],a=s.findIndex(l=>l.kind===r&&(!i||l.label===i)||l.label===t);a===-1&&(console.log(y.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await ft(o),console.log(y.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Cr.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=Re().agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],r=t?s.filter(a=>a.kind===t||a.label===t||`${a.kind}:${a.label}`===t):s;if(!r.length){console.log(y.yellow(" no integrations to test"));return}let i=0;console.log();for(let a of r){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){i+=1,console.log(` ${y.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${y.dim(g)}`)}else console.log(` ${y.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),i>0&&process.exit(1)});mo.addCommand(Cr);var da=new uo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");da.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Re();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(y.bold(" Telegram:"));for(let[r,i]of Object.entries(t.accounts||{}))console.log(` ${y.cyan(r)} -> agent: ${i.agentBinding}`)}else console.log(y.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(y.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let r of o.routes||[]){let i=r.contact?`contact ${r.contact}`:`group "${r.group}"`;console.log(` ${i} -> agent: ${r.agent}`)}}else console.log(y.dim(" WhatsApp: disabled"));let n=e.channels?.email;if(n?.enabled&&Object.keys(n.accounts||{}).length){console.log(y.bold(" Email:"));for(let[r,i]of Object.entries(n.accounts))console.log(` ${r}: ${i.address} -> agent: ${i.agent}, replies ${i.send==="auto"?"sent at once":"wait for approval"}`)}else console.log(y.dim(" Email: disabled (agentx connect email)"));let s=e.channels?.gitlab;if(s?.enabled){console.log(y.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let r of s.routes||[])console.log(` ${r.project} -> agent: ${r.agent}`)}else console.log(y.dim(" GitLab: disabled"));console.log()});da.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=Re(),t=Object.keys(e.agents||{});if(!t.length){console.log(y.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await at({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await at([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:o}]);if(!s.accountName||!s.token)return;try{let i=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!i.ok)throw new Error(i.description);console.log(y.green(` Bot verified: @${i.result.username}`));let a=`@${i.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,i.result.username),e.agents[s.agentBinding].mentions=c)}catch(r){console.log(y.red(` Invalid token: ${r.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await ft(e),console.log(y.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await at([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let r=[],i=s.addRoute;for(;i;){let a=await at([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&r.push({[a.type]:a.value,agent:a.agent}),i=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:r},await ft(e),go(ie(process.cwd(),s.sessionDir),{recursive:!0}),console.log(y.green(` WhatsApp enabled (${r.length} routes, default: ${s.defaultAgent})`)),console.log(y.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await at([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let r=[],i=s.addRoute;for(;i;){let a=await at([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&r.push({project:a.project,agent:a.agent}),i=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:r},await ft(e),console.log(y.green(` GitLab enabled (${r.length} routes, webhook :${s.webhookPort})`)),console.log(y.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(y.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(y.dim(` Secret token: ${s.webhookSecret}`)),console.log(y.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(y.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var js=new uo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");js.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Re();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?y.green("\u25CF"):y.dim("\u25CB");console.log(` ${n} ${y.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(y.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(y.dim(" No cron jobs configured")),console.log()});js.command("add").description("add a cron job").action(async()=>{let e=Re(),t=Object.keys(e.agents||{}),o=await at([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:t.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await ft(e),console.log(y.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});js.command("enable <id>").description("enable a cron job").action(async e=>{let t=Re();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(y.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await ft(t),console.log(y.green(` Cron "${e}" enabled`))});js.command("disable <id>").description("disable a cron job").action(async e=>{let t=Re();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await ft(t),console.log(y.green(` Cron "${e}" disabled`))});var Dt=new uo().name("mesh").description("manage mesh peers \u2014 add, list, remove");Dt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Re();if(console.log(),!e.mesh?.enabled)console.log(y.dim(" Mesh: disabled"));else{console.log(y.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=y.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=y.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${y.cyan(t.name)} ${y.dim(t.url)} ${o}`)}}console.log()});Dt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Re(),t=await at([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(y.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(y.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:t.url,name:t.name,...t.token?{token:t.token}:{}}),await ft(e),console.log(y.green(` Peer "${t.name}" added`)),console.log()}});Dt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=Re();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await ft(t),console.log(y.green(` Peer "${e}" removed`)))});Dt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let t=Re();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(y.red(" --interval must be 5..3600 seconds")),process.exit(1)),t.mesh.healthCheck.interval=n,o.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(y.red(" --timeout must be 1..60 seconds")),process.exit(1)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log(y.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await ft(t),console.log(y.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(y.dim(" Restart the daemon for the new cadence to take effect."))});Dt.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,t)=>{let o=t.node||"";if(!o)try{o=T().dashboard?.daemonUrl||""}catch{}o=(o||"http://localhost:18800").replace(/\/+$/,"");let n=t.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let r=await fetch(`${o}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...t.by?{by:t.by}:{}}),signal:AbortSignal.timeout(1e4)}),i=await r.json().catch(()=>({}));r.ok||(console.log(y.red(` Announcement refused (${r.status}): ${i.error||"unknown error"}`)),process.exit(1)),console.log(y.green(` \u2713 Announced from ${i.event?.node??"this machine"}`)+y.dim(` (event ${i.event?.id??"?"})`))}catch(r){console.log(y.red(` Could not reach the daemon at ${o}: ${r?.message||r}`)),process.exit(1)}});var oy=e=>{let t=e||"";if(!t)try{t=T().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function ga(e,t,o={}){let n=oy(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let r=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:s,body:JSON.stringify(o),signal:AbortSignal.timeout(15e3)}),i=await r.json().catch(()=>({}));r.ok||(console.log(y.red(` ${i.error||`HTTP ${r.status}`}`)),process.exit(1));let a=i.grant;console.log(y.green(` \u2713 ${a?.name??e}: ${a?.state}${i.stopped?`, ${i.stopped} running turn(s) stopped`:""}`))}catch(r){console.log(y.red(` Could not reach the daemon at ${n}: ${r?.message||r}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var En=Dt.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");En.command("invite").description("open a grant to a guest mesh and print the one-time code it joins with").requiredOption("--name <name>",'what you call it, e.g. "Support session for company X"').requiredOption("--guest <name>","the other organisation's name").requiredOption("--agent <id>","the agent of this node that works for them").option("--folders <list>","folders that agent may touch for them, comma-separated").option("--skills <list>","skills it may use for them, comma-separated").option("--commands <list>","commands it may run for them, comma-separated").option("--level <level>","report (read only) | propose (no merge, deploy or delete) | act","propose").option("--days <n>","how long the grant lasts (1 to 365)","7").option("--url <origin>","the address the guest reaches this node on (default: dashboard.daemonUrl)").action(async e=>{let{TokenStore:t}=await import("./token-store-F2PHHO5A.js"),{PairCodeStore:o,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:r}=await import("./grants-COGXFWO3.js"),i=T(),a=r({tokens:new t,codes:new o,guests:new s,hasAgent:l=>!!i.agents[l]},{name:e.name,guest:e.guest,agentId:e.agent,folders:e.folders?.split(","),skills:e.skills?.split(","),commands:e.commands?.split(","),level:e.level,days:Number(e.days)});a.ok||(console.log(y.red(` ${a.error}`)),process.exit(1));let c=(e.url||oy()).replace(/\/+$/,"");console.log(),console.log(` Grant ${y.bold(a.grant.name)} for ${y.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(y.dim(` id ${a.grant.id} \xB7 folders: ${a.grant.folders.join(", ")||"none"} \xB7 skills: ${a.grant.skills.join(", ")||"none"} \xB7 commands: ${a.grant.commands.join(", ")||"none"}`)),console.log(),console.log(" Send the guest this address and code. The code works once, for 10 minutes:"),console.log(),console.log(` ${y.cyan(c)}`),console.log(` ${y.bold(n(a.code))}`),console.log(),console.log(` They run: ${y.cyan(`agentx mesh join ${c} --code ${n(a.code)} --name <what-they-call-you>`)}`),console.log(` When they join, a card "Guest mesh: ${a.grant.guest} wants to join" asks you to approve it.`),console.log()});En.command("list",{isDefault:!0}).alias("ls").description("every grant: state, guest, agent, level, end date, usage").option("--json","machine-readable output").action(async e=>{let{GuestStore:t}=await import("./store-7W2AP5H4.js"),o=new t().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(y.dim(`
|
|
68
|
+
`));return}console.log(),console.log(y.bold(` ${e}`));for(let r of s){let i=r.enabled!==!1,a=[],c=r.credentials??{};for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)?a.push(process.env[d]?y.green(`${g}:${d}=set`):y.yellow(`${g}:${d}=UNSET`)):g==="auth"&&d==="keyring"?a.push(y.dim("auth:keyring")):g==="sessionDir"&&typeof d=="string"&&a.push(y.dim(`sessionDir:${d}`));let l=Object.entries(r.metadata??{}).map(([g,d])=>`${g}=${d}`).join(" ");console.log(` ${i?y.cyan(r.kind.padEnd(14)):y.dim(r.kind.padEnd(14))} ${y.bold(r.label)}`),a.length&&console.log(` ${a.join(" ")}`),l&&console.log(` ${y.dim(l)}`),i||console.log(` ${y.dim("(disabled)")}`)}console.log()});Cr.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=alex,email=alex@example.com')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,t)=>{let o=Re();o.agents?.[e]||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let n=t.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-RHCIE7VE.js"),r=String(t.kind||"").trim();!r&&n&&(r=((await at({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(p=>({title:p,value:p}))})).kind||"").trim()),r||(console.log(y.red(" --kind is required")),process.exit(1));let i=String(t.label||"").trim();!i&&n&&(i=((await at({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Acme CRM", "alex@example.com")'})).label||"").trim()),i||(console.log(y.red(" --label is required")),process.exit(1));let a=String(t.tokenEnv||"").trim(),c=String(t.auth||"").trim(),l=String(t.sessionDir||"").trim();if(!a&&!c&&!l&&n){let f=await at({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});f.scheme==="tokenEnv"?a=((await at({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${r.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():f.scheme==="keyring"?c="keyring":f.scheme==="sessionDir"&&(l=((await at({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${r}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(t.metadata)for(let f of String(t.metadata).split(",")){let[p,...u]=f.split("=");p&&(g[p.trim()]=u.join("=").trim())}else if(n){let f=await at({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(f.metadata)for(let p of String(f.metadata).split(",")){let[u,...h]=p.split("=");u&&(g[u.trim()]=h.join("=").trim())}}let d={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(y.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),d.tokenEnv=a),c==="keyring"&&(d.auth="keyring"),l&&(d.sessionDir=l),Object.keys(d).length||(console.log(y.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),o.agents[e].integrations=o.agents[e].integrations??[],o.agents[e].integrations.find(f=>f.kind===r&&f.label===i)&&(console.log(y.red(` Integration (${r}, ${i}) already exists on ${e}`)),process.exit(1)),o.agents[e].integrations.push({kind:r,label:i,credentials:d,metadata:g,enabled:!0}),await ft(o),console.log(y.green(` \u2713 ${e}: added ${r} integration "${i}"`)),a&&!process.env[a]&&console.log(y.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Cr.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,t)=>{let o=Re(),n=o.agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[r,i]=t.includes(":")?t.split(":",2):[t,""],a=s.findIndex(l=>l.kind===r&&(!i||l.label===i)||l.label===t);a===-1&&(console.log(y.red(` No integration matched "${t}"`)),process.exit(1));let c=s.splice(a,1)[0];await ft(o),console.log(y.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Cr.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,t)=>{let n=Re().agents?.[e];n||(console.log(y.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],r=t?s.filter(a=>a.kind===t||a.label===t||`${a.kind}:${a.label}`===t):s;if(!r.length){console.log(y.yellow(" no integrations to test"));return}let i=0;console.log();for(let a of r){let c=a.credentials??{},l=[];for(let[g,d]of Object.entries(c))typeof d=="string"&&/^[A-Z][A-Z0-9_]*$/.test(d)&&!process.env[d]&&l.push(`${g}: env var ${d} is unset`);if(l.length){i+=1,console.log(` ${y.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of l)console.log(` ${y.dim(g)}`)}else console.log(` ${y.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),i>0&&process.exit(1)});mo.addCommand(Cr);var da=new uo().name("channel").description("manage channels \u2014 add telegram/whatsapp/gitlab, list");da.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Re();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(y.bold(" Telegram:"));for(let[r,i]of Object.entries(t.accounts||{}))console.log(` ${y.cyan(r)} -> agent: ${i.agentBinding}`)}else console.log(y.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(y.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let r of o.routes||[]){let i=r.contact?`contact ${r.contact}`:`group "${r.group}"`;console.log(` ${i} -> agent: ${r.agent}`)}}else console.log(y.dim(" WhatsApp: disabled"));let n=e.channels?.email;if(n?.enabled&&Object.keys(n.accounts||{}).length){console.log(y.bold(" Email:"));for(let[r,i]of Object.entries(n.accounts))console.log(` ${r}: ${i.address} -> agent: ${i.agent}, replies ${i.send==="auto"?"sent at once":"wait for approval"}`)}else console.log(y.dim(" Email: disabled (agentx connect email)"));let s=e.channels?.gitlab;if(s?.enabled){console.log(y.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let r of s.routes||[])console.log(` ${r.project} -> agent: ${r.agent}`)}else console.log(y.dim(" GitLab: disabled"));console.log()});da.command("add").description("add a channel (telegram, whatsapp, or gitlab)").action(async()=>{let e=Re(),t=Object.keys(e.agents||{});if(!t.length){console.log(y.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await at({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await at([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:o}]);if(!s.accountName||!s.token)return;try{let i=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!i.ok)throw new Error(i.description);console.log(y.green(` Bot verified: @${i.result.username}`));let a=`@${i.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,i.result.username),e.agents[s.agentBinding].mentions=c)}catch(r){console.log(y.red(` Invalid token: ${r.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await ft(e),console.log(y.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await at([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let r=[],i=s.addRoute;for(;i;){let a=await at([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +10000000000)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&r.push({[a.type]:a.value,agent:a.agent}),i=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:r},await ft(e),go(ie(process.cwd(),s.sessionDir),{recursive:!0}),console.log(y.green(` WhatsApp enabled (${r.length} routes, default: ${s.defaultAgent})`)),console.log(y.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="gitlab"){let s=await at([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let r=[],i=s.addRoute;for(;i;){let a=await at([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&r.push({project:a.project,agent:a.agent}),i=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:r},await ft(e),console.log(y.green(` GitLab enabled (${r.length} routes, webhook :${s.webhookPort})`)),console.log(y.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(y.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(y.dim(` Secret token: ${s.webhookSecret}`)),console.log(y.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(y.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var js=new uo().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");js.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Re();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?y.green("\u25CF"):y.dim("\u25CB");console.log(` ${n} ${y.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(y.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(y.dim(" No cron jobs configured")),console.log()});js.command("add").description("add a cron job").action(async()=>{let e=Re(),t=Object.keys(e.agents||{}),o=await at([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:t.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await ft(e),console.log(y.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});js.command("enable <id>").description("enable a cron job").action(async e=>{let t=Re();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}if(t.crons[e].approval?.action==="create"){console.log(y.yellow(` Cron "${e}" is awaiting approval \u2014 run: agentx schedule approve ${e}`));return}t.crons[e].enabled=!0,await ft(t),console.log(y.green(` Cron "${e}" enabled`))});js.command("disable <id>").description("disable a cron job").action(async e=>{let t=Re();if(!t.crons?.[e]){console.log(y.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await ft(t),console.log(y.green(` Cron "${e}" disabled`))});var Dt=new uo().name("mesh").description("manage mesh peers \u2014 add, list, remove");Dt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Re();if(console.log(),!e.mesh?.enabled)console.log(y.dim(" Mesh: disabled"));else{console.log(y.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=y.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=y.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${y.cyan(t.name)} ${y.dim(t.url)} ${o}`)}}console.log()});Dt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Re(),t=await at([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.64.0.11:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(y.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(y.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:t.url,name:t.name,...t.token?{token:t.token}:{}}),await ft(e),console.log(y.green(` Peer "${t.name}" added`)),console.log()}});Dt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=Re();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await ft(t),console.log(y.green(` Peer "${e}" removed`)))});Dt.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let t=Re();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(y.red(" --interval must be 5..3600 seconds")),process.exit(1)),t.mesh.healthCheck.interval=n,o.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(y.red(" --timeout must be 1..60 seconds")),process.exit(1)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log(y.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await ft(t),console.log(y.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(y.dim(" Restart the daemon for the new cadence to take effect."))});Dt.command("announce <text...>").description("send a short note to every machine in the mesh (shown in event feeds)").option("--by <name>","who the note is from (an agent id or a person's name)").option("--node <url>","daemon to publish on (default: dashboard.daemonUrl, else this machine on port 18800)").option("--token <token>","mesh token, needed only when --node is another machine (default: MESH_TOKEN)").action(async(e,t)=>{let o=t.node||"";if(!o)try{o=T().dashboard?.daemonUrl||""}catch{}o=(o||"http://localhost:18800").replace(/\/+$/,"");let n=t.token||process.env.MESH_TOKEN||"",s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);try{let r=await fetch(`${o}/mesh/announce`,{method:"POST",headers:s,body:JSON.stringify({text:e.join(" "),...t.by?{by:t.by}:{}}),signal:AbortSignal.timeout(1e4)}),i=await r.json().catch(()=>({}));r.ok||(console.log(y.red(` Announcement refused (${r.status}): ${i.error||"unknown error"}`)),process.exit(1)),console.log(y.green(` \u2713 Announced from ${i.event?.node??"this machine"}`)+y.dim(` (event ${i.event?.id??"?"})`))}catch(r){console.log(y.red(` Could not reach the daemon at ${o}: ${r?.message||r}`)),process.exit(1)}});var oy=e=>{let t=e||"";if(!t)try{t=T().dashboard?.daemonUrl||""}catch{}return(t||"http://localhost:18800").replace(/\/+$/,"")};async function ga(e,t,o={}){let n=oy(),s={"Content-Type":"application/json"};process.env.MESH_TOKEN&&(s.Authorization=`Bearer ${process.env.MESH_TOKEN}`);try{let r=await fetch(`${n}/mesh/guests/${encodeURIComponent(e)}/${t}`,{method:"POST",headers:s,body:JSON.stringify(o),signal:AbortSignal.timeout(15e3)}),i=await r.json().catch(()=>({}));r.ok||(console.log(y.red(` ${i.error||`HTTP ${r.status}`}`)),process.exit(1));let a=i.grant;console.log(y.green(` \u2713 ${a?.name??e}: ${a?.state}${i.stopped?`, ${i.stopped} running turn(s) stopped`:""}`))}catch(r){console.log(y.red(` Could not reach the daemon at ${n}: ${r?.message||r}. The daemon must be running: it stops the guest's running turns.`)),process.exit(1)}}var En=Dt.command("guests").description("other organisations let into part of this mesh: open, watch, pause, widen, narrow, end");En.command("invite").description("open a grant to a guest mesh and print the one-time code it joins with").requiredOption("--name <name>",'what you call it, e.g. "Support session for company X"').requiredOption("--guest <name>","the other organisation's name").requiredOption("--agent <id>","the agent of this node that works for them").option("--folders <list>","folders that agent may touch for them, comma-separated").option("--skills <list>","skills it may use for them, comma-separated").option("--commands <list>","commands it may run for them, comma-separated").option("--level <level>","report (read only) | propose (no merge, deploy or delete) | act","propose").option("--days <n>","how long the grant lasts (1 to 365)","7").option("--url <origin>","the address the guest reaches this node on (default: dashboard.daemonUrl)").action(async e=>{let{TokenStore:t}=await import("./token-store-F2PHHO5A.js"),{PairCodeStore:o,formatCode:n}=await import("./pair-codes-EYGELBPD.js"),{GuestStore:s}=await import("./store-7W2AP5H4.js"),{inviteGuest:r}=await import("./grants-3UVDASRI.js"),i=T(),a=r({tokens:new t,codes:new o,guests:new s,hasAgent:l=>!!i.agents[l]},{name:e.name,guest:e.guest,agentId:e.agent,folders:e.folders?.split(","),skills:e.skills?.split(","),commands:e.commands?.split(","),level:e.level,days:Number(e.days)});a.ok||(console.log(y.red(` ${a.error}`)),process.exit(1));let c=(e.url||oy()).replace(/\/+$/,"");console.log(),console.log(` Grant ${y.bold(a.grant.name)} for ${y.bold(a.grant.guest)}: ${a.grant.agentId}, ${a.grant.level}, until ${a.grant.expiresAt.slice(0,10)}`),console.log(y.dim(` id ${a.grant.id} \xB7 folders: ${a.grant.folders.join(", ")||"none"} \xB7 skills: ${a.grant.skills.join(", ")||"none"} \xB7 commands: ${a.grant.commands.join(", ")||"none"}`)),console.log(),console.log(" Send the guest this address and code. The code works once, for 10 minutes:"),console.log(),console.log(` ${y.cyan(c)}`),console.log(` ${y.bold(n(a.code))}`),console.log(),console.log(` They run: ${y.cyan(`agentx mesh join ${c} --code ${n(a.code)} --name <what-they-call-you>`)}`),console.log(` When they join, a card "Guest mesh: ${a.grant.guest} wants to join" asks you to approve it.`),console.log()});En.command("list",{isDefault:!0}).alias("ls").description("every grant: state, guest, agent, level, end date, usage").option("--json","machine-readable output").action(async e=>{let{GuestStore:t}=await import("./store-7W2AP5H4.js"),o=new t().grants().sort((n,s)=>s.createdAt.localeCompare(n.createdAt));if(e.json){console.log(JSON.stringify(o,null,2));return}if(!o.length){console.log(y.dim(`
|
|
69
69
|
No guest grants. Open one: agentx mesh guests invite --name \u2026 --guest \u2026 --agent \u2026
|
|
70
70
|
`));return}console.log();for(let n of o){let s=n.state==="active"?y.green("active"):n.state==="pending"?y.yellow(n.guestNode?"waiting for your approval":"not joined yet"):n.state==="paused"?y.yellow("paused"):y.red(`ended${n.endedReason?`: ${n.endedReason}`:""}`);console.log(` ${y.cyan(n.id)} ${y.bold(n.name)} ${n.guest} \u2192 ${n.agentId} ${n.level} ${s}`),console.log(y.dim(` until ${n.expiresAt.slice(0,10)} \xB7 ${n.usage.turns} turn(s), ${n.usage.tokens} tokens${n.usage.lastAt?` \xB7 last ${n.usage.lastAt.slice(0,16).replace("T"," ")} UTC`:""}${n.guestNode?.name?` \xB7 node ${n.guestNode.name}`:""}`))}console.log()});En.command("show <id>").description("one grant, what it opens and what the guest did").action(async e=>{let{GuestStore:t}=await import("./store-7W2AP5H4.js"),o=new t,n=o.get(e);n||(console.log(y.red(` No grant "${e}". See \`agentx mesh guests\`.`)),process.exit(1)),console.log(),console.log(` ${y.bold(n.name)} (${n.id}) \xB7 ${n.state}`),console.log(` guest: ${n.guest}${n.guestNode?` \xB7 node ${n.guestNode.name??n.guestNode.id??"?"} at ${n.guestNode.address??"?"}`:""}`),console.log(` agent: ${n.agentId} \xB7 level: ${n.level} \xB7 until ${n.expiresAt.slice(0,10)}`),console.log(` folders: ${n.folders.join(", ")||"none"}
|
|
71
71
|
skills: ${n.skills.join(", ")||"none"}
|
|
@@ -551,7 +551,7 @@ People who asked not to be contacted. The sales agent never drafts a message to
|
|
|
551
551
|
Plan ${P.dim(`[${r.state}] by ${r.createdBy}, ${Hn(r.createdAt)}`)}`),L$(s.steps(e)),console.log(`
|
|
552
552
|
Log`);for(let i of s.events(e))console.log(P.dim(` ${Hn(i.at)} ${i.step?`step ${i.step} `:""}${i.kind}: ${i.detail}`))}});on.command("step <id> <step>").description("move a step of a request's plan on: --retry, --skip or --done").option("--retry","hand the step to its agent again, with a fresh count of nudges (approves a message whose card expired)").option("--skip","leave the step out; the plan goes on with the next one").option("--done","mark the step done yourself").option("--note <text>","why, or the evidence for --done").action((e,t,o)=>{let n=["retry","skip","done"].filter(c=>o[c]);if(n.length!==1){console.error(P.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=Jr();if(!s)return;let r=Ga();if(!r){process.exitCode=1;return}let i=Number(t),a=kp(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(P.red(` ${a}`)),process.exitCode=1;return}console.log(P.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+P.dim(" (the daemon goes on within a minute)")),L$(r.steps(e))});function q$(e,t,o,n){let s=on.command(`${e} <id>`).description(t).option(o,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped");e==="done"&&s.option("--reason <text>",'close it by hand without a link, saying why ("checked by hand"); also closes a loop its check cannot verify'),s.action((r,i)=>{let a=Jr();if(!a)return;let c=e==="done"?i.evidence??(i.reason?`closed by owner: ${i.reason}`:void 0):i.reason??"dropped by the owner";if(!c){console.error(P.red(` ${n}`)),process.exitCode=1;return}let l=a.get(r);if(!l||l.state==="candidate"){console.error(P.red(` no request "${r}"`)),process.exitCode=1;return}if(!a.close(r,e==="done"?"done":"dropped",c,Date.now())){console.error(P.red(` ${r} is already closed (${zd[l.state]??l.state})`)),process.exitCode=1;return}console.log(P.green(` \u2713 ${r} ${e==="done"?"closed as done":"dropped"}`))})}q$("done","close a request as finished, with a link to the evidence or the reason","--evidence <link>","a finished request needs --evidence <link> or --reason <text>");q$("drop","drop a request you no longer want","--reason <text>","");on.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").option("--headlines <on|off>","write a headline for a request its agent did not describe (one small model call each)").option("--catch <on|off>","read the reply of each of your turns for a promise or a question to you (one small model call each)").option("--catch-cap <n>","model calls a day the promise catch may make").option("--settle <on|off>","close a quiet request whose handed work all came back done, instead of bringing it back to you").option("--plans <on|off>","follow requests of two or more steps as tracked plans").option("--stall-minutes <n>","minutes without progress before a plan step's agent is nudged").option("--max-nudges <n>","nudges per step before it counts as blocked and you are told").option("--approve-kinds <kind,...>",'step kinds you approve once when the plan is made; "none" to clear').option("--plans-off-for <agent,...>",'agents that may not open a plan; "none" to clear').option("--plan-for <work,...>",'kinds of work an agent must plan before it starts (default code); "none" to clear').option("--plan-over <minutes>","work estimated over this many minutes needs a plan (default 30); 0 turns it off").option("--checks <kind,...>",`checks agents may use to close a loop (${ui.join(", ")}); "none" to turn them all off`).option("--check-every <minutes>","how often each open loop's check runs").action(async e=>{let t={};try{let l=(u,h)=>{if(h===void 0)return;let w=Number(h);if(!(w>0))throw new Error(`${u} must be a positive number`);return w},g=(u,h)=>u===void 0?void 0:u===h?[]:u.split(",").map(w=>w.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");t.enabled=e.enabled==="on"}if(t.from=g(e.from,"none"),t.channels=g(e.channels,"all"),t.staleAfterHours=l("--stale-hours",e.staleHours),t.retentionDays=l("--retention-days",e.retentionDays),e.headlines!==void 0){if(e.headlines!=="on"&&e.headlines!=="off")throw new Error("--headlines takes on or off");t.headlines={enabled:e.headlines==="on"}}if(e.catch!==void 0||e.catchCap!==void 0){if(e.catch!==void 0&&e.catch!=="on"&&e.catch!=="off")throw new Error("--catch takes on or off");let u=l("--catch-cap",e.catchCap);if(u!==void 0&&!Number.isInteger(u))throw new Error("--catch-cap must be a whole number");t.catchPromises={...e.catch!==void 0?{enabled:e.catch==="on"}:{},...u!==void 0?{dailyCap:u}:{}}}if(e.settle!==void 0){if(e.settle!=="on"&&e.settle!=="off")throw new Error("--settle takes on or off");t.settleHandedBack=e.settle==="on"}let d={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");d.enabled=e.plans==="on"}if(d.stallMinutes=l("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let u=Number(e.maxNudges);if(!Number.isInteger(u)||u<0)throw new Error("--max-nudges must be a whole number, 0 or more");d.maxNudges=u}if(d.approveKinds=g(e.approveKinds,"none"),d.disabledAgents=g(e.plansOffFor,"none"),d.requireForWork=g(e.planFor,"none"),e.planOver!==void 0){let u=Number(e.planOver);if(!(u>=0))throw new Error("--plan-over must be a number of minutes, 0 or more");d.requireOverMinutes=u}Object.values(d).some(u=>u!==void 0)&&(t.plans=d);let f={},p=g(e.checks,"none");if(p){let u=p.filter(h=>!ui.includes(h));if(u.length)throw new Error(`unknown check ${u.join(", ")}: use ${ui.join(", ")}`);f.enabled=p}f.checkEveryMinutes=l("--check-every",e.checkEvery),Object.values(f).some(u=>u!==void 0)&&(t.checkers=f)}catch(l){console.error(P.red(` ${l.message}`)),process.exitCode=1;return}if(Object.values(t).some(l=>l!==void 0)){let l=await sp(t);if(!l.success){console.error(P.red(` ${l.error}`)),process.exitCode=1;return}console.log(P.green(" \u2713 saved")+(l.reloaded?P.dim(" (daemon reloaded)"):""))}let o=Pi();console.log(` Requests ${o.enabled?"on":"off"}`),console.log(` Channels ${o.channels.length?o.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${o.from.length?o.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${o.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${o.retentionDays} day(s)`),console.log(` Headlines ${o.headlines?.enabled===!1?"off: titled with the start of your words":"on: written when the agent gave none"}`);let n=o.catchPromises;console.log(` Catch promises ${n?.enabled?`on: each of your turns' reply is read, up to ${n.dailyCap} call(s) a day`:"off"}`),console.log(` Handed work came back ${o.settleHandedBack===!1?"comes back to you when quiet":"closed when quiet, with its link or marked unproven"}`);let s=o.plans??Mi;console.log(` Plans ${s.enabled?"on":"off"}`),console.log(` Nudge a quiet step after ${s.stallMinutes} minute(s), up to ${s.maxNudges} time(s)`),console.log(` You approve up front ${s.approveKinds.length?s.approveKinds.join(", "):"nothing"}`),console.log(` Plans off for ${s.disabledAgents.length?s.disabledAgents.join(", "):"no agent"}`);let r=s.requireOverMinutes??Mi.requireOverMinutes,i=s.requireForWork??Mi.requireForWork;console.log(` Plan before starting ${[i.length?`${i.join(", ")} work`:"",r>0?`work over ${r} minute(s)`:""].filter(Boolean).join("; ")||"never required"}`);let a=o.checkers??mi;console.log(` Loop checks ${a.enabled.length?a.enabled.join(", "):"off"}, every ${a.checkEveryMinutes} minute(s)`);let c=Object.keys(a.repos);console.log(` Repos for git-ancestor ${c.length?c.join(", "):"none (requests.checkers.repos in agentx.json)"}`)});import{Command as LC}from"commander";import Ys from"chalk";oe();var F$=new LC("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",ml.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(Ys.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await de(r=>{n=Uf(r,e,t==="on")});s.success||(console.error(Ys.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(Ys.green(`\u2713 ${n}`)),s.reloaded&&console.log(Ys.dim(" daemon hot-reloaded"))}let o=T().requestStatus.channels.map(n=>n.toLowerCase());for(let n of ml)console.log(` ${n.padEnd(8)} ${o.includes(n)?Ys.green("on"):Ys.dim("off")}`)});import{Command as mO}from"commander";import Ks from"chalk";import ye from"chalk";import Hr from"prompts";import{readFileSync as qC,writeFileSync as FC,existsSync as UC}from"fs";import{resolve as U$}from"path";var WC=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function BC(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Kd(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function W$(e=".env"){let t=U$(e);if(!UC(t))return[];let o=qC(t,"utf-8"),n=[];for(let s of o.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let r=s.match(WC);r?n.push({kind:"kv",key:r[1],value:BC(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function JC(e){return e.map(t=>t.kind==="kv"?`${t.key}=${Kd(t.value)}`:t.raw).join(`
|
|
553
553
|
`)+`
|
|
554
|
-
`}function Gn(e,t,o=".env"){let n=U$(o),s=W$(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Kd(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Kd(t)}`})),FC(n,JC(s))}function Xd(e,t=".env"){return W$(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var B$="https://t.me/BotFather";async function HC(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function GC(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function J$(e={}){console.log(),console.log(ye.bold(" Connect Telegram")),console.log(),console.log(ye.dim(` 1. Open ${B$}`)),console.log(ye.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ye.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Hr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Ro(B$);let{token:o}=await Hr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:S=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(S.trim())||"That doesn't look like a Telegram token"});o||(console.log(ye.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await HC(o.trim());n||(console.log(ye.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ye.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(ye.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ye.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Hr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),g||(console.log(ye.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await Hr({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ye.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Gn(p,o.trim()),process.env[p]=o.trim();let u=await de(S=>{qe(S,"channels.telegram.enabled",!0),qe(S,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let x=fs(S,`agents.${g}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),qe(S,`agents.${g}.mentions`,x))},{configPath:e.configPath});if(u.success||(console.log(ye.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(ye.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ye.dim(` Token stored in .env as ${p}`)),console.log(ye.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(ye.dim(" Daemon hot-reloaded.")):console.log(ye.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Hr({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ye.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ye.dim(" Waiting up to 90s..."));let w=await GC(o.trim(),9e4);if(!w){console.log(ye.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ye.dim(" agentx config set notifications.destination.channel telegram")),console.log(ye.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ye.dim(` agentx config set notifications.destination.accountId ${f}`));return}let b={channel:"telegram",chatId:String(w.chatId),accountId:f},$=[],v=await de(S=>{qe(S,"notifications.destination",b),$=sa(S,b)},{configPath:e.configPath});if(!v.success){console.log(ye.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(ye.green(" \u2713 Default --notify target set")),console.log(ye.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ye.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(ye.dim(` Schedules that now report here: ${$.join(", ")}`)),v.reloaded&&console.log(ye.dim(" Daemon hot-reloaded."))}import Pe from"chalk";import Vd from"prompts";import{existsSync as Zd,mkdirSync as zC,readdirSync as YC,readFileSync as H$}from"fs";import{resolve as Qd}from"path";var KC=".agentx/whatsapp-sessions";function XC(){let e=Qd(process.cwd(),".agentx/daemon.pid");if(!Zd(e))return!1;try{let t=parseInt(H$(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function VC(e){if(!Zd(e))return!1;try{return YC(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function QC(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Pe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Pe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;zC(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(g=>{let f=setTimeout(()=>{t(Pe.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(Pe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:u}=await import("qrcode-terminal");u.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Pe.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Pe.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function G$(e={}){if(console.log(),console.log(Pe.bold(" Connect WhatsApp")),console.log(),XC()){console.log(Pe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Pe.dim(" agentx daemon stop")),console.log();let{cont:l}=await Vd({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Pe.red(" Aborted")),process.exit(1))}let t=e.configPath||Qd(process.cwd(),"agentx.json");Zd(t)||(console.log(Pe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(H$(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||KC,s=Qd(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Pe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Vd({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(Pe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(VC(s)&&a){let{keep:l}=await Vd({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(Pe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await QC(s,g=>console.log(g))||(console.log(Pe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(l=>{qe(l,"channels.whatsapp.enabled",!0),qe(l,"channels.whatsapp.sessionDir",n),qe(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Pe.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Pe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Pe.dim(` Session: ${n}`)),console.log(Pe.dim(" Start the daemon to begin receiving:")),console.log(Pe.dim(" agentx daemon start")),console.log(Pe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Pe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Pe.dim(" Add routes later with:")),console.log(Pe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import At from"chalk";import ZC from"prompts";import{existsSync as eO,readFileSync as tO}from"fs";import{resolve as oO}from"path";async function nO(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function sO(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Io(e){console.log(At.red(` ${e}`)),process.exit(1)}async function zn(e){return(await ZC(e,{onCancel:()=>Io("Aborted")}))[e.name]}async function z$(e={}){console.log(),console.log(At.bold(" Connect email")),console.log();let t=e.configPath||oO(process.cwd(),"agentx.json");eO(t)||Io(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(tO(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Io("No agents configured. Run: agentx agent add");let s=e.agent??await zn({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(b=>({title:b,value:b}))});o.agents?.[s]||Io(`No agent "${s}" in ${t}`);let r=(e.address??await zn({type:"text",name:"address",message:"Email address customers write to:",validate:b=>/^\S+@\S+\.\S+$/.test(b.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=Bf(r),c=e.imapHost??a?.imapHost??await zn({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await zn({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),g=e.smtpHost??a?.smtpHost??await zn({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await zn({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Io("Ports must be numbers.");let f=e.passwordEnv||Hf(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&Io(`${e.passwordEnv} is not set in the environment.`),p||(a?.imapHost==="imap.gmail.com"&&(console.log(At.dim(` Gmail needs an app password, not your account password: ${Wf}`)),console.log(At.dim(" (2-step verification must be on for that page to show.)"))),p=(await zn({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||Io("Aborted");let u={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:g,smtpPort:d,user:e.user,passwordEnv:f,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let b=await nO(u,p);b&&(console.log(At.red("\u2717")),Io(b)),console.log(At.green("\u2713"))}e.passwordEnv||(Gn(f,p),process.env[f]=p);let h=await de(b=>{qe(b,"channels.email.enabled",!0),qe(b,`channels.email.accounts.${i}`,Jf(u))},{configPath:e.configPath});h.success||Io(`Config save failed: ${h.error}`),console.log(),console.log(At.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(At.dim(` Password stored in .env as ${f}`)),console.log(At.dim(` Who may write: ${u.allowFrom.join(", ")}${u.allowFrom.includes("*")?" (anyone)":""}`));let w=sO(o.agents[s]?.tier,u.allowFrom);w&&console.log(At.yellow(` ${w}`)),console.log(u.send==="auto"?At.yellow(" Replies are sent as soon as the agent writes them."):At.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(At.dim(" Only mail that arrives from now on is answered.")),console.log(At.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as rO}from"crypto";import ze from"chalk";import Y$ from"prompts";var za="agentx-mesh:",Ya="//join/";function iO(e){return Buffer.from(e,"utf-8").toString("base64url")}function aO(e){return Buffer.from(e,"base64url").toString("utf-8")}function cO(e){return`${za}${Ya}${iO(JSON.stringify(e))}`}function lO(e){if(!e.startsWith(`${za}${Ya}`))throw new Error(`Not a mesh invite link \u2014 expected ${za}${Ya}\u2026`);let t=e.slice(za.length+Ya.length),o=JSON.parse(aO(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function dO(){return rO(32).toString("hex")}function gO(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function uO(e){return e?.node?.name||e?.node?.id||"node"}async function K$(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(ze.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Xd("MESH_TOKEN");i||(i=dO(),Gn("MESH_TOKEN",i),console.log(ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||gO(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Y$({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(ze.red(" Aborted")),process.exit(1)),a=d}let l=await de(d=>{qe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ze.red(` \u2717 ${l.error}`)),process.exit(1));let g=cO({url:a,token:i,name:uO(r),version:1});console.log(),console.log(ze.bold(" Mesh invite")),console.log(),console.log(` ${ze.cyan(g)}`),console.log(),console.log(ze.dim(" Run on the other node:")),console.log(ze.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ze.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function X$(e,t={}){let o;try{o=lO(e)}catch(r){console.log(ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Xd("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Y$({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(ze.red(" Aborted (keeping existing .env)")),process.exit(1))}Gn("MESH_TOKEN",o.token);let s=await de(r=>{qe(r,"mesh.enabled",!0);let i=fs(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),qe(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(ze.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ze.green(" \u2713 Joined mesh")),console.log(ze.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(ze.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ze.dim(" Daemon hot-reloaded.")):console.log(ze.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(ze.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(ze.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(ze.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Yn=new mO().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Yn.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 J$({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Yn.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 G$({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});Yn.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await z$({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var V$=Yn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");V$.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 K$({url:e.url,configPath:e.config})});V$.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await X$(e,{configPath:t.config})});Yn.action(()=>{console.log(),console.log(Ks.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ks.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ks.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ks.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ks.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ks.dim(" GitLab connect is the next slice.")),console.log()});oe();import{Command as pO}from"commander";import se from"chalk";var Kn=new pO().name("usage").description("token usage analysis and reporting");Kn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(se.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(se.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${se.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${se.red(String(s.totalErrors))}`),console.log(),console.log(se.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${se.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${se.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${e.message}`))}});Kn.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=T(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:se.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(se.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(se.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",u=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?u<60?`resets in ${u} min`:u<48*60?`resets in ${Math.round(u/60)} h`:`resets in ${Math.round(u/1440)} days`:"",w=l.has(d.window)?se.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(se.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${t.message}`))}});Kn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(se.red(` Script not found: ${s}`)),console.log(se.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(se.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(se.red(" Analysis failed. Is Python 3 installed?"))}});Kn.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=u=>/^\d{4}-\d{2}-\d{2}$/.test(u)&&!Number.isNaN(Date.parse(u));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(se.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(u){console.log(se.red(` Cannot read baseline ${e.baseline}: ${u.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=u=>u===null?"-":`$${u.toFixed(u<10?3:2)}`,g=u=>`${(u/1e6).toFixed(1)}M`;console.log(),console.log(se.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(se.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(se.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(u=>[u,a.channels[u],c?.channels[u]]).sort((u,h)=>(h[1]?.cost||0)-(u[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[u,h,w]of p){let b=r(h),$=` ${u.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${g(h?.cacheRead||0).padStart(11)} ${g(h?.cacheCreate||0).padStart(11)} ${g(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l(b).padStart(9)}`;if(c){let v=r(w),S=b!==null&&v?`${((b-v)/v*100).toFixed(0)}%`:"-";$+=` ${l(v).padStart(9)} ${S.padStart(7)}`}console.log($)}console.log(),c&&console.log(se.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(se.dim(` Saved ${e.save}`)),console.log()});Kn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y7D5W52I.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-2DFU4DCC.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let u=f?`${f} ${p.name()}`:p.name();c.push(u),l(p,u)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(se.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${se.dim("\xB7")} ${d}`);console.log(),console.log(se.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(se.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(se.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(se.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(se.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(se.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=se.dim(`${r.days}d`);console.log(` ${se.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(se.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as fO}from"commander";import We from"chalk";import{readFileSync as hO}from"fs";import{resolve as wO}from"path";oe();var nn=new fO().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");nn.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{$u(wO(process.cwd(),".env"))}catch{}let t=yO(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-TCZ3RAQR.js");o(t)}catch(t){console.log(We.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(We.dim(t.stack)),process.exit(1)}});function yO(e,t){try{let o=T();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(We.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(We.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
554
|
+
`}function Gn(e,t,o=".env"){let n=U$(o),s=W$(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${Kd(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${Kd(t)}`})),FC(n,JC(s))}function Xd(e,t=".env"){return W$(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var B$="https://t.me/BotFather";async function HC(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function GC(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function J$(e={}){console.log(),console.log(ye.bold(" Connect Telegram")),console.log(),console.log(ye.dim(` 1. Open ${B$}`)),console.log(ye.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ye.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await Hr({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Ro(B$);let{token:o}=await Hr({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:S=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(S.trim())||"That doesn't look like a Telegram token"});o||(console.log(ye.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await HC(o.trim());n||(console.log(ye.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ye.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(ye.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ye.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Hr({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),g||(console.log(ye.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await Hr({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ye.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Gn(p,o.trim()),process.env[p]=o.trim();let u=await de(S=>{qe(S,"channels.telegram.enabled",!0),qe(S,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let x=fs(S,`agents.${g}.mentions`)||[],k=`@${n.username}`;x.includes(k)||(x.push(k),qe(S,`agents.${g}.mentions`,x))},{configPath:e.configPath});if(u.success||(console.log(ye.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(ye.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ye.dim(` Token stored in .env as ${p}`)),console.log(ye.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(ye.dim(" Daemon hot-reloaded.")):console.log(ye.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await Hr({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ye.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ye.dim(" Waiting up to 90s..."));let w=await GC(o.trim(),9e4);if(!w){console.log(ye.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ye.dim(" agentx config set notifications.destination.channel telegram")),console.log(ye.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ye.dim(` agentx config set notifications.destination.accountId ${f}`));return}let b={channel:"telegram",chatId:String(w.chatId),accountId:f},$=[],v=await de(S=>{qe(S,"notifications.destination",b),$=sa(S,b)},{configPath:e.configPath});if(!v.success){console.log(ye.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(ye.green(" \u2713 Default --notify target set")),console.log(ye.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(ye.dim(" From now on, --notify me resolves to this chat.")),$.length&&console.log(ye.dim(` Schedules that now report here: ${$.join(", ")}`)),v.reloaded&&console.log(ye.dim(" Daemon hot-reloaded."))}import Pe from"chalk";import Vd from"prompts";import{existsSync as Zd,mkdirSync as zC,readdirSync as YC,readFileSync as H$}from"fs";import{resolve as Qd}from"path";var KC=".agentx/whatsapp-sessions";function XC(){let e=Qd(process.cwd(),".agentx/daemon.pid");if(!Zd(e))return!1;try{let t=parseInt(H$(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function VC(e){if(!Zd(e))return!1;try{return YC(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function QC(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Pe.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Pe.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;zC(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(g=>{let f=setTimeout(()=>{t(Pe.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(Pe.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:u}=await import("qrcode-terminal");u.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Pe.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Pe.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function G$(e={}){if(console.log(),console.log(Pe.bold(" Connect WhatsApp")),console.log(),XC()){console.log(Pe.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Pe.dim(" agentx daemon stop")),console.log();let{cont:l}=await Vd({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Pe.red(" Aborted")),process.exit(1))}let t=e.configPath||Qd(process.cwd(),"agentx.json");Zd(t)||(console.log(Pe.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(H$(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||KC,s=Qd(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Pe.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Vd({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(Pe.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(VC(s)&&a){let{keep:l}=await Vd({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(Pe.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await QC(s,g=>console.log(g))||(console.log(Pe.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await de(l=>{qe(l,"channels.whatsapp.enabled",!0),qe(l,"channels.whatsapp.sessionDir",n),qe(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Pe.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Pe.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Pe.dim(` Session: ${n}`)),console.log(Pe.dim(" Start the daemon to begin receiving:")),console.log(Pe.dim(" agentx daemon start")),console.log(Pe.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Pe.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Pe.dim(" Add routes later with:")),console.log(Pe.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import At from"chalk";import ZC from"prompts";import{existsSync as eO,readFileSync as tO}from"fs";import{resolve as oO}from"path";async function nO(e,t){let o=e.user||e.address,[{ImapFlow:n},{default:s}]=await Promise.all([import("imapflow"),import("nodemailer")]),r=new n({host:e.imapHost,port:e.imapPort,secure:e.imapPort===993,auth:{user:o,pass:t},logger:!1});try{await r.connect(),await r.logout()}catch(a){return r.close(),`IMAP ${e.imapHost}:${e.imapPort}: ${a?.responseText||a?.message||a}`}let i=s.createTransport({host:e.smtpHost,port:e.smtpPort,secure:e.smtpPort===465,auth:{user:o,pass:t},connectionTimeout:15e3});try{await i.verify()}catch(a){return`SMTP ${e.smtpHost}:${e.smtpPort}: ${a?.response||a?.message||a}`}finally{i.close()}return null}function sO(e,t){return!t.includes("*")||e==="sdk"?null:`Anyone can email an agent that runs commands (engine ${e||"claude-code"}). Limit who may write with --allow-from.`}function Io(e){console.log(At.red(` ${e}`)),process.exit(1)}async function zn(e){return(await ZC(e,{onCancel:()=>Io("Aborted")}))[e.name]}async function z$(e={}){console.log(),console.log(At.bold(" Connect email")),console.log();let t=e.configPath||oO(process.cwd(),"agentx.json");eO(t)||Io(`No agentx.json at ${t}. Run: agentx init`);let o=JSON.parse(tO(t,"utf-8")),n=Object.keys(o.agents||{});n.length===0&&Io("No agents configured. Run: agentx agent add");let s=e.agent??await zn({type:"select",name:"agent",message:"Which agent answers this mailbox?",choices:n.map(b=>({title:b,value:b}))});o.agents?.[s]||Io(`No agent "${s}" in ${t}`);let r=(e.address??await zn({type:"text",name:"address",message:"Email address customers write to:",validate:b=>/^\S+@\S+\.\S+$/.test(b.trim())||"an email address"})).trim().toLowerCase(),i=e.account||s,a=Bf(r),c=e.imapHost??a?.imapHost??await zn({type:"text",name:"imapHost",message:"IMAP server (incoming mail):"}),l=Number(e.imapPort??a?.imapPort??await zn({type:"text",name:"imapPort",message:"IMAP port:",initial:"993"})),g=e.smtpHost??a?.smtpHost??await zn({type:"text",name:"smtpHost",message:"SMTP server (outgoing mail):"}),d=Number(e.smtpPort??a?.smtpPort??await zn({type:"text",name:"smtpPort",message:"SMTP port:",initial:"465"}));(!Number.isInteger(l)||!Number.isInteger(d))&&Io("Ports must be numbers.");let f=e.passwordEnv||Hf(i),p=e.passwordEnv?process.env[e.passwordEnv]:void 0;e.passwordEnv&&!p&&Io(`${e.passwordEnv} is not set in the environment.`),p||(a?.imapHost==="imap.gmail.com"&&(console.log(At.dim(` Gmail needs an app password, not your account password: ${Wf}`)),console.log(At.dim(" (2-step verification must be on for that page to show.)"))),p=(await zn({type:"password",name:"password",message:"Password (an app password for Gmail):"}))?.trim()),p||Io("Aborted");let u={agent:s,address:r,imapHost:c,imapPort:l,smtpHost:g,smtpPort:d,user:e.user,passwordEnv:f,allowFrom:e.allowFrom?.length?e.allowFrom:["*"],send:e.auto?"auto":"approve"};if(!e.skipCheck){process.stdout.write(" Logging in to IMAP and SMTP... ");let b=await nO(u,p);b&&(console.log(At.red("\u2717")),Io(b)),console.log(At.green("\u2713"))}e.passwordEnv||(Gn(f,p),process.env[f]=p);let h=await de(b=>{qe(b,"channels.email.enabled",!0),qe(b,`channels.email.accounts.${i}`,Jf(u))},{configPath:e.configPath});h.success||Io(`Config save failed: ${h.error}`),console.log(),console.log(At.green(` \u2713 ${r} is answered by "${s}"`)),e.passwordEnv||console.log(At.dim(` Password stored in .env as ${f}`)),console.log(At.dim(` Who may write: ${u.allowFrom.join(", ")}${u.allowFrom.includes("*")?" (anyone)":""}`));let w=sO(o.agents[s]?.tier,u.allowFrom);w&&console.log(At.yellow(` ${w}`)),console.log(u.send==="auto"?At.yellow(" Replies are sent as soon as the agent writes them."):At.dim(" Each reply waits in Approvals until you send it: agentx approvals list")),console.log(At.dim(" Only mail that arrives from now on is answered.")),console.log(At.dim(" Restart the daemon to start reading the mailbox: agentx daemon restart")),console.log()}import{randomBytes as rO}from"crypto";import ze from"chalk";import Y$ from"prompts";var za="agentx-mesh:",Ya="//join/";function iO(e){return Buffer.from(e,"utf-8").toString("base64url")}function aO(e){return Buffer.from(e,"base64url").toString("utf-8")}function cO(e){return`${za}${Ya}${iO(JSON.stringify(e))}`}function lO(e){if(!e.startsWith(`${za}${Ya}`))throw new Error(`Not a mesh invite link \u2014 expected ${za}${Ya}\u2026`);let t=e.slice(za.length+Ya.length),o=JSON.parse(aO(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function dO(){return rO(32).toString("hex")}function gO(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function uO(e){return e?.node?.name||e?.node?.id||"node"}async function K$(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(ze.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=Xd("MESH_TOKEN");i||(i=dO(),Gn("MESH_TOKEN",i),console.log(ze.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||gO(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Y$({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(ze.red(" Aborted")),process.exit(1)),a=d}let l=await de(d=>{qe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ze.red(` \u2717 ${l.error}`)),process.exit(1));let g=cO({url:a,token:i,name:uO(r),version:1});console.log(),console.log(ze.bold(" Mesh invite")),console.log(),console.log(` ${ze.cyan(g)}`),console.log(),console.log(ze.dim(" Run on the other node:")),console.log(ze.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ze.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function X$(e,t={}){let o;try{o=lO(e)}catch(r){console.log(ze.red(` \u2717 ${r.message}`)),process.exit(1)}let n=Xd("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await Y$({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(ze.red(" Aborted (keeping existing .env)")),process.exit(1))}Gn("MESH_TOKEN",o.token);let s=await de(r=>{qe(r,"mesh.enabled",!0);let i=fs(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),qe(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(ze.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ze.green(" \u2713 Joined mesh")),console.log(ze.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(ze.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ze.dim(" Daemon hot-reloaded.")):console.log(ze.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(ze.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(ze.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(ze.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Yn=new mO().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Yn.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 J$({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Yn.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 G$({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});Yn.command("email").description("bind a mailbox to an agent \u2014 IMAP in, SMTP out; the password goes to .env, replies wait for your approval").option("--agent <id>","agent that answers the mailbox (skips the prompt)").option("--address <email>","the address customers write to").option("--account <name>","account label in channels.email.accounts (defaults to agent id)").option("--imap-host <host>","IMAP server (Gmail is filled in by itself)").option("--imap-port <n>","IMAP port (993: TLS; 143: STARTTLS)").option("--smtp-host <host>","SMTP server").option("--smtp-port <n>","SMTP port (465: TLS; 587: STARTTLS)").option("--user <login>","login name, when it is not the address").option("--password-env <VAR>","read the password from this environment variable instead of asking").option("--allow-from <entries...>","who may write: addresses, @domain, or * (default: *)").option("--auto","send replies as soon as the agent writes them, without your approval").option("--skip-check","don't try the IMAP and SMTP logins first").option("-c, --config <path>","path to agentx.json").action(async e=>{await z$({agent:e.agent,account:e.account,address:e.address,imapHost:e.imapHost,imapPort:e.imapPort,smtpHost:e.smtpHost,smtpPort:e.smtpPort,user:e.user,passwordEnv:e.passwordEnv,allowFrom:e.allowFrom,auto:!!e.auto,skipCheck:!!e.skipCheck,configPath:e.config})});var V$=Yn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");V$.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 K$({url:e.url,configPath:e.config})});V$.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await X$(e,{configPath:t.config})});Yn.action(()=>{console.log(),console.log(Ks.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ks.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ks.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ks.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ks.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ks.dim(" GitLab connect is the next slice.")),console.log()});oe();import{Command as pO}from"commander";import se from"chalk";var Kn=new pO().name("usage").description("token usage analysis and reporting");Kn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=T(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(se.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(se.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${se.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${se.red(String(s.totalErrors))}`),console.log(),console.log(se.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${se.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${se.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${e.message}`))}});Kn.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=T(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:se.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(se.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(se.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",u=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?u<60?`resets in ${u} min`:u<48*60?`resets in ${Math.round(u/60)} h`:`resets in ${Math.round(u/1440)} days`:"",w=l.has(d.window)?se.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,w].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(se.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(se.red(" Daemon not running. Start with: agentx daemon start")):console.log(se.red(` ${t.message}`))}});Kn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(se.red(` Script not found: ${s}`)),console.log(se.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(se.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(se.red(" Analysis failed. Is Python 3 installed?"))}});Kn.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-XTHSSPLB.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=u=>/^\d{4}-\d{2}-\d{2}$/.test(u)&&!Number.isNaN(Date.parse(u));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(se.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(u){console.log(se.red(` Cannot read baseline ${e.baseline}: ${u.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=u=>u===null?"-":`$${u.toFixed(u<10?3:2)}`,g=u=>`${(u/1e6).toFixed(1)}M`;console.log(),console.log(se.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(se.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(se.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(u=>[u,a.channels[u],c?.channels[u]]).sort((u,h)=>(h[1]?.cost||0)-(u[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[u,h,w]of p){let b=r(h),$=` ${u.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${g(h?.cacheRead||0).padStart(11)} ${g(h?.cacheCreate||0).padStart(11)} ${g(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l(b).padStart(9)}`;if(c){let v=r(w),S=b!==null&&v?`${((b-v)/v*100).toFixed(0)}%`:"-";$+=` ${l(v).padStart(9)} ${S.padStart(7)}`}console.log($)}console.log(),c&&console.log(se.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(se.dim(` Saved ${e.save}`)),console.log()});Kn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-Y7D5W52I.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-GQ3YWR5W.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let u=f?`${f} ${p.name()}`:p.name();c.push(u),l(p,u)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(se.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${se.dim("\xB7")} ${d}`);console.log(),console.log(se.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(se.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(se.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(se.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(se.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(se.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=se.dim(`${r.days}d`);console.log(` ${se.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(se.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as fO}from"commander";import We from"chalk";import{readFileSync as hO}from"fs";import{resolve as wO}from"path";oe();var nn=new fO().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");nn.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{$u(wO(process.cwd(),".env"))}catch{}let t=yO(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-BIERRXDD.js");o(t)}catch(t){console.log(We.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(We.dim(t.stack)),process.exit(1)}});function yO(e,t){try{let o=T();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(We.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(We.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
555
555
|
`)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}nn.command("list").description("list configured boards").action(()=>{try{let e=T();if(!e.boards?.length){console.log(We.dim(`
|
|
556
556
|
No boards configured.
|
|
557
557
|
`));return}console.log();for(let t of e.boards){console.log(` ${We.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(We.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(We.dim(` primary label: ${t.primaryToolLabel}`)),console.log(We.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(We.red(` ${e.message}`)),process.exit(1)}});nn.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{Gr(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(r=>r.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(r=>r.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(We.red(` ${o.message}`)),process.exit(1)}});nn.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,t)=>{try{Gr(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=[];if(t.name&&(s.name=t.name,r.push(`name="${t.name}"`)),t.projects){let i=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(i.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:i},r.push(`projects=${i.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,r.push("label cleared")):(s.primaryToolLabel=t.label,r.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,r.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,r.push(`closed-days=${s.closedWindowDays}`)),r.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${r.join(", ")})`})}catch(o){console.log(We.red(` ${o.message}`)),process.exit(1)}});var eg=nn.command("column").description("manage a board's columns (add / remove / edit / list)");eg.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(hO("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log(We.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let r=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${We.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${We.dim(r)}`)}}catch(t){console.log(We.red(` ${t.message}`)),process.exit(1)}});eg.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,t,o)=>{try{Gr(n=>{let r=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!r)throw new Error(`board "${e}" not found`);if(r.columns=r.columns||[],r.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let i={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");i.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");i.mapsToLabel=o.label}return o.accent&&(i.accent=o.accent),r.columns.push(i),`column "${t}" added to board "${e}"`})}catch(n){console.log(We.red(` ${n.message}`)),process.exit(1)}});eg.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Gr(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(i=>i.id!==t),s.columns.length===r)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(We.red(` ${o.message}`)),process.exit(1)}});nn.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Gr(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(We.red(` ${t.message}`)),process.exit(1)}});function Gr(e){let{summary:t,backupPath:o}=jt(n=>e(n));console.log(We.green(`
|
|
@@ -853,7 +853,7 @@ Restart the daemon to activate.
|
|
|
853
853
|
dist/
|
|
854
854
|
*.log
|
|
855
855
|
.env
|
|
856
|
-
`}import{Command as KI}from"commander";import st from"chalk";import{writeFileSync as XI,mkdirSync as VI,existsSync as bc,readFileSync as Vv,appendFileSync as Qv}from"fs";import{resolve as rr,dirname as tx}from"path";import{homedir as Fg}from"os";var ox=new KI().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-
|
|
856
|
+
`}import{Command as KI}from"commander";import st from"chalk";import{writeFileSync as XI,mkdirSync as VI,existsSync as bc,readFileSync as Vv,appendFileSync as Qv}from"fs";import{resolve as rr,dirname as tx}from"path";import{homedir as Fg}from"os";var ox=new KI().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-GQ3YWR5W.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=eN(o);break;case"bash":s=rN(o);break;case"fish":s=iN(o);break;default:console.error(st.red(`unsupported shell: ${n}`)),console.error(st.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?rr(String(e.output)):QI(n);VI(tx(r),{recursive:!0}),XI(r,s),console.log(st.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),ZI(n,r,!!e.yes)});function QI(e){let t=Fg();switch(e){case"zsh":return rr(t,".zsh","completions","_agentx");case"bash":return rr(t,".bash_completion.d","agentx.bash");case"fish":return rr(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function ZI(e,t,o){if(e==="zsh"){let n=rr(Fg(),".zshrc"),s=tx(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=bc(n)?Vv(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(st.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&bc(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),Qv(n,g.join(`
|
|
857
857
|
`)+`
|
|
858
858
|
`),console.log(st.green("\u2713 Patched ~/.zshrc")),console.log(st.dim("Reload your shell: exec zsh"));return}console.log(st.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(st.cyan(` ${r}`)),l&&console.log(st.cyan(` ${i}`)),console.log(),console.log(st.dim("Then reload: exec zsh")),console.log(st.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=rr(Fg(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((bc(n)?Vv(n,"utf-8"):"").includes(t)){console.log(st.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&bc(n)){Qv(n,`
|
|
859
859
|
# agentx completion
|
|
@@ -869,4 +869,4 @@ ${aN({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
|
|
|
869
869
|
${o.url}`)}catch(t){console.error(ar.red(` ${t.message}`)),process.exitCode=1}});ai.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",Wg).action(async(e,t)=>{try{let o=await Hg(t.models);if(!Bg(t.model,o)){console.log(Jg(t.model,o)),process.exitCode=1;return}let n=e==="-"?await dN():await lN(e,"utf8"),s=JSON.parse(n),{version:r}=await xi(),i=ix({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(ar.red(` ${o.message}`)),process.exitCode=1}});async function dN(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function o3(){let e=await xi(),t=new gN().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");t.hook("preAction",(o,n)=>{let s=zf(n);Yf(s)&&Gf("cli",s)});for(let o of[Ww,tw,ew,Yn,xs,lo,Pt,Rf,mo,da,Co,vn,Bn,wo,on,F$,tn,ta,Nv,Vo,My,Ly,zy,Lr,sb,lb,Py,ub,mb,Ob,Pb,_b,qt,Kn,Lv,Rr,Go,ox,ai])t.addCommand(o);for(let o of cx)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=cx.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,uN(o,74," "),""].join(`
|
|
870
870
|
`)}),t}var cx=[z,Qs,jo,to,Or,Bs,Qe,No,nn,Wn,es,er,Ko,kt,_s,xa,qa,Fn,Fa,Ua,Rv,Ov,To,Zr,Dt,dh,Rn,ri,zl,cn,wt,js,Yl,cc,bo,Po,Jv,nr,Hv,Dv];function uN(e,t,o){let n=[],s="";for(let r of e)s&&s.length+r.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+r;return s&&n.push(o+s),n.join(`
|
|
871
871
|
`)}export{o3 as buildProgram};
|
|
872
|
-
//# sourceMappingURL=program-
|
|
872
|
+
//# sourceMappingURL=program-GQ3YWR5W.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentix-cli",
|
|
3
|
-
"version": "0.185.
|
|
3
|
+
"version": "0.185.1",
|
|
4
4
|
"description": "AI staff for a small company: they find sales, answer clients, write your posts and watch the money, on a machine you own. You approve what matters. Runs a team of AI agents across Telegram, WhatsApp, GitLab, GitHub, crons, webhooks and mesh tasks, on Claude Code, Codex, OpenCode or any LLM API. Web wizard for operators, CLI for engineers.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|