agentix-cli 0.63.0 → 0.65.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-D2BHFDUA.js → agent-HUKCS3AK.js} +2 -2
- package/dist/{board-dashboard-SMCZBJKO.js → board-dashboard-S4V4WR2N.js} +382 -213
- package/dist/board-dashboard-S4V4WR2N.js.map +1 -0
- package/dist/{chunk-GUJB53QU.js → chunk-62EJKQFX.js} +2 -2
- package/dist/{chunk-TX3ZOO22.js → chunk-AVDWFQZ5.js} +2 -2
- package/dist/{chunk-KAFO5QZR.js → chunk-C4CDVE2E.js} +28 -28
- package/dist/chunk-C4CDVE2E.js.map +1 -0
- package/dist/chunk-ECBKTFTL.js +20 -0
- package/dist/chunk-ECBKTFTL.js.map +1 -0
- package/dist/chunk-EOKOGQZG.js +131 -0
- package/dist/chunk-EOKOGQZG.js.map +1 -0
- package/dist/{chunk-ZGWW6FZF.js → chunk-HSJRI3NW.js} +184 -184
- package/dist/chunk-HSJRI3NW.js.map +1 -0
- package/dist/{chunk-7LETLAIH.js → chunk-LEFRNHZF.js} +4 -4
- package/dist/{chunk-7LETLAIH.js.map → chunk-LEFRNHZF.js.map} +1 -1
- package/dist/{chunk-JZMKKDT3.js → chunk-OTTAKMGC.js} +54 -54
- package/dist/chunk-OTTAKMGC.js.map +1 -0
- package/dist/{chunk-33YJIUYL.js → chunk-WMDDQVCI.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/processes-TGFDGQYY.js +2 -0
- package/dist/{program-NPPLJAQ7.js → program-DZCKFNHD.js} +2 -2
- package/dist/registry-P7IAAFCX.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-SMCZBJKO.js.map +0 -1
- package/dist/chunk-5UYXEO3I.js +0 -131
- package/dist/chunk-5UYXEO3I.js.map +0 -1
- package/dist/chunk-JZMKKDT3.js.map +0 -1
- package/dist/chunk-KAFO5QZR.js.map +0 -1
- package/dist/chunk-PMGPGMBZ.js +0 -19
- package/dist/chunk-PMGPGMBZ.js.map +0 -1
- package/dist/chunk-ZGWW6FZF.js.map +0 -1
- package/dist/processes-NNXSRQSV.js +0 -2
- package/dist/registry-MRMQBYE4.js +0 -2
- /package/dist/{agent-D2BHFDUA.js.map → agent-HUKCS3AK.js.map} +0 -0
- /package/dist/{chunk-GUJB53QU.js.map → chunk-62EJKQFX.js.map} +0 -0
- /package/dist/{chunk-TX3ZOO22.js.map → chunk-AVDWFQZ5.js.map} +0 -0
- /package/dist/{chunk-33YJIUYL.js.map → chunk-WMDDQVCI.js.map} +0 -0
- /package/dist/{processes-NNXSRQSV.js.map → processes-TGFDGQYY.js.map} +0 -0
- /package/dist/{program-NPPLJAQ7.js.map → program-DZCKFNHD.js.map} +0 -0
- /package/dist/{registry-MRMQBYE4.js.map → registry-P7IAAFCX.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Nc,b as Hn,g as Rc}from"./chunk-5WMHW4A6.js";import{a as xc,c as Sc}from"./chunk-N42YWYIR.js";import{a as ao,b as bc,f as $c,g as kc,h as vc,i as Jn,j as Ec,k as Ac,l as ii,m as jc,o as Cc}from"./chunk-
|
|
1
|
+
import{a as Nc,b as Hn,g as Rc}from"./chunk-5WMHW4A6.js";import{a as xc,c as Sc}from"./chunk-N42YWYIR.js";import{a as ao,b as bc,f as $c,g as kc,h as vc,i as Jn,j as Ec,k as Ac,l as ii,m as jc,o as Cc}from"./chunk-WMDDQVCI.js";import{a as Tc,c as Oc,d as Ic}from"./chunk-Z3IP66SL.js";import{a as Gs,b as Xr}from"./chunk-RKPAVWXF.js";import{a as pt}from"./chunk-GV7S5BAX.js";import{e as qr}from"./chunk-GSX4NK2N.js";import{c as Wr}from"./chunk-SZDACK6O.js";import{$ as yc,A as Vs,B as Ya,C as Va,D as Ka,E as Xa,F as Qa,G as Za,H as sc,I as ic,J as ft,K as Un,L as Zs,M as rc,N as ac,O as cc,P as lc,Q as ht,R as yt,S as dc,T as gc,U as Ne,V as qn,W as en,X as ei,Y as mc,Z as fc,_ as ni,a as ia,aa as Wn,b as ra,ba as wt,ca as Bn,da as si,ea as wc,h as da,i as ga,j as Xt,k as Rn,l as ua,m as fa,n as ha,o as ya,p as Ia,q as ja,r as Mn,s as Ys,t as Da,u as Ua,v as Ba,w as Ja,x as Ha,y as Ga,z as za}from"./chunk-HSJRI3NW.js";import{A as La,B as Fa,Ma as ro,N as Qt,Oa as hc,P as Ks,Q as Ln,R as ec,ba as Eo,ca as oc,da as Xs,fa as Qs,ha as tc,ia as nc,ja as Zt,m as So,na as Fn,q as Pa,t as Ma,va as pc,wa as oi,xa as uc,ya as ti}from"./chunk-EOKOGQZG.js";import{a as aa,d as ca,e as la}from"./chunk-5QP56S4O.js";import{a as _n,b as Dn,c as wa,d as ba,e as $a,g as ka,h as va,j as xa,k as Sa,l as Ea,m as Aa,p as Pn,r as Ta,s as Oa}from"./chunk-BYJ3A55Y.js";import{a as zs,e as Qr,f as Zr,h as ea,i as oa,k as ta,l as na,m as sa}from"./chunk-I2SD4XZ6.js";import{a as ma,p as pa}from"./chunk-XT3E5MLX.js";import{a as Ca,b as Na,c as Ra,d as _a}from"./chunk-2D3RYIDU.js";import{a as qa,b as Wa}from"./chunk-L53FTKEP.js";import{B as xo,H as Vr,S as Kr,h as Dr,q as Pr,v as Bs,w as Fr}from"./chunk-OTTAKMGC.js";import{b as Vt,c as gt,d as Cn,e as Nn,f as mt,g as Ur,h as Ho,i as Kt}from"./chunk-ECBKTFTL.js";import{e as Gr,f as Hs,k as zr}from"./chunk-WP6KLXTP.js";import{a as _r}from"./chunk-N6EWZGIX.js";import{b as dt}from"./chunk-DP7RTNDM.js";import{a as Mr,k as Hr}from"./chunk-BHE5TJSN.js";import{b as ye,c as Oe,d as ut,e as Yr}from"./chunk-EA7H3EUX.js";import{j as Lr}from"./chunk-X5C5W3E4.js";import{f as Br,g as Jr,h as Js}from"./chunk-76Z4VHDX.js";import{h as Rr}from"./chunk-DWADWDMU.js";import{a as Ws}from"./chunk-AZBOYKQA.js";import{b as vo,d as jn}from"./chunk-WGWNVLVW.js";import{b as lt,d as Nr}from"./chunk-2GIDVZ4H.js";import{a as qs,b as yr,c as Dg,d as On,e as wr,f as Ar,g as Lg,h as Tr,i as Fg,m as ct,n as Ir,o as jr,s as Cr,v as io,w as Yt}from"./chunk-PTB2TPOC.js";import{a as fo,b as at,e as xr,f as zt}from"./chunk-72SZI2UW.js";import{a as Or,b as Ug}from"./chunk-FX3D7YON.js";import{a as uo,b as _g}from"./chunk-7I7IEX4S.js";import{m as br,n as $r,p as kr,q as Pg,v as vr,w as j,x as In,z as ae}from"./chunk-OVF37EXJ.js";import{g as Sr,k as Er,l as Mg}from"./chunk-RGDKHYY2.js";import{Command as qg}from"commander";var _c=new qg().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 ra({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()});ae();import{Command as Wg}from"commander";import{execFileSync as Ke}from"node:child_process";import{cpSync as Dc,existsSync as ci,mkdirSync as ri,mkdtempSync as Bg,readdirSync as Jg,rmSync as Pc,writeFileSync as Mc}from"node:fs";import{dirname as Lc,join as _e}from"node:path";import{homedir as Gn,release as Hg,tmpdir as Gg}from"node:os";import{setTimeout as zg}from"node:timers/promises";function zn(){let e=wa(process.platform,process.arch,Hg());if(e)throw new Error(e)}function Yn(){let e=_e(Gn(),"Library/LaunchAgents"),o=[];try{o=Jg(e).filter(ka)}catch{}let t=o.flatMap(n=>{let s=_e(e,n);try{return[{file:s,plist:Ke("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return va(e,t)}function on(e){return`gui/${process.getuid()}/${e.label}`}async function ai(e){try{Ke("launchctl",["bootout",on(e)],{stdio:"pipe"})}catch{}for(let o=0;o<30;o++){try{Ke("launchctl",["print",on(e)],{stdio:"pipe"})}catch{return}await zg(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Fc(e){if(!ci(e.file))throw new Error("Run agentx desktop install first.");let o=!0;try{Ke("launchctl",["print",on(e)],{stdio:"pipe"})}catch{o=!1}o||Ke("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Ke("launchctl",["kickstart",on(e)],{stdio:"pipe"})}function Yg(){let e=Aa();if(e&&ci(_e(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 bt=new Wg("desktop").description("install and control the macOS desktop assistant");bt.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{zn();let o=j(),t=ba(o.agents,e.agent),n=e.agent,s=o.dashboard?.daemonUrl||`http://${o.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,i=Yg(),r=_e(Gn(),"Applications"),{keep:a,remove:c}=Yn();if(console.log(`Desktop assistant \u2192 ${_e(r,_n)}
|
|
2
2
|
Computer-use helper \u2192 ${_e(r,Dn)}
|
|
3
3
|
Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -403,7 +403,7 @@ return aid ?? null`}function Iu(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
403
403
|
settings \u2014 without this an attached production identity would be less
|
|
404
404
|
guarded than a spawned one.)`))):console.log(N.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${N.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(N.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});Po.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=Jc({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${N.green("\u2713")} Removed attach hooks from ${N.gray(o.path)} (${o.events.join(", ")})`:`${N.gray("Nothing to remove.")}`),e.removeGuard||console.log(N.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(N.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});ae();import{Command as mf}from"commander";import we from"chalk";var ws=new mf().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Sd(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=j(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 Ed(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function xd(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 pf(e){return e==="busy"?we.magenta:e==="warm-hot"?we.green:e==="warm-cold"?we.cyan:e==="idle"?we.yellow:e==="dead"?we.red:we.dim}ws.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}=Sd(e),n;try{n=await fetch(`${o}/api/processes`,{headers:Ed(t)})}catch(r){console.log(we.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(we.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(we.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(we.dim(" (no processes)"));return}for(let r of i){let a=pf(r.state)(r.state.padEnd(9)),c=xd(r.spawnedAt),l=r.lastTurnAt?xd(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?we.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?we.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):we.dim("sess=\u2014"),u=r.pendingTaskId?we.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${we.bold(r.key.agentId)}${we.dim(":"+r.key.channel+":"+r.key.chatId)} ${we.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${g} ${u}`),r.deadReason&&console.log(` ${we.red("dead:")} ${r.deadReason}`)}});ws.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}=Sd(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Ed(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(we.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(we.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(we.red(` ${a}`)),process.exit(1)}console.log(we.green(` killed ${e}:${o}:${t}`))});import{Command as uf}from"commander";import Pe from"chalk";import{existsSync as Li,rmSync as ff}from"fs";import{resolve as Fi}from"path";var Ct=new uf().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Ct.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(Pe.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await Br(e,o,{verbose:n}),r=Date.now()-s;console.log(Pe.green(` \u2713 indexed ${i.docs} doc(s) for ${Pe.bold(e)} in ${r}ms`)),console.log(Pe.dim(` \u2192 ${i.path}`))});Ct.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=Fi(e.cwd,".agentx","rag");if(!Li(o)){console.log(Pe.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Li(Fi(o,s,"index.json")));if(n.length===0){console.log(Pe.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Js(s);console.log(` ${Pe.bold(s)} ${i.docs} doc(s) ${Pe.dim(i.path)}`)}});Ct.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=Jr(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=Js(e);i.exists?console.log(Pe.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(Pe.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${Pe.bold(i.title)} ${Pe.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${Pe.dim(i.path)}`),console.log(` ${Pe.dim(i.snippet.slice(0,200))}`)});Ct.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Fi(process.cwd(),".agentx","rag",e);if(!Li(o)){console.log(Pe.dim(` no index for ${e} \u2014 nothing to clear`));return}ff(o,{recursive:!0,force:!0}),console.log(Pe.green(` \u2713 cleared index for ${e}`))});ae();import{Command as hf}from"commander";import X from"chalk";import Nt from"prompts";var nt=new hf().name("backlog").description("manage the local backlog used by business workSource=backlog");function fn(e){let o=j(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new pc(n)}}function yf(e){return e?X.cyan(`${e.type}:${e.project}#${e.iid}`):X.dim("manual")}function wf(e){return{todo:X.gray("todo"),doing:X.yellow("doing"),blocked:X.red("blocked"),done:X.green("done")}[e]}nt.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}=fn(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(X.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?X.magenta(`@${n.assignee}`):X.dim("unassigned");console.log(` ${wf(n.status).padEnd(7)} ${yf(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(X.dim(` ${n.source.url}`))}console.log(),console.log(X.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});nt.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=fn(t.config);n.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(X.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=uc([o],i.source,n.config),a=await ti(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(X.dim(" sync:"),...c));console.log(a.ok?X.dim(` synced -> ${a.url??i.source.type}`):X.yellow(` sync failed: ${a.error}`))}});nt.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=fn(o.config);t.store.findById(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(X.green(` done: ${s.title}`)),s.source){let i=await ti(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(X.dim(" sync:"),...r));console.log(i.ok?X.dim(` synced -> ${i.url??s.source.type}`):X.yellow(` sync failed: ${i.error}`))}});nt.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}=fn(o.config);t.remove(e)||(console.error(X.red(` item ${e} not found`)),process.exit(1)),console.log(X.green(` removed ${e}`))});nt.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=fn(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(X.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 Nt({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!t&&(console.error(X.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(X.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?$f(o.config):kf(o.config);y.length?(i=(await Nt({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 Nt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Nt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Nt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(X.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await vf(o.config,i,a):await xf(o.config,i,a);if(!c.length){console.log(X.yellow(" no open issues matched"));return}console.log(X.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=oi({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?X.dim(" (already imported)"):""}`,value:y,disabled:b}}),f=(await Nt({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(X.dim(" nothing selected"));return}let p=f.map(y=>{let k={type:s,host:s==="gitlab"?bf(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:oi(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(X.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(X.dim(` ${y.id} \u2014 ${y.title}`))});function bf(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function $f(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 kf(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 vf(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 xf(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(Ad)}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(Ad):[]}function Ad(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 Sf}from"commander";import W from"chalk";import{existsSync as Ef,readFileSync as Af}from"fs";import{resolve as Tf}from"path";import Of from"prompts";ae();function Td(e){let o=e||Tf(process.cwd(),"agentx.json");return Ef(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Af(o,"utf-8"))}async function If(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 Of([{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 wo=new Sf().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');wo.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: ${zs})`,zs).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){wo.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=Gs(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=Td(o.config),s=vr(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 If(o.notify,s),r=o.id||Xr(t.matched,o.agent),a=Zr({parsed:t,agent:o.agent,prompt:o.do,timezone:o.timezone,timeout:parseInt(o.timeout,10),model:o.model,notify:i,onError:Qr(o.onError),enabled:!o.disabled}),c=a.onError,l=await ye(d=>Oe(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."))});wo.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=Td(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=oa(ea(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]])wo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await sa(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."))});wo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await ye(t=>{if(!ut(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);Yr(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",ta,"approve an agent's pending create/delete request (enables or removes the job)"],["reject",na,"reject an agent's pending create/delete request (drops the request)"]])wo.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."))});wo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=Gs(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 jf}from"commander";import xe from"chalk";var Mo=new jf("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),Cf={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function Od(){return{root:process.cwd()}}function Ui(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function Nf(e){console.log(` ${xe.cyan(e.key)} ${xe.dim(`[${Cf[e.kind]}] from ${e.raised_by}`)}${e.snoozed_until?xe.dim(` (later: until ${Ui(e.snoozed_until)})`):""}`),console.log(` ${xe.bold(e.title)}`),console.log(` ${e.ask}`),e.recommend&&console.log(` ${xe.green("Recommends:")} ${e.recommend}`),e.expires&&console.log(xe.yellow(` Expires ${Ui(e.expires)}; then: ${e.if_silent}`)),e.detail&&console.log(xe.dim(` ${e.detail}`)),e.source&&console.log(xe.dim(` ${e.source}`)),console.log(xe.dim(` yes: ${e.yes} \xB7 no: ${e.no}${e.more?` \xB7 more: ${e.more}`:""}`))}Mo.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=La(Od(),{includeSnoozed:e.all});if(e.json){console.log(JSON.stringify(o,null,2));return}for(let t of o.errors)console.log(xe.red(` couldn't read ${t.kind}: ${t.error}`));if(o.items.length===0){console.log(xe.dim(` nothing waiting${o.snoozed?` (${o.snoozed} put off; --all shows them)`:""}`));return}console.log();for(let t of o.items)Nf(t),console.log();console.log(xe.dim(` ${o.items.length} waiting${o.snoozed?`, ${o.snoozed} put off (--all)`:""}. Answer with: agentx approvals approve|reject|later <key>`))});async function qi(e,o,t){let n=Jn(),s=t.hours?Number(t.hours):n.laterHours;if(o==="later"&&!(s>0)){console.error(xe.red(" --hours must be a positive number")),process.exitCode=1;return}let i=await Fa(Od(),e,o,{force:t.force,note:t.note,laterHours:s});if(!i.ok){console.error(xe.red(` ${i.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 ${i.message}`))}Mo.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)=>qi(e,"yes",o));Mo.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)=>qi(e,"no",o));Mo.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)=>qi(e,"later",o));Mo.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: ${Pa.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=Jn(),t=Ma(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(xe.red(` ${t.error}`)),process.exitCode=1;return}console.log(xe.green(` \u2713 card:${t.card.id} raised; expires ${Ui(t.card.expires)}, then: ${t.card.if_silent}`))});Mo.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=Ec(e.digestTo);if(!a)throw new Error("--digest-to takes channel:chatId, for example telegram:123456");o.destination=a}}catch(a){console.error(xe.red(` ${a.message}`)),process.exitCode=1;return}if(Object.values(o).some(a=>a!==void 0)){let a=await Ac(o);if(!a.success){console.error(xe.red(` ${a.error}`)),process.exitCode=1;return}console.log(xe.green(" \u2713 saved")+(a.reloaded?xe.dim(" (daemon reloaded)"):""))}let i=Jn(),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 oh}from"commander";import Rt from"chalk";import ne from"chalk";import yn from"prompts";import{readFileSync as Rf,writeFileSync as _f,existsSync as Df}from"fs";import{resolve as Id}from"path";var Pf=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Mf(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function Wi(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function jd(e=".env"){let o=Id(e);if(!Df(o))return[];let t=Rf(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(Pf);i?n.push({kind:"kv",key:i[1],value:Mf(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Lf(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Wi(o.value)}`:o.raw).join(`
|
|
405
405
|
`)+`
|
|
406
|
-
`}function hn(e,o,t=".env"){let n=Id(t),s=jd(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Wi(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Wi(o)}`})),_f(n,Lf(s))}function Bi(e,o=".env"){return jd(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Cd="https://t.me/BotFather";async function Ff(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 Uf(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 Nd(e={}){console.log(),console.log(ne.bold(" Connect Telegram")),console.log(),console.log(ne.dim(` 1. Open ${Cd}`)),console.log(ne.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ne.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await yn({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,[Cd],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await yn({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(ne.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Ff(t.trim());n||(console.log(ne.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ne.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(ne.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(ne.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await yn({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(ne.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await yn({type:"text",name:"account",message:`Account "${u}" 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),u||(console.log(ne.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;hn(f,t.trim()),process.env[f]=t.trim();let p=await ye(b=>{Oe(b,"channels.telegram.enabled",!0),Oe(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let v=ut(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Oe(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(ne.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ne.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ne.dim(` Token stored in .env as ${f}`)),console.log(ne.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ne.dim(" Daemon hot-reloaded.")):console.log(ne.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await yn({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(ne.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ne.dim(" Waiting up to 90s..."));let y=await Uf(t.trim(),9e4);if(!y){console.log(ne.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ne.dim(" agentx config set notifications.destination.channel telegram")),console.log(ne.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ne.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await ye(b=>{Oe(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ne.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ne.green(" \u2713 Default --notify target set")),console.log(ne.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(ne.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ne.dim(" Daemon hot-reloaded."))}import be from"chalk";import Ji from"prompts";import{existsSync as Gi,mkdirSync as qf,readdirSync as Wf,readFileSync as Rd}from"fs";import{resolve as Hi}from"path";var Bf=".agentx/whatsapp-sessions";function Jf(){let e=Hi(process.cwd(),".agentx/daemon.pid");if(!Gi(e))return!1;try{let o=parseInt(Rd(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Hf(e){if(!Gi(e))return!1;try{return Wf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Gf(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;qf(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(be.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(be.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(be.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(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function _d(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),Jf()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await Ji({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let o=e.configPath||Hi(process.cwd(),"agentx.json");Gi(o)||(console.log(be.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Rd(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Bf,s=Hi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Ji({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Hf(s)&&a){let{keep:l}=await Ji({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(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Gf(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ye(l=>{Oe(l,"channels.whatsapp.enabled",!0),Oe(l,"channels.whatsapp.sessionDir",n),Oe(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as zf}from"crypto";import Ee from"chalk";import Dd from"prompts";var bs="agentx-mesh:",$s="//join/";function Yf(e){return Buffer.from(e,"utf-8").toString("base64url")}function Vf(e){return Buffer.from(e,"base64url").toString("utf-8")}function Kf(e){return`${bs}${$s}${Yf(JSON.stringify(e))}`}function Xf(e){if(!e.startsWith(`${bs}${$s}`))throw new Error(`Not a mesh invite link \u2014 expected ${bs}${$s}\u2026`);let o=e.slice(bs.length+$s.length),t=JSON.parse(Vf(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 Qf(){return zf(32).toString("hex")}function Zf(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function eh(e){return e?.node?.name||e?.node?.id||"node"}async function Pd(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(Ee.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Bi("MESH_TOKEN");r||(r=Qf(),hn("MESH_TOKEN",r),console.log(Ee.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Zf(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Dd({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(Ee.red(" Aborted")),process.exit(1)),a=d}let l=await ye(d=>{Oe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ee.red(` \u2717 ${l.error}`)),process.exit(1));let g=Kf({url:a,token:r,name:eh(i),version:1});console.log(),console.log(Ee.bold(" Mesh invite")),console.log(),console.log(` ${Ee.cyan(g)}`),console.log(),console.log(Ee.dim(" Run on the other node:")),console.log(Ee.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ee.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Md(e,o={}){let t;try{t=Xf(e)}catch(i){console.log(Ee.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Bi("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Dd({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ee.red(" Aborted (keeping existing .env)")),process.exit(1))}hn("MESH_TOKEN",t.token);let s=await ye(i=>{Oe(i,"mesh.enabled",!0);let r=ut(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),Oe(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(Ee.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ee.green(" \u2713 Joined mesh")),console.log(Ee.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(Ee.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.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(Ee.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(Ee.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ee.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var _t=new oh().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");_t.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 Nd({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});_t.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 _d({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Ld=_t.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Ld.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 Pd({url:e.url,configPath:e.config})});Ld.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 Md(e,{configPath:o.config})});_t.action(()=>{console.log(),console.log(Rt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Rt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Rt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Rt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Rt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Rt.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as th}from"commander";import ue from"chalk";var wn=new th().name("usage").description("token usage analysis and reporting");wn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=j(),[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(ue.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ue.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ue.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: ${ue.red(String(s.totalErrors))}`),console.log(),console.log(ue.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(` ${ue.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ue.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ue.red(" Daemon not running. Start with: agentx daemon start")):console.log(ue.red(` ${e.message}`))}});wn.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(ue.red(` Script not found: ${s}`)),console.log(ue.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ue.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ue.red(" Analysis failed. Is Python 3 installed?"))}});wn.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-HVVP22SA.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-NPPLJAQ7.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(ue.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ue.dim("\xB7")} ${d}`);console.log(),console.log(ue.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ue.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(ue.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ue.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ue.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ue.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ue.dim(`${i.days}d`);console.log(` ${ue.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ue.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as nh}from"commander";import $e from"chalk";import{readFileSync as sh}from"fs";import{resolve as ih}from"path";ae();var Lo=new nh().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Lo.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{Nr(ih(process.cwd(),".env"))}catch{}let o=rh(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-SMCZBJKO.js");t(o)}catch(o){console.log($e.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log($e.dim(o.stack)),process.exit(1)}});function rh(e,o){try{let t=j();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log($e.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log($e.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
406
|
+
`}function hn(e,o,t=".env"){let n=Id(t),s=jd(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${Wi(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${Wi(o)}`})),_f(n,Lf(s))}function Bi(e,o=".env"){return jd(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var Cd="https://t.me/BotFather";async function Ff(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 Uf(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 Nd(e={}){console.log(),console.log(ne.bold(" Connect Telegram")),console.log(),console.log(ne.dim(` 1. Open ${Cd}`)),console.log(ne.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ne.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await yn({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,[Cd],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await yn({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(ne.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Ff(t.trim());n||(console.log(ne.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ne.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(ne.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(ne.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await yn({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(ne.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},u=e.account||g;d[u]&&d[u].agentBinding!==g&&(u=(await yn({type:"text",name:"account",message:`Account "${u}" 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),u||(console.log(ne.red(" Aborted")),process.exit(1));let f=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;hn(f,t.trim()),process.env[f]=t.trim();let p=await ye(b=>{Oe(b,"channels.telegram.enabled",!0),Oe(b,`channels.telegram.accounts.${u}`,{token:`\${${f}}`,agentBinding:g});let v=ut(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),Oe(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(p.success||(console.log(ne.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(ne.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ne.dim(` Token stored in .env as ${f}`)),console.log(ne.dim(` Mentions updated to include @${n.username}`)),p.reloaded?console.log(ne.dim(" Daemon hot-reloaded.")):console.log(ne.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await yn({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(ne.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ne.dim(" Waiting up to 90s..."));let y=await Uf(t.trim(),9e4);if(!y){console.log(ne.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ne.dim(" agentx config set notifications.destination.channel telegram")),console.log(ne.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ne.dim(` agentx config set notifications.destination.accountId ${u}`));return}let k=await ye(b=>{Oe(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:u})},{configPath:e.configPath});if(!k.success){console.log(ne.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(ne.green(" \u2713 Default --notify target set")),console.log(ne.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(ne.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(ne.dim(" Daemon hot-reloaded."))}import be from"chalk";import Ji from"prompts";import{existsSync as Gi,mkdirSync as qf,readdirSync as Wf,readFileSync as Rd}from"fs";import{resolve as Hi}from"path";var Bf=".agentx/whatsapp-sessions";function Jf(){let e=Hi(process.cwd(),".agentx/daemon.pid");if(!Gi(e))return!1;try{let o=parseInt(Rd(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Hf(e){if(!Gi(e))return!1;try{return Wf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Gf(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(be.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(be.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;qf(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(be.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(be.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(be.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(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function _d(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),Jf()){console.log(be.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(be.dim(" agentx daemon stop")),console.log();let{cont:l}=await Ji({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(be.red(" Aborted")),process.exit(1))}let o=e.configPath||Hi(process.cwd(),"agentx.json");Gi(o)||(console.log(be.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Rd(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||Bf,s=Hi(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(be.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Ji({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(be.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Hf(s)&&a){let{keep:l}=await Ji({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(be.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Gf(s,g=>console.log(g))||(console.log(be.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ye(l=>{Oe(l,"channels.whatsapp.enabled",!0),Oe(l,"channels.whatsapp.sessionDir",n),Oe(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(be.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(be.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(be.dim(` Session: ${n}`)),console.log(be.dim(" Start the daemon to begin receiving:")),console.log(be.dim(" agentx daemon start")),console.log(be.dim(" Add routes later with:")),console.log(be.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as zf}from"crypto";import Ee from"chalk";import Dd from"prompts";var bs="agentx-mesh:",$s="//join/";function Yf(e){return Buffer.from(e,"utf-8").toString("base64url")}function Vf(e){return Buffer.from(e,"base64url").toString("utf-8")}function Kf(e){return`${bs}${$s}${Yf(JSON.stringify(e))}`}function Xf(e){if(!e.startsWith(`${bs}${$s}`))throw new Error(`Not a mesh invite link \u2014 expected ${bs}${$s}\u2026`);let o=e.slice(bs.length+$s.length),t=JSON.parse(Vf(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 Qf(){return zf(32).toString("hex")}function Zf(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function eh(e){return e?.node?.name||e?.node?.id||"node"}async function Pd(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(Ee.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=Bi("MESH_TOKEN");r||(r=Qf(),hn("MESH_TOKEN",r),console.log(Ee.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Zf(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Dd({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(Ee.red(" Aborted")),process.exit(1)),a=d}let l=await ye(d=>{Oe(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Ee.red(` \u2717 ${l.error}`)),process.exit(1));let g=Kf({url:a,token:r,name:eh(i),version:1});console.log(),console.log(Ee.bold(" Mesh invite")),console.log(),console.log(` ${Ee.cyan(g)}`),console.log(),console.log(Ee.dim(" Run on the other node:")),console.log(Ee.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Ee.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Md(e,o={}){let t;try{t=Xf(e)}catch(i){console.log(Ee.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Bi("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Dd({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Ee.red(" Aborted (keeping existing .env)")),process.exit(1))}hn("MESH_TOKEN",t.token);let s=await ye(i=>{Oe(i,"mesh.enabled",!0);let r=ut(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),Oe(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(Ee.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Ee.green(" \u2713 Joined mesh")),console.log(Ee.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(Ee.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Ee.dim(" Daemon hot-reloaded.")):console.log(Ee.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(Ee.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(Ee.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Ee.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var _t=new oh().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");_t.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 Nd({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});_t.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 _d({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Ld=_t.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Ld.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 Pd({url:e.url,configPath:e.config})});Ld.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 Md(e,{configPath:o.config})});_t.action(()=>{console.log(),console.log(Rt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Rt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Rt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Rt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Rt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Rt.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as th}from"commander";import ue from"chalk";var wn=new th().name("usage").description("token usage analysis and reporting");wn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=j(),[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(ue.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(ue.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${ue.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: ${ue.red(String(s.totalErrors))}`),console.log(),console.log(ue.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(` ${ue.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${ue.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(ue.red(" Daemon not running. Start with: agentx daemon start")):console.log(ue.red(` ${e.message}`))}});wn.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(ue.red(` Script not found: ${s}`)),console.log(ue.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(ue.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(ue.red(" Analysis failed. Is Python 3 installed?"))}});wn.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-HVVP22SA.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-DZCKFNHD.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(ue.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${ue.dim("\xB7")} ${d}`);console.log(),console.log(ue.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(ue.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(ue.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(ue.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(ue.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(ue.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=ue.dim(`${i.days}d`);console.log(` ${ue.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(ue.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as nh}from"commander";import $e from"chalk";import{readFileSync as sh}from"fs";import{resolve as ih}from"path";ae();var Lo=new nh().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Lo.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{Nr(ih(process.cwd(),".env"))}catch{}let o=rh(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-S4V4WR2N.js");t(o)}catch(o){console.log($e.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log($e.dim(o.stack)),process.exit(1)}});function rh(e,o){try{let t=j();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log($e.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log($e.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
407
407
|
`)),{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}}}}Lo.command("list").description("list configured boards").action(()=>{try{let e=j();if(!e.boards?.length){console.log($e.dim(`
|
|
408
408
|
No boards configured.
|
|
409
409
|
`));return}console.log();for(let o of e.boards){console.log(` ${$e.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log($e.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log($e.dim(` primary label: ${o.primaryToolLabel}`)),console.log($e.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log($e.red(` ${e.message}`)),process.exit(1)}});Lo.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{bn(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($e.red(` ${t.message}`)),process.exit(1)}});Lo.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{bn(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($e.red(` ${t.message}`)),process.exit(1)}});var zi=Lo.command("column").description("manage a board's columns (add / remove / edit / list)");zi.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(sh("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($e.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(` ${$e.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${$e.dim(i)}`)}}catch(o){console.log($e.red(` ${o.message}`)),process.exit(1)}});zi.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{bn(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($e.red(` ${n.message}`)),process.exit(1)}});zi.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{bn(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($e.red(` ${t.message}`)),process.exit(1)}});Lo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{bn(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($e.red(` ${o.message}`)),process.exit(1)}});function bn(e){let{summary:o,backupPath:t}=ao(n=>e(n));console.log($e.green(`
|
|
@@ -629,7 +629,7 @@ Restart the daemon to activate.
|
|
|
629
629
|
dist/
|
|
630
630
|
*.log
|
|
631
631
|
.env
|
|
632
|
-
`}import{Command as Uy}from"commander";import Ce from"chalk";import{writeFileSync as qy,mkdirSync as Wy,existsSync as Ls,readFileSync as Ag,appendFileSync as Tg}from"fs";import{resolve as Ht,dirname as jg}from"path";import{homedir as fr}from"os";var Cg=new Uy().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-
|
|
632
|
+
`}import{Command as Uy}from"commander";import Ce from"chalk";import{writeFileSync as qy,mkdirSync as Wy,existsSync as Ls,readFileSync as Ag,appendFileSync as Tg}from"fs";import{resolve as Ht,dirname as jg}from"path";import{homedir as fr}from"os";var Cg=new Uy().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-DZCKFNHD.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Hy(t);break;case"bash":s=Ky(t);break;case"fish":s=Xy(t);break;default:console.error(Ce.red(`unsupported shell: ${n}`)),console.error(Ce.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Ht(String(e.output)):By(n);Wy(jg(i),{recursive:!0}),qy(i,s),console.log(Ce.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Jy(n,i,!!e.yes)});function By(e){let o=fr();switch(e){case"zsh":return Ht(o,".zsh","completions","_agentx");case"bash":return Ht(o,".bash_completion.d","agentx.bash");case"fish":return Ht(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Jy(e,o,t){if(e==="zsh"){let n=Ht(fr(),".zshrc"),s=jg(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ls(n)?Ag(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Ce.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Ls(n)){let g=["","# agentx completion"];c&&g.push(i),l&&g.push(r),Tg(n,g.join(`
|
|
633
633
|
`)+`
|
|
634
634
|
`),console.log(Ce.green("\u2713 Patched ~/.zshrc")),console.log(Ce.dim("Reload your shell: exec zsh"));return}console.log(Ce.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ce.cyan(` ${i}`)),l&&console.log(Ce.cyan(` ${r}`)),console.log(),console.log(Ce.dim("Then reload: exec zsh")),console.log(Ce.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Ht(fr(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Ls(n)?Ag(n,"utf-8"):"").includes(o)){console.log(Ce.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Ls(n)){Tg(n,`
|
|
635
635
|
# agentx completion
|
|
@@ -640,4 +640,4 @@ ${s}
|
|
|
640
640
|
`)}function hr(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ur(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=hr(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 U1(){let e=await da(),o=new Qy().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=Oc(n);Ic(s)&&Tc("cli",s)});for(let t of[nl,el,_t,bt,vt,Xe,Sc,Yo,es,wo,Mo,Po,Zn,gg,Ro,xl,Nl,pn,Bl,zl,Yl,gd,fd,hd,jt,wn,hg,rn,Oo,Cg])o.addCommand(t);for(let t of Rg)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Rg.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Zy(t,74," "),""].join(`
|
|
641
641
|
`)}),o}var Rg=[Z,Dt,qo,so,cn,Ct,He,$o,Lo,nt,Ft,Ut,Co,We,At,ws,cg,lg,ho,Vo,_c,Ko,An,wi,Uo,St,bi,js,po,Wo,kg,xg,fg];function Zy(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(`
|
|
642
642
|
`)}export{U1 as a};
|
|
643
|
-
//# sourceMappingURL=chunk-
|
|
643
|
+
//# sourceMappingURL=chunk-LEFRNHZF.js.map
|