agentix-cli 0.49.0 → 0.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/dist/{agent-J7SLJYQ6.js → agent-RY7Z3IYY.js} +2 -2
- package/dist/{board-dashboard-LG3ECH7C.js → board-dashboard-RUOASCSQ.js} +3 -3
- package/dist/board-dashboard-RUOASCSQ.js.map +1 -0
- package/dist/{chunk-DLKRPK5M.js → chunk-4BNQSUWV.js} +7 -2
- package/dist/{chunk-DLKRPK5M.js.map → chunk-4BNQSUWV.js.map} +1 -1
- package/dist/{chunk-DVNIFP7S.js → chunk-6VKCUMCN.js} +2 -2
- package/dist/{chunk-GCHUE3TN.js → chunk-7WDJW37G.js} +2 -2
- package/dist/{chunk-HGT4AKOH.js → chunk-BYD55JXH.js} +3 -3
- package/dist/{chunk-DTJKN5VT.js → chunk-EMI3VJLH.js} +2 -2
- package/dist/chunk-HRBKSZ34.js +2 -0
- package/dist/chunk-HRBKSZ34.js.map +1 -0
- package/dist/{chunk-3L2FKVR6.js → chunk-N2XXKFJ6.js} +2 -2
- package/dist/{chunk-HVQJIROJ.js → chunk-TTL37CS5.js} +4 -4
- package/dist/{chunk-RKAJR37K.js → chunk-TUNQFPVA.js} +2 -2
- package/dist/{chunk-MWUJOAAW.js → chunk-WQLBJ2O5.js} +2 -2
- package/dist/{chunk-FM2GGPSD.js → chunk-Y6I3BYWV.js} +5 -5
- package/dist/{chunk-FM2GGPSD.js.map → chunk-Y6I3BYWV.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/{compaction-U5SAYTX6.js → compaction-PIZINFHR.js} +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/memory-extract-OWTI6MN5.js +2 -0
- package/dist/processes-KUJJ7XE7.js +2 -0
- package/dist/{program-3CDFUJVE.js → program-KY5ZYPFN.js} +2 -2
- package/dist/{registry-722GXALE.js → registry-LLAFJJN4.js} +2 -2
- package/package.json +1 -1
- package/dist/board-dashboard-LG3ECH7C.js.map +0 -1
- package/dist/chunk-7DXE264B.js +0 -2
- package/dist/chunk-7DXE264B.js.map +0 -1
- package/dist/memory-extract-YZI2QZVR.js +0 -2
- package/dist/processes-XWRGOLMT.js +0 -2
- /package/dist/{agent-J7SLJYQ6.js.map → agent-RY7Z3IYY.js.map} +0 -0
- /package/dist/{chunk-DVNIFP7S.js.map → chunk-6VKCUMCN.js.map} +0 -0
- /package/dist/{chunk-GCHUE3TN.js.map → chunk-7WDJW37G.js.map} +0 -0
- /package/dist/{chunk-HGT4AKOH.js.map → chunk-BYD55JXH.js.map} +0 -0
- /package/dist/{chunk-DTJKN5VT.js.map → chunk-EMI3VJLH.js.map} +0 -0
- /package/dist/{chunk-3L2FKVR6.js.map → chunk-N2XXKFJ6.js.map} +0 -0
- /package/dist/{chunk-HVQJIROJ.js.map → chunk-TTL37CS5.js.map} +0 -0
- /package/dist/{chunk-RKAJR37K.js.map → chunk-TUNQFPVA.js.map} +0 -0
- /package/dist/{chunk-MWUJOAAW.js.map → chunk-WQLBJ2O5.js.map} +0 -0
- /package/dist/{compaction-U5SAYTX6.js.map → compaction-PIZINFHR.js.map} +0 -0
- /package/dist/{memory-extract-YZI2QZVR.js.map → memory-extract-OWTI6MN5.js.map} +0 -0
- /package/dist/{processes-XWRGOLMT.js.map → processes-KUJJ7XE7.js.map} +0 -0
- /package/dist/{program-3CDFUJVE.js.map → program-KY5ZYPFN.js.map} +0 -0
- /package/dist/{registry-722GXALE.js.map → registry-LLAFJJN4.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as cc,b as Un,g as lc}from"./chunk-OUZ7YVQZ.js";import{a as po,b as Qa,f as Ln,i as Fn,j as oc,k as tc,l as Ks,m as rc,o as ac}from"./chunk-
|
|
1
|
+
import{a as cc,b as Un,g as lc}from"./chunk-OUZ7YVQZ.js";import{a as po,b as Qa,f as Ln,i as Fn,j as oc,k as tc,l as Ks,m as rc,o as ac}from"./chunk-TUNQFPVA.js";import{a as nc,c as sc,d as ic}from"./chunk-Z3IP66SL.js";import{a as Za,c as ec}from"./chunk-OTW5MPFT.js";import{a as Ls,b as Fr}from"./chunk-RKPAVWXF.js";import{a as dt}from"./chunk-GV7S5BAX.js";import{e as Or}from"./chunk-GSX4NK2N.js";import{c as jr}from"./chunk-SZDACK6O.js";import{$ as Ja,A as Ca,B as Na,C as Ra,D as Ht,E as Ws,F as Cn,G as _a,H as mt,I as vo,J as Da,K as Bs,L as Js,M as Pa,N as Ma,O as zt,P as Nn,Q as La,R as Fa,S as Ua,T as qa,U as pt,V as Wa,W as Ba,X as Ce,Y as Rn,Z as Yt,_ as Gs,a as zr,aa as _n,b as Yr,ba as Dn,ca as za,da as Ys,ea as Va,fa as Pn,ga as ut,h as Qr,ha as Mn,i as Gt,ia as Vs,j as In,ja as Ka,k as oa,ka as Xa,l as ta,m as na,n as sa,o as ua,p as fa,q as $a,r as xa,s as Sa,t as Ea,u as Aa,v as Ia,w as qs,x as Ta,y as Oa,z as ja}from"./chunk-BYD55JXH.js";import{A as Ha,B as zs,P as so,R as Ya,k as ha,n as ya,u as wa,v as ba,y as Ga,z as Hs}from"./chunk-EMI3VJLH.js";import{a as Vr,d as Kr,e as Xr}from"./chunk-PZCTCCC5.js";import{a as Us,b as Tn,c as On,d as ia,e as ra,f as aa,i as ca,j as la,k as da,l as ga,o as jn,q as ma,r as pa}from"./chunk-FULEQYM6.js";import{a as Zr,p as ea}from"./chunk-OHA3J5ZV.js";import{a as ka,b as va}from"./chunk-L53FTKEP.js";import{D as Mr,N as Lr,h as Sr,q as Er,u as Ds,v as Ir,x as ko}from"./chunk-TTL37CS5.js";import{b as Bt,c as ct,d as En,e as An,f as lt,g as Tr,h as Wo,i as Jt}from"./chunk-N2XXKFJ6.js";import{a as xr}from"./chunk-N6EWZGIX.js";import{e as _r,f as Ms,k as Dr}from"./chunk-Q7C3X3R6.js";import{b as at}from"./chunk-DP7RTNDM.js";import{a as Fs,e as Ur,f as qr,h as Wr,i as Br,k as Jr,l as Gr,m as Hr}from"./chunk-5XQCGPQJ.js";import{a as Ar,e as Rr}from"./chunk-B5XHX44Y.js";import{f as Cr,g as Nr,h as Ps}from"./chunk-76Z4VHDX.js";import{b as he,c as Ae,d as gt,e as Pr}from"./chunk-NLZD2QKF.js";import{h as vr}from"./chunk-DWADWDMU.js";import{a as _s}from"./chunk-IXUEJBHD.js";import{b as $o,d as Sn}from"./chunk-JVNFRS26.js";import{b as rt,d as kr}from"./chunk-2GIDVZ4H.js";import{a as Rs,b as lr,c as ig,d as vn,e as dr,f as fr,g as ag,h as hr,i as cg,m as it,n as wr,o as br,s as $r,v as no,w as Wt}from"./chunk-4NBWF4TL.js";import{a as mo,b as st,e as mr,f as qt}from"./chunk-F4HZTZHW.js";import{a as yr,b as lg}from"./chunk-AJONZWLT.js";import{a as go,b as sg}from"./chunk-L2WSPY6S.js";import{l as gr,m as R,n as xn,p as ge}from"./chunk-P2ZYT5D6.js";import{g as pr,k as ur,l as rg}from"./chunk-BH3GTCZ6.js";import{a as ng}from"./chunk-FIOB3MEX.js";import{Command as dg}from"commander";var dc=new dg().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 Yr({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()});ge();import{Command as gg}from"commander";import{execFileSync as io}from"node:child_process";import{cpSync as gc,existsSync as Qs,mkdirSync as Xs,mkdtempSync as mg,rmSync as pg,writeFileSync as mc}from"node:fs";import{dirname as pc,join as Me}from"node:path";import{homedir as qn,release as ug,tmpdir as fg}from"node:os";import{setTimeout as hg}from"node:timers/promises";function Wn(){let e=ia(process.platform,process.arch,ug());if(e)throw new Error(e)}function Vt(){return`gui/${process.getuid()}/${Us}`}function ft(){return Me(qn(),"Library/LaunchAgents",`${Us}.plist`)}async function uc(){try{io("launchctl",["bootout",Vt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{io("launchctl",["print",Vt()],{stdio:"pipe"})}catch{return}await hg(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function fc(){if(!Qs(ft()))throw new Error("Run agentx desktop install first.");let e=!0;try{io("launchctl",["print",Vt()],{stdio:"pipe"})}catch{e=!1}e||io("launchctl",["bootstrap",`gui/${process.getuid()}`,ft()],{stdio:"pipe"}),io("launchctl",["kickstart",Vt()],{stdio:"pipe"})}function yg(){let e=ga();if(e&&Qs(Me(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 ht=new gg("desktop").description("install and control the macOS desktop assistant");ht.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","agent to use (defaults to the first configured agent)").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{Wn();let o=R(),t=ra(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=yg(),i=Me(qn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Me(i,Tn)}
|
|
2
2
|
Computer-use helper \u2192 ${Me(i,On)}
|
|
3
3
|
Agent \u2192 ${t}
|
|
4
4
|
Daemon \u2192 ${n}
|
|
@@ -389,7 +389,7 @@ return aid ?? null`}function Hp(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
389
389
|
settings \u2014 without this an attached production identity would be less
|
|
390
390
|
guarded than a spawned one.)`))):console.log(L.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${L.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(L.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Zo.command("uninstall").description("remove the attach hooks from ~/.claude/settings.json").option("--path <file>","settings file to patch (default: ~/.claude/settings.json)").option("--remove-guard","also remove the PreToolUse guard hook").action(e=>{try{let o=$c({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${L.green("\u2713")} Removed attach hooks from ${L.gray(o.path)} (${o.events.join(", ")})`:`${L.gray("Nothing to remove.")}`),e.removeGuard||console.log(L.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(L.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});ge();import{Command as Tu}from"commander";import ye from"chalk";var ds=new Tu().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Yl(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=R(e.config);o||(o=n.dashboard?.daemonUrl||""),t||(t=n.dashboard?.token||"")}catch{}return o||(o="http://localhost:18800"),{baseUrl:o.replace(/\/+$/,""),token:t}}function Vl(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function zl(e){let o=Math.round((Date.now()-e)/1e3);return o<60?`${o}s`:o<3600?`${Math.round(o/60)}m`:o<86400?`${Math.round(o/3600)}h`:`${Math.round(o/86400)}d`}function Ou(e){return e==="busy"?ye.magenta:e==="warm-hot"?ye.green:e==="warm-cold"?ye.cyan:e==="idle"?ye.yellow:e==="dead"?ye.red:ye.dim}ds.command("list").description("list every live persistent claude process").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("--json","emit JSON").action(async e=>{let{baseUrl:o,token:t}=Yl(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Vl(t)})}catch(r){console.log(ye.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(ye.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(ye.red(` HTTP ${n.status} from ${o}/processes`)),process.exit(1));let i=(await n.json()).processes??[];if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){console.log(ye.dim(" (no processes)"));return}for(let r of i){let a=Ou(r.state)(r.state.padEnd(9)),c=zl(r.spawnedAt),l=r.lastTurnAt?zl(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?ye.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?ye.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):ye.dim("sess=\u2014"),p=r.pendingTaskId?ye.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${ye.bold(r.key.agentId)}${ye.dim(":"+r.key.channel+":"+r.key.chatId)} ${ye.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${p}`),r.deadReason&&console.log(` ${ye.red("dead:")} ${r.deadReason}`)}});ds.command("kill <agentId> <channel> <chatId>").description("force-kill one persistent process (the next dispatch will spawn fresh)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl)").option("--token <token>","bearer token (defaults to dashboard.token)").option("-r, --reason <reason>","kill reason (recorded on the dead-process snapshot)","operator-cli").action(async(e,o,t,n)=>{let{baseUrl:s,token:i}=Yl(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Vl(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(ye.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(ye.dim(" daemon has no persistent-process registry"));return}if(!r.ok){let a=`HTTP ${r.status}`;try{let c=await r.json();c.error&&(a+=` \u2014 ${c.error}`)}catch{}console.log(ye.red(` ${a}`)),process.exit(1)}console.log(ye.green(` killed ${e}:${o}:${t}`))});import{Command as ju}from"commander";import _e from"chalk";import{existsSync as ji,rmSync as Cu}from"fs";import{resolve as Ci}from"path";var It=new ju().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");It.command("add <agentId>").description("build or refresh an agent's lexical index from one or more globs").argument("<globs...>","glob patterns relative to cwd (e.g. './docs/**/*.md')").option("-v, --verbose","log each indexed file").action(async(e,o,t)=>{o.length===0&&(console.log(_e.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Cr(e,o,{verbose:n}),r=Date.now()-s;console.log(_e.green(` \u2713 indexed ${i.docs} doc(s) for ${_e.bold(e)} in ${r}ms`)),console.log(_e.dim(` \u2192 ${i.path}`))});It.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Ci(e.cwd,".agentx","rag");if(!ji(o)){console.log(_e.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>ji(Ci(o,s,"index.json")));if(n.length===0){console.log(_e.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Ps(s);console.log(` ${_e.bold(s)} ${i.docs} doc(s) ${_e.dim(i.path)}`)}});It.command("search <agentId> <query>").description("query an agent's index \u2014 useful for debugging recall before the agent calls rag.lexical").option("-k, --k <n>","top-k results","5").option("--json","emit JSON").action((e,o,t)=>{let n=parseInt(t.k,10)||5,s=Nr(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Ps(e);i.exists?console.log(_e.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(_e.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${_e.bold(i.title)} ${_e.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${_e.dim(i.path)}`),console.log(` ${_e.dim(i.snippet.slice(0,200))}`)});It.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Ci(process.cwd(),".agentx","rag",e);if(!ji(o)){console.log(_e.dim(` no index for ${e} \u2014 nothing to clear`));return}Cu(o,{recursive:!0,force:!0}),console.log(_e.green(` \u2713 cleared index for ${e}`))});ge();import{Command as Nu}from"commander";import K from"chalk";import Tt from"prompts";var et=new Nu().name("backlog").description("manage the local backlog used by business workSource=backlog");function cn(e){let o=R(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new Ga(n)}}function Ru(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function _u(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}et.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:o}=cn(e.config),t=o.list();if(e.status&&(t=t.filter(n=>n.status===e.status)),e.assignee&&(t=t.filter(n=>n.assignee===e.assignee)),e.source&&(t=t.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!t.length){console.log(K.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?K.magenta(`@${n.assignee}`):K.dim("unassigned");console.log(` ${_u(n.status).padEnd(7)} ${Ru(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(K.dim(` ${n.source.url}`))}console.log(),console.log(K.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});et.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=cn(t.config);n.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(K.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Ha([o],i.source,n.config),a=await zs(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(K.dim(" sync:"),...c));console.log(a.ok?K.dim(` synced -> ${a.url??i.source.type}`):K.yellow(` sync failed: ${a.error}`))}});et.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,o)=>{let t=cn(o.config);t.store.findById(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(K.green(` done: ${s.title}`)),s.source){let i=await zs(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(K.dim(" sync:"),...r));console.log(i.ok?K.dim(` synced -> ${i.url??s.source.type}`):K.yellow(` sync failed: ${i.error}`))}});et.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=cn(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});et.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let o=cn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(K.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Tt({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(K.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(K.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Pu(o.config):Mu(o.config);y.length?(i=(await Tt({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Tt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Tt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Tt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(K.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Lu(o.config,i,a):await Fu(o.config,i,a);if(!c.length){console.log(K.yellow(" no open issues matched"));return}console.log(K.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,g=new Set(o.store.list().map(y=>y.id)),d=c.map(y=>{let k=Hs({type:s,project:l,iid:y.iid,url:y.url}),b=g.has(k),v=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${v}${b?K.dim(" (already imported)"):""}`,value:y,disabled:b}}),u=(await Tt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!u.length){console.log(K.dim(" nothing selected"));return}let f=u.map(y=>{let k={type:s,host:s==="gitlab"?Du(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Hs(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=o.store.addMany(f);console.log(K.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(K.dim(` ${y.id} \u2014 ${y.title}`))});function Du(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Pu(e){let o=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&o.add(n.project);let t=e.business?.workSource;if(t?.type==="gitlab")for(let n of t.projects??[])o.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&o.add(n.id);return[...o].sort()}function Mu(e){let o=new Set;for(let t of e.channels.github?.routes??[])t.repo&&t.repo!=="*"&&o.add(t.repo);return[...o].sort()}async function Lu(e,o,t){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});t&&s.set("search",t);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(o)}/issues?${s}`,{headers:{"PRIVATE-TOKEN":n.token}});if(!i.ok)throw new Error(`GitLab ${i.status}: ${await i.text().catch(()=>"")}`);let r=await i.json();return Array.isArray(r)?r.map(a=>({iid:a.iid,title:a.title,description:a.description||void 0,labels:Array.isArray(a.labels)?a.labels.map(c=>typeof c=="string"?c:c.name):[],milestone:a.milestone?.title||void 0,assignee:a.assignee?.username||a.assignees?.[0]?.username||void 0,url:a.web_url})):[]}async function Fu(e,o,t){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(t){let c=`repo:${o} is:issue is:open ${t}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(Kl)}i=`https://api.github.com/repos/${o}/issues?state=open&per_page=100&sort=updated&direction=desc`;let r=await fetch(i,{headers:s});if(!r.ok)throw new Error(`GitHub ${r.status}: ${await r.text().catch(()=>"")}`);let a=await r.json();return Array.isArray(a)?a.filter(c=>!c.pull_request).map(Kl):[]}function Kl(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(o=>typeof o=="string"?o:o.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Uu}from"commander";import W from"chalk";import{existsSync as qu,readFileSync as Wu}from"fs";import{resolve as Bu}from"path";import Ju from"prompts";ge();function Xl(e){let o=e||Bu(process.cwd(),"agentx.json");return qu(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Wu(o,"utf-8"))}async function Gu(e,o){if(!e)return;if(e==="me"){let n=o?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(W.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Ju([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp):"},{type:"text",name:"chatId",message:"Destination chatId:"},{type:"text",name:"accountId",message:"Account id (optional):"}]);return!s||!i?void 0:{channel:s,chatId:i,accountId:r||void 0}}let t=e.split(":");if(t.length>=2)return{channel:t[0],chatId:t[1],accountId:t[2]};console.log(W.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var ho=new Uu().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');ho.argument("[when]",'natural-language schedule, e.g. "every morning at 9"').option("--agent <id>","agent to run").option("--do <prompt>","prompt to run at each tick (required unless --id exists)").option("--id <name>","explicit cron id (default: auto-slug of <when>-<agent>)").option("--notify <target>",'"me" (use notifications.destination) or "channel:chatId[:accountId]"').option("--on-error <modes>",'comma list of "log|notify|disable" (default: log; notify implies "notify")').option("--timezone <tz>",`IANA timezone (default: ${Fs})`,Fs).option("--timeout <seconds>","max run time","600").option("--model <model>","override model").option("--disabled","create but leave disabled").option("--dry-run","print what would be written without writing").action(async(e,o)=>{if(!e){ho.help();return}o.agent||(console.log(W.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(W.red(' --do "<prompt>" is required')),process.exit(1));let t=Ls(e);t||(console.log(W.red(` Couldn't parse: "${e}"`)),console.log(W.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(W.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(W.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Xl(o.config),s=gr(n);n.agents?.[o.agent]||(console.log(W.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(W.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=await Gu(o.notify,s),r=o.id||Fr(t.matched,o.agent),a=qr({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:Ur(o.onError),enabled:!o.disabled}),c=a.onError,l=await he(d=>Ae(d,`crons.${r}`,a),{configPath:o.config,dryRun:!!o.dryRun});l.success||(console.log(W.red(` \u2717 ${l.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(W.green(` \u2713 ${g} cron ${W.cyan(r)}`)),console.log(W.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(W.dim(` Agent: ${o.agent}`)),i&&console.log(W.dim(` Notify: ${i.channel} ${i.chatId}`)),c.length&&console.log(W.dim(` On error: ${c.join(", ")}`)),!o.dryRun&&l.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});ho.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async e=>{let t=Xl(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(W.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.approval?W.yellow("\u25D0"):i.enabled?W.green("\u25CF"):W.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}if(console.log(` ${r} ${W.cyan(s.padEnd(32))} ${W.dim(i.schedule.padEnd(14))} ${W.dim("\u2192")} ${i.agent}`),console.log(W.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(W.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`)),i.createdBy&&console.log(W.dim(` created by agent: ${i.createdBy}`)),i.approval){let c=i.timezone||"UTC",l=Br(Wr(i.schedule,c),c);console.log(W.yellow(` pending ${i.approval.action} approval (requested by ${i.approval.requestedBy}); next fire: ${l}`)),console.log(W.dim(` agentx schedule approve ${s} | agentx schedule reject ${s}`))}}console.log()});for(let[e,o]of[["on",!0],["off",!1]])ho.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await Hr(t,o);n.success||(console.log(W.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});ho.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await he(t=>{if(!gt(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Pr(t,`crons.${e}`)});o.success||(console.log(W.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(W.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});for(let[e,o,t]of[["approve",Jr,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Gr,"reject an agent's pending create/delete request (drops the request)"]])ho.command(`${e} <id>`).description(t).option("-c, --config <path>","path to agentx.json").action(async(n,s)=>{let i=await o(n,{configPath:s.config});i.success||(console.log(W.red(` \u2717 ${i.message}`)),process.exit(1)),console.log(W.green(` \u2713 ${i.message}`)),i.result?.reloaded&&console.log(W.dim(" Daemon hot-reloaded."))});ho.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Ls(o);t||(console.log(W.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(W.green(` "${o}"`)),console.log(W.dim(` \u2192 ${t.cron}`)),console.log(W.dim(` \u2192 ${t.human}`))});import{Command as Hu}from"commander";import ve from"chalk";var Ro=new Hu("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),zu={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function Ql(){return{root:process.cwd()}}function Ni(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Yu(e){console.log(` ${ve.cyan(e.key)} ${ve.dim(`[${zu[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?ve.dim(` (later: until ${Ni(e.snoozed_until)})`):""}`),console.log(` ${ve.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${ve.green("Recommends:")} ${e.recommend}`),e.expires&&console.log(ve.yellow(` Expires ${Ni(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(ve.dim(` ${e.detail}`)),e.source&&console.log(ve.dim(` ${e.source}`)),console.log(ve.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Ro.command("list",{isDefault:!0}).alias("ls").description("what is waiting, most urgent first").option("--all","include items you put off with `later`").option("--json","machine-readable output").action(e=>{let o=wa(Ql(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log(ve.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log(ve.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)Yu(t),console.log();console.log(ve.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function Ri(e,o,t){let n=Fn(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error(ve.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await ba(Ql(),e,o,{force:t.force,note:t.note,laterHours:s});if(!i.ok){console.error(ve.red(` ${i.error}`)),process.exitCode=1;return}console.log(ve.green(` \u2713 ${i.message}`))}Ro.command("approve").alias("yes").description("say yes: enables the schedule, lets the fact be used, writes the wiki article, or tells the agent yes").argument("<key>","item key from `agentx approvals list`, e.g. card:2026-01-05-publish-draft-ab12").option("--force","wiki: approve even if the article changed since the proposal").option("--note <text>","cards: a note passed to the agent with your answer").action((e,o)=>Ri(e,"yes",o));Ro.command("reject").alias("no").description("say no: drops the request, keeps the fact out, declines the article, or tells the agent no").argument("<key>","item key from `agentx approvals list`").option("--note <text>","why; kept with cards and wiki proposals").action((e,o)=>Ri(e,"no",o));Ro.command("later").description("put an item off; it leaves the list and comes back later (a card still expires on time)").argument("<key>","item key from `agentx approvals list`").option("--hours <n>","how long (default: approvals.laterHours, 24)").action((e,o)=>Ri(e,"later",o));Ro.command("request").description("raise a decision card yourself, for example to test the inbox (agents use the agentx_approval tool)").requiredOption("--agent <id>","the agent the card is from; it gets the result").requiredOption("--title <text>","what it is, in one line").requiredOption("--ask <text>","the yes/no question").requiredOption("--recommend <text>","the advice and why, in one line").requiredOption("--if-silent <value>",`what applies if nobody answers: ${ha.join(", ")}`).option("--expires <when>","ISO date or time, or like 12h / 3d (default: approvals.defaultExpiryDays)").option("--source <link>","link to the draft, PR or issue").action(e=>{let o=Fn(),t=ya(process.cwd(),{raised_by:e.agent,title:e.title,ask:e.ask,recommend:e.recommend,if_silent:e.ifSilent,expires:e.expires,source:e.source},{settings:o});if(!t.ok){console.error(ve.red(` ${t.error}`)),process.exitCode=1;return}console.log(ve.green(` \u2713 card:${t.card.id} raised; expires ${Ni(t.card.expires)}, then: ${t.card.if_silent}`))});Ro.command("settings").description('show or change expiry, "later" and digest settings (approvals in agentx.json)').option("--expiry-days <n>","days a card gets when it doesn't say").option("--max-expiry-days <n>","longest a card may wait").option("--later-hours <n>","how long `later` hides an item").option("--notify-agent <on|off>","tell the agent that raised a card its result").option("--digest <on|off>","the daily message about what is waiting").option("--digest-time <HH:MM>","when the digest goes out, 24-hour local time").option("--digest-timezone <zone>",`IANA timezone for --digest-time; "local" for this machine's`).option("--digest-to <channel:chatId>",'where the digest goes; "default" for notifications.destination').action(async e=>{let o={},t=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},n=(a,c)=>{if(c!==void 0){if(c==="on")return!0;if(c==="off")return!1;throw new Error(`${a} takes on or off`)}};try{if(o.defaultExpiryDays=t("--expiry-days",e.expiryDays),o.maxExpiryDays=t("--max-expiry-days",e.maxExpiryDays),o.laterHours=t("--later-hours",e.laterHours),o.notifyAgent=n("--notify-agent",e.notifyAgent),o.digestEnabled=n("--digest",e.digest),e.digestTime!==void 0&&(o.digestTime=e.digestTime),e.digestTimezone!==void 0&&(o.digestTimezone=e.digestTimezone==="local"?null:e.digestTimezone),e.digestTo!==void 0)if(e.digestTo==="default")o.destination=null;else{let a=oc(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=a}}catch(a){console.error(ve.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(o).some(a=>a!==void 0)){let a=await tc(o);if(!a.success){console.error(ve.red(` ${a.error}`)),process.exitCode=1;return}console.log(ve.green(" \u2713 saved")+(a.reloaded?ve.dim(" (daemon reloaded)"):""))}let i=Fn(),r=i.digest.destination;console.log(` Cards expire after ${i.defaultExpiryDays} day(s) unless they say (at most ${i.maxExpiryDays})`),console.log(` "Later" hides an item ${i.laterHours} hour(s)`),console.log(` Tell the agent ${i.notifyAgent?"on":"off"}`),console.log(` Daily digest ${i.digest.enabled?`on, at ${i.digest.time}${i.digest.timezone?` (${i.digest.timezone})`:" (this machine's time)"}`:"off"}`),console.log(` Digest goes to ${r?`${r.channel} ${r.chatId}`:"notifications.destination"}`)});import{Command as wf}from"commander";import Ot from"chalk";import te from"chalk";import dn from"prompts";import{readFileSync as Vu,writeFileSync as Ku,existsSync as Xu}from"fs";import{resolve as Zl}from"path";var Qu=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Zu(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function _i(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function ed(e=".env"){let o=Zl(e);if(!Xu(o))return[];let t=Vu(o,"utf-8"),n=[];for(let s of t.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let i=s.match(Qu);i?n.push({kind:"kv",key:i[1],value:Zu(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function ef(e){return e.map(o=>o.kind==="kv"?`${o.key}=${_i(o.value)}`:o.raw).join(`
|
|
391
391
|
`)+`
|
|
392
|
-
`}function ln(e,o,t=".env"){let n=Zl(t),s=ed(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${_i(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${_i(o)}`})),Ku(n,ef(s))}function Di(e,o=".env"){return ed(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var od="https://t.me/BotFather";async function of(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function tf(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function td(e={}){console.log(),console.log(te.bold(" Connect Telegram")),console.log(),console.log(te.dim(` 1. Open ${od}`)),console.log(te.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(te.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await dn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[od],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await dn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(te.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await of(t.trim());n||(console.log(te.red("\u2717 invalid or revoked")),process.exit(1)),console.log(te.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(te.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(te.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await dn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(te.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||g;d[p]&&d[p].agentBinding!==g&&(p=(await dn({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(te.red(" Aborted")),process.exit(1));let u=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;ln(u,t.trim()),process.env[u]=t.trim();let f=await he(b=>{Ae(b,"channels.telegram.enabled",!0),Ae(b,`channels.telegram.accounts.${p}`,{token:`\${${u}}`,agentBinding:g});let v=gt(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Ae(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(f.success||(console.log(te.red(` \u2717 ${f.error}`)),process.exit(1)),console.log(),console.log(te.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(te.dim(` Token stored in .env as ${u}`)),console.log(te.dim(` Mentions updated to include @${n.username}`)),f.reloaded?console.log(te.dim(" Daemon hot-reloaded.")):console.log(te.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await dn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(te.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(te.dim(" Waiting up to 90s..."));let y=await tf(t.trim(),9e4);if(!y){console.log(te.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(te.dim(" agentx config set notifications.destination.channel telegram")),console.log(te.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(te.dim(` agentx config set notifications.destination.accountId ${p}`));return}let k=await he(b=>{Ae(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{configPath:e.configPath});if(!k.success){console.log(te.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(te.green(" \u2713 Default --notify target set")),console.log(te.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(te.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))}import we from"chalk";import Pi from"prompts";import{existsSync as Li,mkdirSync as nf,readdirSync as sf,readFileSync as nd}from"fs";import{resolve as Mi}from"path";var rf=".agentx/whatsapp-sessions";function af(){let e=Mi(process.cwd(),".agentx/daemon.pid");if(!Li(e))return!1;try{let o=parseInt(nd(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function cf(e){if(!Li(e))return!1;try{return sf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function lf(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(we.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(we.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;nf(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(we.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async u=>{if(u.qr){o(we.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:f}=await import("qrcode-terminal");f.generate(u.qr,{small:!0})}catch{o(` QR: ${u.qr}`)}o("")}if(u.connection==="open"){clearTimeout(p),o(we.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}u.connection==="close"&&!u.qr&&u.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),o(we.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function sd(e={}){if(console.log(),console.log(we.bold(" Connect WhatsApp")),console.log(),af()){console.log(we.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(we.dim(" agentx daemon stop")),console.log();let{cont:l}=await Pi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(we.red(" Aborted")),process.exit(1))}let o=e.configPath||Mi(process.cwd(),"agentx.json");Li(o)||(console.log(we.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(nd(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||rf,s=Mi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(we.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Pi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(we.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(cf(s)&&a){let{keep:l}=await Pi({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(we.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await lf(s,g=>console.log(g))||(console.log(we.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await he(l=>{Ae(l,"channels.whatsapp.enabled",!0),Ae(l,"channels.whatsapp.sessionDir",n),Ae(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(we.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(we.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(we.dim(` Session: ${n}`)),console.log(we.dim(" Start the daemon to begin receiving:")),console.log(we.dim(" agentx daemon start")),console.log(we.dim(" Add routes later with:")),console.log(we.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as df}from"crypto";import xe from"chalk";import id from"prompts";var gs="agentx-mesh:",ms="//join/";function gf(e){return Buffer.from(e,"utf-8").toString("base64url")}function mf(e){return Buffer.from(e,"base64url").toString("utf-8")}function pf(e){return`${gs}${ms}${gf(JSON.stringify(e))}`}function uf(e){if(!e.startsWith(`${gs}${ms}`))throw new Error(`Not a mesh invite link \u2014 expected ${gs}${ms}\u2026`);let o=e.slice(gs.length+ms.length),t=JSON.parse(mf(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function ff(){return df(32).toString("hex")}function hf(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function yf(e){return e?.node?.name||e?.node?.id||"node"}async function rd(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(xe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Di("MESH_TOKEN");r||(r=ff(),ln("MESH_TOKEN",r),console.log(xe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||hf(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await id({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(xe.red(" Aborted")),process.exit(1)),a=d}let l=await he(d=>{Ae(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(xe.red(` \u2717 ${l.error}`)),process.exit(1));let g=pf({url:a,token:r,name:yf(i),version:1});console.log(),console.log(xe.bold(" Mesh invite")),console.log(),console.log(` ${xe.cyan(g)}`),console.log(),console.log(xe.dim(" Run on the other node:")),console.log(xe.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(xe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function ad(e,o={}){let t;try{t=uf(e)}catch(i){console.log(xe.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Di("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await id({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(xe.red(" Aborted (keeping existing .env)")),process.exit(1))}ln("MESH_TOKEN",t.token);let s=await he(i=>{Ae(i,"mesh.enabled",!0);let r=gt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ae(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(xe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(xe.green(" \u2713 Joined mesh")),console.log(xe.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(xe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(xe.dim(" Daemon hot-reloaded.")):console.log(xe.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(xe.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(xe.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(xe.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var jt=new wf().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");jt.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 td({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});jt.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 sd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var cd=jt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");cd.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 rd({url:e.url,configPath:e.config})});cd.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await ad(e,{configPath:o.config})});jt.action(()=>{console.log(),console.log(Ot.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ot.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ot.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ot.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ot.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ot.dim(" GitLab connect is the next slice.")),console.log()});ge();import{Command as bf}from"commander";import pe from"chalk";var gn=new bf().name("usage").description("token usage analysis and reporting");gn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=R(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(pe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(pe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${pe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${pe.red(String(s.totalErrors))}`),console.log(),console.log(pe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${pe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${pe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(pe.red(" Daemon not running. Start with: agentx daemon start")):console.log(pe.red(` ${e.message}`))}});gn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(pe.red(` Script not found: ${s}`)),console.log(pe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(pe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(pe.red(" Analysis failed. Is Python 3 installed?"))}});gn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-V2BX4SBD.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-3CDFUJVE.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let u of d.commands??[]){let f=p?`${p} ${u.name()}`:u.name();c.push(f),l(u,f)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(pe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${pe.dim("\xB7")} ${d}`);console.log(),console.log(pe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(pe.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(pe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(pe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(pe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(pe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=pe.dim(`${i.days}d`);console.log(` ${pe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(pe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as $f}from"commander";import be from"chalk";import{resolve as kf}from"path";ge();var _o=new $f().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");_o.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{kr(kf(process.cwd(),".env"))}catch{}let o=vf(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-LG3ECH7C.js");t(o)}catch(o){console.log(be.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(be.dim(o.stack)),process.exit(1)}});function vf(e,o){try{let t=R();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(be.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(be.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
392
|
+
`}function ln(e,o,t=".env"){let n=Zl(t),s=ed(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${_i(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${_i(o)}`})),Ku(n,ef(s))}function Di(e,o=".env"){return ed(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var od="https://t.me/BotFather";async function of(e){try{let o=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let t=await o.json();return t?.ok?t.result:null}catch{return null}}async function tf(e,o){let t=Date.now()+o,n=0;try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();i?.result?.length&&(n=i.result[0].update_id+1)}catch{}for(;Date.now()<t;)try{let i=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of i?.result||[]){n=Math.max(n,r.update_id+1);let a=r.message||r.edited_message||r.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function td(e={}){console.log(),console.log(te.bold(" Connect Telegram")),console.log(),console.log(te.dim(` 1. Open ${od}`)),console.log(te.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(te.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await dn({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),v=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(v,[od],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await dn({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});t||(console.log(te.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await of(t.trim());n||(console.log(te.red("\u2717 invalid or revoked")),process.exit(1)),console.log(te.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:i}=await import("fs"),{resolve:r}=await import("path"),a=e.configPath||r(process.cwd(),"agentx.json");i(a)||(console.log(te.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(te.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await dn({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(te.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},p=e.account||g;d[p]&&d[p].agentBinding!==g&&(p=(await dn({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(te.red(" Aborted")),process.exit(1));let u=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;ln(u,t.trim()),process.env[u]=t.trim();let f=await he(b=>{Ae(b,"channels.telegram.enabled",!0),Ae(b,`channels.telegram.accounts.${p}`,{token:`\${${u}}`,agentBinding:g});let v=gt(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Ae(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(f.success||(console.log(te.red(` \u2717 ${f.error}`)),process.exit(1)),console.log(),console.log(te.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(te.dim(` Token stored in .env as ${u}`)),console.log(te.dim(` Mentions updated to include @${n.username}`)),f.reloaded?console.log(te.dim(" Daemon hot-reloaded.")):console.log(te.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await dn({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(te.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(te.dim(" Waiting up to 90s..."));let y=await tf(t.trim(),9e4);if(!y){console.log(te.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(te.dim(" agentx config set notifications.destination.channel telegram")),console.log(te.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(te.dim(` agentx config set notifications.destination.accountId ${p}`));return}let k=await he(b=>{Ae(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{configPath:e.configPath});if(!k.success){console.log(te.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(te.green(" \u2713 Default --notify target set")),console.log(te.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(te.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(te.dim(" Daemon hot-reloaded."))}import we from"chalk";import Pi from"prompts";import{existsSync as Li,mkdirSync as nf,readdirSync as sf,readFileSync as nd}from"fs";import{resolve as Mi}from"path";var rf=".agentx/whatsapp-sessions";function af(){let e=Mi(process.cwd(),".agentx/daemon.pid");if(!Li(e))return!1;try{let o=parseInt(nd(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function cf(e){if(!Li(e))return!1;try{return sf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function lf(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(we.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(we.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;nf(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(we.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async u=>{if(u.qr){o(we.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:f}=await import("qrcode-terminal");f.generate(u.qr,{small:!0})}catch{o(` QR: ${u.qr}`)}o("")}if(u.connection==="open"){clearTimeout(p),o(we.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}u.connection==="close"&&!u.qr&&u.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(p),o(we.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function sd(e={}){if(console.log(),console.log(we.bold(" Connect WhatsApp")),console.log(),af()){console.log(we.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(we.dim(" agentx daemon stop")),console.log();let{cont:l}=await Pi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(we.red(" Aborted")),process.exit(1))}let o=e.configPath||Mi(process.cwd(),"agentx.json");Li(o)||(console.log(we.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(nd(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||rf,s=Mi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(we.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Pi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(we.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(cf(s)&&a){let{keep:l}=await Pi({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(we.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await lf(s,g=>console.log(g))||(console.log(we.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await he(l=>{Ae(l,"channels.whatsapp.enabled",!0),Ae(l,"channels.whatsapp.sessionDir",n),Ae(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(we.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(we.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(we.dim(` Session: ${n}`)),console.log(we.dim(" Start the daemon to begin receiving:")),console.log(we.dim(" agentx daemon start")),console.log(we.dim(" Add routes later with:")),console.log(we.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as df}from"crypto";import xe from"chalk";import id from"prompts";var gs="agentx-mesh:",ms="//join/";function gf(e){return Buffer.from(e,"utf-8").toString("base64url")}function mf(e){return Buffer.from(e,"base64url").toString("utf-8")}function pf(e){return`${gs}${ms}${gf(JSON.stringify(e))}`}function uf(e){if(!e.startsWith(`${gs}${ms}`))throw new Error(`Not a mesh invite link \u2014 expected ${gs}${ms}\u2026`);let o=e.slice(gs.length+ms.length),t=JSON.parse(mf(o));if(t.version!==1)throw new Error(`Unsupported invite version: ${t.version}`);if(typeof t.url!="string"||typeof t.token!="string"||typeof t.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return t}function ff(){return df(32).toString("hex")}function hf(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function yf(e){return e?.node?.name||e?.node?.id||"node"}async function rd(e){let{readFileSync:o,existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");t(s)||(console.log(xe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Di("MESH_TOKEN");r||(r=ff(),ln("MESH_TOKEN",r),console.log(xe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||hf(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await id({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(xe.red(" Aborted")),process.exit(1)),a=d}let l=await he(d=>{Ae(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(xe.red(` \u2717 ${l.error}`)),process.exit(1));let g=pf({url:a,token:r,name:yf(i),version:1});console.log(),console.log(xe.bold(" Mesh invite")),console.log(),console.log(` ${xe.cyan(g)}`),console.log(),console.log(xe.dim(" Run on the other node:")),console.log(xe.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(xe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function ad(e,o={}){let t;try{t=uf(e)}catch(i){console.log(xe.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Di("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await id({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(xe.red(" Aborted (keeping existing .env)")),process.exit(1))}ln("MESH_TOKEN",t.token);let s=await he(i=>{Ae(i,"mesh.enabled",!0);let r=gt(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),Ae(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(xe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(xe.green(" \u2713 Joined mesh")),console.log(xe.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(xe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(xe.dim(" Daemon hot-reloaded.")):console.log(xe.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${t.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let r=await i.json(),a=Array.isArray(r.agents)?r.agents.length:"?";console.log(xe.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(xe.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(xe.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var jt=new wf().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");jt.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 td({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});jt.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 sd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var cd=jt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");cd.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 rd({url:e.url,configPath:e.config})});cd.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,o)=>{await ad(e,{configPath:o.config})});jt.action(()=>{console.log(),console.log(Ot.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Ot.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Ot.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Ot.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Ot.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Ot.dim(" GitLab connect is the next slice.")),console.log()});ge();import{Command as bf}from"commander";import pe from"chalk";var gn=new bf().name("usage").description("token usage analysis and reporting");gn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=R(),[o,t]=e.node.bind.split(":"),s=await(await fetch(`http://${o||"127.0.0.1"}:${t}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(pe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(pe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${pe.bold(i(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${i(s.totalInput)}`),console.log(` Output: ${i(s.totalOutput)}`),console.log(` Cache read: ${i(s.totalCacheRead)}`),console.log(` Cache create: ${i(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${pe.red(String(s.totalErrors))}`),console.log(),console.log(pe.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${pe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${pe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(pe.red(" Daemon not running. Start with: agentx daemon start")):console.log(pe.red(` ${e.message}`))}});gn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:o}=await import("child_process"),{existsSync:t}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!t(s)){console.log(pe.red(` Script not found: ${s}`)),console.log(pe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(pe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(pe.red(" Analysis failed. Is Python 3 installed?"))}});gn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:o}=await import("./surface-usage-V2BX4SBD.js"),t=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=o({kind:t,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:i}=await import("./program-KY5ZYPFN.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let u of d.commands??[]){let f=p?`${p} ${u.name()}`:u.name();c.push(f),l(u,f)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(pe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${pe.dim("\xB7")} ${d}`);console.log(),console.log(pe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(pe.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(pe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(pe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(pe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(pe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=pe.dim(`${i.days}d`);console.log(` ${pe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(pe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as $f}from"commander";import be from"chalk";import{resolve as kf}from"path";ge();var _o=new $f().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");_o.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{kr(kf(process.cwd(),".env"))}catch{}let o=vf(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-RUOASCSQ.js");t(o)}catch(o){console.log(be.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(be.dim(o.stack)),process.exit(1)}});function vf(e,o){try{let t=R();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(be.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(be.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
393
393
|
`)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:o||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}_o.command("list").description("list configured boards").action(()=>{try{let e=R();if(!e.boards?.length){console.log(be.dim(`
|
|
394
394
|
No boards configured.
|
|
395
395
|
`));return}console.log();for(let o of e.boards){console.log(` ${be.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(be.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(be.dim(` primary label: ${o.primaryToolLabel}`)),console.log(be.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(be.red(` ${e.message}`)),process.exit(1)}});_o.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,o)=>{try{mn(t=>{if(Array.isArray(t.boards)||(t.boards=[]),t.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(o.projects).split(",").map(i=>i.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:o.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(o.days,10)||30,closedWindowDays:parseInt(o.closedDays,10)||30};return o.label&&(s.primaryToolLabel=o.label),t.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});_o.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,o)=>{try{mn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(o.name&&(s.name=o.name,i.push(`name="${o.name}"`)),o.projects){let r=String(o.projects).split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:r},i.push(`projects=${r.length}`)}if(o.label!==void 0&&(o.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=o.label,i.push(`label="${o.label}"`))),o.days&&(s.timeRangeDays=parseInt(o.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),o.closedDays&&(s.closedWindowDays=parseInt(o.closedDays,10)||s.closedWindowDays,i.push(`closed-days=${s.closedWindowDays}`)),i.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${i.join(", ")})`})}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});var Fi=_o.command("column").description("manage a board's columns (add / remove / edit / list)");Fi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(ng("fs").readFileSync("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(be.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let i=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${be.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${be.dim(i)}`)}}catch(o){console.log(be.red(` ${o.message}`)),process.exit(1)}});Fi.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,o,t)=>{try{mn(n=>{let i=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!i)throw new Error(`board "${e}" not found`);if(i.columns=i.columns||[],i.columns.find(a=>a.id===o))throw new Error(`column "${o}" already exists on board "${e}"`);let r={id:o,title:t.title,kind:t.kind,scopedPrefix:t.scopedPrefix};if(t.kind==="scoped-label"){if(!t.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=t.scoped}if(t.kind==="label"){if(!t.label)throw new Error("--label required for kind=label");r.mapsToLabel=t.label}return t.accent&&(r.accent=t.accent),i.columns.push(r),`column "${o}" added to board "${e}"`})}catch(n){console.log(be.red(` ${n.message}`)),process.exit(1)}});Fi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{mn(t=>{let s=(Array.isArray(t.boards)?t.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(r=>r.id!==o),s.columns.length===i)throw new Error(`column "${o}" not found`);return`column "${o}" removed from board "${e}"`})}catch(t){console.log(be.red(` ${t.message}`)),process.exit(1)}});_o.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{mn(o=>{if(!Array.isArray(o.boards)||o.boards.length===0)throw new Error("no boards configured");let t=o.boards.length;if(o.boards=o.boards.filter(n=>n.id!==e),o.boards.length===t)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(o){console.log(be.red(` ${o.message}`)),process.exit(1)}});function mn(e){let{summary:o,backupPath:t}=po(n=>e(n));console.log(be.green(`
|
|
@@ -541,7 +541,7 @@ ${e.persona}
|
|
|
541
541
|
`),Os(Pe(e.dir,"demo-script.json"),JSON.stringify(e.script,null,2));let s=o.filter(r=>r.id!==e.id).map(r=>({name:r.name,url:`http://127.0.0.1:${r.port}`,token:t})),i={node:{id:e.id,name:e.name,bind:`127.0.0.1:${e.port}`,defaultAgent:e.agentId},dashboard:{enabled:!0,port:e.port+10,bind:"127.0.0.1",daemonUrl:`http://127.0.0.1:${e.port}`},providers:{demo:{apiKey:"demo-mode"}},agents:{[e.agentId]:{name:e.agentName,description:e.persona,workspace:"./workspaces/"+e.agentId,tier:"orchestrator",provider:"demo",mentions:[`@${e.agentId}`,e.agentId],maxConcurrent:2,systemPrompt:e.persona}},mesh:{enabled:!0,peers:s,discovery:"static",healthCheck:{interval:3,timeout:5}},workflows:{enabled:!0}};Os(Pe(e.dir,"agentx.json"),JSON.stringify(i,null,2))}async function tr(e,o,t){let n=Date.now();for(;Date.now()-n<t;){try{if(await o())return}catch{}await new Promise(s=>setTimeout(s,500))}throw new Error(`Timed out waiting for ${e} (${Math.round(t/1e3)}s)`)}async function nr(e,o,t){let n=await fetch(`http://127.0.0.1:${e}${o}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok||s.error)throw new Error(s.error||`${o} HTTP ${n.status}`);return s}function Ts(e,o,t){console.log(),console.log(t(` ${e}`)),console.log(` ${o.split(`
|
|
542
542
|
`).join(`
|
|
543
543
|
`)}`)}var Jd=new Th().name("demo").description("zero-key demo: three daemons, a real A2A mesh, a scripted scenario").option("--base-port <port>","first of three consecutive loopback ports","18921").option("--once","play the scenario once and exit (default: keep daemons up until Ctrl-C)").option("--keep","keep the .agentx-demo directory on exit").option("--no-open","don't open the dashboard in a browser").option("--reuse","resume an existing .agentx-demo instead of starting fresh (implies --keep)").option("--bind <host>","dashboard bind address","127.0.0.1").action(async e=>{let o=parseInt(e.basePort,10),t=Nh(process.cwd(),".agentx-demo"),n=Dh(t,o),s=Pe(t,"mesh-token"),i=!!e.reuse&&Is(s)&&Is(Pe(n[0].dir,"agentx.json")),r=i?jh(s,"utf8").trim():Rh(24).toString("hex"),a=e.keep||e.reuse,c=[],l=process.argv[1];if((!l||!Is(l))&&(console.error(ce.red("Cannot resolve the agentx CLI entrypoint \u2014 run via the installed `agentx` binary.")),process.exit(1)),!i){if(Is(t))for(let u of Ch(t))qd(Pe(t,u),{recursive:!0,force:!0});for(let u of n)Ph(u,n,r);Os(s,r+`
|
|
544
|
-
`,{mode:384})}console.log(),console.log(ce.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ce.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ce.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,d=u=>{if(!g){g=!0;for(let f of c)try{f.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{qd(t,{recursive:!0,force:!0})}catch{}process.exit(u)},800)}};process.on("SIGINT",()=>d(0)),process.on("SIGTERM",()=>d(0));let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD,delete p.OPENAI_API_KEY,delete p.DEEPSEEK_API_KEY;try{for(let y of n){let k=Wd(Pe(y.dir,"daemon.log"),"a"),b=or(process.execPath,[l,"daemon","start","-c",Pe(y.dir,"agentx.json")],{cwd:y.dir,env:{...p,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:Pe(y.dir,"demo-script.json")},stdio:["ignore",k,k]});c.push(b),console.log(ce.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${Pe(y.dir,"daemon.log")})`))}for(let y of n)await tr(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(ce.green(" \u2713 three daemons up"));let u=n[0].port+10;{let y=Wd(Pe(n[0].dir,"board.log"),"a"),k=or(process.execPath,[l,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...p,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push(k)}await tr("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${u}/live`)).ok,3e4),console.log(ce.green(" \u2713 dashboard up")),await tr("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(v=>v.healthy&&v.skills?.length).length>=2,3e4),console.log(ce.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let f=`http://127.0.0.1:${u}/live`;if(console.log(),console.log(` Dashboard: ${ce.cyan(f)} (all three nodes via the mesh)`),console.log(ce.dim(` Daemon APIs: ${n.map(y=>`127.0.0.1:${y.port}`).join(" \xB7 ")}`)),e.open!==!1){let y=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{or(y,[f],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(ce.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Ts("You \u2192 @cx (laptop-paris)",Bd,ce.cyan);let y=await nr(n[0].port,"/task",{agent:"cx",message:Bd});Ts("@cx (laptop-paris)",y.content||"(no content)",ce.green),console.log(),console.log(ce.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let k=await nr(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:_h}),b=typeof k.messageId=="string"?k.messageId:k.content||"(no reply)";Ts("@builder (vps-nyc)",b,ce.yellow);let v=await nr(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});Ts("@cx (laptop-paris)",v.content||"(no content)",ce.green),console.log(),console.log(ce.dim(` Inspect the run: ${f} \xB7 ledger rows on each node record every dispatch`)),console.log(ce.dim(` Worth your time? A star helps others find it: ${ce.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(ce.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(ce.dim(" --once: shutting down.")),d(0);return}console.log(),console.log(ce.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{w().catch(y=>console.error(ce.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(u){console.error(),console.error(ce.red(` Demo failed: ${u.message}`)),console.error(ce.dim(` Node logs: ${n.map(f=>Pe(f.dir,"daemon.log")).join(", ")}`)),d(1)}});import{Command as Mh}from"commander";import{randomUUID as Lh}from"crypto";import{readFileSync as Fh}from"fs";import{resolve as Uh}from"path";ge();var Hd=new Mh().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").action(async(e,o)=>{let t=(e??Fh(0,"utf8")).trim();t||Gd("no task given (pass it as an argument or on stdin)");let n=R(o.config?Uh(o.config):void 0),s=n.agents[o.agent];s||Gd(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";vr(o.agent,s,l,i)}let r=new Lr(n,i),a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:"exec",chatId:`exec-${Lh()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
|
|
544
|
+
`,{mode:384})}console.log(),console.log(ce.bold(" agentx demo \u2014 one message, three machines (simulated on loopback)")),console.log(ce.yellow(" Canned model responses. Real daemons, real A2A mesh, real ledger.")),console.log(ce.dim(" Run `agentx setup` to wire real agents.\n"));let g=!1,d=u=>{if(!g){g=!0;for(let f of c)try{f.kill("SIGTERM")}catch{}setTimeout(()=>{if(!a)try{qd(t,{recursive:!0,force:!0})}catch{}process.exit(u)},800)}};process.on("SIGINT",()=>d(0)),process.on("SIGTERM",()=>d(0));let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD,delete p.OPENAI_API_KEY,delete p.DEEPSEEK_API_KEY,p.INTENT_LEDGER_MODE||="shadow";try{for(let y of n){let k=Wd(Pe(y.dir,"daemon.log"),"a"),b=or(process.execPath,[l,"daemon","start","-c",Pe(y.dir,"agentx.json")],{cwd:y.dir,env:{...p,MESH_TOKEN:r,AGENTX_DEMO_SCRIPT:Pe(y.dir,"demo-script.json")},stdio:["ignore",k,k]});c.push(b),console.log(ce.dim(` \u25B8 ${y.name} starting on 127.0.0.1:${y.port} (log: ${Pe(y.dir,"daemon.log")})`))}for(let y of n)await tr(`${y.name} /health`,async()=>(await fetch(`http://127.0.0.1:${y.port}/health`)).ok,3e4);console.log(ce.green(" \u2713 three daemons up"));let u=n[0].port+10;{let y=Wd(Pe(n[0].dir,"board.log"),"a"),k=or(process.execPath,[l,"board","serve","--bind",e.bind],{cwd:n[0].dir,env:{...p,MESH_TOKEN:r},stdio:["ignore",y,y]});c.push(k)}await tr("dashboard /live",async()=>(await fetch(`http://127.0.0.1:${u}/live`)).ok,3e4),console.log(ce.green(" \u2713 dashboard up")),await tr("mesh discovery (laptop sees both peers)",async()=>((await(await fetch(`http://127.0.0.1:${n[0].port}/health`)).json()).mesh||[]).filter(v=>v.healthy&&v.skills?.length).length>=2,3e4),console.log(ce.green(" \u2713 A2A mesh healthy \u2014 agent cards exchanged across three nodes"));let f=`http://127.0.0.1:${u}/live`;if(console.log(),console.log(` Dashboard: ${ce.cyan(f)} (all three nodes via the mesh)`),console.log(ce.dim(` Daemon APIs: ${n.map(y=>`127.0.0.1:${y.port}`).join(" \xB7 ")}`)),e.open!==!1){let y=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{or(y,[f],{stdio:"ignore",detached:!0}).unref()}catch{}}let w=async()=>{console.log(),console.log(ce.bold(" \u2500\u2500 Scenario: red pipeline, cross-node fix \u2500\u2500")),Ts("You \u2192 @cx (laptop-paris)",Bd,ce.cyan);let y=await nr(n[0].port,"/task",{agent:"cx",message:Bd});Ts("@cx (laptop-paris)",y.content||"(no content)",ce.green),console.log(),console.log(ce.magenta(" \u21C4 mesh hop: laptop-paris \u2192 vps-nyc (A2A /task)"));let k=await nr(n[0].port,"/send/agent",{agentId:"builder",senderAgentId:"cx",text:_h}),b=typeof k.messageId=="string"?k.messageId:k.content||"(no reply)";Ts("@builder (vps-nyc)",b,ce.yellow);let v=await nr(n[0].port,"/task",{agent:"cx",message:`[demo] Builder reports: ${b}`});Ts("@cx (laptop-paris)",v.content||"(no content)",ce.green),console.log(),console.log(ce.dim(` Inspect the run: ${f} \xB7 ledger rows on each node record every dispatch`)),console.log(ce.dim(` Worth your time? A star helps others find it: ${ce.cyan("https://github.com/anis-marrouchi/agentx")}`))};if(i?console.log(ce.dim(" Resumed existing demo state \u2014 press Enter to replay the scenario.")):await w(),e.once){console.log(),console.log(ce.dim(" --once: shutting down.")),d(0);return}console.log(),console.log(ce.bold(" Daemons stay up \u2014 browse the dashboards. Press Enter to replay, Ctrl-C to exit.")),process.stdin.setEncoding("utf8"),process.stdin.on("data",()=>{w().catch(y=>console.error(ce.red(` Replay failed: ${y.message}`)))}),process.stdin.resume()}catch(u){console.error(),console.error(ce.red(` Demo failed: ${u.message}`)),console.error(ce.dim(` Node logs: ${n.map(f=>Pe(f.dir,"daemon.log")).join(", ")}`)),d(1)}});import{Command as Mh}from"commander";import{randomUUID as Lh}from"crypto";import{readFileSync as Fh}from"fs";import{resolve as Uh}from"path";ge();var Hd=new Mh().name("exec").description("run one task through an agent and exit \u2014 for scripts and benchmarks").argument("[message]","the task (default: read from stdin)").requiredOption("-a, --agent <id>","agent id from the config").option("-c, --config <path>","config file (default: ./agentx.json)").option("-m, --model <model>","override the agent's model for this task").option("--timeout <minutes>","upper bound on the task's run time").option("--setup-workspace","write the managed workspace files first, as daemon boot does").option("--json","print one JSON result object instead of the reply text").action(async(e,o)=>{let t=(e??Fh(0,"utf8")).trim();t||Gd("no task given (pass it as an argument or on stdin)");let n=R(o.config?Uh(o.config):void 0),s=n.agents[o.agent];s||Gd(`unknown agent "${o.agent}" \u2014 known: ${Object.keys(n.agents).join(", ")}`);let i=(...l)=>console.error("[agentx exec]",...l);if(o.setupWorkspace){let l=n.node.bind.split(":")[1]||"19900";vr(o.agent,s,l,i)}let r=new Lr(n,i),a=Date.now(),c=await r.execute({agentId:o.agent,message:t,model:o.model,timeoutMinutes:o.timeout?Number(o.timeout):void 0,context:{channel:"exec",chatId:`exec-${Lh()}`,sender:"cli"}});o.json?process.stdout.write(JSON.stringify({content:c.content,error:c.error,errorKind:c.errorKind,usage:c.usage,numTurns:c.numTurns,billedModel:c.billedModel,durationMs:Date.now()-a})+`
|
|
545
545
|
`):c.error?console.error(c.error):process.stdout.write(c.content+`
|
|
546
546
|
`),process.exit(c.error?1:0)});function Gd(e){console.error(`agentx exec: ${e}`),process.exit(1)}ge();import{Command as qh}from"commander";import Oe from"chalk";var Fo=new qh().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Fo.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let t=(await wn("/whatsapp/chats")).chats??[];if(e.group&&(t=t.filter(n=>n.isGroup)),e.dm&&(t=t.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Oe.dim(" no chats cached yet"));return}console.log(),console.log(Oe.bold(` ${t.length} chat${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=n.isGroup?Oe.cyan("group"):Oe.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${Oe.dim(n.jid.padEnd(40))} ${Oe.dim(i)}`)}console.log()}catch(o){Mt(o)}});Fo.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let t=(await wn("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(t,null,2));return}if(t.length===0){console.log(Oe.dim(" no contacts cached yet"));return}console.log(),console.log(Oe.bold(` ${t.length} contact${t.length===1?"":"s"}`)),console.log();for(let n of t){let s=(n.name||n.pushName||n.phone||n.jid).padEnd(30),i=n.phone?`+${n.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${Oe.dim(i)} ${Oe.dim(n.jid)}`)}console.log()}catch(o){Mt(o)}});Fo.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let o={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(o.agent=e.agent);let t=await ir("/whatsapp/ingest",o);sr(t,!!e.dryRun)}catch(o){Mt(o)}});Fo.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};o.agent&&(t.agent=o.agent);let n=await ir("/whatsapp/ingest",t);sr(n,!!o.dryRun)}catch(t){Mt(t)}});Fo.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,o)=>{try{let t={dryRun:!!o.dryRun,force:!0,onlyJid:e};o.agent&&(t.agent=o.agent),o.messages&&(t.forceMode="messages");let n=await ir("/whatsapp/ingest",t);sr(n,!!o.dryRun)}catch(t){Mt(t)}});Fo.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await wn("/whatsapp/state"),o=await wn("/whatsapp/chats"),t=await wn("/whatsapp/contacts");console.log(),console.log(Oe.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${o.chats?.length??0}`),console.log(` cached contacts: ${t.contacts?.length??0}`),console.log()}catch(e){Mt(e)}});function sr(e,o){if(console.log(),console.log(Oe.bold(o?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(Oe.yellow(` errors: ${e.errors.length}`));for(let t of e.errors.slice(0,5))console.log(Oe.yellow(` - [${t.kind}] ${t.jid}: ${t.message}`))}if(o&&e.dryRunEntries?.length){console.log(),console.log(Oe.dim(" would-be entries:"));for(let t of e.dryRunEntries.slice(0,10))console.log(Oe.dim(` - ${t.id} (${t.source}, ${t.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(Oe.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function zd(){try{let e=R(),[o,t]=e.node.bind.split(":");return`http://${o||"127.0.0.1"}:${t||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function wn(e){let o=await fetch(`${zd()}${e}`,{signal:AbortSignal.timeout(1e4)}),t=await o.json().catch(()=>({}));if(!o.ok)throw new Error(t.error||`HTTP ${o.status}`);return t}async function ir(e,o){let t=await fetch(`${zd()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(6e5)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error(n.error||`HTTP ${t.status}`);return n}function Mt(e){console.error(Oe.red(` ${e.message||e}`)),process.exit(1)}ge();import{Command as Wh}from"commander";import le from"chalk";import{existsSync as Bh,mkdirSync as Yd,writeFileSync as bn}from"fs";import{join as Lt,resolve as Jh}from"path";var $n=new Wh().name("plugin").description("manage agentx plugins (Move B)");$n.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let o=R().plugins??[];if(console.log(),o.length===0){console.log(le.dim(" No plugins configured.")),console.log(le.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(le.bold(` Plugins configured: ${o.length}`)),console.log();for(let t of o)console.log(` ${le.cyan(t)}`);console.log(),console.log(le.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(le.red(` ${e.message}`)),process.exitCode=1}});$n.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,o)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(le.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let t=e.startsWith("@")?e.split("/")[1]:e,n=Jh(o.cwd,t);Bh(n)&&!o.force&&(console.log(le.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),Yd(n,{recursive:!0}),Yd(Lt(n,"src"),{recursive:!0});let s=o.description||`AgentX plugin: ${e}`;bn(Lt(n,"package.json"),Yh(e,s)),bn(Lt(n,"tsconfig.json"),Vh()),bn(Lt(n,"src/index.ts"),Kh(e)),bn(Lt(n,"README.md"),Xh(e,s)),bn(Lt(n,".gitignore"),Qh()),console.log(),console.log(le.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(le.bold(" Next steps:")),console.log(le.dim(` cd ${t}`)),console.log(le.dim(" pnpm install")),console.log(le.dim(" pnpm build")),console.log(le.dim(" pnpm link --global # for local testing")),console.log(le.dim(" # then in your agentx project:")),console.log(le.dim(` pnpm link --global ${e}`)),console.log(le.dim(` agentx config set plugins[0] "${e}"`)),console.log(le.dim(" agentx plugin doctor")),console.log()});$n.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let o=R().plugins??[];if(console.log(),o.length===0){console.log(le.dim(" No plugins configured. Nothing to check.")),console.log();return}let t=0;for(let n of o){let s=await Gh(n);s.kind==="ok"?console.log(` ${le.green("\u2713")} ${le.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(t++,console.log(` ${le.red("\u2717")} ${le.cyan(n)} \u2014 ${s.reason}`))}console.log(),t>0&&(console.log(le.red(` ${t}/${o.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(le.red(` ${e.message}`)),process.exitCode=1}});async function Gh(e){let o;try{o=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let t=Hh(o);if(!zh(t))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=$a.safeParse(t.manifest);return n.success?{kind:"ok",manifestName:n.data.name,manifestVersion:n.data.version}:{kind:"fail",reason:`manifest invalid: ${n.error.issues.map(i=>i.message).join("; ")}`}}function Hh(e){if(e==null||typeof e!="object")return e;let o=e;if(o.default&&typeof o.default=="object"){let t=o.default;if(t.manifest&&typeof t.setup=="function")return t;if(t.default&&typeof t.default=="object"){let n=t.default;if(n.manifest&&typeof n.setup=="function")return n}}return o.manifest&&typeof o.setup=="function"?o:o.default??o}function zh(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Yh(e,o){return JSON.stringify({name:e,version:"0.1.0",description:o,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
|
|
547
547
|
`}function Vh(){return JSON.stringify({compilerOptions:{target:"es2020",module:"commonjs",lib:["es2020"],declaration:!0,outDir:"dist",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node"},include:["src/**/*.ts"]},null,2)+`
|
|
@@ -612,7 +612,7 @@ Restart the daemon to activate.
|
|
|
612
612
|
dist/
|
|
613
613
|
*.log
|
|
614
614
|
.env
|
|
615
|
-
`}import{Command as Zh}from"commander";import je from"chalk";import{writeFileSync as ey,mkdirSync as oy,existsSync as js,readFileSync as Vd,appendFileSync as Kd}from"fs";import{resolve as Ft,dirname as Zd}from"path";import{homedir as ar}from"os";var eg=new Zh().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-
|
|
615
|
+
`}import{Command as Zh}from"commander";import je from"chalk";import{writeFileSync as ey,mkdirSync as oy,existsSync as js,readFileSync as Vd,appendFileSync as Kd}from"fs";import{resolve as Ft,dirname as Zd}from"path";import{homedir as ar}from"os";var eg=new Zh().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:o}=await import("./program-KY5ZYPFN.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=sy(t);break;case"bash":s=ly(t);break;case"fish":s=dy(t);break;default:console.error(je.red(`unsupported shell: ${n}`)),console.error(je.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Ft(String(e.output)):ty(n);oy(Zd(i),{recursive:!0}),ey(i,s),console.log(je.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),ny(n,i,!!e.yes)});function ty(e){let o=ar();switch(e){case"zsh":return Ft(o,".zsh","completions","_agentx");case"bash":return Ft(o,".bash_completion.d","agentx.bash");case"fish":return Ft(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function ny(e,o,t){if(e==="zsh"){let n=Ft(ar(),".zshrc"),s=Zd(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=js(n)?Vd(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(je.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&js(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Kd(n,g.join(`
|
|
616
616
|
`)+`
|
|
617
617
|
`),console.log(je.green("\u2713 Patched ~/.zshrc")),console.log(je.dim("Reload your shell: exec zsh"));return}console.log(je.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(je.cyan(` ${i}`)),l&&console.log(je.cyan(` ${r}`)),console.log(),console.log(je.dim("Then reload: exec zsh")),console.log(je.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Ft(ar(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((js(n)?Vd(n,"utf-8"):"").includes(o)){console.log(je.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&js(n)){Kd(n,`
|
|
618
618
|
# agentx completion
|
|
@@ -623,4 +623,4 @@ ${s}
|
|
|
623
623
|
`)}function cr(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function rr(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=cr(e.description||""),r=["complete -c agentx",o.map(a=>`-n "${a}"`).join(" ")];return t&&r.push(`-s ${t}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}async function CA(){let e=await Xa(),o=new gy().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");o.hook("preAction",(t,n)=>{let s=sc(n);ic(s)&&nc("cli",s)});for(let t of[Rc,jc,jt,ht,Ve,ec,Go,Vn,ho,Ro,Zo,Yn,_d,jo,Xc,rl,rn,yl,kl,vl,Fl,Bl,Jl,ls,gn,Fd,Qt,Eo,eg])o.addCommand(t);for(let t of tg)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=tg.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,my(t,74," "),""].join(`
|
|
624
624
|
`)}),o}var tg=[Q,Ct,Lo,to,en,It,Je,wo,_o,et,Dt,Pt,To,qe,xt,ds,Nd,uo,kt,dc,Ho,$n,ai,Mo,$t,ci,vs,Do,Fo,Jd,Hd,Ld];function my(e,o,t){let n=[],s="";for(let i of e)s&&s.length+i.length+2>o&&(n.push(t+s),s=""),s+=(s?", ":"")+i;return s&&n.push(t+s),n.join(`
|
|
625
625
|
`)}export{CA as a};
|
|
626
|
-
//# sourceMappingURL=chunk-
|
|
626
|
+
//# sourceMappingURL=chunk-Y6I3BYWV.js.map
|