agentix-cli 0.25.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/{App-6Y7B3YQH.js → App-BPNHIGUX.js} +2 -2
- package/dist/{ChatApp-KIEUJ2DS.js → ChatApp-6XSSZB4U.js} +2 -2
- package/dist/{agent-QGZIAZMY.js → agent-5QMITZT6.js} +2 -2
- package/dist/{board-dashboard-CQ5F4GPD.js → board-dashboard-M3372FLO.js} +1191 -225
- package/dist/board-dashboard-M3372FLO.js.map +1 -0
- package/dist/{chunk-JXWAGMI2.js → chunk-BTHHSY7D.js} +7 -7
- package/dist/chunk-BTHHSY7D.js.map +1 -0
- package/dist/{chunk-TRJTTBE2.js → chunk-BVGJSPW4.js} +2 -2
- package/dist/{chunk-53GCFZPR.js → chunk-D46VZ7K7.js} +2 -2
- package/dist/{chunk-HA3XI7Z2.js → chunk-E5CXCI33.js} +27 -27
- package/dist/chunk-E5CXCI33.js.map +1 -0
- package/dist/{chunk-FDMWOPEL.js → chunk-K2CAPYES.js} +2 -2
- package/dist/{chunk-TMKLHTCG.js → chunk-METYYZKQ.js} +264 -120
- package/dist/chunk-METYYZKQ.js.map +1 -0
- package/dist/{chunk-Q6YO7LYE.js → chunk-MTAPOCGA.js} +2 -2
- package/dist/{chunk-G57RZCXM.js → chunk-O6YPEOQF.js} +2 -2
- package/dist/{chunk-KUCCW2VG.js → chunk-UHE5FCPB.js} +8 -8
- package/dist/{chunk-LNXCJWOU.js → chunk-V3U4OF7L.js} +2 -2
- package/dist/{chunk-NGSIRE4X.js → chunk-VT5XYFDD.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/client-HGKAC6VP.js +2 -0
- package/dist/{config-7FSZFRTQ.js → config-A4RWEJHV.js} +2 -2
- package/dist/config-mutator-MNSFUN7D.js +2 -0
- package/dist/doctor-3Q36ZFE6.js +2 -0
- package/dist/index.d.ts +58 -1
- package/dist/index.js +1 -1
- package/dist/{program-WVAVJFND.js → program-SAUNRCCD.js} +2 -2
- package/dist/{registry-T36ZIAWV.js → registry-HK3WQ7BS.js} +2 -2
- package/dist/scheduler-6T2SU5ST.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-CQ5F4GPD.js.map +0 -1
- package/dist/chunk-HA3XI7Z2.js.map +0 -1
- package/dist/chunk-JXWAGMI2.js.map +0 -1
- package/dist/chunk-TMKLHTCG.js.map +0 -1
- package/dist/client-GGVVLOOF.js +0 -2
- package/dist/config-mutator-POCOYYJ4.js +0 -2
- package/dist/doctor-DHLBEKA4.js +0 -2
- package/dist/scheduler-GH7TIKYS.js +0 -2
- /package/dist/{App-6Y7B3YQH.js.map → App-BPNHIGUX.js.map} +0 -0
- /package/dist/{ChatApp-KIEUJ2DS.js.map → ChatApp-6XSSZB4U.js.map} +0 -0
- /package/dist/{agent-QGZIAZMY.js.map → agent-5QMITZT6.js.map} +0 -0
- /package/dist/{chunk-TRJTTBE2.js.map → chunk-BVGJSPW4.js.map} +0 -0
- /package/dist/{chunk-53GCFZPR.js.map → chunk-D46VZ7K7.js.map} +0 -0
- /package/dist/{chunk-FDMWOPEL.js.map → chunk-K2CAPYES.js.map} +0 -0
- /package/dist/{chunk-Q6YO7LYE.js.map → chunk-MTAPOCGA.js.map} +0 -0
- /package/dist/{chunk-G57RZCXM.js.map → chunk-O6YPEOQF.js.map} +0 -0
- /package/dist/{chunk-KUCCW2VG.js.map → chunk-UHE5FCPB.js.map} +0 -0
- /package/dist/{chunk-LNXCJWOU.js.map → chunk-V3U4OF7L.js.map} +0 -0
- /package/dist/{chunk-NGSIRE4X.js.map → chunk-VT5XYFDD.js.map} +0 -0
- /package/dist/{client-GGVVLOOF.js.map → client-HGKAC6VP.js.map} +0 -0
- /package/dist/{config-7FSZFRTQ.js.map → config-A4RWEJHV.js.map} +0 -0
- /package/dist/{config-mutator-POCOYYJ4.js.map → config-mutator-MNSFUN7D.js.map} +0 -0
- /package/dist/{doctor-DHLBEKA4.js.map → doctor-3Q36ZFE6.js.map} +0 -0
- /package/dist/{program-WVAVJFND.js.map → program-SAUNRCCD.js.map} +0 -0
- /package/dist/{registry-T36ZIAWV.js.map → registry-HK3WQ7BS.js.map} +0 -0
- /package/dist/{scheduler-GH7TIKYS.js.map → scheduler-6T2SU5ST.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Ks,b as kt,g as Vs}from"./chunk-
|
|
1
|
+
import{a as Ks,b as kt,g as Vs}from"./chunk-O6YPEOQF.js";import{b as qs}from"./chunk-BVGJSPW4.js";import{a as Ao,b as Fs,f as bt,j as Ys}from"./chunk-V3U4OF7L.js";import{a as zs,c as Hs,d as Gs}from"./chunk-UCQ2N3KO.js";import{a as Eo}from"./chunk-GV7S5BAX.js";import{e as cs}from"./chunk-GSX4NK2N.js";import{c as ls}from"./chunk-SZDACK6O.js";import{a as Is,g as As,h as Os,i as Yo,j as $t,k as Cs,l as Rs,m as Ts,n as Ds,o as Ns,p as _s,q as Ps,r as Ms,s as Ws,t as an,u as cn,v as Js,w as Bs}from"./chunk-METYYZKQ.js";import{a as Ls,b as sn,c as Us,d as rn}from"./chunk-3WQFCIB6.js";import{i as ss,k as So,m as en,n as as,p as He,v as Es}from"./chunk-E5CXCI33.js";import{A as Ss,B as js,b as ft,c as jo,d as ht,e as Ue,f as Go,k as Io,m as us,q as ys,r as ws,s as wt,t as $s,u as tn,v as nn,w as bs,x as ks,y as vs,z as xs}from"./chunk-MTAPOCGA.js";import{a as ps}from"./chunk-M4AMWP3H.js";import{f as ds,g as gs,h as on}from"./chunk-76Z4VHDX.js";import{b as rs,f as ms}from"./chunk-D46VZ7K7.js";import{a as K,b as X,c as co,d as hs}from"./chunk-K2CAPYES.js";import{e as fs,f as L,g as yt}from"./chunk-BTHHSY7D.js";import{a as ze,b as ut}from"./chunk-ISEBLHWX.js";import{b as ao,d as is,f as Zt}from"./chunk-BFXONUUN.js";import{a as Le}from"./chunk-VJUTQAPJ.js";import{a as Ar}from"./chunk-4YCH6IZV.js";import{Command as rd}from"commander";import{Command as Or}from"commander";import j from"chalk";import{existsSync as Cr,readFileSync as Rr}from"fs";async function Tr(e){try{let{execFileSync:o}=await import("child_process"),t=o("ps",["-p",String(e),"-o","command="],{encoding:"utf-8",timeout:2e3}).trim();return t?/\bnode\b/.test(t)||/agentx|agentix|cli\.js/.test(t):!1}catch{return!0}}var De=new Or().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");De.command("start").description("start the daemon (default if no subcommand)").option("-c, --config <path>","path to agentx.json").option("-d, --detach","run in background (detached)").option("--port <port>","override bind port").action(async e=>{if(e.detach){let{spawn:d}=await import("child_process"),{openSync:g,writeFileSync:l,existsSync:u}=await import("fs"),m=process.argv[1];(!m||!u(m))&&(console.error(j.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${m||"?"}).`)),console.error(j.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let f=[m,"daemon","start"];e.config&&f.push("-c",e.config),e.port&&f.push("--port",e.port);let y="/tmp/agentx-daemon.log",$;try{$=g(y,"a")}catch(b){console.error(j.red(` Failed to open ${y} for writing: ${b.message}`)),process.exit(1)}let v=d(process.execPath,f,{detached:!0,stdio:["ignore",$,$],cwd:process.cwd()});v.unref(),l("/tmp/agentx-daemon.pid",String(v.pid)),console.log(j.green(`Daemon started in background (PID: ${v.pid})`)),console.log(j.dim(` Logs: tail -f ${y}`)),console.log(j.dim(" Stop: agentx daemon stop")),await new Promise(b=>setTimeout(b,1e3));try{process.kill(v.pid,0)}catch{console.log(),console.log(j.yellow(` Daemon exited within 1s \u2014 check ${y} for the error:`)),console.log(j.dim(` tail -n 40 ${y}`))}return}let{readFileSync:o,writeFileSync:t,mkdirSync:n,existsSync:s}=await import("fs"),{resolve:i}=await import("path"),r=i(process.cwd(),".agentx");s(r)||n(r,{recursive:!0});let a=i(r,"daemon.pid");if(s(a)){let d=parseInt(o(a,"utf-8").trim(),10);if(d&&d!==process.pid){let g=!1;try{process.kill(d,0),g=!0}catch{}g&&await Tr(d)&&(console.error(`Another agentx daemon is already running (PID ${d}). Exiting.`),process.exit(0))}}t(a,String(process.pid));try{Dr(i(process.cwd(),".env"))}catch{}await new cn(e.config).start()});function Dr(e){if(!Cr(e))return;let o=Rr(e,"utf-8");for(let t of o.split(`
|
|
2
2
|
`)){let n=t.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");if(s<0)continue;let i=n.slice(0,s).trim();if(!i||process.env[i]!==void 0)continue;let r=n.slice(s+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),process.env[i]=r}}De.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:o,unlinkSync:t}=await import("fs"),{resolve:n}=await import("path"),s=[n(process.cwd(),".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"];for(let r of s)if(o(r))try{let a=parseInt(e(r,"utf-8").trim(),10);process.kill(a,"SIGTERM"),await new Promise(c=>setTimeout(c,2e3));try{t(r)}catch{}console.log(j.green(`Daemon stopped (PID: ${a})`));return}catch{try{t(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(j.green("Daemon stopped"))}catch{console.log(j.yellow("No daemon process found"))}});De.command("status").alias("st").description("show daemon status, agents, crons, and mesh").option("-c, --config <path>","path to agentx.json").option("--json","output as JSON").action(async e=>{try{let o=L(e.config),[t,n]=o.node.bind.split(":"),s=`http://${t||"127.0.0.1"}:${n}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(e.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(j.bold(` ${r.node.name}`)+j.dim(` (${r.node.id})`)),console.log(j.green(" Status: running")+j.dim(` \u2014 uptime ${Nr(r.uptime)}`)),console.log(),console.log(j.bold(" Agents:"));for(let c of r.agents){let d=c.active>0?j.yellow(` [${c.active} active]`):"",g=c.errors>0?j.red(` (${c.errors} errors)`):"";console.log(` ${j.cyan(c.name)} ${j.dim(`(${c.tier})`)}${d}${g}`),console.log(j.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(j.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let d=c.enabled?j.green("\u25CF"):j.dim("\u25CB"),g=c.nextRun?j.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${d} ${c.id}${g}`)}}if(r.mesh?.length){console.log(),console.log(j.bold(" Mesh:"));for(let c of r.mesh){let d=c.healthy?j.green("\u25CF"):j.red("\u25CF"),g=c.skills?.length?j.dim(` (${c.skills.length} agents)`):"";console.log(` ${d} ${c.peer} ${j.dim(c.peerUrl)}${g}`)}}console.log()}catch(o){if(o.cause?.code==="ECONNREFUSED"||o.name==="TimeoutError")console.log(j.red(" Daemon is not running")),console.log(j.dim(" Start with: agentx daemon start"));else try{let t=L(e.config),n=yt(t);if(console.log(),console.log(j.bold(` ${t.node.name}`)+j.dim(` (${t.node.id})`)),console.log(j.yellow(" Status: stopped")),console.log(j.dim(` ${Object.keys(t.agents).length} agents, ${Object.keys(t.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(j.yellow(` \u26A0 ${s}`))}console.log()}catch(t){console.log(j.red(` ${t.message}`))}}});De.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async e=>{let{execSync:o,spawn:t}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(j.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=t("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else o(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});De.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(L(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(j.dim(` Connecting to ${n}...`)),console.log(j.dim(` Press Ctrl+C to stop
|
|
3
3
|
`));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(j.red(` Failed: ${s.status}`));return}let i=s.body.getReader(),r=new TextDecoder,a="";for(;;){let{done:c,value:d}=await i.read();if(c)break;a+=r.decode(d,{stream:!0});let g=a.split(`
|
|
4
4
|
`);a=g.pop()||"";for(let l of g)if(l.startsWith("data: "))try{let u=JSON.parse(l.slice(6)),m=new Date(u.time).toLocaleTimeString(),f=u.message?.replace(/^\[agentx\]\s*/,"")||"";f.includes("executing")?console.log(`${j.dim(m)} ${j.cyan("\u25B6")} ${f}`):f.includes("completed")?console.log(`${j.dim(m)} ${j.green("\u2713")} ${f}`):f.includes("error")||f.includes("Error")?console.log(`${j.dim(m)} ${j.red("\u2717")} ${f}`):f.includes("Routing")?console.log(`${j.dim(m)} ${j.yellow("\u2192")} ${f}`):f.includes("mention")?console.log(`${j.dim(m)} ${j.magenta("@")} ${f}`):f.includes("Skipping")?console.log(`${j.dim(m)} ${j.dim("\u2298")} ${j.dim(f)}`):console.log(`${j.dim(m)} ${f}`)}catch{}else l.startsWith("event: status")}}catch(s){console.log(j.red(` Connection failed: ${s.message}`)),console.log(j.dim(" Is the daemon running? Diagnostic order:")),console.log(j.dim(" 1) agentx daemon status # is the daemon up?")),console.log(j.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(j.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(j.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(j.dim(" to see the error in the foreground."))}});De.command("send <agent> <message...>").description("send a task to an agent via the daemon API").option("-c, --config <path>","path to agentx.json").option("--peer <peer>","send to a mesh peer's agent").option("--json","output raw JSON response").action(async(e,o,t)=>{let n=o.join(" ");try{let s=L(t.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,d;t.peer?(c=`${a}/mesh/task`,d={peer:t.peer,message:n,agent:e}):(c=`${a}/task`,d={agent:e,message:n}),console.log(j.dim(` Sending to ${t.peer?`${t.peer}/${e}`:e}...`));let l=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})).json();t.json?console.log(JSON.stringify(l,null,2)):l.error?console.log(j.red(` Error: ${l.error}`)):(console.log(),console.log(l.content||l.response||"No response"),l.duration&&console.log(j.dim(`
|
|
@@ -10,14 +10,14 @@ import{a as Ks,b as kt,g as Vs}from"./chunk-G57RZCXM.js";import{b as qs}from"./c
|
|
|
10
10
|
`))}catch(o){console.log(ge.red(` ${o.message}`)),process.exit(1)}});import{Command as _e}from"commander";import h from"chalk";import me from"prompts";import{readFileSync as Ye,writeFileSync as Co,existsSync as ne,mkdirSync as Ne,cpSync as ln,readdirSync as gn}from"fs";import{resolve as _,join as Ge,dirname as Hr}from"path";import{fileURLToPath as Gr}from"url";function Z(){let e=_(process.cwd(),"agentx.json");if(!ne(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ye(e,"utf-8"))}function ye(e){return K(o=>{for(let t of Object.keys(o))delete o[t];Object.assign(o,e)}).then(o=>{if(!o.success){console.error(h.red(` Config save failed: ${o.error}`));return}o.reloaded?console.error(h.dim(" (daemon hot-reloaded)")):o.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(o.reloadSkipped)&&console.error(h.dim(` (daemon reload skipped: ${o.reloadSkipped})`))})}var go=new _e().name("agent").description("manage agents \u2014 add, list, remove");go.command("list").alias("ls").description("list configured agents").action(()=>{let e=Z();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=t.mentions?.join(", ")||"";console.log(` ${h.cyan(o)} \u2014 ${t.name} (${t.tier})`),console.log(h.dim(` workspace: ${t.workspace}`)),n&&console.log(h.dim(` mentions: ${n}`))}console.log()});go.command("add").description("add a new agent interactively").action(async()=>{let e=Z(),o=await me([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:d=>/^[a-z0-9-]+$/.test(d)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:_(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{title:"codex-cli (OpenAI Codex CLI)",value:"codex-cli"},{title:"opencode (configured OpenCode providers)",value:"opencode"},{title:"sdk (API key, programmatic)",value:"sdk"},{title:"orchestrator (any provider)",value:"orchestrator"}]},{type:"text",name:"model",message:"Model",initial:"claude-sonnet-4-6"},{type:"list",name:"mentions",message:"Mention patterns (comma-separated)",separator:","},{type:"number",name:"maxConcurrent",message:"Max concurrent tasks",initial:2},{type:"text",name:"systemPrompt",message:"System prompt"}]);if(!o.id)return;let t=o.workspace.endsWith(o.id)?o.workspace:Ge(o.workspace,o.id);Ne(_(t,".claude/skills"),{recursive:!0});let n={name:o.name,workspace:t,tier:o.tier,model:o.model,mentions:o.mentions?.map(d=>d.trim()).filter(Boolean)||[],maxConcurrent:o.maxConcurrent,systemPrompt:o.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-TBQAHYHJ.js"),i=s(o.id,n,"19900",(...d)=>{console.log(h.dim(` ${d.join(" ")}`))}),r=_(process.cwd(),"src/wiki/SKILL.md"),a=_(Hr(Gr(import.meta.url)),"../wiki/SKILL.md"),c=ne(r)?r:a;ne(c)&&(Ne(_(t,".claude/skills/wiki"),{recursive:!0}),ln(c,_(t,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[o.id]=n,await ye(e),console.log(h.green(`
|
|
11
11
|
Agent "${o.id}" added`)),console.log(h.dim(` Workspace: ${t}`)),console.log(h.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});go.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let o=Z();if(!o.agents?.[e]){console.log(h.red(` Agent "${e}" not found`));return}delete o.agents[e],await ye(o),console.log(h.green(` Agent "${e}" removed from config (workspace preserved)`))});go.command("capability <id>").alias("caps").description("set agent capability flags (intents, maxDelegationDepth, contextReferences, contextStrategy)").option("--intents <csv>","comma-separated intent allow-list (set to '-' to clear)").option("--max-delegation-depth <n>","max distinct upstream agents on the same subject before refusal (0 disables)").option("--context-references <bool>","render the deterministic [Verified References] block (true|false)").option("--context-strategy <name>","per-agent override: layered | planner").option("--max-execution-minutes <n>","wall-clock cap on a single Claude Code call (1\u2013240)").option("--show","just print the current capability fields").action(async(e,o)=>{let t=Z(),n=t.agents?.[e];if(n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1)),o.show){console.log(),console.log(h.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):h.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":h.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||h.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(o.intents!==void 0&&(o.intents==="-"||o.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(o.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),o.maxDelegationDepth!==void 0){let i=parseInt(o.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(h.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(o.contextReferences!==void 0){let i=String(o.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(h.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(o.contextStrategy!==void 0&&(o.contextStrategy==="-"||o.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(o.contextStrategy)?(n.contextStrategy=o.contextStrategy,s.push(`contextStrategy=${o.contextStrategy}`)):(console.log(h.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),o.maxExecutionMinutes!==void 0){let i=parseInt(o.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(h.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(h.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await ye(t),console.log(h.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(h.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Qo=new _e().name("integrations").alias("integ").description("manage per-agent third-party credentials (telegram-bot, hubspot, gitlab-user, gmail, etc.)");Qo.command("list <agentId>").alias("ls").description("list integrations declared on an agent").option("--json","emit JSON").action(async(e,o)=>{let n=Z().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[];if(o.json){console.log(JSON.stringify(s,null,2));return}if(!s.length){console.log(h.dim(`
|
|
12
12
|
${e}: no integrations declared. Add one with: agentx agent integrations add ${e}
|
|
13
|
-
`));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)?a.push(process.env[l]?h.green(`${g}:${l}=set`):h.yellow(`${g}:${l}=UNSET`)):g==="auth"&&l==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof l=="string"&&a.push(h.dim(`sessionDir:${l}`));let d=Object.entries(i.metadata??{}).map(([g,l])=>`${g}=${l}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),d&&console.log(` ${h.dim(d)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Qo.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=anis,email=anis@noqta.tn')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=Z();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-7FSZFRTQ.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await me({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(m=>({title:m,value:m}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await me({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Noqta CRM", "anis@noqta.tn")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),d=String(o.sessionDir||"").trim();if(!a&&!c&&!d&&n){let u=await me({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});u.scheme==="tokenEnv"?a=((await me({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(d=((await me({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[m,...f]=u.split("=");m&&(g[m.trim()]=f.join("=").trim())}else if(n){let u=await me({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let m of String(u.metadata).split(",")){let[f,...y]=m.split("=");f&&(g[f.trim()]=y.join("=").trim())}}let l={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),l.tokenEnv=a),c==="keyring"&&(l.auth="keyring"),d&&(l.sessionDir=d),Object.keys(l).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:l,metadata:g,enabled:!0}),await ye(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Qo.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=Z(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(d=>d.kind===i&&(!r||d.label===r)||d.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await ye(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Qo.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=Z().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},d=[];for(let[g,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)&&!process.env[l]&&d.push(`${g}: env var ${l} is unset`);if(d.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of d)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});go.addCommand(Qo);var vt=new _e().name("channel").description("manage channels \u2014 add telegram/whatsapp/discord, list");vt.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Z();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[i,r]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(i)} -> agent: ${r.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let i of t.routes||[]){let r=i.contact?`contact ${i.contact}`:`group "${i.group}"`;console.log(` ${r} -> agent: ${i.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.discord;n?.enabled?(console.log(h.bold(" Discord:")),console.log(` agent: ${n.agentBinding||"(none)"}`)):console.log(h.dim(" Discord: disabled"));let s=e.channels?.gitlab;if(s?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let i of s.routes||[])console.log(` ${i.project} -> agent: ${i.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});vt.command("add").description("add a channel (telegram, whatsapp, or discord)").action(async()=>{let e=Z(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await me({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"Discord \u2014 bot via Discord developer portal",value:"discord"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await me([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await ye(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await me([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await me([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +21624309128)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await ye(e),Ne(_(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="discord"){let s=await me([{type:"text",name:"token",message:"Discord bot token (from developer portal)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.token)return;e.channels.discord={enabled:!0,token:s.token,agentBinding:s.agentBinding},await ye(e),console.log(h.green(` Discord added -> ${s.agentBinding}`))}if(n==="gitlab"){let s=await me([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await me([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await ye(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Ro=new _e().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Ro.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Z();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});Ro.command("add").description("add a cron job").action(async()=>{let e=Z(),o=Object.keys(e.agents||{}),t=await me([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await ye(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Ro.command("enable <id>").description("enable a cron job").action(async e=>{let o=Z();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!0,await ye(o),console.log(h.green(` Cron "${e}" enabled`))});Ro.command("disable <id>").description("disable a cron job").action(async e=>{let o=Z();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await ye(o),console.log(h.green(` Cron "${e}" disabled`))});var To=new _e().name("mesh").description("manage mesh peers \u2014 add, list, remove");To.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Z();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});To.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Z(),o=await me([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.67.108.119:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await ye(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});To.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=Z();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await ye(o),console.log(h.green(` Peer "${e}" removed`)))});To.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=Z();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await ye(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});var Do=new _e().name("skill").description("manage skills \u2014 add to agent(s), list");Do.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=Z(),n=_(e);if(!ne(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ne(Ge(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await me({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=_(a.workspace,".claude/skills",s);Ne(c,{recursive:!0}),ne(Ge(n,"SKILL.md"))?ln(n,c,{recursive:!0}):n.endsWith(".md")&&ln(n,Ge(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Do.command("list").alias("ls").description("list skills per agent").action(()=>{let e=Z();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=_(t.workspace,".claude/skills"),s=ne(n)?gn(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Do.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[_(n,"src",e,"SKILL.md"),_(n,"skills",e,"SKILL.md")],i=s.find(v=>ne(v));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let v of s)console.log(h.dim(` ${v}`));return}let r=Ye(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),d;try{d=L()}catch(v){console.log(h.red(` Can't load agentx.json: ${v.message}`));return}let g=Object.entries(d.agents||{}),l=o.agent?g.filter(([v])=>v===o.agent):g;if(l.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,m=0,f=0,y=0;for(let[v,b]of l){let S=b.workspace;if(!S||!ne(S)){console.log(` ${h.yellow("\u2717")} ${v.padEnd(22)} ${h.dim("(workspace missing: "+(S||"undefined")+")")}`),y++;continue}let x=_(S,".claude/skills",e),k=_(x,"SKILL.md");if(!ne(k)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${v.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),y++;continue}o.dryRun||(Ne(x,{recursive:!0}),Co(k,r)),console.log(` ${h.green("+")} ${v.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let A=Ye(k,"utf-8");if(t("sha256").update(A).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${v.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),f++;continue}let J=(A.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Co(k,r),console.log(` ${h.yellow("\u21BB")} ${v.padEnd(22)} ${h.dim(`v${J} \u2192 v${c}`)}`),m++}console.log();let $=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${$} seed ${u}, ${$} update ${m}, ${f} already current, ${y} skipped.`)),o.dryRun&&(u>0||m>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Do.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-5CA3O5GM.js"),{auditAll:t}=await import("./audit-JU3HWISB.js"),{loadReferences:n}=await import("./loader-6IHUCPVO.js"),{loadRecipes:s}=await import("./recipes-EPLE2SNT.js"),i=[];if(e.workspace){let m=Z().agents?.[e.workspace];m||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(_(m.workspace))}else if(e.allWorkspaces){let u=Z();for(let m of Object.values(u.agents||{}))m?.workspace&&i.push(_(m.workspace))}else i.push(_(e.cwd));let r=_(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[d,g]=await Promise.all([n(r),s(r)]),l=t({skills:c,references:d,recipes:g});if(e.json)console.log(JSON.stringify(l.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let m of l)u[m.verdict]++;console.log();for(let m of l){let f=m.verdict==="PASS"?h.green("PASS "):m.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${f} ${h.bold(m.name)}${m.skill?.path?h.dim(` (${m.skill.path})`):""}`);for(let y of m.reasons)console.log(` ${h.dim("\xB7")} ${y}`)}console.log(),console.log(` ${h.green(`${u.PASS} PASS`)} ${h.yellow(`${u.REVIEW} REVIEW`)} ${h.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(l.some(u=>u.verdict==="FAILING")?1:0)});var Xo=new _e().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Xo.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=_(o.cwd),n=_(t,"references/example"),s=_(t,"references/recipes/example.yaml");ne(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=_(t,".agentx/references",e),r=_(t,".agentx/references/recipes");Ne(i,{recursive:!0}),Ne(r,{recursive:!0});let a=gn(n).filter(l=>l.endsWith(".yaml")||l.endsWith(".yml")),c=0,d=0;for(let l of a){let u=Ge(i,l);if(ne(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),d++;continue}let f=Ye(Ge(n,l),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Co(u,f),console.log(h.green(` + ${u}`)),c++}let g=Ge(r,`${e}.yaml`);if(ne(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),d++;else if(ne(s)){let l=Ye(s,"utf-8").replaceAll("example.",`${e}.`);Co(g,l),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${d} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Xo.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.noqta.tn)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-5CA3O5GM.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-XJXQXXIO.js"),i=_(o.cwd),r=o.from?String(o.from).split(",").map(y=>y.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let d=Object.fromEntries(Object.entries(c.byKind).map(([y,$])=>[y,$.length]));console.log(` Discovered: ssh=${d.ssh} gitlab=${d.gitlab} paths=${d.path} contacts=${d.contact}`);let g=s(c,e),l=_(o.referencesCwd||o.cwd),u=_(l,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${u}/`));for(let[y,$]of Object.entries(g))console.log(h.cyan(`
|
|
13
|
+
`));return}console.log(),console.log(h.bold(` ${e}`));for(let i of s){let r=i.enabled!==!1,a=[],c=i.credentials??{};for(let[g,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)?a.push(process.env[l]?h.green(`${g}:${l}=set`):h.yellow(`${g}:${l}=UNSET`)):g==="auth"&&l==="keyring"?a.push(h.dim("auth:keyring")):g==="sessionDir"&&typeof l=="string"&&a.push(h.dim(`sessionDir:${l}`));let d=Object.entries(i.metadata??{}).map(([g,l])=>`${g}=${l}`).join(" ");console.log(` ${r?h.cyan(i.kind.padEnd(14)):h.dim(i.kind.padEnd(14))} ${h.bold(i.label)}`),a.length&&console.log(` ${a.join(" ")}`),d&&console.log(` ${h.dim(d)}`),r||console.log(` ${h.dim("(disabled)")}`)}console.log()});Qo.command("add <agentId>").description("declare a new integration on an agent").option("--kind <name>","service kind (e.g. telegram-bot, hubspot, gitlab-user, gmail)").option("--label <text>","human-readable label (must be unique within (agent, kind))").option("--token-env <name>","env-var holding the secret (uppercase identifier)").option("--auth <mode>","alternative to --token-env: 'keyring' for OS keyring").option("--session-dir <path>","for whatsapp / mtproto: file-based session directory").option("--metadata <kvList>","comma-separated key=value pairs (e.g. 'username=anis,email=anis@noqta.tn')").option("--no-prompt","fail instead of prompting for missing values").action(async(e,o)=>{let t=Z();t.agents?.[e]||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let n=o.prompt!==!1,{INTEGRATION_KINDS:s}=await import("./config-A4RWEJHV.js"),i=String(o.kind||"").trim();!i&&n&&(i=((await me({type:"autocomplete",name:"kind",message:"Service kind",choices:s.map(m=>({title:m,value:m}))})).kind||"").trim()),i||(console.log(h.red(" --kind is required")),process.exit(1));let r=String(o.label||"").trim();!r&&n&&(r=((await me({type:"text",name:"label",message:'Label (e.g. "@cx_bot", "Noqta CRM", "anis@noqta.tn")'})).label||"").trim()),r||(console.log(h.red(" --label is required")),process.exit(1));let a=String(o.tokenEnv||"").trim(),c=String(o.auth||"").trim(),d=String(o.sessionDir||"").trim();if(!a&&!c&&!d&&n){let u=await me({type:"select",name:"scheme",message:"Credential scheme",choices:[{title:"Env var (e.g. HUBSPOT_TOKEN_CX)",value:"tokenEnv"},{title:"OS keyring",value:"keyring"},{title:"File-based session (whatsapp / mtproto)",value:"sessionDir"}]});u.scheme==="tokenEnv"?a=((await me({type:"text",name:"tokenEnv",message:"Env var name (uppercase)",initial:`${i.replace(/-/g,"_").toUpperCase()}_${e.replace(/-/g,"_").toUpperCase()}`})).tokenEnv||"").trim():u.scheme==="keyring"?c="keyring":u.scheme==="sessionDir"&&(d=((await me({type:"text",name:"sessionDir",message:"Session directory path",initial:`.agentx/${i}-sessions/${e}`})).sessionDir||"").trim())}let g={};if(o.metadata)for(let u of String(o.metadata).split(",")){let[m,...f]=u.split("=");m&&(g[m.trim()]=f.join("=").trim())}else if(n){let u=await me({type:"text",name:"metadata",message:"Metadata (k=v,k=v) \u2014 non-secret only, optional"});if(u.metadata)for(let m of String(u.metadata).split(",")){let[f,...y]=m.split("=");f&&(g[f.trim()]=y.join("=").trim())}}let l={};a&&(/^[A-Z][A-Z0-9_]*$/.test(a)||(console.log(h.red(` --token-env must be uppercase identifier (got "${a}")`)),process.exit(1)),l.tokenEnv=a),c==="keyring"&&(l.auth="keyring"),d&&(l.sessionDir=d),Object.keys(l).length||(console.log(h.red(" one of --token-env / --auth / --session-dir is required")),process.exit(1)),t.agents[e].integrations=t.agents[e].integrations??[],t.agents[e].integrations.find(u=>u.kind===i&&u.label===r)&&(console.log(h.red(` Integration (${i}, ${r}) already exists on ${e}`)),process.exit(1)),t.agents[e].integrations.push({kind:i,label:r,credentials:l,metadata:g,enabled:!0}),await ye(t),console.log(h.green(` \u2713 ${e}: added ${i} integration "${r}"`)),a&&!process.env[a]&&console.log(h.yellow(` \u26A0 env var ${a} is not set \u2014 set it on the daemon environment before use`))});Qo.command("remove <agentId> <kindOrLabel>").alias("rm").description("remove an integration (matched by kind, label, or 'kind:label')").action(async(e,o)=>{let t=Z(),n=t.agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],[i,r]=o.includes(":")?o.split(":",2):[o,""],a=s.findIndex(d=>d.kind===i&&(!r||d.label===r)||d.label===o);a===-1&&(console.log(h.red(` No integration matched "${o}"`)),process.exit(1));let c=s.splice(a,1)[0];await ye(t),console.log(h.green(` \u2713 removed ${c.kind} integration "${c.label}" from ${e}`))});Qo.command("test <agentId> [kindOrLabel]").description("validate env vars are set for one or all integrations on an agent").action(async(e,o)=>{let n=Z().agents?.[e];n||(console.log(h.red(` Agent "${e}" not found`)),process.exit(1));let s=n.integrations??[],i=o?s.filter(a=>a.kind===o||a.label===o||`${a.kind}:${a.label}`===o):s;if(!i.length){console.log(h.yellow(" no integrations to test"));return}let r=0;console.log();for(let a of i){let c=a.credentials??{},d=[];for(let[g,l]of Object.entries(c))typeof l=="string"&&/^[A-Z][A-Z0-9_]*$/.test(l)&&!process.env[l]&&d.push(`${g}: env var ${l} is unset`);if(d.length){r+=1,console.log(` ${h.red("\u2717")} ${a.kind} "${a.label}"`);for(let g of d)console.log(` ${h.dim(g)}`)}else console.log(` ${h.green("\u2713")} ${a.kind} "${a.label}"`)}console.log(),r>0&&process.exit(1)});go.addCommand(Qo);var vt=new _e().name("channel").description("manage channels \u2014 add telegram/whatsapp/discord, list");vt.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Z();console.log();let o=e.channels?.telegram;if(o?.enabled){console.log(h.bold(" Telegram:"));for(let[i,r]of Object.entries(o.accounts||{}))console.log(` ${h.cyan(i)} -> agent: ${r.agentBinding}`)}else console.log(h.dim(" Telegram: disabled"));let t=e.channels?.whatsapp;if(t?.enabled){console.log(h.bold(" WhatsApp:")),console.log(` default agent: ${t.defaultAgent||"(none)"}`),console.log(` session: ${t.sessionDir||".agentx/whatsapp-sessions"}`);for(let i of t.routes||[]){let r=i.contact?`contact ${i.contact}`:`group "${i.group}"`;console.log(` ${r} -> agent: ${i.agent}`)}}else console.log(h.dim(" WhatsApp: disabled"));let n=e.channels?.discord;n?.enabled?(console.log(h.bold(" Discord:")),console.log(` agent: ${n.agentBinding||"(none)"}`)):console.log(h.dim(" Discord: disabled"));let s=e.channels?.gitlab;if(s?.enabled){console.log(h.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let i of s.routes||[])console.log(` ${i.project} -> agent: ${i.agent}`)}else console.log(h.dim(" GitLab: disabled"));console.log()});vt.command("add").description("add a channel (telegram, whatsapp, or discord)").action(async()=>{let e=Z(),o=Object.keys(e.agents||{});if(!o.length){console.log(h.red(" No agents configured. Run: agentx agent add"));return}let t=o.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await me({type:"select",name:"channelType",message:"Channel type",choices:[{title:"Telegram \u2014 bot via BotFather token",value:"telegram"},{title:"WhatsApp \u2014 link via QR code (self-chat or contacts)",value:"whatsapp"},{title:"Discord \u2014 bot via Discord developer portal",value:"discord"},{title:"GitLab \u2014 webhook for issues, MRs, comments, pipelines",value:"gitlab"}]});if(n){if(e.channels=e.channels||{},n==="telegram"){let s=await me([{type:"text",name:"accountName",message:"Account name (e.g. 'default', 'devops')"},{type:"text",name:"token",message:"Bot token (from @BotFather)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.accountName||!s.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${s.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(h.green(` Bot verified: @${r.result.username}`));let a=`@${r.result.username}`,c=e.agents[s.agentBinding].mentions||[];c.includes(a)||(c.push(a,r.result.username),e.agents[s.agentBinding].mentions=c)}catch(i){console.log(h.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await ye(e),console.log(h.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await me([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:t},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!s.defaultAgent)return;let i=[],r=s.addRoute;for(;r;){let a=await me([{type:"select",name:"type",message:"Route type",choices:[{title:"Contact (phone number)",value:"contact"},{title:"Group (name match)",value:"group"}]},{type:"text",name:"value",message:c=>c==="contact"?"Phone number (e.g. +21624309128)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.value&&a.agent&&i.push({[a.type]:a.value,agent:a.agent}),r=a.more}e.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:i},await ye(e),Ne(_(process.cwd(),s.sessionDir),{recursive:!0}),console.log(h.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(h.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="discord"){let s=await me([{type:"text",name:"token",message:"Discord bot token (from developer portal)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:t}]);if(!s.token)return;e.channels.discord={enabled:!0,token:s.token,agentBinding:s.agentBinding},await ye(e),console.log(h.green(` Discord added -> ${s.agentBinding}`))}if(n==="gitlab"){let s=await me([{type:"text",name:"host",message:"GitLab instance URL",initial:"https://gitlab.example.com"},{type:"text",name:"token",message:"GitLab API token (PRIVATE-TOKEN)"},{type:"number",name:"webhookPort",message:"Webhook listen port",initial:18810},{type:"text",name:"webhookSecret",message:"Webhook secret (X-Gitlab-Token, optional)"},{type:"confirm",name:"addRoute",message:"Add a project route?",initial:!0}]);if(!s.token)return;let i=[],r=s.addRoute;for(;r;){let a=await me([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:t},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);a.project&&a.agent&&i.push({project:a.project,agent:a.agent}),r=a.more}e.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:i},await ye(e),console.log(h.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(h.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(h.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(h.dim(` Secret token: ${s.webhookSecret}`)),console.log(h.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(h.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Ro=new _e().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Ro.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Z();console.log();for(let[o,t]of Object.entries(e.crons||{})){let n=t.enabled?h.green("\u25CF"):h.dim("\u25CB");console.log(` ${n} ${h.cyan(o)} \u2014 ${t.schedule} (${t.timezone})`),console.log(h.dim(` agent: ${t.agent} | timeout: ${t.timeout}s`))}Object.keys(e.crons||{}).length||console.log(h.dim(" No cron jobs configured")),console.log()});Ro.command("add").description("add a cron job").action(async()=>{let e=Z(),o=Object.keys(e.agents||{}),t=await me([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:o.map(n=>({title:n,value:n}))},{type:"text",name:"prompt",message:"Task prompt"},{type:"number",name:"timeout",message:"Timeout (seconds)",initial:600},{type:"confirm",name:"enabled",message:"Enable now?",initial:!1}]);!t.id||!t.schedule||(e.crons=e.crons||{},e.crons[t.id]={enabled:t.enabled,schedule:t.schedule,timezone:t.timezone,agent:t.agent,prompt:t.prompt,timeout:t.timeout,onError:["log"]},await ye(e),console.log(h.green(` Cron "${t.id}" added (${t.enabled?"enabled":"disabled"})`)),console.log())});Ro.command("enable <id>").description("enable a cron job").action(async e=>{let o=Z();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!0,await ye(o),console.log(h.green(` Cron "${e}" enabled`))});Ro.command("disable <id>").description("disable a cron job").action(async e=>{let o=Z();if(!o.crons?.[e]){console.log(h.red(` Cron "${e}" not found`));return}o.crons[e].enabled=!1,await ye(o),console.log(h.green(` Cron "${e}" disabled`))});var To=new _e().name("mesh").description("manage mesh peers \u2014 add, list, remove");To.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Z();if(console.log(),!e.mesh?.enabled)console.log(h.dim(" Mesh: disabled"));else{console.log(h.bold(" Mesh peers:"));for(let o of e.mesh.peers||[]){let t=h.red("unreachable");try{let s=await(await fetch(`${o.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();t=h.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${h.cyan(o.name)} ${h.dim(o.url)} ${t}`)}}console.log()});To.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Z(),o=await me([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.67.108.119:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!o.name||!o.url)){try{let n=await(await fetch(`${o.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(h.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(h.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:o.url,name:o.name,...o.token?{token:o.token}:{}}),await ye(e),console.log(h.green(` Peer "${o.name}" added`)),console.log()}});To.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let o=Z();o.mesh?.peers&&(o.mesh.peers=o.mesh.peers.filter(t=>t.name!==e),o.mesh.peers.length===0&&(o.mesh.enabled=!1),await ye(o),console.log(h.green(` Peer "${e}" removed`)))});To.command("health").description("tune mesh peer health checks (interval + timeout, in seconds)").option("--interval <s>","seconds between health probes (default 60)").option("--timeout <s>","per-probe timeout in seconds (default 10)").option("--show","just print the current values").action(async e=>{let o=Z();if(o.mesh=o.mesh||{},o.mesh.healthCheck=o.mesh.healthCheck||{},e.show){console.log(` interval ${o.mesh.healthCheck.interval??60}s`),console.log(` timeout ${o.mesh.healthCheck.timeout??10}s`);return}let t=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(h.red(" --interval must be 5..3600 seconds")),process.exit(1)),o.mesh.healthCheck.interval=n,t.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(h.red(" --timeout must be 1..60 seconds")),process.exit(1)),o.mesh.healthCheck.timeout=n,t.push(`timeout=${n}s`)}t.length===0&&(console.log(h.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await ye(o),console.log(h.green(` \u2713 mesh.healthCheck: ${t.join(", ")}`)),console.log(h.dim(" Restart the daemon for the new cadence to take effect."))});var Do=new _e().name("skill").description("manage skills \u2014 add to agent(s), list");Do.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,o)=>{let t=Z(),n=_(e);if(!ne(n)){console.log(h.red(` Skill not found: ${n}`));return}let s=ne(Ge(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(o.all)i=Object.keys(t.agents||{});else if(o.agent)i=o.agent;else{let r=Object.keys(t.agents||{});i=(await me({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${t.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=t.agents[r];if(!a){console.log(h.yellow(` Agent "${r}" not found, skipping`));continue}let c=_(a.workspace,".claude/skills",s);Ne(c,{recursive:!0}),ne(Ge(n,"SKILL.md"))?ln(n,c,{recursive:!0}):n.endsWith(".md")&&ln(n,Ge(c,"SKILL.md")),console.log(h.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});Do.command("list").alias("ls").description("list skills per agent").action(()=>{let e=Z();console.log();for(let[o,t]of Object.entries(e.agents||{})){let n=_(t.workspace,".claude/skills"),s=ne(n)?gn(n).filter(i=>!i.startsWith(".")):[];console.log(` ${h.cyan(o)}: ${s.length?s.join(", "):h.dim("(none)")}`)}console.log()});Do.command("sync <name>").description("redeploy a skill's SKILL.md from source to agent workspaces (by default, only those that already have it)").option("--source <path>","explicit source path (defaults to src/<name>/SKILL.md or skills/<name>/SKILL.md)").option("--agent <id>","restrict to a single agent's workspace").option("--all-workspaces","also seed into workspaces that don't have the skill yet").option("--dry-run","report what would change, don't write").action(async(e,o)=>{let{createHash:t}=await import("node:crypto"),n=process.cwd(),s=o.source?[o.source]:[_(n,"src",e,"SKILL.md"),_(n,"skills",e,"SKILL.md")],i=s.find(v=>ne(v));if(!i){console.log(h.red(` No SKILL.md found for "${e}". Searched:`));for(let v of s)console.log(h.dim(` ${v}`));return}let r=Ye(i,"utf-8"),a=t("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),d;try{d=L()}catch(v){console.log(h.red(` Can't load agentx.json: ${v.message}`));return}let g=Object.entries(d.agents||{}),l=o.agent?g.filter(([v])=>v===o.agent):g;if(l.length===0){console.log(h.yellow(o.agent?` Agent "${o.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(h.bold(` Skill sync \u2014 ${e}`)),console.log(h.dim(` Source: ${i}`)),console.log(h.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(h.dim(` Mode: ${o.dryRun?"dry-run":"commit"}${o.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let u=0,m=0,f=0,y=0;for(let[v,b]of l){let S=b.workspace;if(!S||!ne(S)){console.log(` ${h.yellow("\u2717")} ${v.padEnd(22)} ${h.dim("(workspace missing: "+(S||"undefined")+")")}`),y++;continue}let x=_(S,".claude/skills",e),k=_(x,"SKILL.md");if(!ne(k)){if(!o.allWorkspaces){console.log(` ${h.dim("\xB7")} ${v.padEnd(22)} ${h.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),y++;continue}o.dryRun||(Ne(x,{recursive:!0}),Co(k,r)),console.log(` ${h.green("+")} ${v.padEnd(22)} ${h.dim("\u2192 seeded v"+c)}`),u++;continue}let A=Ye(k,"utf-8");if(t("sha256").update(A).digest("hex").slice(0,12)===a){console.log(` ${h.dim("=")} ${v.padEnd(22)} ${h.dim("up to date (v"+c+")")}`),f++;continue}let J=(A.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();o.dryRun||Co(k,r),console.log(` ${h.yellow("\u21BB")} ${v.padEnd(22)} ${h.dim(`v${J} \u2192 v${c}`)}`),m++}console.log();let $=o.dryRun?"would":"did";console.log(h.dim(` Summary: ${$} seed ${u}, ${$} update ${m}, ${f} already current, ${y} skipped.`)),o.dryRun&&(u>0||m>0)&&console.log(h.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});Do.command("audit").description("lint installed skills against the references registry; exits non-zero on FAILING").option("--cwd <cwd>","where to load skills from",process.cwd()).option("--references-cwd <cwd>","where to load references and recipes from (defaults to --cwd; useful when references live in the agentx repo and skills live under ~/.claude)").option("--json","emit JSON instead of a human report").option("--workspace <id>","audit a single agent workspace by id (skills + references; overrides --cwd)").option("--all-workspaces","audit every agent workspace in agentx.json; references default to the current cwd").action(async e=>{let{loadLocalSkills:o}=await import("./loader-5CA3O5GM.js"),{auditAll:t}=await import("./audit-JU3HWISB.js"),{loadReferences:n}=await import("./loader-6IHUCPVO.js"),{loadRecipes:s}=await import("./recipes-EPLE2SNT.js"),i=[];if(e.workspace){let m=Z().agents?.[e.workspace];m||(console.log(h.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(_(m.workspace))}else if(e.allWorkspaces){let u=Z();for(let m of Object.values(u.agents||{}))m?.workspace&&i.push(_(m.workspace))}else i.push(_(e.cwd));let r=_(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(u=>o(u)))).flat(),[d,g]=await Promise.all([n(r),s(r)]),l=t({skills:c,references:d,recipes:g});if(e.json)console.log(JSON.stringify(l.map(u=>({name:u.name,verdict:u.verdict,reasons:u.reasons,path:u.skill?.path})),null,2));else{let u={PASS:0,REVIEW:0,FAILING:0};for(let m of l)u[m.verdict]++;console.log();for(let m of l){let f=m.verdict==="PASS"?h.green("PASS "):m.verdict==="REVIEW"?h.yellow("REVIEW "):h.red("FAILING");console.log(` ${f} ${h.bold(m.name)}${m.skill?.path?h.dim(` (${m.skill.path})`):""}`);for(let y of m.reasons)console.log(` ${h.dim("\xB7")} ${y}`)}console.log(),console.log(` ${h.green(`${u.PASS} PASS`)} ${h.yellow(`${u.REVIEW} REVIEW`)} ${h.red(`${u.FAILING} FAILING`)}`),console.log()}process.exit(l.some(u=>u.verdict==="FAILING")?1:0)});var Xo=new _e().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Xo.command("init <namespace>").description("scaffold .agentx/references/<namespace>/ from the example template (operator-private)").option("--cwd <cwd>","working directory",process.cwd()).option("--force","overwrite existing files").action((e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let t=_(o.cwd),n=_(t,"references/example"),s=_(t,"references/recipes/example.yaml");ne(n)||(console.log(h.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=_(t,".agentx/references",e),r=_(t,".agentx/references/recipes");Ne(i,{recursive:!0}),Ne(r,{recursive:!0});let a=gn(n).filter(l=>l.endsWith(".yaml")||l.endsWith(".yml")),c=0,d=0;for(let l of a){let u=Ge(i,l);if(ne(u)&&!o.force){console.log(h.dim(` skip ${u} (exists; --force to overwrite)`)),d++;continue}let f=Ye(Ge(n,l),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);Co(u,f),console.log(h.green(` + ${u}`)),c++}let g=Ge(r,`${e}.yaml`);if(ne(g)&&!o.force)console.log(h.dim(` skip ${g} (exists; --force to overwrite)`)),d++;else if(ne(s)){let l=Ye(s,"utf-8").replaceAll("example.",`${e}.`);Co(g,l),console.log(h.green(` + ${g}`)),c++}console.log(),console.log(h.dim(` ${c} written, ${d} skipped. Edit the placeholders, then:`)),console.log(h.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(h.dim(" 2. agentx skill audit # verify references resolve")),console.log(h.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Xo.command("discover <namespace>").description("scan installed skills and write detected facts to .agentx/references/<namespace>/").option("--cwd <cwd>","where to scan for skills",process.cwd()).option("--references-cwd <cwd>","where to WRITE the YAML files (defaults to --cwd; useful when skills live under ~/.claude and references live in the agentx repo)").option("--from <skills>","comma-separated skill name/tag substrings to filter by (default: namespace itself)").option("--gitlab-host <url>","validate project URLs against this host (e.g. https://gitlab.noqta.tn)").option("--write","write the YAML files (default: dry-run preview)").option("--force","overwrite existing files when --write is set").action(async(e,o)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(h.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:t}=await import("./loader-5CA3O5GM.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-XJXQXXIO.js"),i=_(o.cwd),r=o.from?String(o.from).split(",").map(y=>y.trim()).filter(Boolean):[e],a=await t(i),c=n(a,{namespace:e,filter:r,gitlabHost:o.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(h.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(h.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(h.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let d=Object.fromEntries(Object.entries(c.byKind).map(([y,$])=>[y,$.length]));console.log(` Discovered: ssh=${d.ssh} gitlab=${d.gitlab} paths=${d.path} contacts=${d.contact}`);let g=s(c,e),l=_(o.referencesCwd||o.cwd),u=_(l,".agentx/references",e);if(!o.write){console.log(),console.log(h.dim(` Dry-run \u2014 would write to ${u}/`));for(let[y,$]of Object.entries(g))console.log(h.cyan(`
|
|
14
14
|
--- ${y} ---`)),console.log($.split(`
|
|
15
15
|
`).slice(0,30).map(v=>` ${v}`).join(`
|
|
16
16
|
`)),$.split(`
|
|
17
17
|
`).length>30&&console.log(h.dim(` \u2026 (${$.split(`
|
|
18
18
|
`).length-30} more lines truncated in preview)`));console.log(),console.log(h.dim(` Re-run with --write to commit these to ${u}/`)),console.log();return}Ne(u,{recursive:!0});let m=0,f=0;for(let[y,$]of Object.entries(g)){let v=Ge(u,y);if(ne(v)&&!o.force){console.log(h.dim(` skip ${v} (exists; --force to overwrite)`)),f++;continue}Co(v,$),console.log(h.green(` + ${v}`)),m++}console.log(),console.log(h.dim(` ${m} written, ${f} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(h.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Xo.command("list").alias("ls").description("list every loaded reference (debug)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(async e=>{let{loadReferences:o}=await import("./loader-6IHUCPVO.js"),t=await o(_(e.cwd)),n=[...t.byId.values()].sort((s,i)=>s.id.localeCompare(i.id));if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.length===0){console.log(h.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=t.sourceById.get(s.id);console.log(` ${h.cyan(s.id)} ${h.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(h.dim(` ${i}`))}console.log(),console.log(h.dim(` ${n.length} reference(s) loaded.`)),console.log()});var mn=new _e().name("hook").description("manage hooks \u2014 add to agent workspace");mn.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let t=Z().agents?.[e];if(!t){console.log(h.red(` Agent "${e}" not found`));return}let n=_(t.workspace,".claude/settings.json"),s=ne(n)?JSON.parse(Ye(n,"utf-8")):{},i=await me([{type:"select",name:"event",message:"Hook event",choices:[{title:"PreToolUse \u2014 before any tool runs",value:"PreToolUse"},{title:"PostToolUse \u2014 after any tool runs",value:"PostToolUse"},{title:"SessionStart \u2014 when session begins",value:"SessionStart"},{title:"Notification \u2014 on notifications",value:"Notification"},{title:"Stop \u2014 before session stops",value:"Stop"}]},{type:"select",name:"type",message:"Hook type",choices:[{title:"command \u2014 run a shell command",value:"command"},{title:"http \u2014 POST to a URL",value:"http"}]},{type:"text",name:"value",message:c=>c==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!i.event||!i.value)return;s.hooks=s.hooks||{},s.hooks[i.event]=s.hooks[i.event]||[];let a={hooks:[{type:i.type,...i.type==="command"?{command:i.value}:{url:i.value}}]};i.matcher&&(a.matcher=i.matcher),s.hooks[i.event].push(a),Ne(_(t.workspace,".claude"),{recursive:!0}),Co(n,JSON.stringify(s,null,2)),console.log(h.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var pn=new _e().name("migrate").description("import configuration from OpenClaw or other tools");pn.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,o)=>{let t=[e,_(process.env.HOME||"",".openclaw/openclaw.json"),_(process.env.HOME||"",".openclaw/clawdbot.json")].filter(Boolean),n;for(let m of t)if(m&&ne(m)){n=m;break}if(!n){console.log(h.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(h.dim(` Reading: ${n}`));let s=JSON.parse(Ye(n,"utf-8")),i=ne(_(process.cwd(),"agentx.json"))?Z():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let m of a)m.match?.channel==="telegram"&&(c[m.match.accountId]=m.agentId);r.find(m=>m.id==="main"||m.default)&&(c.default="main");let d=0;for(let m of r){if(m.workspace?.startsWith("/data"))continue;let f=m.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),y=m.groupChat?.mentionPatterns||[];if(y.some($=>$===f)||y.push(f),i.agents[f]={name:m.name,workspace:m.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:y,maxConcurrent:m.id==="main"?2:1,systemPrompt:`You are ${m.name} on AgentX.`,permissionMode:"bypassPermissions"},d++,!o.dryRun){Ne(_(m.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:$}=await import("./workspace-setup-TBQAHYHJ.js");$(f,i.agents[f])}}console.log(` ${h.green(d)} agents imported (workspaces set up with Claude Code best practices)`);let g=s.channels?.telegram?.accounts||{},l=0;for(let[m,f]of Object.entries(g)){if(!f.botToken)continue;let $=c[m]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[m]={token:f.botToken,agentBinding:$},i.channels.telegram.enabled=!0,l++}console.log(` ${h.green(l)} Telegram accounts imported`);let u=_(n,"../cron/jobs.json");if(ne(u)){let m=JSON.parse(Ye(u,"utf-8")),f=0;for(let y of m.jobs||[]){let $=y.name||y.id,v=y.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[$]={enabled:y.enabled||!1,schedule:y.schedule?.expr||"0 9 * * *",timezone:y.schedule?.tz||"UTC",agent:v,prompt:y.payload?.message||"",timeout:y.payload?.timeoutSeconds||600,onError:["log"]},f++}console.log(` ${h.green(f)} cron jobs imported`)}o.dryRun?(console.log(h.yellow(`
|
|
19
19
|
Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await ye(i),console.log(h.green(`
|
|
20
|
-
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Ke=new _e().name("config").description("validate and inspect configuration");Ke.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=L(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=yt(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ne(_(r,".claude")),c=ne(_(r,"CLAUDE.md")),d=ne(_(r,".claude/settings.json")),g=ne(_(r,".claude/skills"))?gn(_(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,l=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",d?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${l.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Ke.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=L(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Yr(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function dn(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Ke.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-
|
|
20
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Ke=new _e().name("config").description("validate and inspect configuration");Ke.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let o=L(e.config);console.log(h.green(" \u2713 Config valid")),console.log(h.dim(` Node: ${o.node.name} (${o.node.id})`)),console.log(h.dim(` Bind: ${o.node.bind}`)),console.log(h.dim(` Agents: ${Object.keys(o.agents).length}`)),console.log(h.dim(` Crons: ${Object.keys(o.crons).length}`)),console.log(h.dim(` Mesh peers: ${o.mesh.peers.length}`));let t=Object.keys(o.channels.telegram.accounts).length;console.log(h.dim(` Telegram: ${o.channels.telegram.enabled?`${t} accounts`:"disabled"}`)),console.log(h.dim(` WhatsApp: ${o.channels.whatsapp.enabled?`${o.channels.whatsapp.routes.length} routes`:"disabled"}`));let n=yt(o);if(n.length){console.log(),console.log(h.yellow(" Warnings:"));for(let s of n)console.log(h.yellow(` \u26A0 ${s}`))}else console.log(h.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(o.agents)){let r=i.workspace,a=ne(_(r,".claude")),c=ne(_(r,"CLAUDE.md")),d=ne(_(r,".claude/settings.json")),g=ne(_(r,".claude/skills"))?gn(_(r,".claude/skills")).filter(u=>!u.startsWith(".")).length:0,l=[a?h.green("\u2713"):h.red("\u2717"),".claude",c?h.green("\u2713"):h.yellow("\u25CB"),"CLAUDE.md",d?h.green("\u2713"):h.yellow("\u25CB"),"settings",`${g} skills`];console.log(` ${h.cyan(s)}: ${l.join(" ")}`)}}catch(o){console.log(h.red(` \u2717 ${o.message}`))}console.log()});Ke.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let o=L(e.config);console.log(JSON.stringify(o,null,2))}catch(o){console.log(h.red(o.message))}});function Yr(e,o){if(o)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(t=>t.trim()).filter(Boolean):e}function dn(e){return e===void 0?h.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Ke.command("get <path>").description("read a config value by dot-path (e.g. agents.devops.model)").option("-c, --config <path>","path to agentx.json").option("--raw","show ${VAR} tokens instead of env-expanded values").option("--json","output as JSON (for scripting)").action(async(e,o)=>{let{readFileSync:t,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-MNSFUN7D.js"),{expandEnvVars:r}=await import("./config-A4RWEJHV.js"),a=o.config||s(process.cwd(),"agentx.json");n(a)||(console.log(h.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(t(a,"utf-8")),d=o.raw?c:r(c),g=i(d,e);o.json?console.log(JSON.stringify(g)):console.log(dn(g))});Ke.command("set <path> <value>").description("write a config value by dot-path; validates against schema and hot-reloads the daemon").option("-c, --config <path>","path to agentx.json").option("--string","treat the value as a literal string (skip JSON parsing)").option("--dry-run","validate and diff without writing").action(async(e,o,t)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-MNSFUN7D.js"),r=Yr(o,!!t.string),a=await n(d=>{s(d,e,r)},{configPath:t.config,dryRun:!!t.dryRun});a.success||(console.log(h.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);t.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would become: ${dn(c)}`)):(console.log(h.green(` \u2713 ${h.cyan(e)} = ${dn(c)}`)),a.reloaded?console.log(h.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(h.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Ke.command("unset <path>").description("remove a config value by dot-path (validates + hot-reloads)").option("-c, --config <path>","path to agentx.json").option("--dry-run","validate without writing").action(async(e,o)=>{let{applyConfigMutation:t,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-MNSFUN7D.js"),i=await t(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:o.config,dryRun:!!o.dryRun});if(i.success||(console.log(h.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(h.dim(` (no-op) ${h.cyan(e)} was not set`));return}o.dryRun?console.log(h.yellow(` (dry-run) ${h.cyan(e)} would be removed`)):(console.log(h.green(` \u2713 ${h.cyan(e)} removed`)),i.reloaded&&console.log(h.dim(" Daemon hot-reloaded.")))});Ke.command("governance").description("show resolved governance flags (read-only; flags read once at startup)").option("-c, --config <path>","path to agentx.json").option("--json","emit JSON").action(e=>{let o=!1,t=0,n;try{let l=L(e.config);o=!!l.business?.enabled,t=(l.business?.projects??[]).length}catch(l){n=l?.message??String(l)}let s=(process.env.INTENT_LEDGER_MODE||"off").toLowerCase(),i=(process.env.INTENT_PM_GATE_ENABLED||"").toLowerCase(),r=i==="true"||i==="1"||i==="yes",a=r&&o,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:o,active:a,projects:t},configError:n},null,2));return}console.log(),console.log(h.bold(" Governance flags")),console.log(),n&&(console.log(h.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let d=s==="authoritative"?h.green:s==="shadow"?h.cyan:s==="off"?h.dim:h.red;console.log(` INTENT_LEDGER_MODE ${d(s)}${c?"":h.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let g=a?h.green("active"):r?h.yellow("env=true but business.enabled=false \u2192 inactive"):h.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${g}`),console.log(h.dim(` business.enabled ${o?h.green("true"):h.dim("false")}`)),console.log(h.dim(` business.projects[] ${t}`)),console.log(),console.log(h.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(h.dim(" See: https://github.com/anis-marrouchi/agentx/blob/master/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Kr}from"commander";import Ve from"chalk";import{resolve as Qe}from"path";import{existsSync as Vr}from"fs";var We=new Kr().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function mo(e){let o=Qe(e,".agentx/db.sqlite");Vr(o)||(console.log(Ve.red(` No SQLite at ${o}`)),console.log(Ve.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let t=ps({path:o});return t||(console.log(Ve.red(` Could not open ${o}`)),console.log(Ve.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),t}function po(e,o){if(o){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Ve.dim(" (no rows)"));return}let t=Object.keys(e[0]),n=t.map(i=>Math.max(i.length,...e.map(r=>String(r[i]??"").length))),s=i=>i.map((r,a)=>String(r??"").padEnd(n[a])).join(" ");console.log(s(t)),console.log(t.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(t.map(r=>i[r])))}We.command("tasks").description("recent task_history rows (one per agent task)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by start day (UTC)").option("-s, --status <status>","ok | error").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let o=mo(Qe(e.cwd)),t=[],n={};e.agent&&(t.push("agent_id = @agent"),n.agent=e.agent),e.day&&(t.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(t.push("status = @status"),n.status=e.status);let s=`
|
|
21
21
|
SELECT agent_id, channel, status, duration_ms,
|
|
22
22
|
input_tokens, output_tokens,
|
|
23
23
|
substr(message_preview, 1, 60) AS message,
|
|
@@ -209,7 +209,7 @@ rules:
|
|
|
209
209
|
settings \u2014 without this an attached production identity would be less
|
|
210
210
|
guarded than a spawned one.)`))):console.log(C.yellow(" ! Guard hook skipped. An attached production identity will run unguarded.")),console.log(),console.log(`Next: ${C.cyan("agentx attach <agent>")} inside a Claude Code session.`)}catch(o){console.error(C.red(`Install failed: ${o?.message??o}`)),process.exit(1)}});fo.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=fi({path:e.path,keepGuard:!e.removeGuard});console.log(o.changed?`${C.green("\u2713")} Removed attach hooks from ${C.gray(o.path)} (${o.events.join(", ")})`:`${C.gray("Nothing to remove.")}`),e.removeGuard||console.log(C.gray(" PreToolUse guard left in place \u2014 pass --remove-guard to drop it too."))}catch(o){console.error(C.red(`Uninstall failed: ${o?.message??o}`)),process.exit(1)}});import{Command as Aa}from"commander";import se from"chalk";var Rt=new Aa().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function wi(e){let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let n=L(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 $i(e,o){let t={};return e&&(t.Authorization=`Bearer ${e}`),o&&(t["Content-Type"]=o),t}function yi(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 Oa(e){return e==="busy"?se.magenta:e==="warm-hot"?se.green:e==="warm-cold"?se.cyan:e==="idle"?se.yellow:e==="dead"?se.red:se.dim}Rt.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}=wi(e),n;try{n=await fetch(`${o}/api/processes`,{headers:$i(t)})}catch(r){console.log(se.red(` could not reach daemon at ${o}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(se.dim(` daemon at ${o} has no agents with persistentProcess: true`));return}n.ok||(console.log(se.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(se.dim(" (no processes)"));return}for(let r of i){let a=Oa(r.state)(r.state.padEnd(9)),c=yi(r.spawnedAt),d=r.lastTurnAt?yi(r.lastTurnAt)+" ago":"\u2014",g=r.lastInputTokens?se.dim(`last_in=${r.lastInputTokens} tok`):"",l=r.claudeSessionId?se.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):se.dim("sess=\u2014"),u=r.pendingTaskId?se.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${se.bold(r.key.agentId)}${se.dim(":"+r.key.channel+":"+r.key.chatId)} ${se.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${d} ${l} ${g} ${u}`),r.deadReason&&console.log(` ${se.red("dead:")} ${r.deadReason}`)}});Rt.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}=wi(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:$i(i,"application/json"),body:JSON.stringify({agentId:e,channel:o,chatId:t,reason:n.reason})})}catch(a){console.log(se.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(se.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(se.red(` ${a}`)),process.exit(1)}console.log(se.green(` killed ${e}:${o}:${t}`))});import{Command as Ca}from"commander";import we from"chalk";import{existsSync as Sn,rmSync as Ra}from"fs";import{resolve as jn}from"path";var _o=new Ca().name("rag").description("manage per-agent lexical (BM25) RAG indexes (improvement plan #7)");_o.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(we.red(` No globs provided. Example: agentx rag add ${e} './docs/**/*.md'`)),process.exit(1));let n=!!t.verbose,s=Date.now(),i=await ds(e,o,{verbose:n}),r=Date.now()-s;console.log(we.green(` \u2713 indexed ${i.docs} doc(s) for ${we.bold(e)} in ${r}ms`)),console.log(we.dim(` \u2192 ${i.path}`))});_o.command("list").description("list every agent's index, sizes, paths").option("-c, --cwd <path>","search root",process.cwd()).action(async e=>{let o=jn(e.cwd,".agentx","rag");if(!Sn(o)){console.log(we.dim(" (no indexes yet \u2014 try `agentx rag add <agentId> <glob>`)"));return}let{readdirSync:t}=await import("fs"),n=t(o).filter(s=>Sn(jn(o,s,"index.json")));if(n.length===0){console.log(we.dim(" (no indexes)"));return}for(let s of n.sort()){let i=on(s);console.log(` ${we.bold(s)} ${i.docs} doc(s) ${we.dim(i.path)}`)}});_o.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=gs(e,o,{k:n});if(t.json){console.log(JSON.stringify(s,null,2));return}if(s.length===0){let i=on(e);i.exists?console.log(we.dim(` (no hits in ${i.docs} indexed docs)`)):console.log(we.red(` no index for ${e} \u2014 run \`agentx rag add ${e} <glob>\` first`));return}for(let i of s)console.log(` ${we.bold(i.title)} ${we.dim(`(${i.score.toFixed(2)})`)}`),console.log(` ${we.dim(i.path)}`),console.log(` ${we.dim(i.snippet.slice(0,200))}`)});_o.command("clear <agentId>").description("delete an agent's index").action(e=>{let o=jn(process.cwd(),".agentx","rag",e);if(!Sn(o)){console.log(we.dim(` no index for ${e} \u2014 nothing to clear`));return}Ra(o,{recursive:!0,force:!0}),console.log(we.green(` \u2713 cleared index for ${e}`))});import{Command as Ta}from"commander";import q from"chalk";import Po from"prompts";var ho=new Ta().name("backlog").description("manage the local backlog used by business workSource=backlog");function ot(e){let o=L(e),t=o.business?.workSource,n=t?.type==="backlog"?t.path:".agentx/backlog.md";return{config:o,storePath:n,store:new Ls(n)}}function Da(e){return e?q.cyan(`${e.type}:${e.project}#${e.iid}`):q.dim("manual")}function Na(e){return{todo:q.gray("todo"),doing:q.yellow("doing"),blocked:q.red("blocked"),done:q.green("done")}[e]}ho.command("list",{isDefault:!0}).description("list backlog items").option("--status <status>","filter by status (todo|doing|blocked|done)").option("--assignee <agent>","filter by assignee").option("--source <type>","filter by source.type (gitlab|github|manual)").option("-c, --config <path>","config path").action(async e=>{let{store:o}=ot(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(q.dim(" (no items)"));return}console.log();for(let n of t){let s=n.assignee?q.magenta(`@${n.assignee}`):q.dim("unassigned");console.log(` ${Na(n.status).padEnd(7)} ${Da(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(q.dim(` ${n.source.url}`))}console.log(),console.log(q.dim(` ${t.length} item${t.length===1?"":"s"} \u2014 ${o.jsonPath()}`))});ho.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,o,t)=>{let n=ot(t.config);n.store.findById(e)||(console.error(q.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:o,status:"doing"});if(console.log(q.green(` claimed: ${i.title} -> ${o}`)),i.source){let r=Us([o],i.source,n.config),a=await rn(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(q.dim(" sync:"),...c));console.log(a.ok?q.dim(` synced -> ${a.url??i.source.type}`):q.yellow(` sync failed: ${a.error}`))}});ho.command("done <id>").description("mark an item as done; closes the upstream issue if linked").option("--note <text>","comment to post upstream").option("--close","also close the upstream issue (default: only labels change)",!1).option("-c, --config <path>","config path").action(async(e,o)=>{let t=ot(o.config);t.store.findById(e)||(console.error(q.red(` item ${e} not found`)),process.exit(1));let s=t.store.update(e,{status:"done"});if(console.log(q.green(` done: ${s.title}`)),s.source){let i=await rn(s,{addLabels:["Done"],removeLabels:["Doing"],state:o.close?"closed":void 0,note:o.note},t.config,(...r)=>console.log(q.dim(" sync:"),...r));console.log(i.ok?q.dim(` synced -> ${i.url??s.source.type}`):q.yellow(` sync failed: ${i.error}`))}});ho.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,o)=>{let{store:t}=ot(o.config);t.remove(e)||(console.error(q.red(` item ${e} not found`)),process.exit(1)),console.log(q.green(` removed ${e}`))});ho.command("import").description("import open issues from gitlab/github into the backlog (interactive)").option("--source <type>","source type (gitlab|github)").option("--project <id>","project id (group/repo for gitlab, owner/repo for github)").option("--assignee <agent>","assign all imported items to this agentId").option("-c, --config <path>","config path").action(async e=>{let o=ot(e.config),t=!!o.config.channels.gitlab?.token,n=!!o.config.channels.github?.token;!t&&!n&&(console.error(q.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 $=[t&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await Po({type:"select",name:"source",message:"Source",choices:$})).source,!s)return}s==="gitlab"&&!t&&(console.error(q.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(q.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let $=s==="gitlab"?Pa(o.config):Ma(o.config);$.length?(i=(await Po({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...$.map(b=>({title:b,value:b})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await Po({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await Po({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await Po({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(q.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await La(o.config,i,a):await Ua(o.config,i,a);if(!c.length){console.log(q.yellow(" no open issues matched"));return}console.log(q.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let d=i,g=new Set(o.store.list().map($=>$.id)),l=c.map($=>{let v=sn({type:s,project:d,iid:$.iid,url:$.url}),b=g.has(v),S=$.labels.length?` [${$.labels.slice(0,3).join(",")}]`:"";return{title:`#${$.iid} ${$.title}${S}${b?q.dim(" (already imported)"):""}`,value:$,disabled:b}}),m=(await Po({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:l,min:1})).selected||[];if(!m.length){console.log(q.dim(" nothing selected"));return}let f=m.map($=>{let v={type:s,host:s==="gitlab"?_a(o.config):void 0,project:d,iid:$.iid,url:$.url};return{id:sn(v),title:$.title,description:$.description,assignee:e.assignee||$.assignee,labels:$.labels,milestone:$.milestone,status:"todo",source:v,importedAt:new Date().toISOString()}}),y=o.store.addMany(f);console.log(q.green(` imported ${y.length} item${y.length===1?"":"s"}`));for(let $ of y)console.log(q.dim(` ${$.id} \u2014 ${$.title}`))});function _a(e){let o=e.channels.gitlab?.host;if(o)return o.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Pa(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 Ma(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 La(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 Ua(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 d=await fetch(i,{headers:s});if(!d.ok)throw new Error(`GitHub ${d.status}: ${await d.text().catch(()=>"")}`);return((await d.json()).items??[]).map(bi)}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(bi):[]}function bi(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 Ba}from"commander";import U from"chalk";import{existsSync as Fa,readFileSync as qa}from"fs";import{resolve as za}from"path";import Ha from"prompts";import Wa from"cronstrue";var En={sun:0,sunday:0,mon:1,monday:1,tue:2,tuesday:2,tues:2,wed:3,wednesday:3,thu:4,thursday:4,thurs:4,fri:5,friday:5,sat:6,saturday:6},Tt={morning:{h:9,m:0},afternoon:{h:14,m:0},evening:{h:18,m:0},night:{h:22,m:0},noon:{h:12,m:0},midnight:{h:0,m:0}};function Pe(e){try{return Wa.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function Ja(e){if(/\b(noon|midday)\b/.test(e))return Tt.noon;if(/\bmidnight\b/.test(e))return Tt.midnight;let o=e.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(o){let t=parseInt(o[1],10),n=o[2]?parseInt(o[2],10):0,s=o[3];return s==="pm"&&t<12&&(t+=12),s==="am"&&t===12&&(t=0),t>23||n>59?null:{h:t,m:n}}return null}function In(e){let o=e.trim().toLowerCase();if(!o)return null;let t;if(t=o.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let l=parseInt(t[1],10);return l<1||l>59?null:{cron:`*/${l} * * * *`,human:Pe(`*/${l} * * * *`),matched:t[0]}}if(/\bevery\s+minute\b/.test(o))return{cron:"* * * * *",human:Pe("* * * * *"),matched:"every minute"};if(t=o.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let l=parseInt(t[1],10);return l<1||l>23?null:{cron:`0 */${l} * * *`,human:Pe(`0 */${l} * * *`),matched:t[0]}}if(/\b(every hour|hourly)\b/.test(o))return{cron:"0 * * * *",human:Pe("0 * * * *"),matched:"every hour"};let n=Ja(o),s=null;for(let[l,u]of Object.entries(Tt))if(!(l==="noon"||l==="midnight")&&new RegExp(`\\b(every\\s+)?${l}s?\\b`).test(o)){s=u;break}let i=n||s,r=o.match(/\b(first|1st|2nd|3rd|last|(\d+)(?:st|nd|rd|th)?)\s+(day\s+)?of\s+(every|each|the)\s+month\b/);if(r){let l=r[1],u=1;if(l==="last"||(/^\d+(st|nd|rd|th)?$/.test(l)?u=parseInt(l,10):l==="first"||l==="1st"?u=1:l==="2nd"?u=2:l==="3rd"&&(u=3),u<1||u>31))return null;let m=i||{h:9,m:0},f=`${m.m} ${m.h} ${u} * *`;return{cron:f,human:Pe(f),matched:r[0]}}let a=[],c=Object.keys(En).join("|"),d=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),g=o.match(d);if(g){let l=g[1];for(let u of Object.keys(En))if(new RegExp(`\\b${u}s?\\b`).test(l)){let m=En[u];a.includes(m)||a.push(m)}}if(a.length){let l=i||{h:9,m:0};a.sort((f,y)=>f-y);let u=a.join(","),m=`${l.m} ${l.h} * * ${u}`;return{cron:m,human:Pe(m),matched:`on ${u}`}}if(/\b(weekday|workday|business day)s?\b/.test(o)){let l=i||{h:9,m:0},u=`${l.m} ${l.h} * * 1-5`;return{cron:u,human:Pe(u),matched:"weekdays"}}if(/\bweekends?\b/.test(o)){let l=i||{h:9,m:0},u=`${l.m} ${l.h} * * 0,6`;return{cron:u,human:Pe(u),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(o)||s){let l=i||{h:9,m:0},u=`${l.m} ${l.h} * * *`;return{cron:u,human:Pe(u),matched:s&&Object.entries(Tt).find(([,m])=>m===s)?.[0]||"daily"}}if(n){let l=`${n.m} ${n.h} * * *`;return{cron:l,human:Pe(l),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function ki(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${o}`}function vi(e){let o=e||za(process.cwd(),"agentx.json");return Fa(o)||(console.log(U.red(` No config at ${o}. Run: agentx init`)),process.exit(1)),JSON.parse(qa(o,"utf-8"))}function Ga(e){return e?e.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o==="log"||o==="notify"||o==="disable"):["log"]}async function Ya(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(U.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Ha([{type:"text",name:"channel",message:"Destination channel (telegram/whatsapp/discord):"},{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(U.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var eo=new Ba().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');eo.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: Africa/Tunis)","Africa/Tunis").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){eo.help();return}o.agent||(console.log(U.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!o.do&&!o.id&&(console.log(U.red(' --do "<prompt>" is required')),process.exit(1));let t=In(e);t||(console.log(U.red(` Couldn't parse: "${e}"`)),console.log(U.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(U.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(U.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=vi(o.config),s=fs(n);n.agents?.[o.agent]||(console.log(U.red(` Agent "${o.agent}" not found in agentx.json`)),console.log(U.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=Ga(o.onError),r=await Ya(o.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=o.id||ki(t.matched,o.agent),c={enabled:!o.disabled,schedule:t.cron,timezone:o.timezone,agent:o.agent,prompt:o.do,timeout:parseInt(o.timeout,10),onError:i};o.model&&(c.model=o.model),r&&(c.notify=r);let d=await K(l=>X(l,`crons.${a}`,c),{configPath:o.config,dryRun:!!o.dryRun});d.success||(console.log(U.red(` \u2717 ${d.error}`)),process.exit(1));let g=o.dryRun?"would add":"Added";console.log(U.green(` \u2713 ${g} cron ${U.cyan(a)}`)),console.log(U.dim(` Schedule: ${t.cron} (${t.human}, ${o.timezone})`)),console.log(U.dim(` Agent: ${o.agent}`)),r&&console.log(U.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(U.dim(` On error: ${i.join(", ")}`)),!o.dryRun&&d.reloaded&&console.log(U.dim(" Daemon hot-reloaded."))});eo.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=vi(e.config).crons||{},n=Object.entries(t);if(!n.length){console.log(U.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?U.green("\u25CF"):U.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${U.cyan(s.padEnd(32))} ${U.dim(i.schedule.padEnd(14))} ${U.dim("\u2192")} ${i.agent}`),console.log(U.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(U.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,o]of[["on",!0],["off",!1]])eo.command(`${e} <id>`).description(`${o?"enable":"disable"} a scheduled job`).action(async t=>{let n=await K(s=>{if(!co(s,`crons.${t}`))throw new Error(`cron "${t}" not found`);X(s,`crons.${t}.enabled`,o)});n.success||(console.log(U.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(U.green(` \u2713 ${t} ${o?"enabled":"disabled"}`)),n.reloaded&&console.log(U.dim(" Daemon hot-reloaded."))});eo.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let o=await K(t=>{if(!co(t,`crons.${e}`))throw new Error(`cron "${e}" not found`);hs(t,`crons.${e}`)});o.success||(console.log(U.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(U.green(` \u2713 ${e} removed`)),o.reloaded&&console.log(U.dim(" Daemon hot-reloaded."))});eo.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let o=e.join(" "),t=In(o);t||(console.log(U.red(` \u2717 could not parse: "${o}"`)),process.exit(1)),console.log(U.green(` "${o}"`)),console.log(U.dim(` \u2192 ${t.cron}`)),console.log(U.dim(` \u2192 ${t.human}`))});import{Command as bc}from"commander";import wo from"chalk";import H from"chalk";import tt from"prompts";import{readFileSync as Ka,writeFileSync as Va,existsSync as Qa}from"fs";import{resolve as xi}from"path";var Xa=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Za(e){let o=e.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}function An(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Si(e=".env"){let o=xi(e);if(!Qa(o))return[];let t=Ka(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(Xa);i?n.push({kind:"kv",key:i[1],value:Za(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function ec(e){return e.map(o=>o.kind==="kv"?`${o.key}=${An(o.value)}`:o.raw).join(`
|
|
211
211
|
`)+`
|
|
212
|
-
`}function yo(e,o,t=".env"){let n=xi(t),s=Si(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${An(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${An(o)}`})),Va(n,ec(s))}function On(e,o=".env"){return Si(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var ji="https://t.me/BotFather";async function oc(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 tc(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 Ei(e={}){console.log(),console.log(H.bold(" Connect Telegram")),console.log(),console.log(H.dim(` 1. Open ${ji}`)),console.log(H.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(H.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await tt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),S=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(S,[ji],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await tt({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(H.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await oc(t.trim());n||(console.log(H.red("\u2717 invalid or revoked")),process.exit(1)),console.log(H.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(H.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),d=Object.keys(c.agents||{});d.length===0&&(console.log(H.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await tt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:d.map(S=>({title:S,value:S})),initial:0})).agent),g||(console.log(H.red(" Aborted")),process.exit(1));let l=c.channels?.telegram?.accounts||{},u=e.account||g;l[u]&&l[u].agentBinding!==g&&(u=(await tt({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(H.red(" Aborted")),process.exit(1));let m=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;yo(m,t.trim()),process.env[m]=t.trim();let f=await K(b=>{X(b,"channels.telegram.enabled",!0),X(b,`channels.telegram.accounts.${u}`,{token:`\${${m}}`,agentBinding:g});let S=co(b,`agents.${g}.mentions`)||[],x=`@${n.username}`;S.includes(x)||(S.push(x),X(b,`agents.${g}.mentions`,S))},{configPath:e.configPath});if(f.success||(console.log(H.red(` \u2717 ${f.error}`)),process.exit(1)),console.log(),console.log(H.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(H.dim(` Token stored in .env as ${m}`)),console.log(H.dim(` Mentions updated to include @${n.username}`)),f.reloaded?console.log(H.dim(" Daemon hot-reloaded.")):console.log(H.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await tt({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(H.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(H.dim(" Waiting up to 90s..."));let $=await tc(t.trim(),9e4);if(!$){console.log(H.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(H.dim(" agentx config set notifications.destination.channel telegram")),console.log(H.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(H.dim(` agentx config set notifications.destination.accountId ${u}`));return}let v=await K(b=>{X(b,"notifications.destination",{channel:"telegram",chatId:String($.chatId),accountId:u})},{configPath:e.configPath});if(!v.success){console.log(H.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(H.green(" \u2713 Default --notify target set")),console.log(H.dim(` Chat: ${$.chatTitle||$.chatId} (from ${$.from})`)),console.log(H.dim(" From now on, --notify me resolves to this chat.")),v.reloaded&&console.log(H.dim(" Daemon hot-reloaded."))}import ce from"chalk";import Dt from"prompts";import{spawn as nc}from"child_process";var Ii="https://discord.com/developers/applications",sc="67584";async function ic(e){try{let o=await fetch("https://discord.com/api/v10/users/@me",{headers:{Authorization:`Bot ${e}`},signal:AbortSignal.timeout(8e3)});return o.ok?await o.json():null}catch{return null}}function Ai(e){try{let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";nc(o,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}async function Oi(e={}){console.log(),console.log(ce.bold(" Connect Discord")),console.log(),console.log(ce.dim(" 1. Open the Discord Developer Portal")),console.log(ce.dim(` ${Ii}`)),console.log(ce.dim(" 2. New Application \u2192 Bot \u2192 Reset Token \u2192 copy the token")),console.log(ce.dim(" 3. Under Bot \u2192 Privileged Gateway Intents,")),console.log(ce.dim(" enable 'MESSAGE CONTENT INTENT'")),console.log();let{openBrowser:o}=await Dt({type:"confirm",name:"openBrowser",message:"Open the Developer Portal in your browser?",initial:!0});o&&Ai(Ii);let{token:t}=await Dt({type:"password",name:"token",message:"Paste the bot token:",validate:$=>$.trim().length>20||"that looks too short for a Discord token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await ic(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked \u2014 did you enable MESSAGE CONTENT INTENT and copy the right token?")),process.exit(1));let s=n.discriminator&&n.discriminator!=="0"?`${n.username}#${n.discriminator}`:n.username;console.log(ce.green(`\u2713 ${s} (bot id ${n.id})`));let{readFileSync:i,existsSync:r}=await import("fs"),{resolve:a}=await import("path"),c=e.configPath||a(process.cwd(),"agentx.json");r(c)||(console.log(ce.red(` No agentx.json at ${c}. Run: agentx init`)),process.exit(1));let d=JSON.parse(i(c,"utf-8")),g=Object.keys(d.agents||{});g.length===0&&(console.log(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let l=e.agent;l||(l=(await Dt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:g.map(v=>({title:v,value:v})),initial:0})).agent),l||(console.log(ce.red(" Aborted")),process.exit(1));let u="DISCORD_BOT_TOKEN";yo(u,t.trim()),process.env[u]=t.trim();let m=await K($=>{X($,"channels.discord.enabled",!0),X($,"channels.discord.token",`\${${u}}`),X($,"channels.discord.agentBinding",l)},{configPath:e.configPath});m.success||(console.log(ce.red(` \u2717 ${m.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Discord bot ${s} bound to agent "${l}"`)),console.log(ce.dim(` Token stored in .env as ${u}`)),m.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Restart the daemon to start Discord polling.")),console.log(),console.log(ce.bold(" Install the bot to a server")),console.log();let f=`https://discord.com/oauth2/authorize?client_id=${n.id}&scope=bot&permissions=${sc}`;console.log(` ${ce.cyan(f)}`),console.log();let{openInstall:y}=await Dt({type:"confirm",name:"openInstall",message:"Open the install URL in your browser now?",initial:!0});y&&Ai(f),console.log(),console.log(ce.dim(" After you pick a server, the bot will come online on the next daemon restart.")),console.log(ce.dim(" Mention the bot in any channel to route messages to the agent."))}import ie from"chalk";import Cn from"prompts";import{existsSync as Tn,mkdirSync as rc,readdirSync as ac,readFileSync as Ci}from"fs";import{resolve as Rn}from"path";var cc=".agentx/whatsapp-sessions";function lc(){let e=Rn(process.cwd(),".agentx/daemon.pid");if(!Tn(e))return!1;try{let o=parseInt(Ci(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function dc(e){if(!Tn(e))return!1;try{return ac(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function gc(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ie.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ie.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;rc(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},d=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 d.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ie.yellow(" Timed out waiting for scan (2min)."));try{d.end(void 0)}catch{}g(!1)},12e4);d.ev.on("connection.update",async m=>{if(m.qr){o(ie.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:f}=await import("qrcode-terminal");f.generate(m.qr,{small:!0})}catch{o(` QR: ${m.qr}`)}o("")}if(m.connection==="open"){clearTimeout(u),o(ie.green(" \u2713 Paired"));try{d.end(void 0)}catch{}g(!0)}m.connection==="close"&&!m.qr&&m.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ie.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Ri(e={}){if(console.log(),console.log(ie.bold(" Connect WhatsApp")),console.log(),lc()){console.log(ie.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ie.dim(" agentx daemon stop")),console.log();let{cont:d}=await Cn({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});d||(console.log(ie.red(" Aborted")),process.exit(1))}let o=e.configPath||Rn(process.cwd(),"agentx.json");Tn(o)||(console.log(ie.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Ci(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||cc,s=Rn(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ie.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Cn({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ie.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(dc(s)&&a){let{keep:d}=await Cn({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!d,d&&console.log(ie.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await gc(s,g=>console.log(g))||(console.log(ie.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await K(d=>{X(d,"channels.whatsapp.enabled",!0),X(d,"channels.whatsapp.sessionDir",n),X(d,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ie.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ie.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ie.dim(` Session: ${n}`)),console.log(ie.dim(" Start the daemon to begin receiving:")),console.log(ie.dim(" agentx daemon start")),console.log(ie.dim(" Add routes later with:")),console.log(ie.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as mc}from"crypto";import le from"chalk";import Ti from"prompts";var Nt="agentx-mesh:",_t="//join/";function pc(e){return Buffer.from(e,"utf-8").toString("base64url")}function uc(e){return Buffer.from(e,"base64url").toString("utf-8")}function fc(e){return`${Nt}${_t}${pc(JSON.stringify(e))}`}function hc(e){if(!e.startsWith(`${Nt}${_t}`))throw new Error(`Not a mesh invite link \u2014 expected ${Nt}${_t}\u2026`);let o=e.slice(Nt.length+_t.length),t=JSON.parse(uc(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 yc(){return mc(32).toString("hex")}function wc(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function $c(e){return e?.node?.name||e?.node?.id||"node"}async function Di(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(le.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=On("MESH_TOKEN");r||(r=yc(),yo("MESH_TOKEN",r),console.log(le.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||wc(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:l}=await Ti({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://"});l||(console.log(le.red(" Aborted")),process.exit(1)),a=l}let d=await K(l=>{X(l,"mesh.enabled",!0)},{configPath:e.configPath});d.success||(console.log(le.red(` \u2717 ${d.error}`)),process.exit(1));let g=fc({url:a,token:r,name:$c(i),version:1});console.log(),console.log(le.bold(" Mesh invite")),console.log(),console.log(` ${le.cyan(g)}`),console.log(),console.log(le.dim(" Run on the other node:")),console.log(le.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(le.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Ni(e,o={}){let t;try{t=hc(e)}catch(i){console.log(le.red(` \u2717 ${i.message}`)),process.exit(1)}let n=On("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Ti({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(le.red(" Aborted (keeping existing .env)")),process.exit(1))}yo("MESH_TOKEN",t.token);let s=await K(i=>{X(i,"mesh.enabled",!0);let r=co(i,"mesh.peers")||[],a=r.findIndex(d=>d.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),X(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(le.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(le.green(" \u2713 Joined mesh")),console.log(le.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(le.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(le.dim(" Daemon hot-reloaded.")):console.log(le.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(le.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(le.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(le.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var $o=new bc().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");$o.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 Ei({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});$o.command("discord").description("pair a Discord bot \u2014 verify token, emit install URL, save to .env").option("--agent <id>","agent to bind the bot to").option("-c, --config <path>","path to agentx.json").action(async e=>{await Oi({agent:e.agent,configPath:e.config})});$o.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 Ri({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var _i=$o.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");_i.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 Di({url:e.url,configPath:e.config})});_i.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 Ni(e,{configPath:o.config})});$o.action(()=>{console.log(),console.log(wo.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${wo.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${wo.cyan("agentx connect discord")} \u2014 pair a Discord bot, emit install URL`),console.log(` ${wo.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${wo.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${wo.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(wo.dim(" GitLab connect is the next slice.")),console.log()});import{Command as kc}from"commander";import oe from"chalk";var nt=new kc().name("usage").description("token usage analysis and reporting");nt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=L(),[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(oe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(oe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${oe.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: ${oe.red(String(s.totalErrors))}`),console.log(),console.log(oe.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 d=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${oe.cyan(a)}: ${d} tokens (${c.tasks} tasks) ${oe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${e.message}`))}});nt.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(oe.red(` Script not found: ${s}`)),console.log(oe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(oe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(oe.red(" Analysis failed. Is Python 3 installed?"))}});nt.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-PRL6Z4U3.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-WVAVJFND.js"),r=await i(),a=new Set(n.filter(l=>l.kind==="cli").map(l=>l.name)),c=[],d=(l,u)=>{for(let m of l.commands??[]){let f=u?`${u} ${m.name()}`:m.name();c.push(f),d(m,f)}};d(r,"");let g=c.filter(l=>!a.has(l)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(oe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let l of g)console.log(` ${oe.dim("\xB7")} ${l}`);console.log(),console.log(oe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(oe.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(oe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(oe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(oe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(oe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=oe.dim(`${i.days}d`);console.log(` ${oe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(oe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as vc}from"commander";import re from"chalk";var oo=new vc().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");oo.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{let o=xc(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-CQ5F4GPD.js");t(o)}catch(o){console.log(re.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(re.dim(o.stack)),process.exit(1)}});function xc(e,o){try{let t=L();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(re.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(re.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
212
|
+
`}function yo(e,o,t=".env"){let n=xi(t),s=Si(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:o,raw:`${e}=${An(o)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:o,raw:`${e}=${An(o)}`})),Va(n,ec(s))}function On(e,o=".env"){return Si(o).find(s=>s.kind==="kv"&&s.key===e)?.value}var ji="https://t.me/BotFather";async function oc(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 tc(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 Ei(e={}){console.log(),console.log(H.bold(" Connect Telegram")),console.log(),console.log(H.dim(` 1. Open ${ji}`)),console.log(H.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(H.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:o}=await tt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(o)try{let{spawn:b}=await import("child_process"),S=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";b(S,[ji],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:t}=await tt({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(H.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await oc(t.trim());n||(console.log(H.red("\u2717 invalid or revoked")),process.exit(1)),console.log(H.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(H.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),d=Object.keys(c.agents||{});d.length===0&&(console.log(H.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await tt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:d.map(S=>({title:S,value:S})),initial:0})).agent),g||(console.log(H.red(" Aborted")),process.exit(1));let l=c.channels?.telegram?.accounts||{},u=e.account||g;l[u]&&l[u].agentBinding!==g&&(u=(await tt({type:"text",name:"account",message:`Account "${u}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),u||(console.log(H.red(" Aborted")),process.exit(1));let m=`TG_${u.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;yo(m,t.trim()),process.env[m]=t.trim();let f=await K(b=>{X(b,"channels.telegram.enabled",!0),X(b,`channels.telegram.accounts.${u}`,{token:`\${${m}}`,agentBinding:g});let S=co(b,`agents.${g}.mentions`)||[],x=`@${n.username}`;S.includes(x)||(S.push(x),X(b,`agents.${g}.mentions`,S))},{configPath:e.configPath});if(f.success||(console.log(H.red(` \u2717 ${f.error}`)),process.exit(1)),console.log(),console.log(H.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(H.dim(` Token stored in .env as ${m}`)),console.log(H.dim(` Mentions updated to include @${n.username}`)),f.reloaded?console.log(H.dim(" Daemon hot-reloaded.")):console.log(H.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await tt({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!y)return;console.log(),console.log(H.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(H.dim(" Waiting up to 90s..."));let $=await tc(t.trim(),9e4);if(!$){console.log(H.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(H.dim(" agentx config set notifications.destination.channel telegram")),console.log(H.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(H.dim(` agentx config set notifications.destination.accountId ${u}`));return}let v=await K(b=>{X(b,"notifications.destination",{channel:"telegram",chatId:String($.chatId),accountId:u})},{configPath:e.configPath});if(!v.success){console.log(H.red(` \u2717 failed to save destination: ${v.error}`));return}console.log(H.green(" \u2713 Default --notify target set")),console.log(H.dim(` Chat: ${$.chatTitle||$.chatId} (from ${$.from})`)),console.log(H.dim(" From now on, --notify me resolves to this chat.")),v.reloaded&&console.log(H.dim(" Daemon hot-reloaded."))}import ce from"chalk";import Dt from"prompts";import{spawn as nc}from"child_process";var Ii="https://discord.com/developers/applications",sc="67584";async function ic(e){try{let o=await fetch("https://discord.com/api/v10/users/@me",{headers:{Authorization:`Bot ${e}`},signal:AbortSignal.timeout(8e3)});return o.ok?await o.json():null}catch{return null}}function Ai(e){try{let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";nc(o,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}async function Oi(e={}){console.log(),console.log(ce.bold(" Connect Discord")),console.log(),console.log(ce.dim(" 1. Open the Discord Developer Portal")),console.log(ce.dim(` ${Ii}`)),console.log(ce.dim(" 2. New Application \u2192 Bot \u2192 Reset Token \u2192 copy the token")),console.log(ce.dim(" 3. Under Bot \u2192 Privileged Gateway Intents,")),console.log(ce.dim(" enable 'MESSAGE CONTENT INTENT'")),console.log();let{openBrowser:o}=await Dt({type:"confirm",name:"openBrowser",message:"Open the Developer Portal in your browser?",initial:!0});o&&Ai(Ii);let{token:t}=await Dt({type:"password",name:"token",message:"Paste the bot token:",validate:$=>$.trim().length>20||"that looks too short for a Discord token"});t||(console.log(ce.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await ic(t.trim());n||(console.log(ce.red("\u2717 invalid or revoked \u2014 did you enable MESSAGE CONTENT INTENT and copy the right token?")),process.exit(1));let s=n.discriminator&&n.discriminator!=="0"?`${n.username}#${n.discriminator}`:n.username;console.log(ce.green(`\u2713 ${s} (bot id ${n.id})`));let{readFileSync:i,existsSync:r}=await import("fs"),{resolve:a}=await import("path"),c=e.configPath||a(process.cwd(),"agentx.json");r(c)||(console.log(ce.red(` No agentx.json at ${c}. Run: agentx init`)),process.exit(1));let d=JSON.parse(i(c,"utf-8")),g=Object.keys(d.agents||{});g.length===0&&(console.log(ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let l=e.agent;l||(l=(await Dt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:g.map(v=>({title:v,value:v})),initial:0})).agent),l||(console.log(ce.red(" Aborted")),process.exit(1));let u="DISCORD_BOT_TOKEN";yo(u,t.trim()),process.env[u]=t.trim();let m=await K($=>{X($,"channels.discord.enabled",!0),X($,"channels.discord.token",`\${${u}}`),X($,"channels.discord.agentBinding",l)},{configPath:e.configPath});m.success||(console.log(ce.red(` \u2717 ${m.error}`)),process.exit(1)),console.log(),console.log(ce.green(` \u2713 Discord bot ${s} bound to agent "${l}"`)),console.log(ce.dim(` Token stored in .env as ${u}`)),m.reloaded?console.log(ce.dim(" Daemon hot-reloaded.")):console.log(ce.dim(" Restart the daemon to start Discord polling.")),console.log(),console.log(ce.bold(" Install the bot to a server")),console.log();let f=`https://discord.com/oauth2/authorize?client_id=${n.id}&scope=bot&permissions=${sc}`;console.log(` ${ce.cyan(f)}`),console.log();let{openInstall:y}=await Dt({type:"confirm",name:"openInstall",message:"Open the install URL in your browser now?",initial:!0});y&&Ai(f),console.log(),console.log(ce.dim(" After you pick a server, the bot will come online on the next daemon restart.")),console.log(ce.dim(" Mention the bot in any channel to route messages to the agent."))}import ie from"chalk";import Cn from"prompts";import{existsSync as Tn,mkdirSync as rc,readdirSync as ac,readFileSync as Ci}from"fs";import{resolve as Rn}from"path";var cc=".agentx/whatsapp-sessions";function lc(){let e=Rn(process.cwd(),".agentx/daemon.pid");if(!Tn(e))return!1;try{let o=parseInt(Ci(e,"utf-8").trim(),10);return o?(process.kill(o,0),!0):!1}catch{return!1}}function dc(e){if(!Tn(e))return!1;try{return ac(e).some(o=>o.includes("creds")||o.endsWith(".json"))}catch{return!1}}async function gc(e,o){let t;try{t=await import("@whiskeysockets/baileys")}catch{return o(ie.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),o(ie.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=t.default||t;rc(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},d=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 d.ev.on("creds.update",r),await new Promise(g=>{let u=setTimeout(()=>{o(ie.yellow(" Timed out waiting for scan (2min)."));try{d.end(void 0)}catch{}g(!1)},12e4);d.ev.on("connection.update",async m=>{if(m.qr){o(ie.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),o("");try{let{default:f}=await import("qrcode-terminal");f.generate(m.qr,{small:!0})}catch{o(` QR: ${m.qr}`)}o("")}if(m.connection==="open"){clearTimeout(u),o(ie.green(" \u2713 Paired"));try{d.end(void 0)}catch{}g(!0)}m.connection==="close"&&!m.qr&&m.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(u),o(ie.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function Ri(e={}){if(console.log(),console.log(ie.bold(" Connect WhatsApp")),console.log(),lc()){console.log(ie.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(ie.dim(" agentx daemon stop")),console.log();let{cont:d}=await Cn({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});d||(console.log(ie.red(" Aborted")),process.exit(1))}let o=e.configPath||Rn(process.cwd(),"agentx.json");Tn(o)||(console.log(ie.red(` No agentx.json at ${o}. Run: agentx init`)),process.exit(1));let t=JSON.parse(Ci(o,"utf-8")),n=e.sessionDir||t.channels?.whatsapp?.sessionDir||cc,s=Rn(process.cwd(),n),i=Object.keys(t.agents||{});i.length===0&&(console.log(ie.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Cn({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(g=>({title:g,value:g})),initial:0})).agent),r||(console.log(ie.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(dc(s)&&a){let{keep:d}=await Cn({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!d,d&&console.log(ie.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await gc(s,g=>console.log(g))||(console.log(ie.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await K(d=>{X(d,"channels.whatsapp.enabled",!0),X(d,"channels.whatsapp.sessionDir",n),X(d,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(ie.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(ie.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(ie.dim(` Session: ${n}`)),console.log(ie.dim(" Start the daemon to begin receiving:")),console.log(ie.dim(" agentx daemon start")),console.log(ie.dim(" Add routes later with:")),console.log(ie.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as mc}from"crypto";import le from"chalk";import Ti from"prompts";var Nt="agentx-mesh:",_t="//join/";function pc(e){return Buffer.from(e,"utf-8").toString("base64url")}function uc(e){return Buffer.from(e,"base64url").toString("utf-8")}function fc(e){return`${Nt}${_t}${pc(JSON.stringify(e))}`}function hc(e){if(!e.startsWith(`${Nt}${_t}`))throw new Error(`Not a mesh invite link \u2014 expected ${Nt}${_t}\u2026`);let o=e.slice(Nt.length+_t.length),t=JSON.parse(uc(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 yc(){return mc(32).toString("hex")}function wc(e){let o=e?.node?.bind||"127.0.0.1:18800",[t,n]=o.split(":");return`http://${t}:${n}`}function $c(e){return e?.node?.name||e?.node?.id||"node"}async function Di(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(le.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(o(s,"utf-8")),r=On("MESH_TOKEN");r||(r=yc(),yo("MESH_TOKEN",r),console.log(le.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||wc(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:l}=await Ti({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://"});l||(console.log(le.red(" Aborted")),process.exit(1)),a=l}let d=await K(l=>{X(l,"mesh.enabled",!0)},{configPath:e.configPath});d.success||(console.log(le.red(` \u2717 ${d.error}`)),process.exit(1));let g=fc({url:a,token:r,name:$c(i),version:1});console.log(),console.log(le.bold(" Mesh invite")),console.log(),console.log(` ${le.cyan(g)}`),console.log(),console.log(le.dim(" Run on the other node:")),console.log(le.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(le.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Ni(e,o={}){let t;try{t=hc(e)}catch(i){console.log(le.red(` \u2717 ${i.message}`)),process.exit(1)}let n=On("MESH_TOKEN");if(n&&n!==t.token){let{overwrite:i}=await Ti({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(le.red(" Aborted (keeping existing .env)")),process.exit(1))}yo("MESH_TOKEN",t.token);let s=await K(i=>{X(i,"mesh.enabled",!0);let r=co(i,"mesh.peers")||[],a=r.findIndex(d=>d.name===t.name),c={name:t.name,url:t.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),X(i,"mesh.peers",r)},{configPath:o.configPath});s.success||(console.log(le.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(le.green(" \u2713 Joined mesh")),console.log(le.dim(` Peer: ${t.name} @ ${t.url}`)),console.log(le.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(le.dim(" Daemon hot-reloaded.")):console.log(le.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(le.dim(` Reachable \u2014 ${t.name} exposes ${a} agents`))}else console.log(le.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(le.yellow(` Could not reach ${t.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var $o=new bc().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");$o.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 Ei({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});$o.command("discord").description("pair a Discord bot \u2014 verify token, emit install URL, save to .env").option("--agent <id>","agent to bind the bot to").option("-c, --config <path>","path to agentx.json").action(async e=>{await Oi({agent:e.agent,configPath:e.config})});$o.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 Ri({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var _i=$o.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");_i.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 Di({url:e.url,configPath:e.config})});_i.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 Ni(e,{configPath:o.config})});$o.action(()=>{console.log(),console.log(wo.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${wo.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${wo.cyan("agentx connect discord")} \u2014 pair a Discord bot, emit install URL`),console.log(` ${wo.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${wo.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${wo.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(wo.dim(" GitLab connect is the next slice.")),console.log()});import{Command as kc}from"commander";import oe from"chalk";var nt=new kc().name("usage").description("token usage analysis and reporting");nt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=L(),[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(oe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(oe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${oe.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: ${oe.red(String(s.totalErrors))}`),console.log(),console.log(oe.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 d=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${oe.cyan(a)}: ${d} tokens (${c.tasks} tasks) ${oe.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(oe.red(" Daemon not running. Start with: agentx daemon start")):console.log(oe.red(` ${e.message}`))}});nt.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(oe.red(` Script not found: ${s}`)),console.log(oe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(oe.dim(" Analyzing Claude Code sessions..."));try{o(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(oe.red(" Analysis failed. Is Python 3 installed?"))}});nt.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-PRL6Z4U3.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-SAUNRCCD.js"),r=await i(),a=new Set(n.filter(l=>l.kind==="cli").map(l=>l.name)),c=[],d=(l,u)=>{for(let m of l.commands??[]){let f=u?`${u} ${m.name()}`:m.name();c.push(f),d(m,f)}};d(r,"");let g=c.filter(l=>!a.has(l)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(oe.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let l of g)console.log(` ${oe.dim("\xB7")} ${l}`);console.log(),console.log(oe.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(oe.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(oe.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(oe.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(oe.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let i of n){i.kind!==s&&(console.log(oe.dim(` ${i.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=i.kind);let r=String(i.count).padStart(6),a=oe.dim(`${i.days}d`);console.log(` ${oe.cyan(r)} ${i.name.padEnd(28)} ${a}`)}console.log(),console.log(oe.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as vc}from"commander";import re from"chalk";var oo=new vc().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");oo.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{let o=xc(e.port,e.bind),{startBoardDashboard:t}=await import("./board-dashboard-M3372FLO.js");t(o)}catch(o){console.log(re.red(` ${o.message}`)),process.env.DEBUG&&o.stack&&console.log(re.dim(o.stack)),process.exit(1)}});function xc(e,o){try{let t=L();return e&&(t.dashboard.port=parseInt(e,10)),o&&(t.dashboard.bind=o),t}catch{return console.log(re.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(re.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
213
213
|
`)),{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}}}}oo.command("list").description("list configured boards").action(()=>{try{let e=L();if(!e.boards?.length){console.log(re.dim(`
|
|
214
214
|
No boards configured.
|
|
215
215
|
`));return}console.log();for(let o of e.boards){console.log(` ${re.cyan(o.id)} \u2014 ${o.name}`);let t=o.source;console.log(re.dim(` source: ${t.type}${t.projects?" ("+t.projects.join(", ")+")":""}`)),o.primaryToolLabel&&console.log(re.dim(` primary label: ${o.primaryToolLabel}`)),console.log(re.dim(` window: ${o.timeRangeDays} days`))}console.log()}catch(e){console.log(re.red(` ${e.message}`)),process.exit(1)}});oo.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. 'mtgl/system,mtgl/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{st(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(re.red(` ${t.message}`)),process.exit(1)}});oo.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{st(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(re.red(` ${t.message}`)),process.exit(1)}});var Dn=oo.command("column").description("manage a board's columns (add / remove / edit / list)");Dn.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let t=(JSON.parse(Ar("fs").readFileSync("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!t)throw new Error(`board "${e}" not found`);let n=t.columns||[];if(n.length===0){console.log(re.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(` ${re.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${re.dim(i)}`)}}catch(o){console.log(re.red(` ${o.message}`)),process.exit(1)}});Dn.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{st(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(re.red(` ${n.message}`)),process.exit(1)}});Dn.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,o)=>{try{st(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(re.red(` ${t.message}`)),process.exit(1)}});oo.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{st(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(re.red(` ${o.message}`)),process.exit(1)}});function st(e){let{summary:o,backupPath:t}=Ao(n=>e(n));console.log(re.green(`
|
|
@@ -297,7 +297,7 @@ Output (JSON array, one entry per input article, same order):
|
|
|
297
297
|
[
|
|
298
298
|
{"path": "path/to/article.md", "type": "project"},
|
|
299
299
|
...
|
|
300
|
-
]`}ae.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ve(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(p.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${p.dim(s.date)} ${p.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(p.dim(` ... showing last 20 of ${n.length}`)),console.log()});ae.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||N(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-7FSZFRTQ.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(p.bold(" AgentX Wiki Server")),console.log(),console.log(` ${p.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${p.cyan(e.agent)}`):console.log(` Mode: ${p.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${p.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(p.dim(` Wiki: ${o}`)),console.log(p.dim(" Press Ctrl+C to stop")),console.log(),Ys(o,t,e.agent,n,e.mode)});ae.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-HZYYRCLU.js"),n=ve(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let d=n.getAgentWiki(c),g=N(d.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(p.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(p.bold(` Q: ${e}`)),console.log(p.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(p.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(p.dim(" Citations:"));for(let c of a.citations){let d=c.type?p.magenta(` [${c.type}]`):"";console.log(p.dim(` - ${c.title}${d} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(p.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(p.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(d=>!a.candidates.some(g=>g.path===d.path));console.log(p.dim(` followed: ${c.map(d=>`${d.title}@h${d.hop}`).join(" | ")}`))}console.log()}});ae.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action((e,o)=>{let t=ve(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=t.getAgentWiki(i).findRelevant(e,void 0,10);if(a.length>0){console.log(p.bold(` ${p.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(p.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(p.dim(" No matching articles")),console.log()});ae.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=ve(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=N(process.cwd(),".agentx/graph");if(!Re(n)){console.log(p.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new ao({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[l,u]of Object.entries(i.entries))r.set(l,u.path);if(r.size===0){console.log(p.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(p.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,d=0,g=0;for(let l of t){let u=o.getAgentWiki(l),m=u.listArticles(l),f=o.getSharedStore().listEntries(),y=new Map(f.map(S=>[S.id,S])),$=0,v=0,b=0;for(let S of m){if(a++,S.meta.graphPath?.length||!S.meta.sources?.length)continue;$++,c++;let x=new Map;for(let A of S.meta.sources){let I=y.get(A);if(!I)continue;let J=String(I.meta?.sender??""),B=s.fingerprint({text:I.content,channel:I.source,sender:J}),D=r.get(B);if(!D?.length)continue;let ke=D.join("/"),Se=x.get(ke);Se?Se.n++:x.set(ke,{path:D,n:1})}if(x.size===0)continue;v++,d++;let k;for(let A of x.values())(!k||A.n>k.n)&&(k=A);k&&(e.dryRun||(u.writeArticle(S.path,{...S.meta,graphPath:k.path},S.content,l),b++,g++))}console.log(` ${p.cyan(l)}: ${p.bold(m.length)} articles \xB7 ${$} eligible \xB7 ${v} matched \xB7 ${p.green(b)} written`)}console.log(),console.log(p.bold(` Total: ${a} articles, ${c} missing graphPath, ${d} matched (${Math.round(d/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(p.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ae.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.67.108.119:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=ve(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-7FSZFRTQ.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(p.red(" No --peer specified and no daemon config found")),console.log(p.dim(" Usage: agentx wiki sync --peer http://100.67.108.119:19900"));return}if(n.length===0){console.log(p.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(p.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(p.red(` HTTP ${a.status}`));continue}let c=await a.json(),d=c.entries||[],g=c.nodeId||"unknown";console.log(p.dim(` Node: ${g} \u2014 ${d.length} entries`));let l=0;for(let u of d)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),l++);l>0?console.log(p.green(` ${l} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(p.dim(" Already up to date")),i+=l;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let m=await u.json();for(let f of m.agents||[])f.totalEntries>0&&console.log(p.dim(` ${f.agentId}: ${f.totalEntries} entries, ${f.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(p.red(" Connection refused")):console.log(p.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(p.green(` ${i} entries synced.`)):i>0?console.log(p.dim(` ${i} entries would be synced (dry run)`)):console.log(p.dim(" All peers up to date")),console.log()});ae.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||N(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let d=new Zt(o,void 0,c),l=d.getAgentWiki(t).rebuildIndex(),u=d.getAgentEntries(t),m=d.getUnabsorbedEntries(t),f=new Set,y=0,$=new Set;for(let b of l.articles){for(let S of b.tags||[])f.add(S);y+=b.tags?.length||0;for(let S of b.sources||[])$.add(S)}let v=new Set(l.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:_n(c),articles:l.articles.length,entries:u.length,unabsorbed:m.length,uniqueTags:f.size,avgTags:l.articles.length>0?(y/l.articles.length).toFixed(1):"0",dirs:v.size,coverage:$.size,articleList:l.articles}});console.log(),console.log(p.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,d]of r){let g=s.map(l=>d(l).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,d)=>{let g=Math.max(...s.map(u=>u[c])),l=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(p.dim(` Best ${d}: ${l.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ae.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?N(process.cwd(),o.dir):N(process.cwd(),".agentx/wiki");Re(t)||(console.log(p.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?N(process.cwd(),e):N(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=N(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(p.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),d=c("tar",a,{stdio:"inherit"});d.status!==0&&(console.log(p.red(` tar exited with ${d.status}`)),process.exit(d.status||1));let{statSync:g}=await import("fs"),l=Re(s)?g(s).size:0;console.log(),console.log(p.green(` \u2713 wrote ${s} (${Tc(l)})`)),console.log(p.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ae.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=N(process.cwd(),e);Re(t)||(console.log(p.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?N(process.cwd(),o.dir):N(process.cwd(),".agentx/wiki");Re(n)&&!o.force&&(console.log(p.yellow(` ${n} already exists.`)),console.log(p.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=N(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(p.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(p.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(p.green(` \u2713 restored to ${n}`)),console.log(p.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Tc(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}import{Command as Dc}from"commander";import P from"chalk";import{resolve as Pn}from"path";import{existsSync as Nc}from"fs";var rt=new Dc().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");rt.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=L();if(!o.graph?.enabled){console.log(P.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(P.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(P.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new ao({baseDir:Pn(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(P.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(P.bold(` Graph review \u2014 ${r.length} pending`)),console.log(P.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let d=0,g=0,l=0,u=0;for(let f=0;f<r.length;f++){let y=r[f],$=is(y.path,c)||y.path.join(" \u203A ");process.stdout.write(` [${f+1}/${r.length}] ${P.cyan(y.msgHash.slice(0,8))} ${P.dim($)} ... `);let v=_c(y,a,c),b=null;try{b=await Pc(n,t,v,o.dashboard?.token)}catch(k){u++,console.log(P.red(`ERR ${k.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(P.red("ERR no decision"));continue}let S=String(b.decision).toLowerCase().trim(),x=(b.reason||"").toString().slice(0,180);if(S==="approve")if(console.log(P.green("APPROVE")+" "+P.dim(x)),e.dryRun)d++;else try{Mc(i,y,a,c,t),i.updateClassificationStatus(y.msgHash,{status:"approved",reviewer:t,reviewReason:x}),d++}catch(k){console.log(P.yellow(` (commit failed, staying pending: ${k.message?.slice(0,100)})`)),u++}else S==="reject"?(console.log(P.red("REJECT")+" "+P.dim(x)),e.dryRun||i.updateClassificationStatus(y.msgHash,{status:"rejected",reviewer:t,reviewReason:x}),g++):(console.log(P.yellow("SKIP")+" "+P.dim(x||S)),l++)}console.log();let m=e.dryRun?"would":"did";console.log(P.dim(` Summary: ${m} approve ${d}, ${m} reject ${g}, ${l} skipped, ${u} errors.`)),e.dryRun&&(d>0||g>0)&&console.log(P.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});rt.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=L();if(!o.graph){console.log(P.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Pn(process.cwd(),o.graph.baseDir);if(!Nc(t)){console.log(P.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-QO7SLKIM.js"),s=new ao({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(P.dim(" "),...a)});console.log(),console.log(P.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(P.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(P.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(P.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});rt.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://clawd.noqta.tn:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=L();if(!o.graph?.enabled){console.log(P.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new ao({baseDir:Pn(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(I=>I.id));console.log(),console.log(P.bold(` graph pull \u2190 ${t}`));let d,g,l;try{let I=await fetch(`${t}/graph/schema`,{headers:s});if(!I.ok)throw new Error(`schema HTTP ${I.status}`);d=(await I.json()).schema;let B=await fetch(`${t}/graph/nodes`,{headers:s});if(!B.ok)throw new Error(`nodes HTTP ${B.status}`);g=(await B.json()).nodes||[];let D=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!D.ok)throw new Error(`classifications HTTP ${D.status}`);l=(await D.json()).classifications||[]}catch(I){console.log(P.red(` fetch failed: ${I.message}`));return}let u=r.levels.map(I=>I.id).join(","),m=d?.levels?.map(I=>I.id).join(","),f=u===m;f?console.log(P.dim(` schema matches (${r.levels.length} levels)`)):(console.log(P.yellow(" \u26A0 schema levels differ:")),console.log(P.dim(` local: ${u}`)),console.log(P.dim(` peer: ${m}`)),a.length===0&&!e.dryRun?(console.log(P.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(d)):console.log(P.yellow(" keeping local schema; node import may fail if levels disagree")));let y=f?r:d,$=new Map;y.levels.forEach((I,J)=>$.set(I.id,J));let v=[...g].sort((I,J)=>($.get(I.level)??99)-($.get(J.level)??99)),b=0,S=0,x=0;for(let I of v){if(c.has(I.id)){S++;continue}if(e.dryRun){b++,c.add(I.id);continue}try{i.addNode({...I,createdBy:I.createdBy?`${I.createdBy} (sync)`:`sync:${t}`}),c.add(I.id),b++}catch(J){x++,console.log(P.yellow(` skip node ${I.id}: ${J.message?.slice(0,100)}`))}}console.log(P.dim(` nodes: +${b} added \xB7 ${S} already-present \xB7 ${x} failed`));let k=0,A=0;for(let I of l)if(!(!I.msgHash||!Array.isArray(I.path))){if(i.getFingerprint(I.msgHash)){A++;continue}if(e.dryRun){k++;continue}i.setFingerprint(I.msgHash,{path:I.path,leaf:I.leaf||{}}),k++}console.log(P.dim(` fingerprints: +${k} cached \xB7 ${A} already-present`)),console.log(),e.dryRun?console.log(P.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(P.green(` \u2713 pulled from ${t}`)),console.log()});function _c(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
300
|
+
]`}ae.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ve(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(p.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${p.dim(s.date)} ${p.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(p.dim(` ... showing last 20 of ${n.length}`)),console.log()});ae.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","serve only this agent's wiki").option("--port <n>","port number","4200").option("--peer <urls...>","mesh peer URLs to federate").action(async e=>{let o=e.dir||N(process.cwd(),".agentx/wiki"),t=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-A4RWEJHV.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(p.bold(" AgentX Wiki Server")),console.log(),console.log(` ${p.green(">")} http://localhost:${t}`),e.agent?console.log(` Agent: ${p.cyan(e.agent)}`):console.log(` Mode: ${p.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${p.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(p.dim(` Wiki: ${o}`)),console.log(p.dim(" Press Ctrl+C to stop")),console.log(),Ys(o,t,e.agent,n,e.mode)});ae.command("query <question>").description("agentic wiki query \u2014 walks the catalog + wikilink graph, synthesizes an answer").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to query (default: first one with a catalog)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","synthesis model","sonnet").option("--max-candidates <n>","candidates from selector","3").option("--max-hops <n>","wikilink hops from candidates","2").option("--max-articles <n>","cap on total articles walked","8").option("--json","emit full result as JSON (for A/B harnesses)").option("--trace","print selector + walk trace").action(async(e,o)=>{let{agenticQuery:t}=await import("./query-HZYYRCLU.js"),n=ve(o.dir),s=o.agent?[o.agent]:n.listAgents(),i=null;for(let c of s){let d=n.getAgentWiki(c),g=N(d.baseDir,"_index.md");try{if((await import("fs")).existsSync(g)){i=c;break}}catch{}}if(!i){console.log(p.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await t(e,r,i,{selectorModel:o.selectorModel,synthModel:o.synthModel,maxCandidates:parseInt(o.maxCandidates),maxHops:parseInt(o.maxHops),maxArticles:parseInt(o.maxArticles)});if(o.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(p.bold(` Q: ${e}`)),console.log(p.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(p.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(p.dim(" Citations:"));for(let c of a.citations){let d=c.type?p.magenta(` [${c.type}]`):"";console.log(p.dim(` - ${c.title}${d} (${c.path})`))}console.log()}if(o.trace&&a.trace){if(console.log(p.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(p.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(d=>!a.candidates.some(g=>g.path===d.path));console.log(p.dim(` followed: ${c.map(d=>`${d.title}@h${d.hop}`).join(" | ")}`))}console.log()}});ae.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","search specific agent's wiki").action((e,o)=>{let t=ve(o.dir,o.mode),n=o.agent?[o.agent]:t.listAgents();console.log();let s=0;for(let i of n){let a=t.getAgentWiki(i).findRelevant(e,void 0,10);if(a.length>0){console.log(p.bold(` ${p.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(p.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(p.dim(" No matching articles")),console.log()});ae.command("backfill-graphpath").description("populate graphPath on existing articles by looking up source-entry classifications").option("--dir <path>","wiki directory").option("--agent <id>","backfill only this agent").option("--dry-run","preview without writing",!1).action(e=>{let o=ve(e.dir),t=e.agent?[e.agent]:o.listAgents(),n=N(process.cwd(),".agentx/graph");if(!Re(n)){console.log(p.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new ao({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[l,u]of Object.entries(i.entries))r.set(l,u.path);if(r.size===0){console.log(p.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(p.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,d=0,g=0;for(let l of t){let u=o.getAgentWiki(l),m=u.listArticles(l),f=o.getSharedStore().listEntries(),y=new Map(f.map(S=>[S.id,S])),$=0,v=0,b=0;for(let S of m){if(a++,S.meta.graphPath?.length||!S.meta.sources?.length)continue;$++,c++;let x=new Map;for(let A of S.meta.sources){let I=y.get(A);if(!I)continue;let J=String(I.meta?.sender??""),B=s.fingerprint({text:I.content,channel:I.source,sender:J}),D=r.get(B);if(!D?.length)continue;let ke=D.join("/"),Se=x.get(ke);Se?Se.n++:x.set(ke,{path:D,n:1})}if(x.size===0)continue;v++,d++;let k;for(let A of x.values())(!k||A.n>k.n)&&(k=A);k&&(e.dryRun||(u.writeArticle(S.path,{...S.meta,graphPath:k.path},S.content,l),b++,g++))}console.log(` ${p.cyan(l)}: ${p.bold(m.length)} articles \xB7 ${$} eligible \xB7 ${v} matched \xB7 ${p.green(b)} written`)}console.log(),console.log(p.bold(` Total: ${a} articles, ${c} missing graphPath, ${d} matched (${Math.round(d/Math.max(1,c)*100)}%), ${g} written`)),e.dryRun&&console.log(p.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});ae.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.67.108.119:19900)").option("--dry-run","show what would be synced without writing").action(async e=>{let t=ve(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-A4RWEJHV.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(p.red(" No --peer specified and no daemon config found")),console.log(p.dim(" Usage: agentx wiki sync --peer http://100.67.108.119:19900"));return}if(n.length===0){console.log(p.dim(" No mesh peers configured"));return}let s=new Set(t.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(p.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(p.red(` HTTP ${a.status}`));continue}let c=await a.json(),d=c.entries||[],g=c.nodeId||"unknown";console.log(p.dim(` Node: ${g} \u2014 ${d.length} entries`));let l=0;for(let u of d)s.has(u.id)||(e.dryRun||(t.addEntry({id:u.id,date:u.date,agentId:u.agentId,source:`${u.source}@${g}`,sourceContext:u.sourceContext,content:u.content}),s.add(u.id)),l++);l>0?console.log(p.green(` ${l} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(p.dim(" Already up to date")),i+=l;try{let u=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(u.ok){let m=await u.json();for(let f of m.agents||[])f.totalEntries>0&&console.log(p.dim(` ${f.agentId}: ${f.totalEntries} entries, ${f.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(p.red(" Connection refused")):console.log(p.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(p.green(` ${i} entries synced.`)):i>0?console.log(p.dim(` ${i} entries would be synced (dry run)`)):console.log(p.dim(" All peers up to date")),console.log()});ae.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(e=>{let o=e.dir||N(process.cwd(),".agentx/wiki"),t=e.agent,s=["flat","graph","unified"].map(c=>{let d=new Zt(o,void 0,c),l=d.getAgentWiki(t).rebuildIndex(),u=d.getAgentEntries(t),m=d.getUnabsorbedEntries(t),f=new Set,y=0,$=new Set;for(let b of l.articles){for(let S of b.tags||[])f.add(S);y+=b.tags?.length||0;for(let S of b.sources||[])$.add(S)}let v=new Set(l.articles.map(b=>b.path.includes("/")?b.path.split("/")[0]:"/"));return{mode:c,label:_n(c),articles:l.articles.length,entries:u.length,unabsorbed:m.length,uniqueTags:f.size,avgTags:l.articles.length>0?(y/l.articles.length).toFixed(1):"0",dirs:v.size,coverage:$.size,articleList:l.articles}});console.log(),console.log(p.bold(` Wiki Compare: ${t}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let i=22;console.log(` ${"".padEnd(20)} ${s.map(c=>c.label.padEnd(i)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(i)).join(" ")}`);let r=[["Articles",c=>String(c.articles)],["Unabsorbed",c=>String(c.unabsorbed)],["Unique tags",c=>String(c.uniqueTags)],["Avg tags/article",c=>c.avgTags],["Directories",c=>String(c.dirs)],["Entry coverage",c=>`${c.coverage}/${c.entries}`]];for(let[c,d]of r){let g=s.map(l=>d(l).padEnd(i));console.log(` ${c.padEnd(20)} ${g.join(" ")}`)}console.log();let a=(c,d)=>{let g=Math.max(...s.map(u=>u[c])),l=s.filter(u=>u[c]===g).map(u=>u.label);g>0&&console.log(p.dim(` Best ${d}: ${l.join(", ")} (${g})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});ae.command("export [output]").description("export the entire wiki tree to a .tar.gz").option("--dir <path>","wiki directory to archive (default: .agentx/wiki)").option("--include-raw","also include raw entries (.agentx/wiki/raw/) \u2014 bigger archive").action(async(e,o)=>{let t=o.dir?N(process.cwd(),o.dir):N(process.cwd(),".agentx/wiki");Re(t)||(console.log(p.red(` Wiki dir not found: ${t}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?N(process.cwd(),e):N(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=N(t,".."),r=t.split("/").pop()||"wiki",a=["-C",i,"-czf",s];o.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(p.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),d=c("tar",a,{stdio:"inherit"});d.status!==0&&(console.log(p.red(` tar exited with ${d.status}`)),process.exit(d.status||1));let{statSync:g}=await import("fs"),l=Re(s)?g(s).size:0;console.log(),console.log(p.green(` \u2713 wrote ${s} (${Tc(l)})`)),console.log(p.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});ae.command("import <archive>").description("restore a wiki archive (created with `agentx wiki export`)").option("--dir <path>","where to restore (default: .agentx/wiki)").option("--force","overwrite existing wiki without prompting").action(async(e,o)=>{let t=N(process.cwd(),e);Re(t)||(console.log(p.red(` archive not found: ${t}`)),process.exit(1));let n=o.dir?N(process.cwd(),o.dir):N(process.cwd(),".agentx/wiki");Re(n)&&!o.force&&(console.log(p.yellow(` ${n} already exists.`)),console.log(p.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=N(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",t];console.log(p.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(p.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(p.green(` \u2713 restored to ${n}`)),console.log(p.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function Tc(e){return e<1024?e+"B":e<1024*1024?(e/1024).toFixed(1)+"K":e<1024*1024*1024?(e/1024/1024).toFixed(1)+"M":(e/1024/1024/1024).toFixed(2)+"G"}import{Command as Dc}from"commander";import P from"chalk";import{resolve as Pn}from"path";import{existsSync as Nc}from"fs";var rt=new Dc().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");rt.command("review").description("triage pending classifications via the configured review agent (the agent uses `wiki query` for context before deciding)").option("--agent <id>","override the review agent (defaults to graph.reviewAgent or graph.draftAgent)").option("--max <n>","cap reviews this run","20").option("--dry-run","show the agent's decision but don't apply approvals/rejections").option("--daemon-url <url>","daemon URL (default: http://localhost:18800)").action(async e=>{let o=L();if(!o.graph?.enabled){console.log(P.yellow(" graph.enabled is false \u2014 nothing to review"));return}let t=e.agent||o.graph.reviewAgent||o.graph.draftAgent;if(!t){console.log(P.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!o.agents?.[t]){console.log(P.red(` agent "${t}" not in config`));return}let n=(e.daemonUrl||o.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new ao({baseDir:Pn(process.cwd(),o.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(P.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(P.bold(` Graph review \u2014 ${r.length} pending`)),console.log(P.dim(` Reviewer: ${t} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let d=0,g=0,l=0,u=0;for(let f=0;f<r.length;f++){let y=r[f],$=is(y.path,c)||y.path.join(" \u203A ");process.stdout.write(` [${f+1}/${r.length}] ${P.cyan(y.msgHash.slice(0,8))} ${P.dim($)} ... `);let v=_c(y,a,c),b=null;try{b=await Pc(n,t,v,o.dashboard?.token)}catch(k){u++,console.log(P.red(`ERR ${k.message?.slice(0,80)}`));continue}if(!b||!b.decision){u++,console.log(P.red("ERR no decision"));continue}let S=String(b.decision).toLowerCase().trim(),x=(b.reason||"").toString().slice(0,180);if(S==="approve")if(console.log(P.green("APPROVE")+" "+P.dim(x)),e.dryRun)d++;else try{Mc(i,y,a,c,t),i.updateClassificationStatus(y.msgHash,{status:"approved",reviewer:t,reviewReason:x}),d++}catch(k){console.log(P.yellow(` (commit failed, staying pending: ${k.message?.slice(0,100)})`)),u++}else S==="reject"?(console.log(P.red("REJECT")+" "+P.dim(x)),e.dryRun||i.updateClassificationStatus(y.msgHash,{status:"rejected",reviewer:t,reviewReason:x}),g++):(console.log(P.yellow("SKIP")+" "+P.dim(x||S)),l++)}console.log();let m=e.dryRun?"would":"did";console.log(P.dim(` Summary: ${m} approve ${d}, ${m} reject ${g}, ${l} skipped, ${u} errors.`)),e.dryRun&&(d>0||g>0)&&console.log(P.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});rt.command("migrate").description("remap past classifications from v1 (scope/location/org/unit/activity) to v2 (category/verb) via keyword heuristics. No LLM calls. Idempotent.").option("--dry-run","report what would change, don't write").action(async e=>{let o=L();if(!o.graph){console.log(P.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let t=Pn(process.cwd(),o.graph.baseDir);if(!Nc(t)){console.log(P.yellow(` ${t} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-QO7SLKIM.js"),s=new ao({baseDir:t,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(P.dim(" "),...a)});console.log(),console.log(P.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(P.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(P.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(P.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});rt.command("pull").description("pull schema + nodes + approved classifications from a peer's graph").requiredOption("--from <url>","peer daemon URL (e.g. http://clawd.noqta.tn:19900)").option("--token <t>","bearer token for the peer (if it requires auth)").option("--limit <n>","max approved classifications to pull","500").option("--dry-run","show what would change, don't write").action(async e=>{let o=L();if(!o.graph?.enabled){console.log(P.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let t=String(e.from).replace(/\/+$/,""),n=Math.max(1,parseInt(e.limit)||500),s={Accept:"application/json"};e.token&&(s.Authorization=`Bearer ${e.token}`);let i=new ao({baseDir:Pn(process.cwd(),o.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(I=>I.id));console.log(),console.log(P.bold(` graph pull \u2190 ${t}`));let d,g,l;try{let I=await fetch(`${t}/graph/schema`,{headers:s});if(!I.ok)throw new Error(`schema HTTP ${I.status}`);d=(await I.json()).schema;let B=await fetch(`${t}/graph/nodes`,{headers:s});if(!B.ok)throw new Error(`nodes HTTP ${B.status}`);g=(await B.json()).nodes||[];let D=await fetch(`${t}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!D.ok)throw new Error(`classifications HTTP ${D.status}`);l=(await D.json()).classifications||[]}catch(I){console.log(P.red(` fetch failed: ${I.message}`));return}let u=r.levels.map(I=>I.id).join(","),m=d?.levels?.map(I=>I.id).join(","),f=u===m;f?console.log(P.dim(` schema matches (${r.levels.length} levels)`)):(console.log(P.yellow(" \u26A0 schema levels differ:")),console.log(P.dim(` local: ${u}`)),console.log(P.dim(` peer: ${m}`)),a.length===0&&!e.dryRun?(console.log(P.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(d)):console.log(P.yellow(" keeping local schema; node import may fail if levels disagree")));let y=f?r:d,$=new Map;y.levels.forEach((I,J)=>$.set(I.id,J));let v=[...g].sort((I,J)=>($.get(I.level)??99)-($.get(J.level)??99)),b=0,S=0,x=0;for(let I of v){if(c.has(I.id)){S++;continue}if(e.dryRun){b++,c.add(I.id);continue}try{i.addNode({...I,createdBy:I.createdBy?`${I.createdBy} (sync)`:`sync:${t}`}),c.add(I.id),b++}catch(J){x++,console.log(P.yellow(` skip node ${I.id}: ${J.message?.slice(0,100)}`))}}console.log(P.dim(` nodes: +${b} added \xB7 ${S} already-present \xB7 ${x} failed`));let k=0,A=0;for(let I of l)if(!(!I.msgHash||!Array.isArray(I.path))){if(i.getFingerprint(I.msgHash)){A++;continue}if(e.dryRun){k++;continue}i.setFingerprint(I.msgHash,{path:I.path,leaf:I.leaf||{}}),k++}console.log(P.dim(` fingerprints: +${k} cached \xB7 ${A} already-present`)),console.log(),e.dryRun?console.log(P.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(P.green(` \u2713 pulled from ${t}`)),console.log()});function _c(e,o,t){let n={};for(let r of t)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=o.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
301
301
|
`),i=JSON.stringify(e.proposedAxes||{},null,2);return["You are reviewing a pending intent classification. Decide whether it is reasonable.","","--- MESSAGE (first 500 chars) ---",(e.preview||"").slice(0,500),`channel: ${e.channel||"?"} \xB7 sender: ${e.sender||"?"}`,"","--- PROPOSED PATH ---",e.path.join(" \u203A "),"","--- PROPOSED AXES (per new node) ---",i,"","--- CURRENT NODES BY LEVEL (first 10 per level) ---",s,"","--- YOUR JOB ---","Decide one of:"," approve \u2014 the path is right and the axes make sense for the message"," reject \u2014 the path is wrong (e.g. the message is NOT about the proposed org/topic, or the axes are bogus)"," skip \u2014 you can't confidently decide; leave it for a human","",'BEFORE you decide, you MAY call `agentx wiki query` (via Bash) to check institutional context \u2014 e.g. "is there an article for this project" or "who is this person". This is optional; don\'t call it for obvious cases.',"","Bias toward reject over approve when uncertain. A wrong approval pollutes the graph; a wrong rejection just keeps the entry pending.","","Return EXACTLY one JSON object on one line, no prose, no fences:",' {"decision":"approve"|"reject"|"skip","reason":"one sentence"}'].join(`
|
|
302
302
|
`)}async function Pc(e,o,t,n){let s={"Content-Type":"application/json"};n&&(s.Authorization=`Bearer ${n}`);let i=new AbortController,r=setTimeout(()=>i.abort(),12e4);try{let a=await fetch(`${e}/task`,{method:"POST",headers:s,body:JSON.stringify({agent:o,message:t,context:{channel:"a2a",sender:"graph-review"}}),signal:i.signal});if(!a.ok)throw new Error(`daemon /task HTTP ${a.status}`);let c=await a.json();if(c?.error)throw new Error(String(c.error));return Lc((c?.content||"").toString())}finally{clearTimeout(r)}}function Mc(e,o,t,n,s){e.commitNodesAlongPath(o.path,o.proposedAxes||{},t,s),e.setFingerprint(o.msgHash,{path:o.path,leaf:o.leaf||{}})}function Lc(e){if(!e)return null;try{return JSON.parse(e)}catch{}let o=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(o)try{return JSON.parse(o[1])}catch{}let t=e.indexOf("{");if(t<0)return null;let n=0;for(let s=t;s<e.length;s++)if(e[s]==="{")n++;else if(e[s]==="}"&&(n--,n===0))try{return JSON.parse(e.slice(t,s+1))}catch{return null}return null}import{Command as qc}from"commander";import W from"chalk";import{Command as Bi}from"commander";import V from"chalk";import{existsSync as Uc}from"fs";import{resolve as Wc}from"path";import Jc from"better-sqlite3";function Bc(e){if(!e)return;let o=/^(\d+)\s*([smhd])$/.exec(e.trim());if(o){let n=Number(o[1]),s=o[2];return Date.now()-n*(s==="s"?1e3:s==="m"?6e4:s==="h"?36e5:864e5)}let t=Number(e);if(Number.isFinite(t)&&t>0)return t;console.log(V.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}function Fc(e){let o=Wc(process.cwd(),e);return Uc(o)||(console.log(V.red(` No db at ${o}`)),process.exit(1)),new Jc(o,{readonly:!0})}var Fi=new Bi().name("extract").description("mine recurring user activity into procedure drafts (dry-run by default)").option("--path <path>","SQLite db path",".agentx/db.sqlite").option("--since <duration>","activity window, e.g. 24h, 7d, or ms epoch","7d").option("--agent <id>","only mine one agent's activity").option("--min-occurrences <n>","recurrences before a pattern becomes a draft",String(Yo)).option("--max <n>","max clusters distilled per run",String($t)).option("--via <agentId>","route the LLM call through a running agent \u2014 uses the agent's own session").option("--model <model>","direct Anthropic API model \u2014 needs ANTHROPIC_API_KEY").option("--daemon <url>","daemon API base URL for --via","http://127.0.0.1:18800").option("--commit","write drafts and persist recurrence counts",!1).action(async e=>{e.commit&&!e.via&&!e.model&&(console.log(V.red(" --commit needs an LLM: pass --via <agentId> or --model <model>")),process.exit(1));let o=Fc(e.path),t=await Cs(o,{since:Bc(e.since),agentId:e.agent,sessions:new ss(process.cwd()),minOccurrences:Number(e.minOccurrences)||Yo,max:Number(e.max)||$t,commit:!!e.commit,llm:{viaAgent:e.via,model:e.model,daemonUrl:e.daemon,chatId:"procedure-miner"},log:n=>console.log(V.dim(` ${n}`))});console.log(),console.log(` ${t.episodes} episode(s) \u2192 ${t.clusters} cluster(s), ${t.ready.length} at threshold`);for(let n of t.ready)console.log(` ${V.cyan(n.key)} ${V.bold(`\xD7${n.count}`)} ${V.dim(n.status)}`),n.sampleMessage&&console.log(V.dim(` "${n.sampleMessage.slice(0,100)}"`));if(t.nearMisses.length){console.log(V.dim(`
|
|
303
303
|
near-misses (same intent, different activity shape \u2014 tuning signal):`));for(let n of t.nearMisses.slice(0,5))console.log(V.dim(` ${n.intent} \u2192 ${n.keys.length} variants`))}for(let n of t.drafted)console.log(V.green(` \u2713 draft written: ${n.id}`)+V.dim(` (${n.count} occurrences)`));for(let n of t.skipped)console.log(V.yellow(` skipped ${n.cluster}: ${n.reason}`));for(let n of t.warnings)console.log(V.yellow(` \u26A0 ${n}`));t.dryRun?console.log(V.dim(`
|
|
@@ -327,7 +327,7 @@ Output (JSON array, one entry per input article, same order):
|
|
|
327
327
|
`))});so.command("remove <id>").alias("rm").description("delete an action").action(e=>{new Eo().delete(e)||(console.log(R.red(` no action "${e}"`)),process.exit(1)),console.log(R.green(` \u2713 action "${e}" removed`))});so.command("run <id>").description("invoke an action and print its output").option("--input <kv...>","input as key=value (repeat for each)").option("--json","JSON output (full ActionRunResult)").action(async(e,o)=>{let n=new Eo().get(e);n||(console.log(R.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of o.input||[]){let r=i.indexOf("=");r<0&&(console.log(R.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await ls(n,s);if(o.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?R.green("\u2713 ok"):R.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(R.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(R.dim(" --- errors ---")),console.log(R.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(R.red(` ${i.message}`)),process.exit(1)}});so.command("builtin [name]").description("list registered built-in actions, or run one with --input").option("--input <json>","JSON input matching the action's inputSchema").option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").option("--json","raw JSON output (omit chrome)").option("--schema","show the action's input/output schema instead of running it").action(async(e,o)=>{let t=String(o.daemon).replace(/\/+$/,"");if(!e){try{let s=await fetch(`${t}/api/actions/builtin`);s.ok||(console.log(R.red(` list failed (${s.status}): ${(await s.text()).slice(0,200)}`)),process.exit(1));let r=(await s.json()).actions||[];if(o.json){console.log(JSON.stringify(r,null,2));return}if(r.length===0){console.log(R.dim(" No built-in actions registered. Daemon may not be running, or registerAllBuiltins() didn't fire at boot."));return}console.log(),console.log(R.bold(" Built-in typed actions")),console.log(R.dim(" Invoke: agentx actions builtin <name> --input '<json>'")),console.log();for(let a of r){let c=a.timeoutMs?R.dim(` (timeout=${Math.round(a.timeoutMs/1e3)}s)`):"";console.log(` ${R.cyan(a.name.padEnd(22))} ${a.description||""}${c}`)}console.log()}catch(s){console.log(R.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}return}if(o.schema){try{let r=((await(await fetch(`${t}/api/actions/builtin`)).json()).actions||[]).find(a=>a.name===e);if(r||(console.log(R.red(` unknown action: ${e}`)),process.exit(1)),o.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(R.bold(` ${r.name}`)),r.description&&console.log(R.dim(` ${r.description}`)),console.log(),console.log(R.dim(" --- input schema ---")),console.log(JSON.stringify(r.inputSchema??{},null,2)),r.outputSchema&&(console.log(),console.log(R.dim(" --- output schema ---")),console.log(JSON.stringify(r.outputSchema,null,2))),console.log()}catch(s){console.log(R.red(` schema fetch failed: ${s.message||s}`)),process.exit(1)}return}let n={};if(o.input)try{n=JSON.parse(o.input)}catch(s){console.log(R.red(` --input must be valid JSON: ${s.message}`)),process.exit(1)}try{let s=await fetch(`${t}/api/actions/builtin/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await s.json().catch(()=>({}));if(s.ok||(o.json&&(console.log(JSON.stringify(i,null,2)),process.exit(1)),console.log(R.red(` action failed (${s.status}): ${i.error||JSON.stringify(i).slice(0,300)}`)),process.exit(1)),o.json){console.log(JSON.stringify(i,null,2));return}console.log(JSON.stringify(i,null,2))}catch(s){console.log(R.red(` daemon unreachable: ${s.message||s}`)),process.exit(1)}});function ul(e){if(!e)return[];let o=[];for(let t of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=t.endsWith("!"),s=n?t.slice(0,-1):t,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";o.push({name:r,type:a,required:n})}return o}import{Command as fl}from"commander";import z from"chalk";var cr=new fl().name("watch").description("stream live daemon events \u2014 workflow runs, user tasks, signals, mesh health").option("-c, --config <path>","daemon config file").option("-t, --type <kinds>","comma-separated event kinds (run,task,signal,mesh,channel,status)").option("-w, --workflow <id>","only events for this workflow id").option("-a, --actor <id>","only task events involving this actor id").option("-r, --run <id>","only events for this run id").option("--channel <name>","only channel events on this channel (telegram/whatsapp/\u2026)").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").action(async e=>{let o=typeof e.node=="string"?e.node:"",t=typeof e.token=="string"?e.token:"";if(!o||!t)try{let r=L(e.config);o||(o=r.dashboard?.daemonUrl||""),t||(t=r.dashboard?.token||"")}catch{}o||(o="http://localhost:18800");let n=[];typeof e.type=="string"&&n.push(`type=${encodeURIComponent(e.type)}`),typeof e.workflow=="string"&&n.push(`workflow=${encodeURIComponent(e.workflow)}`),typeof e.actor=="string"&&n.push(`actor=${encodeURIComponent(e.actor)}`),typeof e.run=="string"&&n.push(`run=${encodeURIComponent(e.run)}`),typeof e.channel=="string"&&n.push(`channel=${encodeURIComponent(e.channel)}`);let s=`${o.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(z.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};t&&(i.Authorization=`Bearer ${t}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(z.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(z.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,d="";for(;;){let{done:g,value:l}=await a.read();if(g)break;d+=c.decode(l,{stream:!0});let u;for(;(u=d.indexOf(`
|
|
328
328
|
|
|
329
329
|
`))>=0;){let m=d.slice(0,u);d=d.slice(u+2),hl(m)}}}catch(r){console.error(z.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function hl(e){let o="message",t="";for(let i of e.split(`
|
|
330
|
-
`))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?z.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=z.cyan(n.phase?.padEnd(9)??"run"),r=z.bold(n.workflowId??""),a=z.dim((n.runId??"").slice(0,8)),c=n.nodeId?z.yellow(n.nodeId):"",d=n.note?z.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${d}`);break}case"task":{let i=z.magenta(`task.${n.phase}`.padEnd(14)),r=z.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?z.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${z.cyan(a)} ${c}`);break}case"signal":{let i=z.green("signal".padEnd(9)),r=z.bold(n.name),a=z.dim(`(${n.scope})`),c=n.workflowId?z.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=z.blue("mesh".padEnd(9)),r=z.bold(n.peer),a=n.healthy?z.green("\u2713 healthy"):z.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${z.dim(n.delta??"")}`);break}case"channel":{let i=z.yellow("channel".padEnd(9)),r=n.direction==="in"?z.cyan("\u2190"):z.magenta("\u2192"),a=z.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?z.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(z.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}import{Command as yl}from"commander";import wl from"chalk";import qt from"chalk";function zt(e){console.error(),console.error(qt.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(qt.dim(` ${e.why}`)),console.error(),console.error(` Use ${qt.cyan(e.instead)} instead.`),e.note&&console.error(qt.dim(` ${e.note}`)),console.error()}var Ht={why:"No recorded use on any node since 2026-07-03.",instead:"agentx attach <agent>",note:"Wears the identity in the Claude Code session you already have open \u2014 see docs/reference/attach.md"};var lr=new yl().name("tui").description("[deprecated \u2014 see agentx attach] interactive terminal mission control").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--poll <ms>","snapshot poll interval in ms","3000").action(async e=>{zt({what:"agentx tui",...Ht}),process.stdout.isTTY||(console.error(wl.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-
|
|
330
|
+
`))i.startsWith("event: ")?o=i.slice(7):i.startsWith("data: ")&&(t=i.slice(6));if(!t)return;let n={};try{n=JSON.parse(t)}catch{console.log(`${o}: ${t}`);return}let s=n.at?z.dim(new Date(n.at).toLocaleTimeString()):"";switch(o){case"run":{let i=z.cyan(n.phase?.padEnd(9)??"run"),r=z.bold(n.workflowId??""),a=z.dim((n.runId??"").slice(0,8)),c=n.nodeId?z.yellow(n.nodeId):"",d=n.note?z.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${d}`);break}case"task":{let i=z.magenta(`task.${n.phase}`.padEnd(14)),r=z.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?z.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${z.cyan(a)} ${c}`);break}case"signal":{let i=z.green("signal".padEnd(9)),r=z.bold(n.name),a=z.dim(`(${n.scope})`),c=n.workflowId?z.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=z.blue("mesh".padEnd(9)),r=z.bold(n.peer),a=n.healthy?z.green("\u2713 healthy"):z.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${z.dim(n.delta??"")}`);break}case"channel":{let i=z.yellow("channel".padEnd(9)),r=n.direction==="in"?z.cyan("\u2190"):z.magenta("\u2192"),a=z.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?z.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(z.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${o} ${JSON.stringify(n)}`)}}import{Command as yl}from"commander";import wl from"chalk";import qt from"chalk";function zt(e){console.error(),console.error(qt.yellow(` \u26A0 ${e.what} is deprecated.`)),console.error(qt.dim(` ${e.why}`)),console.error(),console.error(` Use ${qt.cyan(e.instead)} instead.`),e.note&&console.error(qt.dim(` ${e.note}`)),console.error()}var Ht={why:"No recorded use on any node since 2026-07-03.",instead:"agentx attach <agent>",note:"Wears the identity in the Claude Code session you already have open \u2014 see docs/reference/attach.md"};var lr=new yl().name("tui").description("[deprecated \u2014 see agentx attach] interactive terminal mission control").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--poll <ms>","snapshot poll interval in ms","3000").action(async e=>{zt({what:"agentx tui",...Ht}),process.stdout.isTTY||(console.error(wl.red("agentx tui requires an interactive terminal")),process.exit(1));let{resolveConn:o}=await import("./client-HGKAC6VP.js"),{App:t}=await import("./App-BPNHIGUX.js"),{render:n}=await import("ink"),s=(await import("react")).default,i=o({node:e.node,token:e.token,config:e.config}),r=Math.max(500,Number(e.poll)||3e3);await n(s.createElement(t,{conn:i,pollMs:r})).waitUntilExit()});import{Command as $l}from"commander";import F from"chalk";import{randomUUID as dr}from"crypto";import{createInterface as bl}from"node:readline/promises";import kl from"ora";var gr=new $l().name("chat").description("[deprecated \u2014 see agentx attach] interactive chat with a daemon-registered agent").argument("[agent]","agent id to talk to (with or without leading @)").option("-c, --config <path>","daemon config file").option("--node <url>","daemon URL (defaults to dashboard.daemonUrl from config)").option("--token <token>","bearer token (defaults to dashboard.token from config)").option("--channel <name>","logical channel name passed in context","chat-cli").option("--chat-id <id>","resume an existing chatId (otherwise a fresh one is generated)").action(async(e,o)=>{zt({what:"agentx chat",...Ht});let t=Ks({node:o.node,token:o.token,config:o.config}),n=(e??"").replace(/^@/,"").trim(),s=o.channel,i=o.chatId||`chat-cli:${dr().slice(0,12)}`,r=[];try{r=await kt(t)}catch(g){console.error(F.red(` cannot reach daemon at ${t.baseUrl}: ${g?.message||g}`)),console.error(F.dim(" is the daemon running? try: agentx daemon status")),process.exit(1)}if(r.length===0&&(console.error(F.red(" no agents registered with the daemon")),process.exit(1)),n?r.find(g=>g.id===n)||(console.error(F.red(` unknown agent: @${n}`)),console.error(F.dim(` registered: ${r.map(g=>`@${g.id}`).join(", ")}`)),process.exit(1)):(n=r[0].id,console.log(F.dim(` no agent given \u2014 defaulting to @${n}`))),process.stdout.isTTY&&process.stdin.isTTY){let{render:g}=await import("ink"),{ChatApp:l}=await import("./ChatApp-6XSSZB4U.js"),u=(await import("react")).default;await g(u.createElement(l,{conn:t,agentId:n,channel:s,chatId:i,agents:r})).waitUntilExit();return}xl(t.baseUrl,n,i,s);let a=bl({input:process.stdin,output:process.stdout}),c=!1,d=!1;for(a.on("close",()=>{if(c){d=!0;return}console.log(F.dim(`
|
|
331
331
|
bye`)),process.exit(0)});;){let g;try{g=(await a.question(F.cyan("you \u203A "))).trim()}catch{a.close();return}if(!g)continue;if(g==="/exit"||g==="/quit"){a.close();return}if(g==="/who"){console.log(F.dim(` @${n} chatId=${i} channel=${s}`));continue}if(g==="/clear"){i=`chat-cli:${dr().slice(0,12)}`,console.log(F.dim(` fresh chatId=${i} (warm process dropped)`));continue}if(g==="/agents"){try{let f=await kt(t);for(let y of f){let $=y.id===n?F.green("\u25CF"):F.dim("\u25CB");console.log(` ${$} @${y.id} ${F.dim(y.tier)} ${y.model??""}`)}}catch(f){console.error(F.red(` failed to list agents: ${f?.message||f}`))}continue}if(g.startsWith("/agent ")){let f=g.slice(7).replace(/^@/,"").trim();if(!f){console.log(F.red(" usage: /agent <id>"));continue}try{if(!(await kt(t)).find($=>$.id===f)){console.log(F.red(` unknown agent: @${f}`));continue}n=f,console.log(F.dim(` now talking to @${n}`))}catch(y){console.error(F.red(` failed to switch agent: ${y?.message||y}`))}continue}if(g.startsWith("/")){console.log(F.red(` unknown command: ${g.split(/\s+/)[0]}`)),console.log(F.dim(" available: /exit /quit /clear /agent <id> /who /agents"));continue}c=!0;let l=kl({text:`@${n}\u2026`,color:"cyan"}).start(),u=Date.now(),m=vl(n);try{let f=await Vs(t,n,g,{channel:s,chatId:i,onText:$=>{l.stop(),m.text($)},onThinking:()=>{},onTool:$=>{l.stop(),m.tool($)}});l.stop();let y=Math.round((Date.now()-u)/100)/10;f.error?m.finishError(f.error):m.finish(y,f.usage)}catch(f){l.stop(),m.finishError(f?.message||String(f))}finally{c=!1}if(d){console.log(F.dim(" bye"));return}}});function vl(e){let o=!1,t=!0,n=!1,s=new Set,i=()=>{o||(process.stdout.write(`${F.green(`@${e}`)}
|
|
332
332
|
`),o=!0)};return{text(r){if(r){i(),n=!0;for(let a of r)t&&a!==`
|
|
333
333
|
`&&(process.stdout.write(" "),t=!1),process.stdout.write(a),a===`
|
|
@@ -417,7 +417,7 @@ Restart the daemon to activate.
|
|
|
417
417
|
dist/
|
|
418
418
|
*.log
|
|
419
419
|
.env
|
|
420
|
-
`}import{Command as Yl}from"commander";import ue from"chalk";import{writeFileSync as Kl,mkdirSync as Vl,existsSync as Kt,readFileSync as br,appendFileSync as kr}from"fs";import{resolve as qo,dirname as Sr}from"path";import{homedir as es}from"os";var jr=new Yl().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-
|
|
420
|
+
`}import{Command as Yl}from"commander";import ue from"chalk";import{writeFileSync as Kl,mkdirSync as Vl,existsSync as Kt,readFileSync as br,appendFileSync as kr}from"fs";import{resolve as qo,dirname as Sr}from"path";import{homedir as es}from"os";var jr=new Yl().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-SAUNRCCD.js"),t=await o(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Zl(t);break;case"bash":s=sd(t);break;case"fish":s=id(t);break;default:console.error(ue.red(`unsupported shell: ${n}`)),console.error(ue.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?qo(String(e.output)):Ql(n);Vl(Sr(i),{recursive:!0}),Kl(i,s),console.log(ue.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Xl(n,i,!!e.yes)});function Ql(e){let o=es();switch(e){case"zsh":return qo(o,".zsh","completions","_agentx");case"bash":return qo(o,".bash_completion.d","agentx.bash");case"fish":return qo(o,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Xl(e,o,t){if(e==="zsh"){let n=qo(es(),".zshrc"),s=Sr(o),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=Kt(n)?br(n,"utf-8"):"",c=!a.includes(s),d=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!d){console.log(ue.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(t&&Kt(n)){let g=["","# agentx completion"];c&&g.push(i),d&&g.push(r),kr(n,g.join(`
|
|
421
421
|
`)+`
|
|
422
422
|
`),console.log(ue.green("\u2713 Patched ~/.zshrc")),console.log(ue.dim("Reload your shell: exec zsh"));return}console.log(ue.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(ue.cyan(` ${i}`)),d&&console.log(ue.cyan(` ${r}`)),console.log(),console.log(ue.dim("Then reload: exec zsh")),console.log(ue.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=qo(es(),".bashrc"),s=`[ -f "${o}" ] && source "${o}"`;if((Kt(n)?br(n,"utf-8"):"").includes(o)){console.log(ue.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(t&&Kt(n)){kr(n,`
|
|
423
423
|
# agentx completion
|
|
@@ -428,4 +428,4 @@ ${s}
|
|
|
428
428
|
`)}function os(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Zn(e,o){let t=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!t&&!n)return null;let s=os(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 gh(){let e=await Bs(),o=new rd().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=Hs(n);Gs(s)&&zs("cli",s)});for(let t of[ni,ei,$o,De,qs,go,vt,eo,fo,Ze,nt,mr,Vo,Ke,jr])o.addCommand(t);for(let t of Ir)o.addCommand(t,{hidden:!0});return o.addHelpText("after",()=>{let t=Ir.map(n=>n.name()).sort();return["",`Advanced (${t.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,ad(t,74," "),""].join(`
|
|
429
429
|
`)}),o}var Ir=[ae,rt,xo,Te,Xo,_o,de,Be,oo,ho,Uo,Wo,Xe,Zo,Rt,cr,We,To,Do,mt,mn,so,Ro,pn,Ft,Jo,io,yr,gr,lr];function ad(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(`
|
|
430
430
|
`)}export{gh as a};
|
|
431
|
-
//# sourceMappingURL=chunk-
|
|
431
|
+
//# sourceMappingURL=chunk-UHE5FCPB.js.map
|