agentix-cli 0.47.0 → 0.47.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-ZEVB6LE4.js → agent-I6RXAEXG.js} +2 -2
- package/dist/{board-dashboard-GADOZ7XY.js → board-dashboard-4LAQOB74.js} +3 -3
- package/dist/{chunk-WCAKT4FN.js → chunk-FQBPSL36.js} +2 -2
- package/dist/{chunk-PTFW5TYY.js → chunk-FXGSSZAP.js} +2 -2
- package/dist/chunk-LYOXXD4T.js +123 -0
- package/dist/chunk-LYOXXD4T.js.map +1 -0
- package/dist/{chunk-GPQTI5KD.js → chunk-OSSI6R4K.js} +2 -2
- package/dist/{chunk-3AZ2OZMU.js → chunk-QURVHYBP.js} +4 -4
- package/dist/chunk-XMRI32CY.js +160 -0
- package/dist/chunk-XMRI32CY.js.map +1 -0
- package/dist/{chunk-FPXYQ4IM.js → chunk-XMWOV2D5.js} +2 -2
- package/dist/{chunk-KFXLQNDQ.js → chunk-YIXQDOPN.js} +3 -3
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +10 -6
- package/dist/index.js +1 -1
- package/dist/{program-3IZMYDWS.js → program-PMHQRD5E.js} +2 -2
- package/dist/{registry-GROS7A2D.js → registry-GGU43EOI.js} +2 -2
- package/dist/{schedule-tool-3EFQMD2F.js → schedule-tool-6SNLG2NA.js} +2 -2
- package/dist/scheduler-N25EAWF6.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-VCT7ZPIA.js +0 -123
- package/dist/chunk-VCT7ZPIA.js.map +0 -1
- package/dist/chunk-ZYL3TO4I.js +0 -160
- package/dist/chunk-ZYL3TO4I.js.map +0 -1
- package/dist/scheduler-NT4YXVA6.js +0 -2
- /package/dist/{agent-ZEVB6LE4.js.map → agent-I6RXAEXG.js.map} +0 -0
- /package/dist/{board-dashboard-GADOZ7XY.js.map → board-dashboard-4LAQOB74.js.map} +0 -0
- /package/dist/{chunk-WCAKT4FN.js.map → chunk-FQBPSL36.js.map} +0 -0
- /package/dist/{chunk-PTFW5TYY.js.map → chunk-FXGSSZAP.js.map} +0 -0
- /package/dist/{chunk-GPQTI5KD.js.map → chunk-OSSI6R4K.js.map} +0 -0
- /package/dist/{chunk-3AZ2OZMU.js.map → chunk-QURVHYBP.js.map} +0 -0
- /package/dist/{chunk-FPXYQ4IM.js.map → chunk-XMWOV2D5.js.map} +0 -0
- /package/dist/{chunk-KFXLQNDQ.js.map → chunk-YIXQDOPN.js.map} +0 -0
- /package/dist/{program-3IZMYDWS.js.map → program-PMHQRD5E.js.map} +0 -0
- /package/dist/{registry-GROS7A2D.js.map → registry-GGU43EOI.js.map} +0 -0
- /package/dist/{schedule-tool-3EFQMD2F.js.map → schedule-tool-6SNLG2NA.js.map} +0 -0
- /package/dist/{scheduler-NT4YXVA6.js.map → scheduler-N25EAWF6.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as va,b as On,g as xa}from"./chunk-BHPIAG3E.js";import{a as _o,b as fa,f as An,i as _s,j as $a,l as ka}from"./chunk-VHTFHGVW.js";import{a as ya,c as wa,d as ba}from"./chunk-SFLF64Q3.js";import{b as ha}from"./chunk-W544ZCCO.js";import{a as Ss,b as wr,c as Es,g as br,h as $r,j as kr,k as vr,m as xr,n as Sr,o as Er}from"./chunk-
|
|
1
|
+
import{a as va,b as On,g as xa}from"./chunk-BHPIAG3E.js";import{a as _o,b as fa,f as An,i as _s,j as $a,l as ka}from"./chunk-VHTFHGVW.js";import{a as ya,c as wa,d as ba}from"./chunk-SFLF64Q3.js";import{b as ha}from"./chunk-W544ZCCO.js";import{a as Ss,b as wr,c as Es,g as br,h as $r,j as kr,k as vr,m as xr,n as Sr,o as Er}from"./chunk-OSSI6R4K.js";import{a as tt}from"./chunk-GV7S5BAX.js";import{e as lr}from"./chunk-GSX4NK2N.js";import{c as dr}from"./chunk-SZDACK6O.js";import{A as yo,B as ea,C as Ts,D as js,E as oa,F as ta,G as Pt,H as vn,I as na,J as sa,K as ia,L as ra,M as it,N as aa,O as ca,P as ke,Q as xn,R as Mt,S as Is,T as la,U as Sn,V as En,W as ma,X as Rs,Y as Ds,Z as pa,_ as ua,a as Ar,b as Or,h as Dt,i as yn,j as Rr,k as Dr,l as _r,m as Pr,n as Gr,o as Hr,p as zr,q as Yr,r as Vr,s as Kr,t as Xr,u as Qr,v as _t,w as Os,x as kn,y as Zr,z as st}from"./chunk-YIXQDOPN.js";import{l as $n,m as Br,n as Jr,q as da,r as Cs,s as ga,t as Ns}from"./chunk-FQBPSL36.js";import{a as Tr,d as jr,e as Ir}from"./chunk-FNLGY4UV.js";import{a as As,b as wn,c as bn,d as Mr,e as Lr,f as Fr,i as Ur,j as qr,k as Wr}from"./chunk-7L6M3P2N.js";import{a as Cr,p as Nr}from"./chunk-VZDKE2EZ.js";import{E as hr,O as yr,h as sr,q as ir,s as Nt,v as ks,w as ar,y as ho}from"./chunk-XMRI32CY.js";import{b as et,c as fn,d as hn,e as ot,f as cr,g as Do,h as Rt}from"./chunk-FXGSSZAP.js";import{a as nr}from"./chunk-DJQA2CWD.js";import{d as xs,i as ur}from"./chunk-WZGABQ72.js";import{b as Zo}from"./chunk-DP7RTNDM.js";import{a as rr,e as pr}from"./chunk-LYOXXD4T.js";import{f as gr,g as mr,h as vs}from"./chunk-76Z4VHDX.js";import{b as fe,c as Ee,d as nt,e as fr}from"./chunk-J63MRNXF.js";import{h as tr}from"./chunk-DWADWDMU.js";import{a as $s}from"./chunk-BJWK7FPT.js";import{b as fo,d as un}from"./chunk-KTM7HSEB.js";import{b as Qo,d as or}from"./chunk-2GIDVZ4H.js";import{a as bs,b as Bi,c as rd,d as mn,e as Ji,f as Vi,g as cd,h as Ki,i as ld,m as Xo,n as Qi,o as Zi,s as er,v as Ze,w as Ct}from"./chunk-BZLHS3VF.js";import{a as ao,b as Ko,e as Hi,f as It}from"./chunk-F4HZTZHW.js";import{a as Xi,b as dd}from"./chunk-AJONZWLT.js";import{a as ro,b as id}from"./chunk-L2WSPY6S.js";import{k as Gi,l as _,m as pn,o as me}from"./chunk-ANLKBCYH.js";import{g as zi,k as Yi,l as ad}from"./chunk-BH3GTCZ6.js";import{a as sd}from"./chunk-FIOB3MEX.js";import{Command as gd}from"commander";var Sa=new gd().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 Or({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()});me();import{Command as md}from"commander";import{execFileSync as eo}from"node:child_process";import{cpSync as Ea,existsSync as Ls,mkdirSync as Ps,mkdtempSync as pd,readFileSync as ud,rmSync as fd,writeFileSync as Aa}from"node:fs";import{dirname as Ms,join as Ce,resolve as Oa}from"node:path";import{homedir as Tn,release as hd,tmpdir as yd}from"node:os";import{fileURLToPath as wd}from"node:url";import{setTimeout as bd}from"node:timers/promises";function jn(){let e=Mr(process.platform,process.arch,hd());if(e)throw new Error(e)}function Lt(){return`gui/${process.getuid()}/${As}`}function rt(){return Ce(Tn(),"Library/LaunchAgents",`${As}.plist`)}async function Ta(){try{eo("launchctl",["bootout",Lt()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{eo("launchctl",["print",Lt()],{stdio:"pipe"})}catch{return}await bd(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function ja(){if(!Ls(rt()))throw new Error("Run agentx desktop install first.");let e=!0;try{eo("launchctl",["print",Lt()],{stdio:"pipe"})}catch{e=!1}e||eo("launchctl",["bootstrap",`gui/${process.getuid()}`,rt()],{stdio:"pipe"}),eo("launchctl",["kickstart",Lt()],{stdio:"pipe"})}function $d(){let e=Ms(wd(import.meta.url));for(let o of[Oa(e,".."),Oa(e,"../.."),process.cwd()])try{if(JSON.parse(ud(Ce(o,"package.json"),"utf8")).name==="agentix-cli"&&Ls(Ce(o,"apps/mac-voice/build.sh")))return o}catch{}throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var at=new md("desktop").description("install and control the macOS desktop assistant");at.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=>{jn();let o=_(),t=Lr(o.agents,e.agent),n=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,s=$d(),i=Ce(Tn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Ce(i,wn)}
|
|
2
2
|
Computer-use helper \u2192 ${Ce(i,bn)}
|
|
3
3
|
Agent \u2192 ${t}
|
|
4
4
|
Daemon \u2192 ${n}
|
|
@@ -379,7 +379,7 @@ return aid ?? null`}function Fm(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
379
379
|
settings \u2014 without this an attached production identity would be less
|
|
380
380
|
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)}});Go.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=Da({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)}});me();import{Command as kp}from"commander";import he from"chalk";var Kn=new kp().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Kc(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=_(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 Xc(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function Vc(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 vp(e){return e==="busy"?he.magenta:e==="warm-hot"?he.green:e==="warm-cold"?he.cyan:e==="idle"?he.yellow:e==="dead"?he.red:he.dim}Kn.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}=Kc(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Xc(t)})}catch(r){console.log(he.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(he.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(he.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(he.dim(" (no processes)"));return}for(let r of i){let a=vp(r.state)(r.state.padEnd(9)),c=Vc(r.spawnedAt),l=r.lastTurnAt?Vc(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?he.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?he.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):he.dim("sess=\u2014"),u=r.pendingTaskId?he.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${he.bold(r.key.agentId)}${he.dim(":"+r.key.channel+":"+r.key.chatId)} ${he.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${he.red("dead:")} ${r.deadReason}`)}});Kn.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}=Kc(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Xc(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(he.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(he.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(he.red(` ${a}`)),process.exit(1)}console.log(he.green(` killed ${e}:${o}:${t}`))});import{Command as xp}from"commander";import Re from"chalk";import{existsSync as mi,rmSync as Sp}from"fs";import{resolve as pi}from"path";var ht=new xp().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");ht.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(Re.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await gr(e,o,{verbose:n}),r=Date.now()-s;console.log(Re.green(` \u2713 indexed ${i.docs} doc(s) for ${Re.bold(e)} in ${r}ms`)),console.log(Re.dim(` \u2192 ${i.path}`))});ht.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=pi(e.cwd,".agentx","rag");if(!mi(o)){console.log(Re.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>mi(pi(o,s,"index.json")));if(n.length===0){console.log(Re.dim(" (no indexes)"));return}for(let s of n.sort()){let i=vs(s);console.log(` ${Re.bold(s)} ${i.docs} doc(s) ${Re.dim(i.path)}`)}});ht.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=mr(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=vs(e);i.exists?console.log(Re.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Re.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Re.bold(i.title)} ${Re.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Re.dim(i.path)}`),console.log(` ${Re.dim(i.snippet.slice(0,200))}`)});ht.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=pi(process.cwd(),".agentx","rag",e);if(!mi(o)){console.log(Re.dim(` no index for ${e} \u2014 nothing to clear`));return}Sp(o,{recursive:!0,force:!0}),console.log(Re.green(` \u2713 cleared index for ${e}`))});me();import{Command as Ep}from"commander";import K from"chalk";import yt from"prompts";var Ho=new Ep().name("backlog").description("manage the local backlog used by business workSource=backlog");function Xt(e){let o=_(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new da(n)}}function Ap(e){return e?K.cyan(`${e.type}:${e.project}#${e.iid}`):K.dim("manual")}function Op(e){return{todo:K.gray("todo"),doing:K.yellow("doing"),blocked:K.red("blocked"),done:K.green("done")}[e]}Ho.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}=Xt(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(` ${Op(n.status).padEnd(7)} ${Ap(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()}`))});Ho.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=Xt(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=ga([o],i.source,n.config),a=await Ns(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}`))}});Ho.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=Xt(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 Ns(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}`))}});Ho.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}=Xt(o.config);t.remove(e)||(console.error(K.red(` item ${e} not found`)),process.exit(1)),console.log(K.green(` removed ${e}`))});Ho.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=Xt(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 yt({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"?jp(o.config):Ip(o.config);y.length?(i=(await yt({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 yt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await yt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await yt({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 Cp(o.config,i,a):await Np(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=Cs({type:s,project:l,iid:y.iid,url:y.url}),b=g.has(k),S=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${S}${b?K.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await yt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!f.length){console.log(K.dim(" nothing selected"));return}let p=f.map(y=>{let k={type:s,host:s==="gitlab"?Tp(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:Cs(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(p);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 Tp(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function jp(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 Ip(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 Cp(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 Np(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(Qc)}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(Qc):[]}function Qc(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 Rp}from"commander";import W from"chalk";import{existsSync as Dp,readFileSync as _p}from"fs";import{resolve as Pp}from"path";import Mp from"prompts";me();function Zc(e){let o=e||Pp(process.cwd(),"agentx.json");return Dp(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(_p(o,"utf-8"))}async function Lp(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 Mp([{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 go=new Rp().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');go.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: ${Es})`,Es).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){go.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=Ss(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=Zc(o.config),s=Gi(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 Lp(o.notify,s),r=o.id||wr(t.matched,o.agent),a=$r({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:br(o.onError),enabled:!o.disabled}),c=a.onError,l=await fe(d=>Ee(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."))});go.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=Zc(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=vr(kr(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]])go.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await Er(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."))});go.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await fe(t=>{if(!nt(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);fr(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",xr,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",Sr,"reject an agent's pending create/delete request (drops the request)"]])go.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."))});go.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Ss(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 au}from"commander";import wt from"chalk";import ee from"chalk";import Zt from"prompts";import{readFileSync as Fp,writeFileSync as Up,existsSync as qp}from"fs";import{resolve as el}from"path";var Wp=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Bp(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function ui(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function ol(e=".env"){let o=el(e);if(!qp(o))return[];let t=Fp(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(Wp);i?n.push({kind:"kv",key:i[1],value:Bp(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Jp(e){return e.map(o=>o.kind==="kv"?`${o.key}=${ui(o.value)}`:o.raw).join(`
|
|
381
381
|
`)+`
|
|
382
|
-
`}function Qt(e,o,t=".env"){let n=el(t),s=ol(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${ui(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${ui(o)}`})),Up(n,Jp(s))}function fi(e,o=".env"){return ol(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var tl="https://t.me/BotFather";async function Gp(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 Hp(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 nl(e={}){console.log(),console.log(ee.bold(" Connect Telegram")),console.log(),console.log(ee.dim(` 1. Open ${tl}`)),console.log(ee.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ee.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Zt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),S=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(S,[tl],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Zt({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(ee.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Gp(t.trim());n||(console.log(ee.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ee.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(ee.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(ee.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Zt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),g||(console.log(ee.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Zt({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ee.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Qt(f,t.trim()),process.env[f]=t.trim();let p=await fe(b=>{Ee(b,"channels.telegram.enabled",!0),Ee(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let S=nt(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;S.includes(A)||(S.push(A),Ee(b,`agents.${g}.mentions`,S))},{configPath:e.configPath});if(p.success||(console.log(ee.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ee.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ee.dim(` Token stored in .env as ${f}`)),console.log(ee.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ee.dim(" Daemon hot-reloaded.")):console.log(ee.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Zt({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(ee.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ee.dim(" Waiting up to 90s..."));let y=await Hp(t.trim(),9e4);if(!y){console.log(ee.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ee.dim(" agentx config set notifications.destination.channel telegram")),console.log(ee.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ee.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await fe(b=>{Ee(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ee.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ee.green(" \u2713 Default --notify target set")),console.log(ee.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(ee.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ee.dim(" Daemon hot-reloaded."))}import ye from"chalk";import hi from"prompts";import{existsSync as wi,mkdirSync as zp,readdirSync as Yp,readFileSync as sl}from"fs";import{resolve as yi}from"path";var Vp=".agentx/whatsapp-sessions";function Kp(){let e=yi(process.cwd(),".agentx/daemon.pid");if(!wi(e))return!1;try{let o=parseInt(sl(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Xp(e){if(!wi(e))return!1;try{return Yp(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Qp(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ye.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ye.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;zp(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ye.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ye.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ye.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ye.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function il(e={}){if(console.log(),console.log(ye.bold(" Connect WhatsApp")),console.log(),Kp()){console.log(ye.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ye.dim(" agentx daemon stop")),console.log();let{cont:l}=await hi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ye.red(" Aborted")),process.exit(1))}let o=e.configPath||yi(process.cwd(),"agentx.json");wi(o)||(console.log(ye.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(sl(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Vp,s=yi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ye.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await hi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ye.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Xp(s)&&a){let{keep:l}=await hi({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(ye.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Qp(s,g=>console.log(g))||(console.log(ye.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await fe(l=>{Ee(l,"channels.whatsapp.enabled",!0),Ee(l,"channels.whatsapp.sessionDir",n),Ee(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ye.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ye.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ye.dim(` Session: ${n}`)),console.log(ye.dim(" Start the daemon to begin receiving:")),console.log(ye.dim(" agentx daemon start")),console.log(ye.dim(" Add routes later with:")),console.log(ye.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Zp}from"crypto";import ve from"chalk";import rl from"prompts";var Xn="agentx-mesh:",Qn="//join/";function eu(e){return Buffer.from(e,"utf-8").toString("base64url")}function ou(e){return Buffer.from(e,"base64url").toString("utf-8")}function tu(e){return`${Xn}${Qn}${eu(JSON.stringify(e))}`}function nu(e){if(!e.startsWith(`${Xn}${Qn}`))throw new Error(`Not a mesh invite link \u2014 expected ${Xn}${Qn}\u2026`);let o=e.slice(Xn.length+Qn.length),t=JSON.parse(ou(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 su(){return Zp(32).toString("hex")}function iu(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function ru(e){return e?.node?.name||e?.node?.id||"node"}async function al(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(ve.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=fi("MESH_TOKEN");r||(r=su(),Qt("MESH_TOKEN",r),console.log(ve.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||iu(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await rl({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(ve.red(" Aborted")),process.exit(1)),a=d}let l=await fe(d=>{Ee(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ve.red(` \u2717 ${l.error}`)),process.exit(1));let g=tu({url:a,token:r,name:ru(i),version:1});console.log(),console.log(ve.bold(" Mesh invite")),console.log(),console.log(` ${ve.cyan(g)}`),console.log(),console.log(ve.dim(" Run on the other node:")),console.log(ve.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ve.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function cl(e,o={}){let t;try{t=nu(e)}catch(i){console.log(ve.red(` \u2717 ${i.message}`)),process.exit(1)}let n=fi("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await rl({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(ve.red(" Aborted (keeping existing .env)")),process.exit(1))}Qt("MESH_TOKEN",t.token);let s=await fe(i=>{Ee(i,"mesh.enabled",!0);let r=nt(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),Ee(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(ve.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ve.green(" \u2713 Joined mesh")),console.log(ve.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(ve.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ve.dim(" Daemon hot-reloaded.")):console.log(ve.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(ve.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(ve.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(ve.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var bt=new au().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");bt.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 nl({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});bt.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 il({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var ll=bt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");ll.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 al({url:e.url,configPath:e.config})});ll.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 cl(e,{configPath:o.config})});bt.action(()=>{console.log(),console.log(wt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${wt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${wt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${wt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${wt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(wt.dim(" GitLab connect is the next slice.")),console.log()});me();import{Command as cu}from"commander";import ge from"chalk";var en=new cu().name("usage").description("token usage analysis and reporting");en.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=_(),[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(ge.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ge.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ge.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: ${ge.red(String(s.totalErrors))}`),console.log(),console.log(ge.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(` ${ge.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ge.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ge.red(" Daemon not running. Start with: agentx daemon start")):console.log(ge.red(` ${e.message}`))}});en.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(ge.red(` Script not found: ${s}`)),console.log(ge.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ge.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ge.red(" Analysis failed. Is Python 3 installed?"))}});en.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-FM2ZHGYE.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-3IZMYDWS.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(ge.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ge.dim("\xB7")} ${d}`);console.log(),console.log(ge.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ge.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(ge.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ge.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ge.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ge.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ge.dim(`${i.days}d`);console.log(` ${ge.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ge.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as lu}from"commander";import we from"chalk";import{resolve as du}from"path";me();var Ao=new lu().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ao.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{or(du(process.cwd(),".env"))}catch{}let o=gu(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-GADOZ7XY.js");t(o)}catch(o){console.log(we.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(we.dim(o.stack)),process.exit(1)}});function gu(e,o){try{let t=_();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(we.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(we.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
382
|
+
`}function Qt(e,o,t=".env"){let n=el(t),s=ol(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${ui(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${ui(o)}`})),Up(n,Jp(s))}function fi(e,o=".env"){return ol(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var tl="https://t.me/BotFather";async function Gp(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 Hp(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 nl(e={}){console.log(),console.log(ee.bold(" Connect Telegram")),console.log(),console.log(ee.dim(` 1. Open ${tl}`)),console.log(ee.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ee.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await Zt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),S=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(S,[tl],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await Zt({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(ee.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Gp(t.trim());n||(console.log(ee.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ee.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(ee.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(ee.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await Zt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),g||(console.log(ee.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await Zt({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(ee.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Qt(f,t.trim()),process.env[f]=t.trim();let p=await fe(b=>{Ee(b,"channels.telegram.enabled",!0),Ee(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let S=nt(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;S.includes(A)||(S.push(A),Ee(b,`agents.${g}.mentions`,S))},{configPath:e.configPath});if(p.success||(console.log(ee.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ee.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ee.dim(` Token stored in .env as ${f}`)),console.log(ee.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ee.dim(" Daemon hot-reloaded.")):console.log(ee.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Zt({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(ee.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ee.dim(" Waiting up to 90s..."));let y=await Hp(t.trim(),9e4);if(!y){console.log(ee.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ee.dim(" agentx config set notifications.destination.channel telegram")),console.log(ee.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ee.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await fe(b=>{Ee(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ee.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ee.green(" \u2713 Default --notify target set")),console.log(ee.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(ee.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ee.dim(" Daemon hot-reloaded."))}import ye from"chalk";import hi from"prompts";import{existsSync as wi,mkdirSync as zp,readdirSync as Yp,readFileSync as sl}from"fs";import{resolve as yi}from"path";var Vp=".agentx/whatsapp-sessions";function Kp(){let e=yi(process.cwd(),".agentx/daemon.pid");if(!wi(e))return!1;try{let o=parseInt(sl(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Xp(e){if(!wi(e))return!1;try{return Yp(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Qp(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ye.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ye.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;zp(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ye.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async f=>{if(f.qr){o(ye.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:p}=await import("qrcode-terminal");p.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(u),o(ye.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}f.connection==="close"&&!f.qr&&f.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ye.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function il(e={}){if(console.log(),console.log(ye.bold(" Connect WhatsApp")),console.log(),Kp()){console.log(ye.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ye.dim(" agentx daemon stop")),console.log();let{cont:l}=await hi({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(ye.red(" Aborted")),process.exit(1))}let o=e.configPath||yi(process.cwd(),"agentx.json");wi(o)||(console.log(ye.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(sl(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Vp,s=yi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ye.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await hi({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ye.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Xp(s)&&a){let{keep:l}=await hi({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(ye.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Qp(s,g=>console.log(g))||(console.log(ye.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await fe(l=>{Ee(l,"channels.whatsapp.enabled",!0),Ee(l,"channels.whatsapp.sessionDir",n),Ee(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ye.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ye.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ye.dim(` Session: ${n}`)),console.log(ye.dim(" Start the daemon to begin receiving:")),console.log(ye.dim(" agentx daemon start")),console.log(ye.dim(" Add routes later with:")),console.log(ye.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Zp}from"crypto";import ve from"chalk";import rl from"prompts";var Xn="agentx-mesh:",Qn="//join/";function eu(e){return Buffer.from(e,"utf-8").toString("base64url")}function ou(e){return Buffer.from(e,"base64url").toString("utf-8")}function tu(e){return`${Xn}${Qn}${eu(JSON.stringify(e))}`}function nu(e){if(!e.startsWith(`${Xn}${Qn}`))throw new Error(`Not a mesh invite link \u2014 expected ${Xn}${Qn}\u2026`);let o=e.slice(Xn.length+Qn.length),t=JSON.parse(ou(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 su(){return Zp(32).toString("hex")}function iu(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function ru(e){return e?.node?.name||e?.node?.id||"node"}async function al(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(ve.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=fi("MESH_TOKEN");r||(r=su(),Qt("MESH_TOKEN",r),console.log(ve.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||iu(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await rl({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:u=>/^https?:\/\//.test(u)||"must start with http:// or https://"});d||(console.log(ve.red(" Aborted")),process.exit(1)),a=d}let l=await fe(d=>{Ee(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ve.red(` \u2717 ${l.error}`)),process.exit(1));let g=tu({url:a,token:r,name:ru(i),version:1});console.log(),console.log(ve.bold(" Mesh invite")),console.log(),console.log(` ${ve.cyan(g)}`),console.log(),console.log(ve.dim(" Run on the other node:")),console.log(ve.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(ve.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function cl(e,o={}){let t;try{t=nu(e)}catch(i){console.log(ve.red(` \u2717 ${i.message}`)),process.exit(1)}let n=fi("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await rl({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(ve.red(" Aborted (keeping existing .env)")),process.exit(1))}Qt("MESH_TOKEN",t.token);let s=await fe(i=>{Ee(i,"mesh.enabled",!0);let r=nt(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),Ee(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(ve.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ve.green(" \u2713 Joined mesh")),console.log(ve.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(ve.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ve.dim(" Daemon hot-reloaded.")):console.log(ve.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(ve.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(ve.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(ve.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var bt=new au().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");bt.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 nl({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});bt.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 il({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var ll=bt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");ll.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 al({url:e.url,configPath:e.config})});ll.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 cl(e,{configPath:o.config})});bt.action(()=>{console.log(),console.log(wt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${wt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${wt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${wt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${wt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(wt.dim(" GitLab connect is the next slice.")),console.log()});me();import{Command as cu}from"commander";import ge from"chalk";var en=new cu().name("usage").description("token usage analysis and reporting");en.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=_(),[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(ge.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ge.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ge.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: ${ge.red(String(s.totalErrors))}`),console.log(),console.log(ge.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(` ${ge.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ge.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ge.red(" Daemon not running. Start with: agentx daemon start")):console.log(ge.red(` ${e.message}`))}});en.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(ge.red(` Script not found: ${s}`)),console.log(ge.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ge.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ge.red(" Analysis failed. Is Python 3 installed?"))}});en.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-FM2ZHGYE.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-PMHQRD5E.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,u)=>{for(let f of d.commands??[]){let p=u?`${u} ${f.name()}`:f.name();c.push(p),l(f,p)}};l(r,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(ge.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ge.dim("\xB7")} ${d}`);console.log(),console.log(ge.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ge.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(ge.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ge.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ge.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ge.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ge.dim(`${i.days}d`);console.log(` ${ge.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ge.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as lu}from"commander";import we from"chalk";import{resolve as du}from"path";me();var Ao=new lu().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ao.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{or(du(process.cwd(),".env"))}catch{}let o=gu(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-4LAQOB74.js");t(o)}catch(o){console.log(we.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(we.dim(o.stack)),process.exit(1)}});function gu(e,o){try{let t=_();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(we.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(we.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
383
383
|
`)),{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}}}}Ao.command("list").description("list configured boards").action(()=>{try{let e=_();if(!e.boards?.length){console.log(we.dim(`
|
|
384
384
|
No boards configured.
|
|
385
385
|
`));return}console.log();for(let o of e.boards){console.log(` ${we.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(we.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(we.dim(` primary label: ${o.primaryToolLabel}`)),console.log(we.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(we.red(` ${e.message}`)),process.exit(1)}});Ao.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{on(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(we.red(` ${t.message}`)),process.exit(1)}});Ao.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{on(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(we.red(` ${t.message}`)),process.exit(1)}});var bi=Ao.command("column").description("manage a board's columns (add / remove / edit / list)");bi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(sd("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(we.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(` ${we.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${we.dim(i)}`)}}catch(o){console.log(we.red(` ${o.message}`)),process.exit(1)}});bi.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{on(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(we.red(` ${n.message}`)),process.exit(1)}});bi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{on(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(we.red(` ${t.message}`)),process.exit(1)}});Ao.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{on(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(we.red(` ${o.message}`)),process.exit(1)}});function on(e){let{summary:o,backupPath:t}=_o(n=>e(n));console.log(we.green(`
|
|
@@ -602,7 +602,7 @@ Restart the daemon to activate.
|
|
|
602
602
|
dist/
|
|
603
603
|
*.log
|
|
604
604
|
.env
|
|
605
|
-
`}import{Command as Bf}from"commander";import je from"chalk";import{writeFileSync as Jf,mkdirSync as Gf,existsSync as hs,readFileSync as Kl,appendFileSync as Xl}from"fs";import{resolve as Tt,dirname as ed}from"path";import{homedir as qi}from"os";var od=new Bf().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-
|
|
605
|
+
`}import{Command as Bf}from"commander";import je from"chalk";import{writeFileSync as Jf,mkdirSync as Gf,existsSync as hs,readFileSync as Kl,appendFileSync as Xl}from"fs";import{resolve as Tt,dirname as ed}from"path";import{homedir as qi}from"os";var od=new Bf().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-PMHQRD5E.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Yf(t);break;case"bash":s=Zf(t);break;case"fish":s=eh(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?Tt(String(e.output)):Hf(n);Gf(ed(i),{recursive:!0}),Jf(i,s),console.log(je.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),zf(n,i,!!e.yes)});function Hf(e){let o=qi();switch(e){case"zsh":return Tt(o,".zsh","completions","_agentx");case"bash":return Tt(o,".bash_completion.d","agentx.bash");case"fish":return Tt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function zf(e,o,t){if(e==="zsh"){let n=Tt(qi(),".zshrc"),s=ed(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=hs(n)?Kl(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&&hs(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Xl(n,g.join(`
|
|
606
606
|
`)+`
|
|
607
607
|
`),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=Tt(qi(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((hs(n)?Kl(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&&hs(n)){Xl(n,`
|
|
608
608
|
# agentx completion
|
|
@@ -613,4 +613,4 @@ ${s}
|
|
|
613
613
|
`)}function Wi(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ui(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=Wi(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 PS(){let e=await ua(),o=new oh().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=wa(n);ba(s)&&ya("cli",s)});for(let t of[Ja,qa,bt,at,oo,ha,Mo,Pn,go,Go,_n,_l,So,oc,dc,$c,xc,Sc,qc,Gc,Hc,Vn,en,Ul,Wt,$o,od])o.addCommand(t);for(let t of nd)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=nd.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,th(t,74," "),""].join(`
|
|
614
614
|
`)}),o}var nd=[Q,$t,Io,Qe,Jt,ht,qe,po,Ao,Ho,St,Et,xo,Le,Gt,Kn,Rl,co,gt,Sa,Lo,dn,Js,jo,dt,Gs,cs,Oo,Co,Gl,zl,Fl];function th(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(`
|
|
615
615
|
`)}export{PS as a};
|
|
616
|
-
//# sourceMappingURL=chunk-
|
|
616
|
+
//# sourceMappingURL=chunk-QURVHYBP.js.map
|