agentix-cli 0.60.0 → 0.61.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/{board-dashboard-BVRRDYAG.js → board-dashboard-C6AZHDHU.js} +655 -188
- package/dist/board-dashboard-C6AZHDHU.js.map +1 -0
- package/dist/{chunk-TM762AXU.js → chunk-BCXKRD5L.js} +4 -4
- package/dist/{chunk-TM762AXU.js.map → chunk-BCXKRD5L.js.map} +1 -1
- package/dist/chunk-RVEMQCWW.js +130 -0
- package/dist/chunk-RVEMQCWW.js.map +1 -0
- package/dist/{chunk-RYFUFX6F.js → chunk-Y76THZUQ.js} +154 -252
- package/dist/chunk-Y76THZUQ.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{program-BOCLU6ES.js → program-L6VAFALE.js} +2 -2
- package/package.json +1 -1
- package/dist/board-dashboard-BVRRDYAG.js.map +0 -1
- package/dist/chunk-PAOV37KQ.js +0 -29
- package/dist/chunk-PAOV37KQ.js.map +0 -1
- package/dist/chunk-RYFUFX6F.js.map +0 -1
- /package/dist/{program-BOCLU6ES.js.map → program-L6VAFALE.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Ic,b as Gn,g as Cc}from"./chunk-DTEQNXK3.js";import{a as kc,c as vc}from"./chunk-N5KD3TVN.js";import{a as ro,b as yc,f as wc,g as bc,h as $c,i as Hn,j as xc,k as Sc,l as ri,m as Oc,o as jc}from"./chunk-WOPFHKBF.js";import{a as Ec,c as Ac,d as Tc}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
|
|
1
|
+
import{a as Ic,b as Gn,g as Cc}from"./chunk-DTEQNXK3.js";import{a as kc,c as vc}from"./chunk-N5KD3TVN.js";import{a as ro,b as yc,f as wc,g as bc,h as $c,i as Hn,j as xc,k as Sc,l as ri,m as Oc,o as jc}from"./chunk-WOPFHKBF.js";import{a as Ec,c as Ac,d as Tc}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 Ne,A as Ha,B as Ga,C as za,D as Ya,E as Va,F as Ka,G as Eo,H as Qa,I as Qs,J as Zs,K as Za,L as ec,M as en,N as Un,O as oc,P as tc,Q as ft,R as qn,S as ei,T as nc,U as sc,V as ic,W as rc,X as ht,Y as yt,Z as ac,_ as cc,a as ia,aa as Wn,b as ra,ba as on,ca as oi,da as lc,ea as mc,fa as si,ga as uc,h as da,ha as Bn,i as Qt,ia as wt,j as _n,ja as Jn,k as pa,ka as ii,l as ua,la as fc,m as fa,ma as hc,n as ha,o as Aa,p as Ta,q as Ln,r as Vs,s as Na,t as Ma,u as Ua,v as qa,w as Wa,x as Ba,y as Ja,z as Ks}from"./chunk-Y76THZUQ.js";import{A as Pa,J as Zt,M as Xs,N as Fn,Q as Xa,ca as dc,da as ti,ea as gc,fa as ni,m as So,p as Ra,s as _a,ta as io,va as pc,z as Da}from"./chunk-RVEMQCWW.js";import{a as aa,d as ca,e as la}from"./chunk-E2PWCU2N.js";import{a as Ys,b as Dn,c as Pn,d as ya,e as wa,f as ba,i as $a,j as ka,k as va,l as xa,o as Mn,q as Sa,r as Ea}from"./chunk-S7CVSKOX.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-27P5NLTC.js";import{a as ga,p as ma}from"./chunk-LXUG2X26.js";import{a as Oa,b as ja,c as Ia,d as Ca}from"./chunk-2D3RYIDU.js";import{a as La,b as Fa}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-JO3PSLWL.js";import{b as Kt,c as gt,d as Nn,e as Rn,f as mt,g as Ur,h as Ho,i as Xt}from"./chunk-WIBMNQKJ.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-JORXRF4E.js";import{b as ye,c as Oe,d as ut,e as Yr}from"./chunk-CRSXKQLZ.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-2VQIPJH5.js";import{b as vo,d as Cn}from"./chunk-E2BJVHBR.js";import{b as lt,d as Nr}from"./chunk-2GIDVZ4H.js";import{a as qs,b as yr,c as Rg,d as jn,e as wr,f as Ar,g as Pg,h as Tr,i as Mg,m as ct,n as jr,o as Ir,s as Cr,v as so,w as Vt}from"./chunk-NBGNPKAF.js";import{a as fo,b as at,e as xr,f as Yt}from"./chunk-72SZI2UW.js";import{a as Or,b as Lg}from"./chunk-FX3D7YON.js";import{a as uo,b as Ng}from"./chunk-7I7IEX4S.js";import{m as br,n as $r,p as kr,q as _g,v as vr,w as I,x as In,z as ae}from"./chunk-S7TCVIET.js";import{g as Sr,k as Er,l as Dg}from"./chunk-RGDKHYY2.js";import{Command as Fg}from"commander";var Nc=new Fg().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 Ug}from"commander";import{execFileSync as ao}from"node:child_process";import{cpSync as Rc,existsSync as ci,mkdirSync as ai,mkdtempSync as qg,rmSync as Wg,writeFileSync as _c}from"node:fs";import{dirname as Dc,join as Le}from"node:path";import{homedir as zn,release as Bg,tmpdir as Jg}from"node:os";import{setTimeout as Hg}from"node:timers/promises";function Yn(){let e=ya(process.platform,process.arch,Bg());if(e)throw new Error(e)}function tn(){return`gui/${process.getuid()}/${Ys}`}function bt(){return Le(zn(),"Library/LaunchAgents",`${Ys}.plist`)}async function Pc(){try{ao("launchctl",["bootout",tn()],{stdio:"pipe"})}catch{}for(let e=0;e<30;e++){try{ao("launchctl",["print",tn()],{stdio:"pipe"})}catch{return}await Hg(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Mc(){if(!ci(bt()))throw new Error("Run agentx desktop install first.");let e=!0;try{ao("launchctl",["print",tn()],{stdio:"pipe"})}catch{e=!1}e||ao("launchctl",["bootstrap",`gui/${process.getuid()}`,bt()],{stdio:"pipe"}),ao("launchctl",["kickstart",tn()],{stdio:"pipe"})}function Gg(){let e=xa();if(e&&ci(Le(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 $t=new Ug("desktop").description("install and control the macOS desktop assistant");$t.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=>{Yn();let o=I(),t=wa(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=Gg(),r=Le(zn(),"Applications");if(console.log(`Desktop assistant \u2192 ${Le(r,Dn)}
|
|
2
2
|
Computer-use helper \u2192 ${Le(r,Pn)}
|
|
3
3
|
Agent \u2192 ${n?`${t} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -402,7 +402,7 @@ return aid ?? null`}function Tu(e,o){if(e.kind==="path"){let s=e.pts,i=s[Math.fl
|
|
|
402
402
|
settings \u2014 without this an attached production identity would be less
|
|
403
403
|
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=Wc({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 df}from"commander";import we from"chalk";var ws=new df().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function vd(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=I(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 xd(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function kd(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 gf(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}=vd(e),n;try{n=await fetch(`${o}/api/processes`,{headers:xd(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=gf(r.state)(r.state.padEnd(9)),c=kd(r.spawnedAt),l=r.lastTurnAt?kd(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"),p=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} ${p}`),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}=vd(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:xd(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 mf}from"commander";import De from"chalk";import{existsSync as Li,rmSync as pf}from"fs";import{resolve as Fi}from"path";var Nt=new mf().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");Nt.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(De.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(De.green(` \u2713 indexed ${i.docs} doc(s) for ${De.bold(e)} in ${r}ms`)),console.log(De.dim(` \u2192 ${i.path}`))});Nt.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(De.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(De.dim(" (no indexes)"));return}for(let s of n.sort()){let i=Js(s);console.log(` ${De.bold(s)} ${i.docs} doc(s) ${De.dim(i.path)}`)}});Nt.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(De.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(De.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${De.bold(i.title)} ${De.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${De.dim(i.path)}`),console.log(` ${De.dim(i.snippet.slice(0,200))}`)});Nt.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=Fi(process.cwd(),".agentx","rag",e);if(!Li(o)){console.log(De.dim(` no index for ${e} \u2014 nothing to clear`));return}pf(o,{recursive:!0,force:!0}),console.log(De.green(` \u2713 cleared index for ${e}`))});ae();import{Command as uf}from"commander";import X from"chalk";import Rt from"prompts";var nt=new uf().name("backlog").description("manage the local backlog used by business workSource=backlog");function hn(e){let o=I(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new dc(n)}}function ff(e){return e?X.cyan(`${e.type}:${e.project}#${e.iid}`):X.dim("manual")}function hf(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}=hn(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(` ${hf(n.status).padEnd(7)} ${ff(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=hn(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=gc([o],i.source,n.config),a=await ni(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=hn(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 ni(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}=hn(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=hn(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 Rt({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"?wf(o.config):bf(o.config);y.length?(i=(await Rt({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 Rt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Rt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Rt({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 $f(o.config,i,a):await kf(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=ti({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 Rt({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 u=f.map(y=>{let k={type:s,host:s==="gitlab"?yf(o.config):void 0,project:l,iid:y.iid,url:y.url};return{id:ti(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(u);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 yf(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function wf(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 bf(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 $f(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 kf(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(Sd)}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(Sd):[]}function Sd(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 vf}from"commander";import W from"chalk";import{existsSync as xf,readFileSync as Sf}from"fs";import{resolve as Ef}from"path";import Af from"prompts";ae();function Ed(e){let o=e||Ef(process.cwd(),"agentx.json");return xf(o)||(console.log(W.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(Sf(o,"utf-8"))}async function Tf(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 Af([{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 vf().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=Ed(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 Tf(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=Ed(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 Of}from"commander";import xe from"chalk";var Mo=new Of("approvals").description("one inbox for every decision waiting for you (cards, schedules, memory facts, wiki proposals)"),jf={card:"card",schedule:"schedule",memory:"memory",wiki:"wiki"};function Ad(){return{root:process.cwd()}}function Ui(e){return e?e.slice(0,16).replace("T"," ")+" UTC":"unknown"}function If(e){console.log(` ${xe.cyan(e.key)} ${xe.dim(`[${jf[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=Da(Ad(),{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)If(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=Hn(),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 Pa(Ad(),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: ${Ra.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=Hn(),t=_a(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=xc(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 Sc(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=Hn(),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 Zf}from"commander";import _t from"chalk";import ne from"chalk";import wn from"prompts";import{readFileSync as Cf,writeFileSync as Nf,existsSync as Rf}from"fs";import{resolve as Td}from"path";var _f=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Df(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 Od(e=".env"){let o=Td(e);if(!Rf(o))return[];let t=Cf(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(_f);i?n.push({kind:"kv",key:i[1],value:Df(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Pf(e){return e.map(o=>o.kind==="kv"?`${o.key}=${Wi(o.value)}`:o.raw).join(`
|
|
404
404
|
`)+`
|
|
405
|
-
`}function yn(e,o,t=".env"){let n=Td(t),s=Od(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)}`})),Nf(n,Pf(s))}function Bi(e,o=".env"){return Od(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var jd="https://t.me/BotFather";async function Mf(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 Lf(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 Id(e={}){console.log(),console.log(ne.bold(" Connect Telegram")),console.log(),console.log(ne.dim(` 1. Open ${jd}`)),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 wn({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,[jd],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await wn({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 Mf(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 wn({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||{},p=e.account||g;d[p]&&d[p].agentBinding!==g&&(p=(await wn({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(ne.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;yn(f,t.trim()),process.env[f]=t.trim();let u=await ye(b=>{Oe(b,"channels.telegram.enabled",!0),Oe(b,`channels.telegram.accounts.${p}`,{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(u.success||(console.log(ne.red(` \u2717 ${u.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}`)),u.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 wn({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 Lf(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 ${p}`));return}let k=await ye(b=>{Oe(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{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 Ff,readdirSync as Uf,readFileSync as Cd}from"fs";import{resolve as Hi}from"path";var qf=".agentx/whatsapp-sessions";function Wf(){let e=Hi(process.cwd(),".agentx/daemon.pid");if(!Gi(e))return!1;try{let o=parseInt(Cd(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Bf(e){if(!Gi(e))return!1;try{return Uf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Jf(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;Ff(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(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:u}=await import("qrcode-terminal");u.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(p),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(p),o(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Nd(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),Wf()){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(Cd(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||qf,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(Bf(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 Jf(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 Hf}from"crypto";import Ee from"chalk";import Rd from"prompts";var bs="agentx-mesh:",$s="//join/";function Gf(e){return Buffer.from(e,"utf-8").toString("base64url")}function zf(e){return Buffer.from(e,"base64url").toString("utf-8")}function Yf(e){return`${bs}${$s}${Gf(JSON.stringify(e))}`}function Vf(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(zf(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 Kf(){return Hf(32).toString("hex")}function Xf(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Qf(e){return e?.node?.name||e?.node?.id||"node"}async function _d(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=Kf(),yn("MESH_TOKEN",r),console.log(Ee.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Xf(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Rd({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(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=Yf({url:a,token:r,name:Qf(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 Dd(e,o={}){let t;try{t=Vf(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 Rd({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))}yn("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 Dt=new Zf().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Dt.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 Id({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Dt.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 Nd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Pd=Dt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Pd.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 _d({url:e.url,configPath:e.config})});Pd.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 Dd(e,{configPath:o.config})});Dt.action(()=>{console.log(),console.log(_t.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${_t.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${_t.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${_t.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${_t.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(_t.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as eh}from"commander";import ue from"chalk";var bn=new eh().name("usage").description("token usage analysis and reporting");bn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=I(),[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}`))}});bn.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?"))}});bn.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-BOCLU6ES.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let f of d.commands??[]){let u=p?`${p} ${f.name()}`:f.name();c.push(u),l(f,u)}};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 oh}from"commander";import $e from"chalk";import{readFileSync as th}from"fs";import{resolve as nh}from"path";ae();var Lo=new oh().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(nh(process.cwd(),".env"))}catch{}let o=sh(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-BVRRDYAG.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 sh(e,o){try{let t=I();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.
|
|
405
|
+
`}function yn(e,o,t=".env"){let n=Td(t),s=Od(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)}`})),Nf(n,Pf(s))}function Bi(e,o=".env"){return Od(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var jd="https://t.me/BotFather";async function Mf(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 Lf(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 Id(e={}){console.log(),console.log(ne.bold(" Connect Telegram")),console.log(),console.log(ne.dim(` 1. Open ${jd}`)),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 wn({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,[jd],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await wn({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 Mf(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 wn({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||{},p=e.account||g;d[p]&&d[p].agentBinding!==g&&(p=(await wn({type:"text",name:"account",message:`Account "${p}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),p||(console.log(ne.red(" Aborted")),process.exit(1));let f=`TG_${p.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;yn(f,t.trim()),process.env[f]=t.trim();let u=await ye(b=>{Oe(b,"channels.telegram.enabled",!0),Oe(b,`channels.telegram.accounts.${p}`,{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(u.success||(console.log(ne.red(` \u2717 ${u.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}`)),u.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 wn({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 Lf(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 ${p}`));return}let k=await ye(b=>{Oe(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:p})},{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 Ff,readdirSync as Uf,readFileSync as Cd}from"fs";import{resolve as Hi}from"path";var qf=".agentx/whatsapp-sessions";function Wf(){let e=Hi(process.cwd(),".agentx/daemon.pid");if(!Gi(e))return!1;try{let o=parseInt(Cd(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function Bf(e){if(!Gi(e))return!1;try{return Uf(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function Jf(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;Ff(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await t.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:t.makeCacheableSignalKeyStore?t.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(g=>{let p=setTimeout(()=>{o(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:u}=await import("qrcode-terminal");u.generate(f.qr,{small:!0})}catch{o(` QR: ${f.qr}`)}o("")}if(f.connection==="open"){clearTimeout(p),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(p),o(be.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Nd(e={}){if(console.log(),console.log(be.bold(" Connect WhatsApp")),console.log(),Wf()){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(Cd(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||qf,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(Bf(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 Jf(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 Hf}from"crypto";import Ee from"chalk";import Rd from"prompts";var bs="agentx-mesh:",$s="//join/";function Gf(e){return Buffer.from(e,"utf-8").toString("base64url")}function zf(e){return Buffer.from(e,"base64url").toString("utf-8")}function Yf(e){return`${bs}${$s}${Gf(JSON.stringify(e))}`}function Vf(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(zf(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 Kf(){return Hf(32).toString("hex")}function Xf(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function Qf(e){return e?.node?.name||e?.node?.id||"node"}async function _d(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=Kf(),yn("MESH_TOKEN",r),console.log(Ee.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Xf(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Rd({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:p=>/^https?:\/\//.test(p)||"must start with http:// or https://"});d||(console.log(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=Yf({url:a,token:r,name:Qf(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 Dd(e,o={}){let t;try{t=Vf(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 Rd({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))}yn("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 Dt=new Zf().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Dt.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 Id({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Dt.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 Nd({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Pd=Dt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Pd.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 _d({url:e.url,configPath:e.config})});Pd.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 Dd(e,{configPath:o.config})});Dt.action(()=>{console.log(),console.log(_t.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${_t.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${_t.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${_t.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${_t.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(_t.dim(" GitLab connect is the next slice.")),console.log()});ae();import{Command as eh}from"commander";import ue from"chalk";var bn=new eh().name("usage").description("token usage analysis and reporting");bn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=I(),[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}`))}});bn.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?"))}});bn.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-L6VAFALE.js"),r=await i(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,p)=>{for(let f of d.commands??[]){let u=p?`${p} ${f.name()}`:f.name();c.push(u),l(f,u)}};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 oh}from"commander";import $e from"chalk";import{readFileSync as th}from"fs";import{resolve as nh}from"path";ae();var Lo=new oh().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(nh(process.cwd(),".env"))}catch{}let o=sh(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-C6AZHDHU.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 sh(e,o){try{let t=I();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
406
|
`)),{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=I();if(!e.boards?.length){console.log($e.dim(`
|
|
407
407
|
No boards configured.
|
|
408
408
|
`));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{$n(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{$n(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(th("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{$n(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{$n(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{$n(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 $n(e){let{summary:o,backupPath:t}=ro(n=>e(n));console.log($e.green(`
|
|
@@ -628,7 +628,7 @@ Restart the daemon to activate.
|
|
|
628
628
|
dist/
|
|
629
629
|
*.log
|
|
630
630
|
.env
|
|
631
|
-
`}import{Command as Ly}from"commander";import Ce from"chalk";import{writeFileSync as Fy,mkdirSync as Uy,existsSync as Ls,readFileSync as Sg,appendFileSync as Eg}from"fs";import{resolve as Gt,dirname as Og}from"path";import{homedir as fr}from"os";var jg=new Ly().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-
|
|
631
|
+
`}import{Command as Ly}from"commander";import Ce from"chalk";import{writeFileSync as Fy,mkdirSync as Uy,existsSync as Ls,readFileSync as Sg,appendFileSync as Eg}from"fs";import{resolve as Gt,dirname as Og}from"path";import{homedir as fr}from"os";var jg=new Ly().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-L6VAFALE.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=By(t);break;case"bash":s=Yy(t);break;case"fish":s=Vy(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?Gt(String(e.output)):qy(n);Uy(Og(i),{recursive:!0}),Fy(i,s),console.log(Ce.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Wy(n,i,!!e.yes)});function qy(e){let o=fr();switch(e){case"zsh":return Gt(o,".zsh","completions","_agentx");case"bash":return Gt(o,".bash_completion.d","agentx.bash");case"fish":return Gt(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Wy(e,o,t){if(e==="zsh"){let n=Gt(fr(),".zshrc"),s=Og(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Ls(n)?Sg(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),Eg(n,g.join(`
|
|
632
632
|
`)+`
|
|
633
633
|
`),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=Gt(fr(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Ls(n)?Sg(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)){Eg(n,`
|
|
634
634
|
# agentx completion
|
|
@@ -639,4 +639,4 @@ ${s}
|
|
|
639
639
|
`)}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 L1(){let e=await hc(),o=new Ky().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=Ac(n);Tc(s)&&Ec("cli",s)});for(let t of[ol,Qc,Dt,$t,xt,Ke,vc,Yo,es,wo,Mo,Po,Zn,lg,Ro,kl,Il,un,ql,Hl,Gl,ld,pd,ud,Ct,bn,ug,an,Oo,jg])o.addCommand(t);for(let t of Cg)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Cg.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,Xy(t,74," "),""].join(`
|
|
640
640
|
`)}),o}var Cg=[Z,Pt,qo,no,ln,Nt,He,$o,Lo,nt,Ut,qt,Co,We,Tt,ws,rg,ag,ho,Vo,Nc,Ko,Tn,wi,Uo,Et,bi,Is,po,Wo,bg,kg,pg];function Xy(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(`
|
|
641
641
|
`)}export{L1 as a};
|
|
642
|
-
//# sourceMappingURL=chunk-
|
|
642
|
+
//# sourceMappingURL=chunk-BCXKRD5L.js.map
|