agentix-cli 0.21.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-I3ILI3MO.js → agent-Y4U4R3ZZ.js} +2 -2
- package/dist/{board-dashboard-ASI6MDKX.js → board-dashboard-2CPBWFOB.js} +4 -4
- package/dist/{chunk-EQNM3TOF.js → chunk-2HXSJYAJ.js} +2 -2
- package/dist/{chunk-K6MC66D6.js → chunk-ABVZHJUO.js} +2 -2
- package/dist/chunk-BHSPAP4U.js +44 -0
- package/dist/chunk-BHSPAP4U.js.map +1 -0
- package/dist/chunk-CO4YCIIA.js +13 -0
- package/dist/{chunk-5GDCJ2SF.js.map → chunk-CO4YCIIA.js.map} +1 -1
- package/dist/{chunk-4MREHZP5.js → chunk-GOLZ6NEL.js} +2 -2
- package/dist/chunk-GOLZ6NEL.js.map +1 -0
- package/dist/{chunk-FUYZUGNQ.js → chunk-KX626FN4.js} +2 -2
- package/dist/chunk-OPKQNLGX.js +450 -0
- package/dist/chunk-OPKQNLGX.js.map +1 -0
- package/dist/chunk-OZOQKPJV.js +102 -0
- package/dist/chunk-OZOQKPJV.js.map +1 -0
- package/dist/{chunk-AANSVC5A.js → chunk-P3TJHGO5.js} +2 -2
- package/dist/{chunk-AGINLNAW.js → chunk-VYLZ7UYM.js} +2 -2
- package/dist/{chunk-2B2DIQKD.js → chunk-WHP4I44J.js} +2 -2
- package/dist/chunk-X5D5AV5N.js +833 -0
- package/dist/chunk-X5D5AV5N.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/{config-RWHSEE4N.js → config-BLOKGMER.js} +2 -2
- package/dist/config-mutator-RG7QY2EL.js +2 -0
- package/dist/doctor-ZTECTUHX.js +2 -0
- package/dist/index.d.ts +140 -3
- package/dist/index.js +1 -1
- package/dist/program-GZOJIWTB.js +2 -0
- package/dist/registry-QZIUSQ5J.js +2 -0
- package/dist/scheduler-B2BQPV4M.js +2 -0
- package/dist/workspace-setup-DQCZX2NE.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-4MREHZP5.js.map +0 -1
- package/dist/chunk-5GDCJ2SF.js +0 -13
- package/dist/chunk-5XZ73VM4.js +0 -102
- package/dist/chunk-5XZ73VM4.js.map +0 -1
- package/dist/chunk-BLRLUF2H.js +0 -743
- package/dist/chunk-BLRLUF2H.js.map +0 -1
- package/dist/chunk-IFQQVDM6.js +0 -442
- package/dist/chunk-IFQQVDM6.js.map +0 -1
- package/dist/chunk-ZE2YFX4K.js +0 -45
- package/dist/chunk-ZE2YFX4K.js.map +0 -1
- package/dist/config-mutator-JKCNCY2F.js +0 -2
- package/dist/doctor-KWN7NUFQ.js +0 -2
- package/dist/program-JEKM7SCS.js +0 -2
- package/dist/registry-EGKDMVSP.js +0 -2
- package/dist/scheduler-ED4FCI2Y.js +0 -2
- package/dist/workspace-setup-FPGN5VNY.js +0 -2
- /package/dist/{agent-I3ILI3MO.js.map → agent-Y4U4R3ZZ.js.map} +0 -0
- /package/dist/{board-dashboard-ASI6MDKX.js.map → board-dashboard-2CPBWFOB.js.map} +0 -0
- /package/dist/{chunk-EQNM3TOF.js.map → chunk-2HXSJYAJ.js.map} +0 -0
- /package/dist/{chunk-K6MC66D6.js.map → chunk-ABVZHJUO.js.map} +0 -0
- /package/dist/{chunk-FUYZUGNQ.js.map → chunk-KX626FN4.js.map} +0 -0
- /package/dist/{chunk-AANSVC5A.js.map → chunk-P3TJHGO5.js.map} +0 -0
- /package/dist/{chunk-AGINLNAW.js.map → chunk-VYLZ7UYM.js.map} +0 -0
- /package/dist/{chunk-2B2DIQKD.js.map → chunk-WHP4I44J.js.map} +0 -0
- /package/dist/{config-RWHSEE4N.js.map → config-BLOKGMER.js.map} +0 -0
- /package/dist/{config-mutator-JKCNCY2F.js.map → config-mutator-RG7QY2EL.js.map} +0 -0
- /package/dist/{doctor-KWN7NUFQ.js.map → doctor-ZTECTUHX.js.map} +0 -0
- /package/dist/{program-JEKM7SCS.js.map → program-GZOJIWTB.js.map} +0 -0
- /package/dist/{registry-EGKDMVSP.js.map → registry-QZIUSQ5J.js.map} +0 -0
- /package/dist/{scheduler-ED4FCI2Y.js.map → scheduler-B2BQPV4M.js.map} +0 -0
- /package/dist/{workspace-setup-FPGN5VNY.js.map → workspace-setup-DQCZX2NE.js.map} +0 -0
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
import{a as ut,b as On,f as Qt,j as Dn}from"./chunk-WHP4I44J.js";import{b as Rn}from"./chunk-KX626FN4.js";import{a as pt}from"./chunk-GV7S5BAX.js";import{c as Sn}from"./chunk-SZDACK6O.js";import{e as xn}from"./chunk-GSX4NK2N.js";import{a as dn,g as un,h as fn,i as hn,j as yn,k as En,l as So,m as jo,n as In,o as An}from"./chunk-X5D5AV5N.js";import{a as wn,b as $n,c as bn,d as kn,e as vn,f as Vt,g as _t,l as jn,m as vo,n as Cn,o as xo}from"./chunk-2HXSJYAJ.js";import{b as Ee}from"./chunk-EW27SCCC.js";import{c as mn}from"./chunk-ABVZHJUO.js";import{a as le,b as ee,c as Qe,d as pn}from"./chunk-P3TJHGO5.js";import{d as gn,e as R,f as Kt}from"./chunk-CO4YCIIA.js";import{g as mt}from"./chunk-OZOQKPJV.js";import{b as ln}from"./chunk-GOLZ6NEL.js";import{b as Ve,d as cn,f as ko}from"./chunk-7P5QRX5W.js";import{a as Te}from"./chunk-VJUTQAPJ.js";import{a as Bs}from"./chunk-4YCH6IZV.js";import{Command as Aa}from"commander";import{Command as qs}from"commander";import x from"chalk";import{existsSync as Js,readFileSync as zs}from"fs";var Ie=new qs().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Ie.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:l}=await import("child_process"),{openSync:p,writeFileSync:d,existsSync:m}=await import("fs"),u=process.argv[1];(!u||!m(u))&&(console.error(x.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${u||"?"}).`)),console.error(x.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let h=[u,"daemon","start"];e.config&&h.push("-c",e.config),e.port&&h.push("--port",e.port);let y="/tmp/agentx-daemon.log",w;try{w=p(y,"a")}catch($){console.error(x.red(` Failed to open ${y} for writing: ${$.message}`)),process.exit(1)}let b=l(process.execPath,h,{detached:!0,stdio:["ignore",w,w],cwd:process.cwd()});b.unref(),d("/tmp/agentx-daemon.pid",String(b.pid)),console.log(x.green(`Daemon started in background (PID: ${b.pid})`)),console.log(x.dim(` Logs: tail -f ${y}`)),console.log(x.dim(" Stop: agentx daemon stop")),await new Promise($=>setTimeout($,1e3));try{process.kill(b.pid,0)}catch{console.log(),console.log(x.yellow(` Daemon exited within 1s \u2014 check ${y} for the error:`)),console.log(x.dim(` tail -n 40 ${y}`))}return}let{readFileSync:t,writeFileSync:o,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 l=parseInt(t(a,"utf-8").trim(),10);if(l&&l!==process.pid)try{process.kill(l,0),console.error(`Another agentx daemon is already running (PID ${l}). Exiting.`),process.exit(0)}catch{}}o(a,String(process.pid));try{Gs(i(process.cwd(),".env"))}catch{}await new jo(e.config).start()});function Gs(e){if(!Js(e))return;let t=zs(e,"utf-8");for(let o of t.split(`
|
|
2
|
+
`)){let n=o.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}}Ie.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:e,existsSync:t,unlinkSync:o}=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(t(r))try{let a=parseInt(e(r,"utf-8").trim(),10);process.kill(a,"SIGTERM"),await new Promise(c=>setTimeout(c,2e3));try{o(r)}catch{}console.log(x.green(`Daemon stopped (PID: ${a})`));return}catch{try{o(r)}catch{}}let{execSync:i}=await import("child_process");try{i("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(x.green("Daemon stopped"))}catch{console.log(x.yellow("No daemon process found"))}});Ie.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 t=R(e.config),[o,n]=t.node.bind.split(":"),s=`http://${o||"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(x.bold(` ${r.node.name}`)+x.dim(` (${r.node.id})`)),console.log(x.green(" Status: running")+x.dim(` \u2014 uptime ${Hs(r.uptime)}`)),console.log(),console.log(x.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?x.yellow(` [${c.active} active]`):"",p=c.errors>0?x.red(` (${c.errors} errors)`):"";console.log(` ${x.cyan(c.name)} ${x.dim(`(${c.tier})`)}${l}${p}`),console.log(x.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(x.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?x.green("\u25CF"):x.dim("\u25CB"),p=c.nextRun?x.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${p}`)}}if(r.mesh?.length){console.log(),console.log(x.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?x.green("\u25CF"):x.red("\u25CF"),p=c.skills?.length?x.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${x.dim(c.peerUrl)}${p}`)}}console.log()}catch(t){if(t.cause?.code==="ECONNREFUSED"||t.name==="TimeoutError")console.log(x.red(" Daemon is not running")),console.log(x.dim(" Start with: agentx daemon start"));else try{let o=R(e.config),n=Kt(o);if(console.log(),console.log(x.bold(` ${o.node.name}`)+x.dim(` (${o.node.id})`)),console.log(x.yellow(" Status: stopped")),console.log(x.dim(` ${Object.keys(o.agents).length} agents, ${Object.keys(o.crons).length} crons configured`)),n.length){console.log();for(let s of n)console.log(x.yellow(` \u26A0 ${s}`))}console.log()}catch(o){console.log(x.red(` ${o.message}`))}}});Ie.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:t,spawn:o}=await import("child_process"),n="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(n)){console.log(x.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(e.follow){let i=o("tail",["-f","-n",e.lines,n],{stdio:"inherit"});process.on("SIGINT",()=>{i.kill(),process.exit(0)})}else t(`tail -n ${e.lines} ${n}`,{stdio:"inherit"})});Ie.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(R(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(x.dim(` Connecting to ${n}...`)),console.log(x.dim(` Press Ctrl+C to stop
|
|
3
|
+
`));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(x.red(` Failed: ${s.status}`));return}let i=s.body.getReader(),r=new TextDecoder,a="";for(;;){let{done:c,value:l}=await i.read();if(c)break;a+=r.decode(l,{stream:!0});let p=a.split(`
|
|
4
|
+
`);a=p.pop()||"";for(let d of p)if(d.startsWith("data: "))try{let m=JSON.parse(d.slice(6)),u=new Date(m.time).toLocaleTimeString(),h=m.message?.replace(/^\[agentx\]\s*/,"")||"";h.includes("executing")?console.log(`${x.dim(u)} ${x.cyan("\u25B6")} ${h}`):h.includes("completed")?console.log(`${x.dim(u)} ${x.green("\u2713")} ${h}`):h.includes("error")||h.includes("Error")?console.log(`${x.dim(u)} ${x.red("\u2717")} ${h}`):h.includes("Routing")?console.log(`${x.dim(u)} ${x.yellow("\u2192")} ${h}`):h.includes("mention")?console.log(`${x.dim(u)} ${x.magenta("@")} ${h}`):h.includes("Skipping")?console.log(`${x.dim(u)} ${x.dim("\u2298")} ${x.dim(h)}`):console.log(`${x.dim(u)} ${h}`)}catch{}else d.startsWith("event: status")}}catch(s){console.log(x.red(` Connection failed: ${s.message}`)),console.log(x.dim(" Is the daemon running? Diagnostic order:")),console.log(x.dim(" 1) agentx daemon status # is the daemon up?")),console.log(x.dim(" 2) tail -n 60 /tmp/agentx-daemon.log # detach-mode crash log")),console.log(x.dim(" 3) journalctl -u agentx -n 60 # systemd-managed installs")),console.log(x.dim(" If the log file is missing, the daemon never started \u2014 re-run without --detach")),console.log(x.dim(" to see the error in the foreground."))}});Ie.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,t,o)=>{let n=t.join(" ");try{let s=R(o.config),[i,r]=s.node.bind.split(":"),a=`http://${i||"127.0.0.1"}:${r}`,c,l;o.peer?(c=`${a}/mesh/task`,l={peer:o.peer,message:n,agent:e}):(c=`${a}/task`,l={agent:e,message:n}),console.log(x.dim(` Sending to ${o.peer?`${o.peer}/${e}`:e}...`));let d=await(await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();o.json?console.log(JSON.stringify(d,null,2)):d.error?console.log(x.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(x.dim(`
|
|
5
|
+
(${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(x.red(` Failed: ${s.message}`)),console.log(x.dim(" Is the daemon running? Try: agentx daemon status"))}});Ie.command("deploy <host>").description("deploy agentx to a remote server via rsync").option("-i, --identity <key>","SSH identity file").option("-u, --user <user>","SSH user","root").option("-p, --path <path>","remote agentx path","~/agentx").option("--restart","restart remote daemon after deploy",!1).option("--skip-checks","skip build and test before deploy",!1).action(async(e,t)=>{let{execSync:o}=await import("child_process"),n=t.identity?`-e "ssh -i ${t.identity}"`:"",s=`${t.user}@${e}:${t.path}/dist/`;if(!t.skipChecks){try{console.log(x.dim(" Running tests...")),o("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(x.green(" \u2713 Tests passed"))}catch{console.log(x.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(x.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:i,statSync:r}=await import("fs"),{resolve:a}=await import("path"),c=a(process.cwd(),"dist/cli.js");if(!i(c)){console.log(x.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(x.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),o("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(x.green(" \u2713 Build complete")))}console.log(x.dim(` Deploying to ${t.user}@${e}:${t.path}...`));try{if(o(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(x.green(" \u2713 Deploy complete")),t.restart){console.log(x.dim(" Restarting remote daemon..."));let i=t.identity?`ssh -i ${t.identity}`:"ssh";o(`${i} ${t.user}@${e} "pkill -f 'node dist/cli.js daemon' 2>/dev/null; sleep 2; cd ${t.path} && nohup node dist/cli.js daemon start > /tmp/agentx-daemon.log 2>&1 &"`,{stdio:"inherit"}),console.log(x.green(" Remote daemon restarted"))}}catch(i){console.log(x.red(` Deploy failed: ${i.message}`))}});Ie.action(async e=>{await new jo(e.config).start()});function Hs(e){return e<60?`${Math.round(e)}s`:e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h ${Math.round(e%3600/60)}m`:`${Math.round(e/86400)}d ${Math.round(e%86400/3600)}h`}import{Command as Ys}from"commander";import je from"chalk";import{existsSync as Nt,readFileSync as Ks,writeFileSync as Tn,mkdirSync as _n}from"fs";import{hostname as Nn}from"os";import{resolve as ft}from"path";var Pn=new Ys().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let t=process.cwd(),o=ft(t,"agentx.json"),n=ft(t,".env"),s=ft(t,".agentx/sessions");if(console.log(),console.log(je.bold(" agentx init")),console.log(),Nt(o)&&!e.force){console.log(je.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[ft(t,"agentx.example.json"),ft(t,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(Nt(c)){r=Ks(c,"utf-8");break}r||(r=JSON.stringify({node:{id:Nn().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:Nn(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:t,tier:"claude-code",model:"claude-sonnet-4-6",mentions:["@assistant","assistant"],maxConcurrent:2,systemPrompt:"You are a helpful assistant.",permissionMode:"default"}},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}}},null,2)),Tn(o,r),console.log(je.green(" \u2713 Created agentx.json")),Nt(n)||(Tn(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
|
|
6
|
+
`)),console.log(je.green(" \u2713 Created .env template"))),Nt(s)||(_n(s,{recursive:!0}),console.log(je.green(" \u2713 Created .agentx/sessions/")));let a=ft(t,".claude");Nt(a)||(_n(a,{recursive:!0}),console.log(je.green(" \u2713 Created .claude/"))),console.log(),console.log(je.bold(" Next steps:")),console.log(` 1. Edit ${je.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${je.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${je.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${je.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Vs}from"commander";import Xe from"chalk";import{spawn as Ln}from"child_process";import{existsSync as Qs}from"fs";import{resolve as Xs}from"path";var Wn=new Vs().name("setup").description("open the web setup wizard to create or extend your AgentX install").option("--port <n>","dashboard port (default: from agentx.json, else 4202)").option("--no-open","don't try to open the browser").action(async e=>{let t=On(),o=e.port?parseInt(e.port,10):Zs(),n=`http://127.0.0.1:${o}/setup`;if(console.log(),t.configExists?console.log(Xe.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Xe.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Xe.bold(` Opening ${n}`)),console.log(),await ti(n).catch(()=>!1))console.log(Xe.dim(" Dashboard is already running.")),e.open!==!1&&Mn(n);else{console.log(Xe.dim(` Starting dashboard server on port ${o} (Ctrl-C to quit)\u2026`));let i=ei(),r=Ln(process.execPath,[i,"board","serve","--port",String(o)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&Mn(n),await new Promise(a=>r.on("exit",()=>a()))}});function Zs(){try{return R().dashboard.port||4202}catch{return 4202}}function ei(){let e=Xs(import.meta.dirname,"cli.js");return Qs(e)?e:process.argv[1]||e}async function ti(e){try{let t=await fetch(e,{method:"GET"});return t.ok||t.status===302}catch{return!1}}function Mn(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let o=Ln(t,[e],{stdio:"ignore",detached:!0});o.once("error",()=>{console.log(Xe.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),o.unref()}catch{console.log(Xe.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as oi}from"commander";import ne from"chalk";var Pt=new oi().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Pt.command("create").description("mint a new token \u2014 prints the secret once, store it somewhere safe").requiredOption("--name <name>","human-readable label (e.g. 'Slack integration')").option("--scope <scopes>","comma-separated scopes (default: dashboard:read)","dashboard:read").option("--expires <days>","expire after N days (default: no expiry)").action(e=>{try{let t=new Qt,o=String(e.scope).split(",").map(r=>r.trim()).filter(Boolean),n=e.expires?parseInt(e.expires,10):void 0;if(e.expires&&(!n||n<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:i}=t.create({name:e.name,scopes:o,expiresInDays:n});console.log(),console.log(ne.bold(" Token created.")),console.log(),console.log(` id: ${ne.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||ne.dim("never")}`),console.log(),console.log(ne.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${ne.green.bold(s)}`),console.log(),console.log(ne.dim(" Use it via the Authorization header:")),console.log(ne.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(t){console.log(ne.red(` ${t.message}`)),process.exit(1)}});Pt.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new Qt().list();if(e.length===0){console.log(ne.dim(`
|
|
7
|
+
No tokens issued.
|
|
8
|
+
`));return}console.log();for(let t of e){let o=t.revokedAt?ne.red("revoked"):t.expiresAt&&Date.parse(t.expiresAt)<Date.now()?ne.red("expired"):ne.green("active");console.log(` ${ne.cyan(t.id)} ${o} ${t.name}`),console.log(ne.dim(` prefix: ${t.prefix}\u2026 scopes: ${t.scopes.join(", ")}`)),console.log(ne.dim(` created: ${t.createdAt}${t.expiresAt?` expires: ${t.expiresAt}`:""}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(ne.red(` ${e.message}`)),process.exit(1)}});Pt.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let t=new Qt().revoke(e);t||(console.log(ne.red(` Token ${e} not found.`)),process.exit(1)),console.log(ne.green(`
|
|
9
|
+
\u2713 Revoked ${e} (${t.name})
|
|
10
|
+
`))}catch(t){console.log(ne.red(` ${t.message}`)),process.exit(1)}});import{Command as _e}from"commander";import f from"chalk";import xe from"prompts";import{readFileSync as Fe,writeFileSync as ht,existsSync as Y,mkdirSync as Ae,cpSync as Co,readdirSync as Io}from"fs";import{resolve as T,join as We}from"path";function te(){let e=T(process.cwd(),"agentx.json");if(!Y(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Fe(e,"utf-8"))}function he(e){return le(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(f.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(f.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(f.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var yt=new _e().name("agent").description("manage agents \u2014 add, list, remove");yt.command("list").alias("ls").description("list configured agents").action(()=>{let e=te();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${f.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(f.dim(` workspace: ${o.workspace}`)),n&&console.log(f.dim(` mentions: ${n}`))}console.log()});yt.command("add").description("add a new agent interactively").action(async()=>{let e=te(),t=await xe([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:l=>/^[a-z0-9-]+$/.test(l)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:T(process.cwd(),"agents/")},{type:"select",name:"tier",message:"Execution tier",choices:[{title:"claude-code (subscription, full features)",value:"claude-code"},{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(!t.id)return;let o=t.workspace.endsWith(t.id)?t.workspace:We(t.workspace,t.id);Ae(T(o,".claude/skills"),{recursive:!0});let n={name:t.name,workspace:o,tier:t.tier,model:t.model,mentions:t.mentions?.map(l=>l.trim()).filter(Boolean)||[],maxConcurrent:t.maxConcurrent,systemPrompt:t.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-DQCZX2NE.js"),i=s(t.id,n,"19900",(...l)=>{console.log(f.dim(` ${l.join(" ")}`))}),r=T(process.cwd(),"src/wiki/SKILL.md"),a=T(import.meta.dirname,"../wiki/SKILL.md"),c=Y(r)?r:a;Y(c)&&(Ae(T(o,".claude/skills/wiki"),{recursive:!0}),Co(c,T(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await he(e),console.log(f.green(`
|
|
11
|
+
Agent "${t.id}" added`)),console.log(f.dim(` Workspace: ${o}`)),console.log(f.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});yt.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=te();if(!t.agents?.[e]){console.log(f.red(` Agent "${e}" not found`));return}delete t.agents[e],await he(t),console.log(f.green(` Agent "${e}" removed from config (workspace preserved)`))});yt.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,t)=>{let o=te(),n=o.agents?.[e];if(n||(console.log(f.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log(f.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):f.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":f.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||f.dim("(global default)")}`),console.log(` maxExecutionMinutes ${n.maxExecutionMinutes??20}`),console.log();return}let s=[];if(t.intents!==void 0&&(t.intents==="-"||t.intents===""?(n.intents=[],s.push("intents cleared (permissive)")):(n.intents=String(t.intents).split(",").map(i=>i.trim()).filter(Boolean),s.push(`intents=[${n.intents.join(", ")}]`))),t.maxDelegationDepth!==void 0){let i=parseInt(t.maxDelegationDepth,10);(!Number.isFinite(i)||i<0||i>50)&&(console.log(f.red(" --max-delegation-depth must be 0..50")),process.exit(1)),n.maxDelegationDepth=i,s.push(`maxDelegationDepth=${i}`)}if(t.contextReferences!==void 0){let i=String(t.contextReferences).toLowerCase();["true","false","on","off","1","0"].includes(i)||(console.log(f.red(" --context-references must be true|false")),process.exit(1)),n.contextReferences=i==="true"||i==="on"||i==="1",s.push(`contextReferences=${n.contextReferences}`)}if(t.contextStrategy!==void 0&&(t.contextStrategy==="-"||t.contextStrategy===""?(delete n.contextStrategy,s.push("contextStrategy cleared (uses global default)")):["layered","planner"].includes(t.contextStrategy)?(n.contextStrategy=t.contextStrategy,s.push(`contextStrategy=${t.contextStrategy}`)):(console.log(f.red(" --context-strategy must be layered|planner (or '-' to clear)")),process.exit(1))),t.maxExecutionMinutes!==void 0){let i=parseInt(t.maxExecutionMinutes,10);(!Number.isFinite(i)||i<1||i>240)&&(console.log(f.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(f.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await he(o),console.log(f.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(f.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Xt=new _e().name("channel").description("manage channels \u2014 add telegram/whatsapp/discord, list");Xt.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=te();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(f.bold(" Telegram:"));for(let[i,r]of Object.entries(t.accounts||{}))console.log(` ${f.cyan(i)} -> agent: ${r.agentBinding}`)}else console.log(f.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(f.bold(" WhatsApp:")),console.log(` default agent: ${o.defaultAgent||"(none)"}`),console.log(` session: ${o.sessionDir||".agentx/whatsapp-sessions"}`);for(let i of o.routes||[]){let r=i.contact?`contact ${i.contact}`:`group "${i.group}"`;console.log(` ${r} -> agent: ${i.agent}`)}}else console.log(f.dim(" WhatsApp: disabled"));let n=e.channels?.discord;n?.enabled?(console.log(f.bold(" Discord:")),console.log(` agent: ${n.agentBinding||"(none)"}`)):console.log(f.dim(" Discord: disabled"));let s=e.channels?.gitlab;if(s?.enabled){console.log(f.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(f.dim(" GitLab: disabled"));console.log()});Xt.command("add").description("add a channel (telegram, whatsapp, or discord)").action(async()=>{let e=te(),t=Object.keys(e.agents||{});if(!t.length){console.log(f.red(" No agents configured. Run: agentx agent add"));return}let o=t.map(s=>({title:`${s} (${e.agents[s].name})`,value:s})),{channelType:n}=await xe({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 xe([{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:o}]);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(f.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(f.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 he(e),console.log(f.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await xe([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:o},{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 xe([{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:o},{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 he(e),Ae(T(process.cwd(),s.sessionDir),{recursive:!0}),console.log(f.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(f.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="discord"){let s=await xe([{type:"text",name:"token",message:"Discord bot token (from developer portal)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:o}]);if(!s.token)return;e.channels.discord={enabled:!0,token:s.token,agentBinding:s.agentBinding},await he(e),console.log(f.green(` Discord added -> ${s.agentBinding}`))}if(n==="gitlab"){let s=await xe([{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 xe([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:o},{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 he(e),console.log(f.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(f.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(f.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(f.dim(` Secret token: ${s.webhookSecret}`)),console.log(f.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(f.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var wt=new _e().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");wt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=te();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?f.green("\u25CF"):f.dim("\u25CB");console.log(` ${n} ${f.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(f.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(f.dim(" No cron jobs configured")),console.log()});wt.command("add").description("add a cron job").action(async()=>{let e=te(),t=Object.keys(e.agents||{}),o=await xe([{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:t.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}]);!o.id||!o.schedule||(e.crons=e.crons||{},e.crons[o.id]={enabled:o.enabled,schedule:o.schedule,timezone:o.timezone,agent:o.agent,prompt:o.prompt,timeout:o.timeout,onError:["log"]},await he(e),console.log(f.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});wt.command("enable <id>").description("enable a cron job").action(async e=>{let t=te();if(!t.crons?.[e]){console.log(f.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!0,await he(t),console.log(f.green(` Cron "${e}" enabled`))});wt.command("disable <id>").description("disable a cron job").action(async e=>{let t=te();if(!t.crons?.[e]){console.log(f.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await he(t),console.log(f.green(` Cron "${e}" disabled`))});var $t=new _e().name("mesh").description("manage mesh peers \u2014 add, list, remove");$t.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=te();if(console.log(),!e.mesh?.enabled)console.log(f.dim(" Mesh: disabled"));else{console.log(f.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=f.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=f.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${f.cyan(t.name)} ${f.dim(t.url)} ${o}`)}}console.log()});$t.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=te(),t=await xe([{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(!(!t.name||!t.url)){try{let n=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(f.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(f.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:t.url,name:t.name,...t.token?{token:t.token}:{}}),await he(e),console.log(f.green(` Peer "${t.name}" added`)),console.log()}});$t.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=te();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await he(t),console.log(f.green(` Peer "${e}" removed`)))});$t.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 t=te();if(t.mesh=t.mesh||{},t.mesh.healthCheck=t.mesh.healthCheck||{},e.show){console.log(` interval ${t.mesh.healthCheck.interval??60}s`),console.log(` timeout ${t.mesh.healthCheck.timeout??10}s`);return}let o=[];if(e.interval!==void 0){let n=parseInt(e.interval,10);(!Number.isFinite(n)||n<5||n>3600)&&(console.log(f.red(" --interval must be 5..3600 seconds")),process.exit(1)),t.mesh.healthCheck.interval=n,o.push(`interval=${n}s`)}if(e.timeout!==void 0){let n=parseInt(e.timeout,10);(!Number.isFinite(n)||n<1||n>60)&&(console.log(f.red(" --timeout must be 1..60 seconds")),process.exit(1)),t.mesh.healthCheck.timeout=n,o.push(`timeout=${n}s`)}o.length===0&&(console.log(f.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await he(t),console.log(f.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(f.dim(" Restart the daemon for the new cadence to take effect."))});var bt=new _e().name("skill").description("manage skills \u2014 add to agent(s), list");bt.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,t)=>{let o=te(),n=T(e);if(!Y(n)){console.log(f.red(` Skill not found: ${n}`));return}let s=Y(We(n,"SKILL.md"))?n.split("/").pop():n.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(t.all)i=Object.keys(o.agents||{});else if(t.agent)i=t.agent;else{let r=Object.keys(o.agents||{});i=(await xe({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(c=>({title:`${c} (${o.agents[c].name})`,value:c}))})).agents||[]}for(let r of i){let a=o.agents[r];if(!a){console.log(f.yellow(` Agent "${r}" not found, skipping`));continue}let c=T(a.workspace,".claude/skills",s);Ae(c,{recursive:!0}),Y(We(n,"SKILL.md"))?Co(n,c,{recursive:!0}):n.endsWith(".md")&&Co(n,We(c,"SKILL.md")),console.log(f.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});bt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=te();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=T(o.workspace,".claude/skills"),s=Y(n)?Io(n).filter(i=>!i.startsWith(".")):[];console.log(` ${f.cyan(t)}: ${s.length?s.join(", "):f.dim("(none)")}`)}console.log()});bt.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,t)=>{let{createHash:o}=await import("node:crypto"),n=process.cwd(),s=t.source?[t.source]:[T(n,"src",e,"SKILL.md"),T(n,"skills",e,"SKILL.md")],i=s.find(b=>Y(b));if(!i){console.log(f.red(` No SKILL.md found for "${e}". Searched:`));for(let b of s)console.log(f.dim(` ${b}`));return}let r=Fe(i,"utf-8"),a=o("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=R()}catch(b){console.log(f.red(` Can't load agentx.json: ${b.message}`));return}let p=Object.entries(l.agents||{}),d=t.agent?p.filter(([b])=>b===t.agent):p;if(d.length===0){console.log(f.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(f.bold(` Skill sync \u2014 ${e}`)),console.log(f.dim(` Source: ${i}`)),console.log(f.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(f.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let m=0,u=0,h=0,y=0;for(let[b,$]of d){let S=$.workspace;if(!S||!Y(S)){console.log(` ${f.yellow("\u2717")} ${b.padEnd(22)} ${f.dim("(workspace missing: "+(S||"undefined")+")")}`),y++;continue}let v=T(S,".claude/skills",e),k=T(v,"SKILL.md");if(!Y(k)){if(!t.allWorkspaces){console.log(` ${f.dim("\xB7")} ${b.padEnd(22)} ${f.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),y++;continue}t.dryRun||(Ae(v,{recursive:!0}),ht(k,r)),console.log(` ${f.green("+")} ${b.padEnd(22)} ${f.dim("\u2192 seeded v"+c)}`),m++;continue}let C=Fe(k,"utf-8");if(o("sha256").update(C).digest("hex").slice(0,12)===a){console.log(` ${f.dim("=")} ${b.padEnd(22)} ${f.dim("up to date (v"+c+")")}`),h++;continue}let L=(C.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||ht(k,r),console.log(` ${f.yellow("\u21BB")} ${b.padEnd(22)} ${f.dim(`v${L} \u2192 v${c}`)}`),u++}console.log();let w=t.dryRun?"would":"did";console.log(f.dim(` Summary: ${w} seed ${m}, ${w} update ${u}, ${h} already current, ${y} skipped.`)),t.dryRun&&(m>0||u>0)&&console.log(f.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});bt.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:t}=await import("./loader-5CA3O5GM.js"),{auditAll:o}=await import("./audit-JU3HWISB.js"),{loadReferences:n}=await import("./loader-6IHUCPVO.js"),{loadRecipes:s}=await import("./recipes-EPLE2SNT.js"),i=[];if(e.workspace){let u=te().agents?.[e.workspace];u||(console.log(f.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(T(u.workspace))}else if(e.allWorkspaces){let m=te();for(let u of Object.values(m.agents||{}))u?.workspace&&i.push(T(u.workspace))}else i.push(T(e.cwd));let r=T(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(m=>t(m)))).flat(),[l,p]=await Promise.all([n(r),s(r)]),d=o({skills:c,references:l,recipes:p});if(e.json)console.log(JSON.stringify(d.map(m=>({name:m.name,verdict:m.verdict,reasons:m.reasons,path:m.skill?.path})),null,2));else{let m={PASS:0,REVIEW:0,FAILING:0};for(let u of d)m[u.verdict]++;console.log();for(let u of d){let h=u.verdict==="PASS"?f.green("PASS "):u.verdict==="REVIEW"?f.yellow("REVIEW "):f.red("FAILING");console.log(` ${h} ${f.bold(u.name)}${u.skill?.path?f.dim(` (${u.skill.path})`):""}`);for(let y of u.reasons)console.log(` ${f.dim("\xB7")} ${y}`)}console.log(),console.log(` ${f.green(`${m.PASS} PASS`)} ${f.yellow(`${m.REVIEW} REVIEW`)} ${f.red(`${m.FAILING} FAILING`)}`),console.log()}process.exit(d.some(m=>m.verdict==="FAILING")?1:0)});var Mt=new _e().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Mt.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,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(f.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let o=T(t.cwd),n=T(o,"references/example"),s=T(o,"references/recipes/example.yaml");Y(n)||(console.log(f.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=T(o,".agentx/references",e),r=T(o,".agentx/references/recipes");Ae(i,{recursive:!0}),Ae(r,{recursive:!0});let a=Io(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let m=We(i,d);if(Y(m)&&!t.force){console.log(f.dim(` skip ${m} (exists; --force to overwrite)`)),l++;continue}let h=Fe(We(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);ht(m,h),console.log(f.green(` + ${m}`)),c++}let p=We(r,`${e}.yaml`);if(Y(p)&&!t.force)console.log(f.dim(` skip ${p} (exists; --force to overwrite)`)),l++;else if(Y(s)){let d=Fe(s,"utf-8").replaceAll("example.",`${e}.`);ht(p,d),console.log(f.green(` + ${p}`)),c++}console.log(),console.log(f.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(f.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(f.dim(" 2. agentx skill audit # verify references resolve")),console.log(f.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Mt.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,t)=>{/^[a-z0-9][a-z0-9-]*$/.test(e)||(console.log(f.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let{loadLocalSkills:o}=await import("./loader-5CA3O5GM.js"),{discoverFromSkills:n,renderDiscovery:s}=await import("./discover-XJXQXXIO.js"),i=T(t.cwd),r=t.from?String(t.from).split(",").map(y=>y.trim()).filter(Boolean):[e],a=await o(i),c=n(a,{namespace:e,filter:r,gitlabHost:t.gitlabHost});if(console.log(),c.scannedSkills.length===0){console.log(f.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(f.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(f.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([y,w])=>[y,w.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let p=s(c,e),d=T(t.referencesCwd||t.cwd),m=T(d,".agentx/references",e);if(!t.write){console.log(),console.log(f.dim(` Dry-run \u2014 would write to ${m}/`));for(let[y,w]of Object.entries(p))console.log(f.cyan(`
|
|
12
|
+
--- ${y} ---`)),console.log(w.split(`
|
|
13
|
+
`).slice(0,30).map(b=>` ${b}`).join(`
|
|
14
|
+
`)),w.split(`
|
|
15
|
+
`).length>30&&console.log(f.dim(` \u2026 (${w.split(`
|
|
16
|
+
`).length-30} more lines truncated in preview)`));console.log(),console.log(f.dim(` Re-run with --write to commit these to ${m}/`)),console.log();return}Ae(m,{recursive:!0});let u=0,h=0;for(let[y,w]of Object.entries(p)){let b=We(m,y);if(Y(b)&&!t.force){console.log(f.dim(` skip ${b} (exists; --force to overwrite)`)),h++;continue}ht(b,w),console.log(f.green(` + ${b}`)),u++}console.log(),console.log(f.dim(` ${u} written, ${h} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(f.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Mt.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:t}=await import("./loader-6IHUCPVO.js"),o=await t(T(e.cwd)),n=[...o.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(f.dim(" (no references loaded \u2014 try `agentx references init <namespace>`)")),console.log();return}for(let s of n){let i=o.sourceById.get(s.id);console.log(` ${f.cyan(s.id)} ${f.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(f.dim(` ${i}`))}console.log(),console.log(f.dim(` ${n.length} reference(s) loaded.`)),console.log()});var Ao=new _e().name("hook").description("manage hooks \u2014 add to agent workspace");Ao.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=te().agents?.[e];if(!o){console.log(f.red(` Agent "${e}" not found`));return}let n=T(o.workspace,".claude/settings.json"),s=Y(n)?JSON.parse(Fe(n,"utf-8")):{},i=await xe([{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),Ae(T(o.workspace,".claude"),{recursive:!0}),ht(n,JSON.stringify(s,null,2)),console.log(f.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var Oo=new _e().name("migrate").description("import configuration from OpenClaw or other tools");Oo.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,t)=>{let o=[e,T(process.env.HOME||"",".openclaw/openclaw.json"),T(process.env.HOME||"",".openclaw/clawdbot.json")].filter(Boolean),n;for(let u of o)if(u&&Y(u)){n=u;break}if(!n){console.log(f.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(f.dim(` Reading: ${n}`));let s=JSON.parse(Fe(n,"utf-8")),i=Y(T(process.cwd(),"agentx.json"))?te():{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 u of a)u.match?.channel==="telegram"&&(c[u.match.accountId]=u.agentId);r.find(u=>u.id==="main"||u.default)&&(c.default="main");let l=0;for(let u of r){if(u.workspace?.startsWith("/data"))continue;let h=u.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),y=u.groupChat?.mentionPatterns||[];if(y.some(w=>w===h)||y.push(h),i.agents[h]={name:u.name,workspace:u.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:y,maxConcurrent:u.id==="main"?2:1,systemPrompt:`You are ${u.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!t.dryRun){Ae(T(u.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-DQCZX2NE.js");w(h,i.agents[h])}}console.log(` ${f.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let p=s.channels?.telegram?.accounts||{},d=0;for(let[u,h]of Object.entries(p)){if(!h.botToken)continue;let w=c[u]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[u]={token:h.botToken,agentBinding:w},i.channels.telegram.enabled=!0,d++}console.log(` ${f.green(d)} Telegram accounts imported`);let m=T(n,"../cron/jobs.json");if(Y(m)){let u=JSON.parse(Fe(m,"utf-8")),h=0;for(let y of u.jobs||[]){let w=y.name||y.id,b=y.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[w]={enabled:y.enabled||!1,schedule:y.schedule?.expr||"0 9 * * *",timezone:y.schedule?.tz||"UTC",agent:b,prompt:y.payload?.message||"",timeout:y.payload?.timeoutSeconds||600,onError:["log"]},h++}console.log(` ${f.green(h)} cron jobs imported`)}t.dryRun?(console.log(f.yellow(`
|
|
17
|
+
Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await he(i),console.log(f.green(`
|
|
18
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Ue=new _e().name("config").description("validate and inspect configuration");Ue.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 t=R(e.config);console.log(f.green(" \u2713 Config valid")),console.log(f.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(f.dim(` Bind: ${t.node.bind}`)),console.log(f.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(f.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(f.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(f.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(f.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`)),console.log(f.dim(` Discord: ${t.channels.discord?.enabled?"enabled":"disabled"}`));let n=Kt(t);if(n.length){console.log(),console.log(f.yellow(" Warnings:"));for(let s of n)console.log(f.yellow(` \u26A0 ${s}`))}else console.log(f.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(t.agents)){let r=i.workspace,a=Y(T(r,".claude")),c=Y(T(r,"CLAUDE.md")),l=Y(T(r,".claude/settings.json")),p=Y(T(r,".claude/skills"))?Io(T(r,".claude/skills")).filter(m=>!m.startsWith(".")).length:0,d=[a?f.green("\u2713"):f.red("\u2717"),".claude",c?f.green("\u2713"):f.yellow("\u25CB"),"CLAUDE.md",l?f.green("\u2713"):f.yellow("\u25CB"),"settings",`${p} skills`];console.log(` ${f.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(f.red(` \u2717 ${t.message}`))}console.log()});Ue.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=R(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(f.red(t.message))}});function ni(e,t){if(t)return e;try{return JSON.parse(e)}catch{}return e.includes(",")&&!e.includes(" ")?e.split(",").map(o=>o.trim()).filter(Boolean):e}function Eo(e){return e===void 0?f.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Ue.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,t)=>{let{readFileSync:o,existsSync:n}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:i}=await import("./config-mutator-RG7QY2EL.js"),{expandEnvVars:r}=await import("./config-BLOKGMER.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(f.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(o(a,"utf-8")),l=t.raw?c:r(c),p=i(l,e);t.json?console.log(JSON.stringify(p)):console.log(Eo(p))});Ue.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,t,o)=>{let{applyConfigMutation:n,setAtPath:s,getAtPath:i}=await import("./config-mutator-RG7QY2EL.js"),r=ni(t,!!o.string),a=await n(l=>{s(l,e,r)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(f.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);o.dryRun?console.log(f.yellow(` (dry-run) ${f.cyan(e)} would become: ${Eo(c)}`)):(console.log(f.green(` \u2713 ${f.cyan(e)} = ${Eo(c)}`)),a.reloaded?console.log(f.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(f.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Ue.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,t)=>{let{applyConfigMutation:o,getAtPath:n,unsetAtPath:s}=await import("./config-mutator-RG7QY2EL.js"),i=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(i.success||(console.log(f.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(f.dim(` (no-op) ${f.cyan(e)} was not set`));return}t.dryRun?console.log(f.yellow(` (dry-run) ${f.cyan(e)} would be removed`)):(console.log(f.green(` \u2713 ${f.cyan(e)} removed`)),i.reloaded&&console.log(f.dim(" Daemon hot-reloaded.")))});Ue.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 t=!1,o=0,n;try{let d=R(e.config);t=!!d.business?.enabled,o=(d.business?.projects??[]).length}catch(d){n=d?.message??String(d)}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&&t,c=["off","shadow","authoritative"].includes(s);if(e.json){console.log(JSON.stringify({ledger:{mode:s,valid:c},pmGate:{envSet:r,businessEnabled:t,active:a,projects:o},configError:n},null,2));return}console.log(),console.log(f.bold(" Governance flags")),console.log(),n&&(console.log(f.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?f.green:s==="shadow"?f.cyan:s==="off"?f.dim:f.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":f.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let p=a?f.green("active"):r?f.yellow("env=true but business.enabled=false \u2192 inactive"):f.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${p}`),console.log(f.dim(` business.enabled ${t?f.green("true"):f.dim("false")}`)),console.log(f.dim(` business.projects[] ${o}`)),console.log(),console.log(f.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(f.dim(" See: https://github.com/anis-marrouchi/agentx/blob/master/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as si}from"commander";import Be from"chalk";import{resolve as qe}from"path";import{existsSync as ii}from"fs";var Ne=new si().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Ze(e){let t=qe(e,".agentx/db.sqlite");ii(t)||(console.log(Be.red(` No SQLite at ${t}`)),console.log(Be.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=un({path:t});return o||(console.log(Be.red(` Could not open ${t}`)),console.log(Be.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function et(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Be.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.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(o)),console.log(o.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(o.map(r=>i[r])))}Ne.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 t=Ze(qe(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.day&&(o.push("started_at LIKE @day"),n.day=`${e.day}%`),e.status&&(o.push("status = @status"),n.status=e.status);let s=`
|
|
19
|
+
SELECT agent_id, channel, status, duration_ms,
|
|
20
|
+
input_tokens, output_tokens,
|
|
21
|
+
substr(message_preview, 1, 60) AS message,
|
|
22
|
+
started_at
|
|
23
|
+
FROM task_history
|
|
24
|
+
${o.length?"WHERE "+o.join(" AND "):""}
|
|
25
|
+
ORDER BY started_at DESC
|
|
26
|
+
LIMIT @limit
|
|
27
|
+
`,i=t.prepare(s).all({...n,limit:Number(e.limit)});et(i,!!e.json)});Ne.command("rotations").description("session rotation events (stale | tier-2 | max-turns)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-r, --reason <r>","stale | tier-2 | max-turns").option("-n, --limit <n>","max rows","20").option("--summary","group by agent + reason").option("--json","emit JSON").action(e=>{let t=Ze(qe(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.reason&&(o.push("reason = @reason"),n.reason=e.reason);let s=o.length?"WHERE "+o.join(" AND "):"",i=e.summary?`
|
|
28
|
+
SELECT agent_id, reason, COUNT(*) AS n,
|
|
29
|
+
ROUND(AVG(last_turn_input_tokens)) AS avg_input_tokens,
|
|
30
|
+
MAX(last_turn_input_tokens) AS max_input_tokens
|
|
31
|
+
FROM rotations
|
|
32
|
+
${s}
|
|
33
|
+
GROUP BY agent_id, reason
|
|
34
|
+
ORDER BY n DESC
|
|
35
|
+
`:`
|
|
36
|
+
SELECT agent_id, channel, reason, last_turn_input_tokens, rotated_at
|
|
37
|
+
FROM rotations
|
|
38
|
+
${s}
|
|
39
|
+
ORDER BY rotated_at DESC
|
|
40
|
+
LIMIT @limit
|
|
41
|
+
`,r=t.prepare(i).all({...n,limit:Number(e.limit)});et(r,!!e.json)});Ne.command("usage").description("token usage rolled up per (agent, model, day)").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-d, --day <YYYY-MM-DD>","filter by day (UTC)").option("--json","emit JSON").action(e=>{let t=Ze(qe(e.cwd)),o=[],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent),e.day&&(o.push("day = @day"),n.day=e.day);let s=`
|
|
42
|
+
SELECT day, agent_id, model, tasks,
|
|
43
|
+
input_tokens AS in_tok, output_tokens AS out_tok,
|
|
44
|
+
cache_read_tokens AS cache_read, cache_create_tokens AS cache_create
|
|
45
|
+
FROM usage_daily
|
|
46
|
+
${o.length?"WHERE "+o.join(" AND "):""}
|
|
47
|
+
ORDER BY day DESC, agent_id
|
|
48
|
+
`,i=t.prepare(s).all(n);et(i,!!e.json)});Ne.command("routes").description("inbound routing decisions captured by the pipeline trace").option("--cwd <cwd>","working directory",process.cwd()).option("-c, --channel <ch>","filter by channel (telegram, gitlab, github, ...)").option("-k, --kind <k>","match | drop").option("-n, --limit <n>","max rows","20").option("--summary","group by channel + kind + deciding stage").option("--json","emit JSON").action(e=>{let t=Ze(qe(e.cwd)),o=[],n={};e.channel&&(o.push("channel = @channel"),n.channel=e.channel),e.kind&&(o.push("kind = @kind"),n.kind=e.kind);let s=o.length?"WHERE "+o.join(" AND "):"",i=e.summary?`
|
|
49
|
+
SELECT channel, kind, deciding_stage, COUNT(*) AS n
|
|
50
|
+
FROM route_traces
|
|
51
|
+
${s}
|
|
52
|
+
GROUP BY channel, kind, deciding_stage
|
|
53
|
+
ORDER BY n DESC
|
|
54
|
+
`:`
|
|
55
|
+
SELECT channel, chat_id, kind, deciding_stage, agent_id,
|
|
56
|
+
substr(reason, 1, 60) AS reason, at
|
|
57
|
+
FROM route_traces
|
|
58
|
+
${s}
|
|
59
|
+
ORDER BY at DESC
|
|
60
|
+
LIMIT @limit
|
|
61
|
+
`,r=t.prepare(i).all({...n,limit:Number(e.limit)});et(r,!!e.json)});Ne.command("errors").description("failed tasks (status='error') with their error message").option("--cwd <cwd>","working directory",process.cwd()).option("-a, --agent <id>","filter by agent id").option("-n, --limit <n>","max rows","20").option("--json","emit JSON").action(e=>{let t=Ze(qe(e.cwd)),o=["status = 'error'"],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent);let s=`
|
|
62
|
+
SELECT agent_id, channel, duration_ms,
|
|
63
|
+
substr(error, 1, 120) AS error,
|
|
64
|
+
started_at
|
|
65
|
+
FROM task_history
|
|
66
|
+
WHERE ${o.join(" AND ")}
|
|
67
|
+
ORDER BY started_at DESC
|
|
68
|
+
LIMIT @limit
|
|
69
|
+
`,i=t.prepare(s).all({...n,limit:Number(e.limit)});et(i,!!e.json)});Ne.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let t=Ze(qe(e.cwd)),n=t.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all().map(s=>({table:s.name,rows:t.prepare(`SELECT COUNT(*) AS c FROM ${s.name}`).get().c}));et(n,!!e.json)});Ne.command("query <sql>").description("run an arbitrary read-only SQL query (escape hatch)").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action((e,t)=>{let o=Ze(qe(t.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(Be.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(Be.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=o.prepare(e).all();et(n,!!t.json)}catch(n){console.log(Be.red(` ${n.message}`)),process.exit(1)}});import{Command as ci}from"commander";import P from"chalk";import{mkdtempSync as li}from"fs";import{tmpdir as di}from"os";import{resolve as Un,join as Bn}from"path";import{existsSync as gi}from"fs";import mi from"better-sqlite3";function Fn(e,t,o,n=[]){let s=new Map;for(let c of t)s.set(c.id,c);let i=[];for(let c of o)i.push({kind:"decision",ts:c.decidedAt,decision:c});for(let c of n)i.push({kind:"resolution",ts:c.resolvedAt,resolution:c});i.sort((c,l)=>c.ts!==l.ts?c.ts-l.ts:c.kind===l.kind?0:c.kind==="decision"?-1:1);let r=[],a=0;for(let c of i){if(c.kind==="resolution"){try{e.recordResolution(c.resolution)}catch(h){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${h?.message??h}`})}continue}let l=c.decision,p=s.get(l.eventId);if(!p){r.push({eventId:l.eventId,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:null,outcome:"skipped"},reason:"decision references event not in snapshot"});continue}let d=ri(l),m={id:p.id,ts:p.ts,source:p.source,sourceEventId:p.sourceEventId,project:p.project,subject:p.subject,intent:p.intent,rawJson:p.rawJson},u=mn(e,m,d,()=>l.decidedAt);a+=1,(u.outcome!==l.outcome||u.agentId!==l.agentId)&&r.push({eventId:p.id,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:u.agentId,outcome:u.outcome},reason:ai(l,u)})}return{eventsCount:t.length,decisionsCount:a,divergences:r,skipped:[]}}function ri(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function ai(e,t){return e.outcome==="dispatched"&&t.outcome==="deduped"?"active-task-safety-now-fires (slot held by earlier decision)":e.outcome==="deduped"&&t.outcome==="halted"?"policy-returned-null (recorded as deduped means the live system hit active-task safety; playback policy returned null because deduped is illegal at the policy layer \u2014 investigate whether the in-flight decision is present in the snapshot)":e.agentId!==t.agentId?`agent-changed (recorded=${e.agentId} replayed=${t.agentId})`:e.outcome!==t.outcome?`outcome-changed (recorded=${e.outcome} replayed=${t.outcome})`:"unknown"}var Je=new ci().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function kt(e){let t=Un(e.cwd??process.cwd()),o=Un(t,e.path??".agentx/intent/ledger.sqlite");gi(o)||(console.log(P.red(` No ledger at ${o}`)),console.log(P.dim(' Make sure the daemon has run with INTENT_LEDGER_MODE != "off". The file is created on first ledger write.')),process.exit(1));try{return new mi(o,{readonly:!0})}catch(n){console.log(P.red(` Could not open ${o}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(P.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function tt(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(P.dim(" (no rows)"));return}let o=Object.keys(e[0]),n=o.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(o)),console.log(o.map((i,r)=>"-".repeat(n[r])).join(" "));for(let i of e)console.log(s(o.map(r=>i[r])))}function pi(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Zt(e){if(!e)return;let t=pi(e);if(t===null){let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(P.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-t}Je.command("stats").description("overview: events by source, decisions, divergences, in-flight count").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("--json","emit JSON").action(e=>{let t=kt(e),o=Zt(e.since),n=o!==void 0?"WHERE ts >= @since":"",s=o!==void 0?"WHERE decided_at >= @since":"",i=n,r=t.prepare(`SELECT source, COUNT(*) as n FROM intent_events ${n} GROUP BY source ORDER BY n DESC`).all({since:o}),a=t.prepare(`SELECT COUNT(*) as n FROM intent_decisions ${s}`).get({since:o}).n,c=t.prepare(`SELECT outcome, COUNT(*) as n FROM intent_decisions ${s} GROUP BY outcome ORDER BY n DESC`).all({since:o}),l=t.prepare(`SELECT COUNT(*) as n FROM intent_divergences ${i}`).get({since:o}).n,p=t.prepare(`SELECT source, COUNT(*) as n FROM intent_divergences ${i} GROUP BY source ORDER BY n DESC`).all({since:o}),d=t.prepare(`
|
|
70
|
+
SELECT COUNT(*) as n FROM intent_decisions d
|
|
71
|
+
LEFT JOIN intent_resolutions r
|
|
72
|
+
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
73
|
+
WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL
|
|
74
|
+
`).get().n;if(e.json){console.log(JSON.stringify({since:o??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:p,inFlight:d},null,2));return}console.log(P.bold("Events by source")),tt(r,!1),console.log(),console.log(P.bold(`Decisions: ${a}`)),tt(c,!1),console.log(),console.log(P.bold(`Divergences: ${l}`)),tt(p,!1),console.log(),console.log(P.bold(`In-flight (dispatched, no resolution): ${d}`))});Je.command("divergences").description("recent divergence rows (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source (telegram, gitlab, workflow, cron, mesh, github)").option("--since <duration>","limit to divergences newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let t=kt(e),o=Zt(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),o!==void 0&&(n.push("ts >= @since"),s.since=o);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=t.prepare(`
|
|
75
|
+
SELECT
|
|
76
|
+
datetime(ts/1000, 'unixepoch') AS at,
|
|
77
|
+
source,
|
|
78
|
+
decided_by,
|
|
79
|
+
ledger_outcome AS L_outcome,
|
|
80
|
+
COALESCE(ledger_agent_id, '-') AS L_agent,
|
|
81
|
+
legacy_outcome AS X_outcome,
|
|
82
|
+
COALESCE(legacy_agent_id, '-') AS X_agent,
|
|
83
|
+
substr(COALESCE(legacy_reason, ledger_reason, ''), 1, 60) AS reason
|
|
84
|
+
FROM intent_divergences
|
|
85
|
+
${i}
|
|
86
|
+
ORDER BY ts DESC
|
|
87
|
+
LIMIT @limit
|
|
88
|
+
`).all(s);tt(r,!!e.json)});Je.command("active").description("currently in-flight dispatched decisions (no resolution yet)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-n, --limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let t=kt(e),o=["d.outcome = 'dispatched'","r.decision_event_id IS NULL"],n={limit:Number(e.limit)};e.source&&(o.push("e.source = @source"),n.source=e.source);let s=t.prepare(`
|
|
89
|
+
SELECT
|
|
90
|
+
datetime(d.decided_at/1000, 'unixepoch') AS dispatched_at,
|
|
91
|
+
e.source,
|
|
92
|
+
d.decided_by,
|
|
93
|
+
COALESCE(d.agent_id, '-') AS agent,
|
|
94
|
+
COALESCE(e.project, '-') AS project,
|
|
95
|
+
COALESCE(e.subject, '-') AS subject,
|
|
96
|
+
ROUND((strftime('%s', 'now')*1000 - d.decided_at) / 1000.0) AS age_s
|
|
97
|
+
FROM intent_decisions d
|
|
98
|
+
JOIN intent_events e ON e.id = d.event_id
|
|
99
|
+
LEFT JOIN intent_resolutions r
|
|
100
|
+
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
101
|
+
WHERE ${o.join(" AND ")}
|
|
102
|
+
ORDER BY d.decided_at DESC
|
|
103
|
+
LIMIT @limit
|
|
104
|
+
`).all(n);tt(s,!!e.json)});Je.command("events").description("recent events (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("-s, --source <name>","filter by source").option("-p, --project <name>","filter by project").option("--since <duration>","limit to newer than (e.g. 1h, 24h)").option("-n, --limit <n>","max rows","30").option("--json","emit JSON").action(e=>{let t=kt(e),o=Zt(e.since),n=[],s={limit:Number(e.limit)};e.source&&(n.push("source = @source"),s.source=e.source),e.project&&(n.push("project = @project"),s.project=e.project),o!==void 0&&(n.push("ts >= @since"),s.since=o);let i=n.length?`WHERE ${n.join(" AND ")}`:"",r=t.prepare(`
|
|
105
|
+
SELECT
|
|
106
|
+
datetime(ts/1000, 'unixepoch') AS at,
|
|
107
|
+
source,
|
|
108
|
+
COALESCE(project, '-') AS project,
|
|
109
|
+
COALESCE(subject, '-') AS subject,
|
|
110
|
+
COALESCE(intent, '-') AS intent
|
|
111
|
+
FROM intent_events
|
|
112
|
+
${i}
|
|
113
|
+
ORDER BY ts DESC
|
|
114
|
+
LIMIT @limit
|
|
115
|
+
`).all(s);tt(r,!!e.json)});Je.command("lineage <eventOrSubject>").description("walk the dispatch chain on the same (project, subject) and print every decision + resolution").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--by-subject","treat the argument as `<project>:<subject>` instead of an event id").option("--json","emit JSON").action((e,t)=>{let o=kt(t),n=null,s=null;if(t.bySubject){let d=e.indexOf(":");d<0&&(console.log(P.red(' --by-subject expects "<project>:<subject>"')),process.exit(1)),n=e.slice(0,d),s=e.slice(d+1)}else{let d=o.prepare("SELECT project, subject FROM intent_events WHERE id = ?").get(e);d||(console.log(P.red(` no event with id ${e}`)),process.exit(1)),n=d.project,s=d.subject,(n===null||s===null)&&(console.log(P.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(P.dim(` project: ${n}`)),s&&console.log(P.dim(` subject: ${s}`)),process.exit(1))}let i=o.prepare(`SELECT id, ts, source, COALESCE(intent, '-') AS intent, COALESCE(source_event_id, '-') AS source_event_id
|
|
116
|
+
FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(P.dim(` (no events for ${n}:${s})`));return}let r=i.map(d=>d.id),a=r.map((d,m)=>`@id${m}`).join(", "),c=Object.fromEntries(r.map((d,m)=>[`id${m}`,d])),l=o.prepare(`
|
|
117
|
+
SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason,
|
|
118
|
+
r.resolved_at, r.status AS resolution_status, r.duration_ms, r.result_summary
|
|
119
|
+
FROM intent_decisions d
|
|
120
|
+
LEFT JOIN intent_resolutions r
|
|
121
|
+
ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
|
|
122
|
+
WHERE d.event_id IN (${a})
|
|
123
|
+
ORDER BY d.decided_at ASC
|
|
124
|
+
`).all(c);if(t.json){let d=i.map(m=>({event:m,decisions:l.filter(u=>u.event_id===m.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:d},null,2));return}let p=new Set;for(let d of l)d.outcome==="dispatched"&&d.agent_id&&p.add(d.agent_id);console.log(),console.log(P.bold(` Lineage for ${P.cyan(n+":"+s)}`)),console.log(P.dim(` ${i.length} event(s), ${l.length} decision(s), ${p.size} distinct agent(s) dispatched`)),console.log();for(let d of i){let m=new Date(d.ts).toISOString().slice(0,19).replace("T"," ");console.log(` ${P.dim(m)} ${P.bold(d.id)} ${P.dim(`(${d.source}/${d.intent})`)}`);let u=l.filter(h=>h.event_id===d.id);if(u.length===0){console.log(P.dim(" (no decisions yet)"));continue}for(let h of u){let y=h.outcome==="dispatched"?P.green(h.outcome):h.outcome==="dropped"?P.dim(h.outcome):P.yellow(h.outcome),w=h.agent_id?P.cyan(h.agent_id):P.dim("-"),b=h.reason?P.dim(` \u2014 ${h.reason.slice(0,60)}`):"";if(console.log(` ${P.dim(h.decided_by)} \u2192 ${y} ${w}${b}`),h.resolution_status){let $=h.resolution_status==="ok"?P.green(h.resolution_status):P.red(h.resolution_status),S=h.duration_ms?`${(h.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${P.dim("resolved")} ${$} ${P.dim(S)}`)}else h.outcome==="dispatched"&&console.log(` ${P.yellow("(in-flight, no resolution)")}`)}}console.log()});Je.command("replay").description("replay the source ledger onto a fresh tmp ledger; report divergences").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","ledger path relative to cwd",".agentx/intent/ledger.sqlite").option("--since <duration>","limit to events newer than (e.g. 1h, 24h, 7d)").option("-s, --source <name>","filter to one source").option("-n, --limit <n>","max events to replay (defaults to all)").option("--json","emit JSON").action(e=>{let t=kt(e),o=Zt(e.since),n=[],s={};e.source&&(n.push("source = @source"),s.source=e.source),o!==void 0&&(n.push("ts >= @since"),s.since=o);let i=e.limit?`LIMIT ${Number(e.limit)}`:"",r=t.prepare(`
|
|
125
|
+
SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
126
|
+
FROM intent_events
|
|
127
|
+
${n.length?"WHERE "+n.join(" AND "):""}
|
|
128
|
+
ORDER BY ts ASC
|
|
129
|
+
${i}
|
|
130
|
+
`).all(s).map(h=>({id:h.id,ts:h.ts,source:h.source,sourceEventId:h.source_event_id,project:h.project,subject:h.subject,intent:h.intent,rawJson:h.raw_json}));if(r.length===0){console.log(P.dim(" (no events match filter)"));return}let a=new Set(r.map(h=>h.id)),c=r.map((h,y)=>`@id${y}`).join(", "),l=Object.fromEntries(r.map((h,y)=>[`id${y}`,h.id])),p=t.prepare(`
|
|
131
|
+
SELECT event_id, decided_at, decided_by, agent_id, outcome, reason
|
|
132
|
+
FROM intent_decisions
|
|
133
|
+
WHERE event_id IN (${c})
|
|
134
|
+
`).all(l).map(h=>({eventId:h.event_id,decidedAt:h.decided_at,decidedBy:h.decided_by,agentId:h.agent_id,outcome:h.outcome,reason:h.reason})),d=t.prepare(`
|
|
135
|
+
SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
|
|
136
|
+
FROM intent_resolutions
|
|
137
|
+
WHERE decision_event_id IN (${c})
|
|
138
|
+
`).all(l).map(h=>({decisionEventId:h.decision_event_id,decisionDecidedBy:h.decision_decided_by,resolvedAt:h.resolved_at,status:h.status,durationMs:h.duration_ms,resultSummary:h.result_summary})),m=li(Bn(di(),"agentx-ledger-replay-")),u=new ln({path:Bn(m,"target.sqlite")});try{let h=Fn(u,r,p,d);if(e.json){console.log(JSON.stringify(h,null,2));return}console.log(P.bold(`Replayed ${h.eventsCount} events, ${h.decisionsCount} decisions, ${d.length} resolutions`)),h.divergences.length===0?console.log(P.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(P.red(` \u2717 ${h.divergences.length} divergences`)),tt(h.divergences.map(y=>({event_id:y.eventId,decided_by:y.decidedBy,recorded:`${y.expected.outcome}/${y.expected.agentId??"-"}`,replayed:`${y.actual.outcome}/${y.actual.agentId??"-"}`,reason:y.reason.slice(0,80)})),!1))}finally{u.close()}});import{Command as ui}from"commander";import I from"chalk";import{resolve as qn}from"path";import{existsSync as fi}from"fs";import hi from"better-sqlite3";var eo=new ui().name("trace").description("inspect per-task execution traces (.agentx/db.sqlite)");function Jn(e){let t=qn(e.cwd??process.cwd()),o=qn(t,e.path??".agentx/db.sqlite");fi(o)||(console.log(I.red(` No db at ${o}`)),console.log(I.dim(" The file is created on first SQLite write \u2014 start the daemon and run a task.")),process.exit(1));try{return new hi(o,{readonly:!0})}catch(n){console.log(I.red(` Could not open ${o}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(I.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function yi(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let o=Number(t[1]),n=t[2];return o*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function wi(e){if(!e)return;let t=yi(e);if(t===null){let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(I.red(` Invalid --since "${e}". Use "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-t}function $i(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s ago`:t<3600?`${Math.round(t/60)}m ago`:t<86400?`${Math.round(t/3600)}h ago`:`${Math.round(t/86400)}d ago`}function Ro(e){return e==="ok"?I.green:e==="error"||e==="timeout"?I.red:e==="in-flight"?I.yellow:I.dim}eo.command("list").description("list recent traces (newest first)").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--agent <id>","filter by agentId").option("--channel <name>","filter by channel (telegram|whatsapp|gitlab|...)").option("--chat <id>","filter by chatId").option("--workflow <runId>","filter by workflowRunId").option("--status <s>","filter by status (in-flight|ok|error|timeout)").option("--since <duration>","limit to traces newer than (e.g. 1h, 24h, 7d)").option("--limit <n>","max rows","50").option("--json","emit JSON").action(e=>{let t=Jn(e),o=hn(t,{agentId:e.agent,channel:e.channel,chatId:e.chat,workflowRunId:e.workflow,status:e.status,since:wi(e.since),limit:parseInt(e.limit,10)||50});if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(I.dim(" (no traces)"));return}for(let n of o){let s=Ro(n.status)(n.status.padEnd(9)),i=n.durationMs!=null?`${(n.durationMs/1e3).toFixed(2)}s`:"\u2014",r=n.workflowRunId?I.cyan(` wf=${n.workflowRunId}`):"",a=n.inputTokens!=null?I.dim(` ${n.inputTokens}/${n.outputTokens??0} tok`):"";console.log(`${I.dim(n.taskId)} ${s} ${I.bold(n.agentId)}${I.dim(` ${n.channel??"\u2014"}:${n.chatId??"\u2014"}`)}${r} ${I.dim("\xB7")} ${i}${a} ${I.dim($i(n.startedAt))}`),n.error&&console.log(` ${I.red("error:")} ${n.error}`)}});eo.command("show <taskId>").description("show one trace with its full ordered step log").option("--cwd <cwd>","working directory",process.cwd()).option("--path <path>","db path relative to cwd",".agentx/db.sqlite").option("--json","emit JSON").action((e,t)=>{let o=Jn(t),n=fn(o,e);if(n||(console.log(I.red(` No trace at ${e}`)),process.exit(1)),t.json){console.log(JSON.stringify(n,null,2));return}bi(n.task,n.steps)});function bi(e,t){let o=Ro(e.status)(e.status);if(console.log(I.bold(`Trace ${e.taskId}`)),console.log(` ${I.dim("agent")} ${e.agentId}`),console.log(` ${I.dim("channel")} ${e.channel??"\u2014"}:${e.chatId??"\u2014"}`),e.workflowRunId){let n=[e.workflowId,e.workflowNodeId].filter(Boolean).join("/");console.log(` ${I.dim("workflow")} ${I.cyan(e.workflowRunId)}${n?I.dim(` (${n})`):""}`)}if(e.intentEventId&&console.log(` ${I.dim("intent")} ${e.intentEventId} ${I.dim(`(${e.intentDecidedBy??"?"})`)}`),e.model&&console.log(` ${I.dim("model")} ${e.model}`),e.resumeSessionId&&console.log(` ${I.dim("resume")} ${e.resumeSessionId.slice(0,12)}\u2026`),e.finalSessionId&&console.log(` ${I.dim("final")} ${e.finalSessionId.slice(0,12)}\u2026`),console.log(` ${I.dim("status")} ${o}`),e.durationMs!=null&&console.log(` ${I.dim("duration")} ${(e.durationMs/1e3).toFixed(2)}s`),(e.inputTokens!=null||e.outputTokens!=null)&&console.log(` ${I.dim("tokens")} in=${e.inputTokens??0} out=${e.outputTokens??0} cache_read=${e.cacheReadTokens??0} cache_create=${e.cacheCreateTokens??0}`),e.error&&console.log(` ${I.red("error")} ${e.error}`),e.messagePreview&&console.log(` ${I.dim("message")} ${e.messagePreview}`),console.log(),t.length===0){console.log(I.dim(" (no recorded steps \u2014 task may have been on a non-streaming tier or completed before any tool call)"));return}console.log(I.bold(`Steps (${t.length}):`));for(let n of t){let s=n.status?Ro(n.status)(n.status):I.dim("\u2014"),i=n.action?I.cyan(n.action):"";if(console.log(` ${I.dim(`#${n.seq}`)} ${I.bold(n.name)}${i?" "+i:""} ${s}${n.ms!=null?I.dim(` ${n.ms}ms`):""}`),n.inputSummary){let r=n.inputSummary.split(`
|
|
139
|
+
`).slice(0,8);console.log(r.map(a=>` ${I.dim("\u2192")} ${a}`).join(`
|
|
140
|
+
`)),n.inputSummary.split(`
|
|
141
|
+
`).length>8&&console.log(` ${I.dim("\u2026")}`)}if(n.outputSummary){let r=n.outputSummary.split(`
|
|
142
|
+
`).slice(0,8);console.log(r.map(a=>` ${I.dim("\u2190")} ${a}`).join(`
|
|
143
|
+
`)),n.outputSummary.split(`
|
|
144
|
+
`).length>8&&console.log(` ${I.dim("\u2026")}`)}n.error&&console.log(` ${I.red("error:")} ${n.error}`)}}import{Command as ki}from"commander";import Q from"chalk";var to=new ki().name("process").description("inspect / rotate persistent claude processes (--persistentProcess agents)");function Gn(e){let t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let n=R(e.config);t||(t=n.dashboard?.daemonUrl||""),o||(o=n.dashboard?.token||"")}catch{}return t||(t="http://localhost:18800"),{baseUrl:t.replace(/\/+$/,""),token:o}}function Hn(e,t){let o={};return e&&(o.Authorization=`Bearer ${e}`),t&&(o["Content-Type"]=t),o}function zn(e){let t=Math.round((Date.now()-e)/1e3);return t<60?`${t}s`:t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function vi(e){return e==="warm-hot"?Q.green:e==="warm-cold"?Q.cyan:e==="idle"?Q.yellow:e==="dead"?Q.red:Q.dim}to.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:t,token:o}=Gn(e),n;try{n=await fetch(`${t}/api/processes`,{headers:Hn(o)})}catch(r){console.log(Q.red(` could not reach daemon at ${t}: ${r.message||r}`)),process.exit(1)}if(n.status===503){console.log(Q.dim(` daemon at ${t} has no agents with persistentProcess: true`));return}n.ok||(console.log(Q.red(` HTTP ${n.status} from ${t}/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(Q.dim(" (no processes)"));return}for(let r of i){let a=vi(r.state)(r.state.padEnd(9)),c=zn(r.spawnedAt),l=r.lastTurnAt?zn(r.lastTurnAt)+" ago":"\u2014",p=r.lastInputTokens?Q.dim(`last_in=${r.lastInputTokens} tok`):"",d=r.claudeSessionId?Q.dim(`sess=${r.claudeSessionId.slice(0,8)}\u2026`):Q.dim("sess=\u2014"),m=r.pendingTaskId?Q.cyan(`task=${String(r.pendingTaskId).slice(0,12)}`):"";console.log(`${a} ${Q.bold(r.key.agentId)}${Q.dim(":"+r.key.channel+":"+r.key.chatId)} ${Q.dim("\xB7")} pid=${r.pid??"?"} age=${c} turn#${r.turnCount} last=${l} ${d} ${p} ${m}`),r.deadReason&&console.log(` ${Q.red("dead:")} ${r.deadReason}`)}});to.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,t,o,n)=>{let{baseUrl:s,token:i}=Gn(n),r;try{r=await fetch(`${s}/api/processes/kill`,{method:"POST",headers:Hn(i,"application/json"),body:JSON.stringify({agentId:e,channel:t,chatId:o,reason:n.reason})})}catch(a){console.log(Q.red(` could not reach daemon at ${s}: ${a.message||a}`)),process.exit(1)}if(r.status===503){console.log(Q.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(Q.red(` ${a}`)),process.exit(1)}console.log(Q.green(` killed ${e}:${t}:${o}`))});import{Command as xi}from"commander";import F from"chalk";import vt from"prompts";var ot=new xi().name("backlog").description("manage the local backlog used by business workSource=backlog");function Lt(e){let t=R(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new jn(n)}}function Si(e){return e?F.cyan(`${e.type}:${e.project}#${e.iid}`):F.dim("manual")}function ji(e){return{todo:F.gray("todo"),doing:F.yellow("doing"),blocked:F.red("blocked"),done:F.green("done")}[e]}ot.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:t}=Lt(e.config),o=t.list();if(e.status&&(o=o.filter(n=>n.status===e.status)),e.assignee&&(o=o.filter(n=>n.assignee===e.assignee)),e.source&&(o=o.filter(n=>e.source==="manual"?!n.source:n.source?.type===e.source)),!o.length){console.log(F.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?F.magenta(`@${n.assignee}`):F.dim("unassigned");console.log(` ${ji(n.status).padEnd(7)} ${Si(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(F.dim(` ${n.source.url}`))}console.log(),console.log(F.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});ot.command("claim <id> <agent>").description("assign an item to an agent and set status=doing").option("-c, --config <path>","config path").action(async(e,t,o)=>{let n=Lt(o.config);n.store.findById(e)||(console.error(F.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:t,status:"doing"});if(console.log(F.green(` claimed: ${i.title} -> ${t}`)),i.source){let r=Cn([t],i.source,n.config),a=await xo(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(F.dim(" sync:"),...c));console.log(a.ok?F.dim(` synced -> ${a.url??i.source.type}`):F.yellow(` sync failed: ${a.error}`))}});ot.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,t)=>{let o=Lt(t.config);o.store.findById(e)||(console.error(F.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(F.green(` done: ${s.title}`)),s.source){let i=await xo(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...r)=>console.log(F.dim(" sync:"),...r));console.log(i.ok?F.dim(` synced -> ${i.url??s.source.type}`):F.yellow(` sync failed: ${i.error}`))}});ot.command("remove <id>").description("remove an item from the local backlog (does NOT touch upstream)").option("-c, --config <path>","config path").action(async(e,t)=>{let{store:o}=Lt(t.config);o.remove(e)||(console.error(F.red(` item ${e} not found`)),process.exit(1)),console.log(F.green(` removed ${e}`))});ot.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 t=Lt(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(F.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 w=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await vt({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!o&&(console.error(F.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(F.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?Ei(t.config):Ii(t.config);w.length?(i=(await vt({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...w.map($=>({title:$,value:$})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await vt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await vt({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await vt({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(F.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Ai(t.config,i,a):await Oi(t.config,i,a);if(!c.length){console.log(F.yellow(" no open issues matched"));return}console.log(F.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,p=new Set(t.store.list().map(w=>w.id)),d=c.map(w=>{let b=vo({type:s,project:l,iid:w.iid,url:w.url}),$=p.has(b),S=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${S}${$?F.dim(" (already imported)"):""}`,value:w,disabled:$}}),u=(await vt({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!u.length){console.log(F.dim(" nothing selected"));return}let h=u.map(w=>{let b={type:s,host:s==="gitlab"?Ci(t.config):void 0,project:l,iid:w.iid,url:w.url};return{id:vo(b),title:w.title,description:w.description,assignee:e.assignee||w.assignee,labels:w.labels,milestone:w.milestone,status:"todo",source:b,importedAt:new Date().toISOString()}}),y=t.store.addMany(h);console.log(F.green(` imported ${y.length} item${y.length===1?"":"s"}`));for(let w of y)console.log(F.dim(` ${w.id} \u2014 ${w.title}`))});function Ci(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Ei(e){let t=new Set;for(let n of e.channels.gitlab?.routes??[])n.project&&n.project!=="*"&&t.add(n.project);let o=e.business?.workSource;if(o?.type==="gitlab")for(let n of o.projects??[])t.add(n);for(let n of e.business?.projects??[])n?.id&&n.id.includes("/")&&t.add(n.id);return[...t].sort()}function Ii(e){let t=new Set;for(let o of e.channels.github?.routes??[])o.repo&&o.repo!=="*"&&t.add(o.repo);return[...t].sort()}async function Ai(e,t,o){let n=e.channels.gitlab,s=new URLSearchParams({state:"opened",scope:"all",per_page:"100",order_by:"updated_at",sort:"desc"});o&&s.set("search",o);let i=await fetch(`${n.host}/api/v4/projects/${encodeURIComponent(t)}/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 Oi(e,t,o){let s={Authorization:`Bearer ${e.channels.github.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},i;if(o){let c=`repo:${t} is:issue is:open ${o}`;i=`https://api.github.com/search/issues?q=${encodeURIComponent(c)}&per_page=100&sort=updated&order=desc`;let l=await fetch(i,{headers:s});if(!l.ok)throw new Error(`GitHub ${l.status}: ${await l.text().catch(()=>"")}`);return((await l.json()).items??[]).map(Yn)}i=`https://api.github.com/repos/${t}/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(Yn):[]}function Yn(e){return{iid:e.number,title:e.title,description:e.body||void 0,labels:Array.isArray(e.labels)?e.labels.map(t=>typeof t=="string"?t:t.name):[],milestone:e.milestone?.title||void 0,assignee:e.assignee?.login||e.assignees?.[0]?.login||void 0,url:e.html_url}}import{Command as Ti}from"commander";import M from"chalk";import{existsSync as _i,readFileSync as Ni}from"fs";import{resolve as Pi}from"path";import Mi from"prompts";import Ri from"cronstrue";var Do={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},oo={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 Oe(e){try{return Ri.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function Di(e){if(/\b(noon|midday)\b/.test(e))return oo.noon;if(/\bmidnight\b/.test(e))return oo.midnight;let t=e.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(t){let o=parseInt(t[1],10),n=t[2]?parseInt(t[2],10):0,s=t[3];return s==="pm"&&o<12&&(o+=12),s==="am"&&o===12&&(o=0),o>23||n>59?null:{h:o,m:n}}return null}function To(e){let t=e.trim().toLowerCase();if(!t)return null;let o;if(o=t.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let d=parseInt(o[1],10);return d<1||d>59?null:{cron:`*/${d} * * * *`,human:Oe(`*/${d} * * * *`),matched:o[0]}}if(/\bevery\s+minute\b/.test(t))return{cron:"* * * * *",human:Oe("* * * * *"),matched:"every minute"};if(o=t.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let d=parseInt(o[1],10);return d<1||d>23?null:{cron:`0 */${d} * * *`,human:Oe(`0 */${d} * * *`),matched:o[0]}}if(/\b(every hour|hourly)\b/.test(t))return{cron:"0 * * * *",human:Oe("0 * * * *"),matched:"every hour"};let n=Di(t),s=null;for(let[d,m]of Object.entries(oo))if(!(d==="noon"||d==="midnight")&&new RegExp(`\\b(every\\s+)?${d}s?\\b`).test(t)){s=m;break}let i=n||s,r=t.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 d=r[1],m=1;if(d==="last"||(/^\d+(st|nd|rd|th)?$/.test(d)?m=parseInt(d,10):d==="first"||d==="1st"?m=1:d==="2nd"?m=2:d==="3rd"&&(m=3),m<1||m>31))return null;let u=i||{h:9,m:0},h=`${u.m} ${u.h} ${m} * *`;return{cron:h,human:Oe(h),matched:r[0]}}let a=[],c=Object.keys(Do).join("|"),l=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),p=t.match(l);if(p){let d=p[1];for(let m of Object.keys(Do))if(new RegExp(`\\b${m}s?\\b`).test(d)){let u=Do[m];a.includes(u)||a.push(u)}}if(a.length){let d=i||{h:9,m:0};a.sort((h,y)=>h-y);let m=a.join(","),u=`${d.m} ${d.h} * * ${m}`;return{cron:u,human:Oe(u),matched:`on ${m}`}}if(/\b(weekday|workday|business day)s?\b/.test(t)){let d=i||{h:9,m:0},m=`${d.m} ${d.h} * * 1-5`;return{cron:m,human:Oe(m),matched:"weekdays"}}if(/\bweekends?\b/.test(t)){let d=i||{h:9,m:0},m=`${d.m} ${d.h} * * 0,6`;return{cron:m,human:Oe(m),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(t)||s){let d=i||{h:9,m:0},m=`${d.m} ${d.h} * * *`;return{cron:m,human:Oe(m),matched:s&&Object.entries(oo).find(([,u])=>u===s)?.[0]||"daily"}}if(n){let d=`${n.m} ${n.h} * * *`;return{cron:d,human:Oe(d),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function Kn(e,t){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${t}`}function Vn(e){let t=e||Pi(process.cwd(),"agentx.json");return _i(t)||(console.log(M.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(Ni(t,"utf-8"))}function Li(e){return e?e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t==="log"||t==="notify"||t==="disable"):["log"]}async function Wi(e,t){if(!e)return;if(e==="me"){let n=t?.notifications?.destination;if(n?.channel&&n?.chatId)return{channel:n.channel,chatId:n.chatId,accountId:n.accountId};console.log(M.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await Mi([{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 o=e.split(":");if(o.length>=2)return{channel:o[0],chatId:o[1],accountId:o[2]};console.log(M.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var ze=new Ti().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');ze.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,t)=>{if(!e){ze.help();return}t.agent||(console.log(M.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(M.red(' --do "<prompt>" is required')),process.exit(1));let o=To(e);o||(console.log(M.red(` Couldn't parse: "${e}"`)),console.log(M.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(M.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(M.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Vn(t.config),s=gn(n);n.agents?.[t.agent]||(console.log(M.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(M.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=Li(t.onError),r=await Wi(t.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=t.id||Kn(o.matched,t.agent),c={enabled:!t.disabled,schedule:o.cron,timezone:t.timezone,agent:t.agent,prompt:t.do,timeout:parseInt(t.timeout,10),onError:i};t.model&&(c.model=t.model),r&&(c.notify=r);let l=await le(d=>ee(d,`crons.${a}`,c),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(M.red(` \u2717 ${l.error}`)),process.exit(1));let p=t.dryRun?"would add":"Added";console.log(M.green(` \u2713 ${p} cron ${M.cyan(a)}`)),console.log(M.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(M.dim(` Agent: ${t.agent}`)),r&&console.log(M.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(M.dim(` On error: ${i.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(M.dim(" Daemon hot-reloaded."))});ze.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 o=Vn(e.config).crons||{},n=Object.entries(o);if(!n.length){console.log(M.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?M.green("\u25CF"):M.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${M.cyan(s.padEnd(32))} ${M.dim(i.schedule.padEnd(14))} ${M.dim("\u2192")} ${i.agent}`),console.log(M.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(M.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,t]of[["on",!0],["off",!1]])ze.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await le(s=>{if(!Qe(s,`crons.${o}`))throw new Error(`cron "${o}" not found`);ee(s,`crons.${o}.enabled`,t)});n.success||(console.log(M.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(M.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(M.dim(" Daemon hot-reloaded."))});ze.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await le(o=>{if(!Qe(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);pn(o,`crons.${e}`)});t.success||(console.log(M.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(M.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(M.dim(" Daemon hot-reloaded."))});ze.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=To(t);o||(console.log(M.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(M.green(` "${t}"`)),console.log(M.dim(` \u2192 ${o.cron}`)),console.log(M.dim(` \u2192 ${o.human}`))});import{Command as gr}from"commander";import st from"chalk";import J from"chalk";import Wt from"prompts";import{readFileSync as Fi,writeFileSync as Ui,existsSync as Bi}from"fs";import{resolve as Qn}from"path";var qi=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Ji(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function _o(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function Xn(e=".env"){let t=Qn(e);if(!Bi(t))return[];let o=Fi(t,"utf-8"),n=[];for(let s of o.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(qi);i?n.push({kind:"kv",key:i[1],value:Ji(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function zi(e){return e.map(t=>t.kind==="kv"?`${t.key}=${_o(t.value)}`:t.raw).join(`
|
|
145
|
+
`)+`
|
|
146
|
+
`}function nt(e,t,o=".env"){let n=Qn(o),s=Xn(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${_o(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${_o(t)}`})),Ui(n,zi(s))}function No(e,t=".env"){return Xn(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Zn="https://t.me/BotFather";async function Gi(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function Hi(e,t){let o=Date.now()+t,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()<o;)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 es(e={}){console.log(),console.log(J.bold(" Connect Telegram")),console.log(),console.log(J.dim(` 1. Open ${Zn}`)),console.log(J.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(J.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await Wt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:$}=await import("child_process"),S=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";$(S,[Zn],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await Wt({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:$=>/^\d+:[A-Za-z0-9_-]{20,}$/.test($.trim())||"That doesn't look like a Telegram token"});o||(console.log(J.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Gi(o.trim());n||(console.log(J.red("\u2717 invalid or revoked")),process.exit(1)),console.log(J.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(J.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(J.red(" No agents configured. Run: agentx agent add")),process.exit(1));let p=e.agent;p||(p=(await Wt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),p||(console.log(J.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},m=e.account||p;d[m]&&d[m].agentBinding!==p&&(m=(await Wt({type:"text",name:"account",message:`Account "${m}" is already in use. Pick a different label:`,initial:`${p}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),m||(console.log(J.red(" Aborted")),process.exit(1));let u=`TG_${m.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;nt(u,o.trim()),process.env[u]=o.trim();let h=await le($=>{ee($,"channels.telegram.enabled",!0),ee($,`channels.telegram.accounts.${m}`,{token:`\${${u}}`,agentBinding:p});let S=Qe($,`agents.${p}.mentions`)||[],v=`@${n.username}`;S.includes(v)||(S.push(v),ee($,`agents.${p}.mentions`,S))},{configPath:e.configPath});if(h.success||(console.log(J.red(` \u2717 ${h.error}`)),process.exit(1)),console.log(),console.log(J.green(` \u2713 Bot @${n.username} bound to agent "${p}"`)),console.log(J.dim(` Token stored in .env as ${u}`)),console.log(J.dim(` Mentions updated to include @${n.username}`)),h.reloaded?console.log(J.dim(" Daemon hot-reloaded.")):console.log(J.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Wt({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(J.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(J.dim(" Waiting up to 90s..."));let w=await Hi(o.trim(),9e4);if(!w){console.log(J.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(J.dim(" agentx config set notifications.destination.channel telegram")),console.log(J.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(J.dim(` agentx config set notifications.destination.accountId ${m}`));return}let b=await le($=>{ee($,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:m})},{configPath:e.configPath});if(!b.success){console.log(J.red(` \u2717 failed to save destination: ${b.error}`));return}console.log(J.green(" \u2713 Default --notify target set")),console.log(J.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(J.dim(" From now on, --notify me resolves to this chat.")),b.reloaded&&console.log(J.dim(" Daemon hot-reloaded."))}import X from"chalk";import no from"prompts";import{spawn as Yi}from"child_process";var ts="https://discord.com/developers/applications",Ki="67584";async function Vi(e){try{let t=await fetch("https://discord.com/api/v10/users/@me",{headers:{Authorization:`Bot ${e}`},signal:AbortSignal.timeout(8e3)});return t.ok?await t.json():null}catch{return null}}function os(e){try{let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Yi(t,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}async function ns(e={}){console.log(),console.log(X.bold(" Connect Discord")),console.log(),console.log(X.dim(" 1. Open the Discord Developer Portal")),console.log(X.dim(` ${ts}`)),console.log(X.dim(" 2. New Application \u2192 Bot \u2192 Reset Token \u2192 copy the token")),console.log(X.dim(" 3. Under Bot \u2192 Privileged Gateway Intents,")),console.log(X.dim(" enable 'MESSAGE CONTENT INTENT'")),console.log();let{openBrowser:t}=await no({type:"confirm",name:"openBrowser",message:"Open the Developer Portal in your browser?",initial:!0});t&&os(ts);let{token:o}=await no({type:"password",name:"token",message:"Paste the bot token:",validate:w=>w.trim().length>20||"that looks too short for a Discord token"});o||(console.log(X.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Vi(o.trim());n||(console.log(X.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(X.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(X.red(` No agentx.json at ${c}. Run: agentx init`)),process.exit(1));let l=JSON.parse(i(c,"utf-8")),p=Object.keys(l.agents||{});p.length===0&&(console.log(X.red(" No agents configured. Run: agentx agent add")),process.exit(1));let d=e.agent;d||(d=(await no({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:p.map(b=>({title:b,value:b})),initial:0})).agent),d||(console.log(X.red(" Aborted")),process.exit(1));let m="DISCORD_BOT_TOKEN";nt(m,o.trim()),process.env[m]=o.trim();let u=await le(w=>{ee(w,"channels.discord.enabled",!0),ee(w,"channels.discord.token",`\${${m}}`),ee(w,"channels.discord.agentBinding",d)},{configPath:e.configPath});u.success||(console.log(X.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(X.green(` \u2713 Discord bot ${s} bound to agent "${d}"`)),console.log(X.dim(` Token stored in .env as ${m}`)),u.reloaded?console.log(X.dim(" Daemon hot-reloaded.")):console.log(X.dim(" Restart the daemon to start Discord polling.")),console.log(),console.log(X.bold(" Install the bot to a server")),console.log();let h=`https://discord.com/oauth2/authorize?client_id=${n.id}&scope=bot&permissions=${Ki}`;console.log(` ${X.cyan(h)}`),console.log();let{openInstall:y}=await no({type:"confirm",name:"openInstall",message:"Open the install URL in your browser now?",initial:!0});y&&os(h),console.log(),console.log(X.dim(" After you pick a server, the bot will come online on the next daemon restart.")),console.log(X.dim(" Mention the bot in any channel to route messages to the agent."))}import K from"chalk";import Po from"prompts";import{existsSync as Lo,mkdirSync as Qi,readdirSync as Xi,readFileSync as ss}from"fs";import{resolve as Mo}from"path";var Zi=".agentx/whatsapp-sessions";function er(){let e=Mo(process.cwd(),".agentx/daemon.pid");if(!Lo(e))return!1;try{let t=parseInt(ss(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function tr(e){if(!Lo(e))return!1;try{return Xi(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function or(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(K.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(K.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;Qi(e,{recursive:!0});let{state:i,saveCreds:r}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:i.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(i.keys,c):i.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",r),await new Promise(p=>{let m=setTimeout(()=>{t(K.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}p(!1)},12e4);l.ev.on("connection.update",async u=>{if(u.qr){t(K.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:h}=await import("qrcode-terminal");h.generate(u.qr,{small:!0})}catch{t(` QR: ${u.qr}`)}t("")}if(u.connection==="open"){clearTimeout(m),t(K.green(" \u2713 Paired"));try{l.end(void 0)}catch{}p(!0)}u.connection==="close"&&!u.qr&&u.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(m),t(K.red(" \u2717 Authorization failed \u2014 rescan required")),p(!1))})})}async function is(e={}){if(console.log(),console.log(K.bold(" Connect WhatsApp")),console.log(),er()){console.log(K.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(K.dim(" agentx daemon stop")),console.log();let{cont:l}=await Po({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(K.red(" Aborted")),process.exit(1))}let t=e.configPath||Mo(process.cwd(),"agentx.json");Lo(t)||(console.log(K.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(ss(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||Zi,s=Mo(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log(K.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Po({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(p=>({title:p,value:p})),initial:0})).agent),r||(console.log(K.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(tr(s)&&a){let{keep:l}=await Po({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(K.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await or(s,p=>console.log(p))||(console.log(K.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await le(l=>{ee(l,"channels.whatsapp.enabled",!0),ee(l,"channels.whatsapp.sessionDir",n),ee(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(K.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(K.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(K.dim(` Session: ${n}`)),console.log(K.dim(" Start the daemon to begin receiving:")),console.log(K.dim(" agentx daemon start")),console.log(K.dim(" Add routes later with:")),console.log(K.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as nr}from"crypto";import oe from"chalk";import rs from"prompts";var so="agentx-mesh:",io="//join/";function sr(e){return Buffer.from(e,"utf-8").toString("base64url")}function ir(e){return Buffer.from(e,"base64url").toString("utf-8")}function rr(e){return`${so}${io}${sr(JSON.stringify(e))}`}function ar(e){if(!e.startsWith(`${so}${io}`))throw new Error(`Not a mesh invite link \u2014 expected ${so}${io}\u2026`);let t=e.slice(so.length+io.length),o=JSON.parse(ir(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function cr(){return nr(32).toString("hex")}function lr(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function dr(e){return e?.node?.name||e?.node?.id||"node"}async function as(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(oe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=No("MESH_TOKEN");r||(r=cr(),nt("MESH_TOKEN",r),console.log(oe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||lr(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await rs({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:m=>/^https?:\/\//.test(m)||"must start with http:// or https://"});d||(console.log(oe.red(" Aborted")),process.exit(1)),a=d}let l=await le(d=>{ee(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(oe.red(` \u2717 ${l.error}`)),process.exit(1));let p=rr({url:a,token:r,name:dr(i),version:1});console.log(),console.log(oe.bold(" Mesh invite")),console.log(),console.log(` ${oe.cyan(p)}`),console.log(),console.log(oe.dim(" Run on the other node:")),console.log(oe.dim(` agentx connect mesh join "${p}"`)),console.log(),console.log(oe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function cs(e,t={}){let o;try{o=ar(e)}catch(i){console.log(oe.red(` \u2717 ${i.message}`)),process.exit(1)}let n=No("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await rs({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(oe.red(" Aborted (keeping existing .env)")),process.exit(1))}nt("MESH_TOKEN",o.token);let s=await le(i=>{ee(i,"mesh.enabled",!0);let r=Qe(i,"mesh.peers")||[],a=r.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?r[a]=c:r.push(c),ee(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(oe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(oe.green(" \u2713 Joined mesh")),console.log(oe.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(oe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(oe.dim(" Daemon hot-reloaded.")):console.log(oe.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${o.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(oe.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(oe.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(oe.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var it=new gr().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");it.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 es({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});it.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 ns({agent:e.agent,configPath:e.config})});it.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 is({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var ls=it.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");ls.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 as({url:e.url,configPath:e.config})});ls.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await cs(e,{configPath:t.config})});it.action(()=>{console.log(),console.log(st.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${st.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${st.cyan("agentx connect discord")} \u2014 pair a Discord bot, emit install URL`),console.log(` ${st.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${st.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${st.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(st.dim(" GitLab connect is the next slice.")),console.log()});import{Command as mr}from"commander";import $e from"chalk";var ro=new mr().name("usage").description("token usage analysis and reporting");ro.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=R(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log($e.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log($e.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${$e.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: ${$e.red(String(s.totalErrors))}`),console.log(),console.log($e.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of r){let l=i(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),p=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${$e.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${$e.dim(p)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log($e.red(" Daemon not running. Start with: agentx daemon start")):console.log($e.red(` ${e.message}`))}});ro.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:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log($e.red(` Script not found: ${s}`)),console.log($e.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log($e.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log($e.red(" Analysis failed. Is Python 3 installed?"))}});import{Command as pr}from"commander";import V from"chalk";var Ge=new pr().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ge.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 t=ur(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-2CPBWFOB.js");o(t)}catch(t){console.log(V.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(V.dim(t.stack)),process.exit(1)}});function ur(e,t){try{let o=R();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(V.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(V.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
147
|
+
`)),{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:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Ge.command("list").description("list configured boards").action(()=>{try{let e=R();if(!e.boards?.length){console.log(V.dim(`
|
|
148
|
+
No boards configured.
|
|
149
|
+
`));return}console.log();for(let t of e.boards){console.log(` ${V.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(V.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(V.dim(` primary label: ${t.primaryToolLabel}`)),console.log(V.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(V.red(` ${e.message}`)),process.exit(1)}});Ge.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,t)=>{try{Ft(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(i=>i.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.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:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(V.red(` ${o.message}`)),process.exit(1)}});Ge.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,t)=>{try{Ft(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(r=>r.id===e);if(!s)throw new Error(`board "${e}" not found`);let i=[];if(t.name&&(s.name=t.name,i.push(`name="${t.name}"`)),t.projects){let r=String(t.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(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,i.push("label cleared")):(s.primaryToolLabel=t.label,i.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,i.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.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(o){console.log(V.red(` ${o.message}`)),process.exit(1)}});var Wo=Ge.command("column").description("manage a board's columns (add / remove / edit / list)");Wo.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(Bs("fs").readFileSync("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log(V.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(` ${V.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${V.dim(i)}`)}}catch(t){console.log(V.red(` ${t.message}`)),process.exit(1)}});Wo.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,t,o)=>{try{Ft(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===t))throw new Error(`column "${t}" already exists on board "${e}"`);let r={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");r.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");r.mapsToLabel=o.label}return o.accent&&(r.accent=o.accent),i.columns.push(r),`column "${t}" added to board "${e}"`})}catch(n){console.log(V.red(` ${n.message}`)),process.exit(1)}});Wo.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Ft(o=>{let s=(Array.isArray(o.boards)?o.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!==t),s.columns.length===i)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(V.red(` ${o.message}`)),process.exit(1)}});Ge.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Ft(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(V.red(` ${t.message}`)),process.exit(1)}});function Ft(e){let{summary:t,backupPath:o}=ut(n=>e(n));console.log(V.green(`
|
|
150
|
+
\u2713 ${t}
|
|
151
|
+
`)),o&&console.log(V.dim(` Backup: ${o}`)),console.log(V.dim(` Restart the dashboard to pick up the change if not auto-reloading.
|
|
152
|
+
`))}import{Command as hr}from"commander";import g from"chalk";function ds(e,t,o,n,s,i){return fr(t,o,n,s,i)}function fr(e,t,o,n,s){let i=t?`
|
|
153
|
+
## Worldview
|
|
154
|
+
|
|
155
|
+
${t}
|
|
156
|
+
`:"",r=new Map;for(let c of o){let l=c.type||"untyped",p=r.get(l)||[];p.push(c),r.set(l,p)}let a=o.length===0?"":`
|
|
157
|
+
## Existing Articles (the current catalog)
|
|
158
|
+
|
|
159
|
+
`+Array.from(r.entries()).sort().map(([c,l])=>`**${c}**
|
|
160
|
+
`+l.sort((p,d)=>p.title.localeCompare(d.title)).map(p=>`- [[${p.title}]] \u2014 ${p.path}`).join(`
|
|
161
|
+
`)).join(`
|
|
162
|
+
|
|
163
|
+
`)+`
|
|
164
|
+
`;return`You are compiling a personal wiki for the "${e}" agent in the Karpathy / Farzapedia pattern.
|
|
165
|
+
|
|
166
|
+
## The Pattern (read this first \u2014 it shapes every decision below)
|
|
167
|
+
|
|
168
|
+
The wiki is a compounding knowledge base of interlinked markdown articles that a future LLM will read by walking the graph, NOT by bag-of-words search. Your job is to produce articles that another agent can navigate via \`type\` + wikilinks. If the wikilinks don't form a coherent graph, the wiki is useless regardless of how many tags you add.
|
|
169
|
+
|
|
170
|
+
**Three rules, in priority order:**
|
|
171
|
+
|
|
172
|
+
1. **\`type\` is the organizational spine.** Every article has exactly one of: \`person | project | place | concept | event | decision | pattern\`. Choose the type BEFORE writing; if you can't pick one, the article probably isn't needed.
|
|
173
|
+
2. **\`related\` is the navigation surface.** Every article cross-references 2\u20135 other articles via \`[[Article Title]]\` wikilinks in the body AND lists them in the \`related\` frontmatter field. Links the reader could follow to learn more.
|
|
174
|
+
3. **Tags are a secondary hint, not a retrieval spine.** 2\u20134 specific tags max. Do NOT tag aggressively. Do NOT tag with dates unless the article is an \`event\`. Do NOT tag with generic terms ("deploy", "work") that will match half the corpus.
|
|
175
|
+
|
|
176
|
+
## Path convention
|
|
177
|
+
|
|
178
|
+
Path reflects type: \`<type>s/<slug>.md\` where slug is a kebab-case title.
|
|
179
|
+
|
|
180
|
+
- People: \`people/anis-marrouchi.md\`
|
|
181
|
+
- Projects: \`projects/mtgl-system-v2.md\`
|
|
182
|
+
- Concepts: \`concepts/staging-deployment.md\`
|
|
183
|
+
- Events: \`events/YYYY-MM-DD-<slug>.md\` (date in path)
|
|
184
|
+
- Decisions: \`decisions/<slug>.md\`
|
|
185
|
+
- Patterns: \`patterns/<slug>.md\`
|
|
186
|
+
- Places: \`places/<slug>.md\`
|
|
187
|
+
|
|
188
|
+
## How to process entries
|
|
189
|
+
|
|
190
|
+
For each of the ${s} raw entries below, ask in this order:
|
|
191
|
+
|
|
192
|
+
1. **Does it extend an existing article?** If a person/project/concept mentioned in the entry already has an article in the catalog, produce an UPDATE with the full merged content. Prefer merging over proliferating.
|
|
193
|
+
2. **Does it deserve a new article?** Only if the subject is a persistent entity (a person, a project, a recurring concept, a specific event/decision) that future queries will need to find. Not every conversation deserves an article.
|
|
194
|
+
3. **Does it belong in an existing \`event\` or \`decision\`?** Most work entries fold into one of these.
|
|
195
|
+
4. **Can you skip it?** If the entry is small talk, a transient status ping, or already covered elsewhere \u2014 skip. The wiki is curated, not exhaustive.
|
|
196
|
+
|
|
197
|
+
## Writing standards
|
|
198
|
+
|
|
199
|
+
- **Wikipedia-style, flat, factual, encyclopedic.** This is the agent's knowledge, not a diary. Write about the *role* of the entity in our work, not a product description.
|
|
200
|
+
- **Synthesize, don't quote.** At most 2 short quoted lines per article.
|
|
201
|
+
- **Organize by theme, not chronology.** An article about a person lists what they do, who they work with, how they prefer to be contacted \u2014 not a log of every interaction.
|
|
202
|
+
- **Length: 20\u2013100 lines.** Articles exceeding 100 lines should split into multiple type-specific articles.
|
|
203
|
+
- **Every paragraph earns its place.** Cut narrative filler. If you can remove a sentence without losing a fact, remove it.
|
|
204
|
+
|
|
205
|
+
## Wikilink discipline
|
|
206
|
+
|
|
207
|
+
- Use \`[[Article Title]]\` **inside the body** every time another tracked entity is referenced.
|
|
208
|
+
- List those same targets in the \`related\` frontmatter field.
|
|
209
|
+
- If you reference something that has no article yet (\`[[New Thing]]\`), add "New Thing" to the output \`gaps\` array so the next pass can create it.
|
|
210
|
+
|
|
211
|
+
## Article frontmatter (exact shape \u2014 do not invent fields)
|
|
212
|
+
|
|
213
|
+
\`\`\`yaml
|
|
214
|
+
---
|
|
215
|
+
title: "Article Title"
|
|
216
|
+
type: person | project | place | concept | event | decision | pattern
|
|
217
|
+
related: ["Other Article", "Another Article"]
|
|
218
|
+
tags: ["2-4-specific-tags", "no-dates-unless-event"]
|
|
219
|
+
owner: ${e}
|
|
220
|
+
access: public | shared | private
|
|
221
|
+
created: YYYY-MM-DD
|
|
222
|
+
last_updated: YYYY-MM-DD
|
|
223
|
+
sources: ["entry-id-1", "entry-id-2"]
|
|
224
|
+
---
|
|
225
|
+
\`\`\`
|
|
226
|
+
|
|
227
|
+
Access guidance: default \`public\`; \`private\` only for sensitive credentials or agent-specific learnings; \`shared\` with specific agent IDs when the article matters only to a subset.
|
|
228
|
+
${i}${a}
|
|
229
|
+
## Gap Detection
|
|
230
|
+
|
|
231
|
+
After compiling, populate a \`gaps\` array: wikilink targets you referenced but for which no article exists yet. Be specific:
|
|
232
|
+
|
|
233
|
+
- Good: "Karim Rahmouni \u2014 coach for Tunis Padel club, mentioned twice but no \`people/\` article"
|
|
234
|
+
- Bad: "We need more content about deployments"
|
|
235
|
+
|
|
236
|
+
## Output \u2014 valid JSON only, no markdown fencing
|
|
237
|
+
|
|
238
|
+
\`\`\`
|
|
239
|
+
{
|
|
240
|
+
"articles": [
|
|
241
|
+
{
|
|
242
|
+
"path": "projects/mtgl-system-v2.md",
|
|
243
|
+
"title": "MTGL System V2",
|
|
244
|
+
"type": "project",
|
|
245
|
+
"related": ["Anis Marrouchi", "Laravel", "Staging Deployment"],
|
|
246
|
+
"tags": ["mtgl", "laravel", "react"],
|
|
247
|
+
"content": "MTGL System V2 is [[Anis Marrouchi]]'s production Laravel + React app for \u2026",
|
|
248
|
+
"sources": ["entry-id-1", "entry-id-2"]
|
|
249
|
+
}
|
|
250
|
+
],
|
|
251
|
+
"gaps": [
|
|
252
|
+
"Karim Rahmouni \u2014 Tunis Padel coach, mentioned in entries but no people/ article"
|
|
253
|
+
]
|
|
254
|
+
}
|
|
255
|
+
\`\`\`
|
|
256
|
+
|
|
257
|
+
ENTRIES (${s}):
|
|
258
|
+
|
|
259
|
+
${n}`}import{resolve as _,relative as gs,dirname as ms}from"path";import{execSync as rt}from"child_process";import{writeFileSync as at,mkdirSync as Pe,readFileSync as Ut,readdirSync as yr,renameSync as ao,rmSync as wr,existsSync as Ce}from"fs";function ue(e,t){return new ko(e||_(process.cwd(),".agentx/wiki"),void 0,t||"graph")}function Uo(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var Z=new hr().name("wiki").description("wiki knowledge base management");Z.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").action(e=>{let t=e.mode,o=ue(e.dir,t),n=o.summary(),i=o.getSharedStore().listEntries().length;console.log(),console.log(g.bold(` Wiki Hub Status [${Uo(t)}]`)),console.log(),console.log(` Total raw entries: ${i}`),console.log(` Agents: ${n.length}`),console.log();for(let a of n){let c=a.unabsorbed>0?g.yellow(`${a.unabsorbed} unabsorbed`):g.green("up to date");if(console.log(` ${g.cyan(a.agentId)}`),console.log(` Entries: ${a.totalEntries} Articles: ${a.totalArticles} ${c}`),a.articles.length>0){for(let l of a.articles.slice(0,3))console.log(g.dim(` - ${l.title} [${(l.tags||[]).slice(0,3).join(", ")}]`));a.articles.length>3&&console.log(g.dim(` ... and ${a.articles.length-3} more`))}console.log()}let r=n.reduce((a,c)=>a+c.unabsorbed,0);r>0&&(console.log(g.dim(` ${r} raw entries on disk. Absorb is deprecated \u2014 see 'agentx wiki absorb --help'.`)),console.log())});Z.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","lint a specific agent's wiki").action(e=>{let t=ue(e.dir,e.mode),o=e.agent?[e.agent]:t.listAgents(),n=0;console.log();for(let s of o){let r=t.getAgentWiki(s).lint();if(n+=r.length,r.length===0)console.log(` ${g.cyan(s)}: ${g.green("healthy")}`);else{console.log(` ${g.cyan(s)}: ${g.yellow(`${r.length} issues`)}`);for(let a of r){let c=a.type==="broken-link"?"x":a.type==="orphan"?"?":"!";console.log(` [${c}] ${g.dim(a.type)} ${a.article}: ${a.message}`)}}}console.log(),n===0&&console.log(g.green(" All agent wikis are healthy")),console.log()});Z.command("absorb").description("compile unabsorbed entries into typed per-agent wiki articles (Farzapedia-faithful)").option("--dir <path>","wiki directory").option("--mode <mode>","graph (default, canonical) | unified | flat (legacy, back-compat)","graph").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--max <n>","max entries per agent","10").action(async e=>{let t=e.mode,o=ue(e.dir,t),n=e.agent?[e.agent]:o.listAgents(),s=parseInt(e.max),i=(()=>{try{let d=_(process.cwd(),".agentx/graph");return Ce(d)?new Ve({baseDir:d}):null}catch{return null}})(),r=new Map;if(i)try{let d=i.loadIndex();for(let[m,u]of Object.entries(d.entries))r.set(m,u.path)}catch{}let a=d=>{let m=d.meta?.intentPath;if(Array.isArray(m)&&m.every(y=>typeof y=="string")&&m.length>0)return m;if(!i||r.size===0)return;let u=String(d.meta?.sender??""),h=i.fingerprint({text:d.content,channel:d.source,sender:u});return r.get(h)},c=(d,m)=>{let u=new Map;for(let y of d){let w=m.find(v=>v.id===y);if(!w)continue;let b=a(w);if(!b?.length)continue;let $=b.join("/"),S=u.get($);S?S.n++:u.set($,{path:b,n:1})}if(u.size===0)return;let h;for(let y of u.values())(!h||y.n>h.n)&&(h=y);return h?.path},l=0,p=0;for(let d of n){let m=o.getUnabsorbedEntries(d).slice(0,s);if(m.length===0){console.log(` ${g.cyan(d)}: ${g.green("all absorbed")}`);continue}console.log(),console.log(g.bold(` ${g.cyan(d)}: ${m.length} entries to absorb`));for(let v of m.slice(0,3))console.log(g.dim(` [${v.date} via ${v.source}] ${v.content.slice(0,80)}...`));if(m.length>3&&console.log(g.dim(` ... and ${m.length-3} more`)),e.dryRun)continue;let u=o.getAgentWiki(d),h=u.rebuildIndex(),y=u.getWorldview()||o.getSharedStore().getWorldview()||"",w=m.map(v=>`--- ENTRY ${v.id} [${v.date} ${v.agentId} via ${v.source}] ---
|
|
260
|
+
${v.content}
|
|
261
|
+
--- END ENTRY ---`).join(`
|
|
262
|
+
|
|
263
|
+
`),b=ds(t,d,y,h.articles,w,m.length);console.log(g.dim(` Mode: ${Uo(t)}`));let $=_(u.baseDir,"_tmp");Pe($,{recursive:!0});let S=_($,"absorb-prompt.txt");at(S,b),console.log(g.dim(" Compiling with Claude..."));try{let v;try{v=rt(`cat '${S}' | claude -p - --output-format json --max-turns 3 --model sonnet --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,{encoding:"utf-8",timeout:9e5,maxBuffer:10*1024*1024})}catch(E){if(v=E.stdout||"",!v)throw E}let k=v;try{let E=JSON.parse(v);k=E.result||E.content||"",k||(console.log(g.dim(` Claude envelope keys: ${Object.keys(E).join(", ")}`)),console.log(g.dim(` is_error: ${E.is_error}, stop_reason: ${E.stop_reason}`)))}catch{}let C,j=[],L=k.indexOf("{"),W=k.indexOf("["),O=L>=0&&(W<0||L<W)?L:W;if(O===-1){console.log(g.red(" No JSON found in response")),console.log(g.dim(k.slice(0,500)));continue}let pe=k[O],we=pe==="{"?"}":"]",Me=0,ce=-1;for(let E=O;E<k.length;E++)if(k[E]===pe)Me++;else if(k[E]===we&&(Me--,Me===0)){ce=E+1;break}if(ce===-1){console.log(g.red(" Unbalanced JSON"));continue}let ke=k.slice(O,ce);try{let E=JSON.parse(ke);Array.isArray(E)?C=E:(C=E.articles||[],j=E.gaps||[])}catch(E){console.log(g.red(` JSON parse error: ${E.message}`)),console.log(g.dim(` First 300 chars: ${ke.slice(0,300)}`));continue}for(let E of C){let De=new Date().toISOString().slice(0,10),ve=c(E.sources||[],m);u.writeArticle(E.path,{title:E.title,type:E.type,related:Array.isArray(E.related)?E.related:void 0,tags:E.tags||[],owner:d,access:"public",created:De,lastUpdated:De,sources:E.sources||[],graphPath:ve},E.content,d);let rn=E.type?g.magenta(`[${E.type}]`)+" ":"",wo=Array.isArray(E.related)&&E.related.length?` \u2192 ${E.related.slice(0,3).join(", ")}${E.related.length>3?", \u2026":""}`:"";console.log(` ${g.green("+")} ${rn}${E.path}: ${E.title}${g.dim(wo)}`);let Dt=(E.tags||[]).slice(0,4).join(", ");Dt&&console.log(g.dim(` tags: ${Dt}`)),ve?.length&&(console.log(g.dim(` graphPath: ${ve.join(" \u203A ")}`)),p++),l++}if(j.length>0){console.log(),console.log(g.yellow(` Gaps detected (${j.length} missing pieces):`));for(let E of j)console.log(g.yellow(` ? ${E}`))}u.rebuildIndex()}catch(v){console.log(g.red(` Absorb failed: ${v.message?.slice(0,200)}`)),v.stderr&&console.log(g.dim(String(v.stderr).slice(0,300))),v.stdout&&console.log(g.dim("stdout: "+String(v.stdout).slice(0,300)))}}if(console.log(),e.dryRun)console.log(g.dim(" Dry run \u2014 no changes made"));else if(l>0&&(console.log(g.green(` ${l} articles compiled across ${n.length} agent(s)`)),i)){let d=l>0?Math.round(p/l*100):0;console.log(g.dim(` ${p}/${l} carry graphPath (${d}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});Z.command("ab-test").description("side-by-side comparison: BM25 preload (old) vs agentic query (new) on real task-history messages").option("--dir <path>","wiki directory").option("--agent <id>","which agent to test against (required)").option("--history <path>","task-history root",_(process.cwd(),".agentx/task-history")).option("--n <n>","number of messages to sample (newest first)","10").option("--out <path>","markdown output file (default: stdout)").option("--selector-model <m>","agentic selector model","haiku").option("--synth-model <m>","agentic synthesis model","sonnet").action(async e=>{let{agenticQuery:t}=await import("./query-HZYYRCLU.js"),{readdirSync:o,readFileSync:n,existsSync:s}=await import("fs"),{resolve:i,join:r}=await import("path"),a=ue(e.dir),c=e.agent;if(!c){console.log(g.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),p=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(g.yellow(` no task-history at ${d}`));return}let m=[],u=o(d).sort().reverse();for(let w of u){let b=r(d,w),$=[];try{$=o(b).filter(S=>S.endsWith(".json")).sort().reverse()}catch{continue}for(let S of $){if(m.length>=p)break;try{let v=JSON.parse(n(r(b,S),"utf-8")),k=v.message||v.task?.message;typeof k=="string"&&k.trim().length>10&&m.push({id:v.id||S.replace(".json",""),message:k.trim(),ts:v.at||v.timestamp||w})}catch{}}if(m.length>=p)break}if(m.length===0){console.log(g.yellow(` no task messages found under ${d}`));return}console.log(),console.log(g.bold(` A/B harness \u2014 ${m.length} messages from ${c}`)),console.log(g.dim(" OLD: findRelevant() BM25 over title+tags+content, top 3 truncated")),console.log(g.dim(` NEW: agenticQuery() catalog+wikilink walk (selector=${e.selectorModel}, synth=${e.synthModel})`)),console.log();let h=[`# Wiki A/B: ${c}`,"",`_Generated ${new Date().toISOString()} \xB7 ${m.length} messages sampled_`,"","For each message, the OLD BM25 retrieval (what Layer 10 used to preload) is shown alongside the NEW agentic query's selected articles + synthesized answer. Rate each pair on relevance 0\u20132 in the notes column.",""];for(let w=0;w<m.length;w++){let b=m[w];process.stdout.write(g.dim(` [${w+1}/${m.length}] querying... `));let S=l.findRelevant(b.message,c,3).map(k=>`- **${k.meta.title}** [${k.meta.type||"?"}] (${k.path})`).join(`
|
|
264
|
+
`)||"_(none returned)_",v;try{let k=await t(b.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(k.status!=="ok")v=`_(status: ${k.status}${k.error?" \u2014 "+k.error:""})_`;else{let C=k.citations.map(j=>`\`${j.title}\` [${j.type||"?"}]`).join(", ");v=`**Answer:**
|
|
265
|
+
|
|
266
|
+
${k.answer}
|
|
267
|
+
|
|
268
|
+
**Citations:** ${C}`}}catch(k){v=`_(error: ${k.message})_`}console.log(g.dim("done")),h.push(`## ${w+1}. ${b.id}`,"",`> ${b.message.replace(/\n/g," ").slice(0,400)}${b.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",S,"","### NEW \u2014 agentic query","",v,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let y=h.join(`
|
|
269
|
+
`);e.out?((await import("fs")).writeFileSync(e.out,y),console.log(),console.log(g.green(` Wrote ${y.length} bytes to ${e.out}`))):(console.log(),console.log(y))});Z.command("interview").description("interactive interview session \u2014 Q&A with an LLM synthesizer, produces one typed wiki article").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to write to (required)").option("--topic <text>","what to interview about (e.g. 'MTGL deployment procedure')").option("--type <t>","article type hint (person|project|place|concept|event|decision|pattern)").option("--model <m>","synthesis model","sonnet").option("--no-commit","show the draft but don't write").option("--answers <path>","non-interactive: one answer per line (same order as questions); last line = save|edit|scrap").action(async e=>{let t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{WIKI_ARTICLE_TYPES:n}=await import("./types-VECTMYTO.js"),s=e.answers?Ut(e.answers,"utf-8").split(/\r?\n/).filter(A=>A.length>0):null,i=0;if(!e.agent){console.log(g.red(" --agent <id> is required. The article will be owned by this agent."));return}let r=ue(e.dir),a;try{a=r.getAgentWiki(e.agent)}catch(A){console.log(g.red(` can't open wiki for agent "${e.agent}": ${A.message}`));return}let c=s?null:t.createInterface({input:process.stdin,output:process.stdout}),l=async A=>{if(s){let ae=s[i++]??"";return process.stdout.write(A+g.dim(`[scripted] ${ae.slice(0,80)}${ae.length>80?"\u2026":""}`)+`
|
|
270
|
+
`),ae.trim()}return(await c.question(A)).trim()};console.log(),console.log(g.bold(" Wiki Interview")),console.log(g.dim(" One article per session. Empty answer = skip field. /done = stop & synthesize. /abort = quit.")),console.log();let p=e.topic||"";if(!p&&(p=await l(g.cyan(" Topic? ")+g.dim("(a person, a procedure, a past event, \u2026) ")),!p||p==="/abort")){c?.close();return}let d=(e.type||"").toLowerCase(),m=new Set(n);if(!m.has(d)){console.log(g.dim(` Types: ${n.join(" | ")}`));let A=await l(g.cyan(" Type? "));if(A==="/abort"){c?.close();return}m.has(A)?d=A:(console.log(g.yellow(` "${A}" isn't a valid type. Falling back to "concept".`)),d="concept")}let u={person:["Full name (and any aliases / Telegram handle / GitLab username)?","Role or title?","Which org or team are they part of (use the article title if you have one)?","Key responsibilities in OUR work?","Preferred channel to reach them (Telegram, email, in-person, \u2026)?","Who do they report to? (skip if none)","Notable decisions, events, or patterns they're involved in?","Anything quirky we should remember (timezone, working hours, style)?"],project:["One-line description \u2014 what is this project?","Who owns it? (person article title)","Tech stack or key tools involved?","Current status (active / paused / archived)?","Repo / URL / path on disk?","Two or three key decisions made so far?","Any open blockers, risks, or known issues?","Related projects or patterns?"],place:["Kind \u2014 office / server / environment / domain / URL?","Address \u2014 URL, IP, hostname, or physical location?","Owner (person or team)?","How to access it (SSH host, login, VPN, \u2026)?","What lives there (services, people, data)?","Known quirks (timezone, uptime, access restrictions)?"],concept:["Define it in one sentence \u2014 what does this term mean in OUR work?","Where did we first adopt it (origin story, date)?","Two or three concrete examples from our team?","What does it replace or extend (older concept, related concept)?","Common misunderstandings to avoid?"],event:["Date (YYYY-MM-DD)?","One-line summary \u2014 what happened?","Who was involved?","Timeline \u2014 key moments (start \u2192 resolution)?","Impact \u2014 what broke, what got delivered, who was affected?","Resolution / outcome?","Follow-ups or lessons captured?"],decision:["Context \u2014 what was the situation forcing a choice?","Options that were considered?","Chosen option \u2014 and one-sentence why?","Alternatives rejected \u2014 and one-sentence why not?","Who decided, and when (date)?","Is this reversible, and what would trigger a revisit?"],pattern:["Trigger \u2014 when should someone follow this pattern?","Inputs required (what do you need before starting)?","Steps in order \u2014 keep it tight, one line per step?","Expected output \u2014 how do you know it worked?","Common failure modes?","Related patterns, decisions, or runbooks?"]},h=u[d]||u.concept;console.log(),console.log(g.bold(` Topic: ${g.cyan(p)} \xB7 Type: ${g.magenta(d)}`)),console.log(g.dim(` ${h.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let y=[],w=!1;for(let A=0;A<h.length;A++){let ae=h[A],Se=await l(` ${g.dim(`[${A+1}/${h.length}]`)} ${ae}
|
|
271
|
+
${g.green(">")} `);if(Se==="/abort"){w=!0;break}if(Se==="/done")break;Se!=="/skip"&&Se&&y.push({q:ae,a:Se})}if(!w){let A=await l(`
|
|
272
|
+
${g.dim("Anything else worth capturing?")}
|
|
273
|
+
${g.green(">")} `);A&&A!=="/abort"&&A!=="/done"&&y.push({q:"Anything else worth capturing?",a:A})}if(w||y.length===0){console.log(g.yellow(`
|
|
274
|
+
Nothing captured. Exiting.`)),c?.close();return}let $=a.listArticles(e.agent).slice(0,40).map(A=>`- ${A.meta.title} [${A.meta.type||"?"}]`).join(`
|
|
275
|
+
`),S=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${p}`,`**Type:** ${d}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...y.map(A=>`
|
|
276
|
+
Q: ${A.q}
|
|
277
|
+
A: ${A.a}`),"","## Existing articles (use [[Title]] wikilinks when referencing these)",$||"(none yet)","","## Output rules","- Output EXACTLY one markdown file: frontmatter (---) + body. No code fences, no preamble.","- Frontmatter fields in this exact order: title, type, related, tags, owner, access, created, last_updated, sources.",' - `title`: "\u2026"',` - \`type\`: ${d}`,' - `related`: ["Article Title", \u2026] (titles that exist in the catalog above; drop if none)'," - `tags`: 2-4 specific tags, lowercase-kebab \u2014 no dates unless type=event",` - \`owner\`: ${e.agent}`," - `access`: public (unless the content is sensitive)",` - \`created\`: ${new Date().toISOString().slice(0,10)}`,` - \`last_updated\`: ${new Date().toISOString().slice(0,10)}`,` - \`sources\`: ["interview-${new Date().toISOString().slice(0,10)}"]`,"- Body: 20-80 lines, Wikipedia-style, organized by theme (not by question), synthesized (not verbatim Q&A).","- Use [[Title]] inline every time you reference something that has an article in the catalog.","- Do NOT invent facts. If the transcript didn't cover something, skip that sub-topic."].join(`
|
|
278
|
+
`),v=_(a.baseDir,"_tmp");Pe(v,{recursive:!0});let k=_(v,`interview-${o().slice(0,8)}.txt`);at(k,S),console.log(),console.log(g.dim(` Synthesizing draft with ${e.model}...`));let C="";try{let A=`cat '${k}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ae=rt(A,{encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let Se=JSON.parse(ae);C=String(Se.result||Se.content||"")}catch{C=ae}}catch(A){console.log(g.red(` synthesis failed: ${A.message?.slice(0,200)}`)),c?.close();return}C=C.trim();let j=C.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);j&&(C=j[1].trim());let L=C.indexOf("---");L>0&&(C=C.slice(L));let W=C.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!W){console.log(g.red(" LLM output is not a valid frontmatter+body article:")),console.log(C.slice(0,600)),c?.close();return}let O={};for(let A of W[1].split(`
|
|
279
|
+
`)){let ae=A.match(/^(\w+):\s*(.+)$/);ae&&(O[ae[1]]=ae[2].trim().replace(/^"(.*)"$/,"$1"))}let pe=W[2],we=O.title||p,Me=we.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ke=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${Me}.md`;console.log(),console.log(g.bold(" === Draft preview ===")),console.log(g.dim(` Path: ${ke}`)),console.log(),console.log(C),console.log();let E=await l(` ${g.green("save")} / ${g.yellow("edit (opens $EDITOR)")} / ${g.red("scrap")} ? `);if(c?.close(),E==="scrap"||E==="/abort"){console.log(g.dim(" Discarded."));return}if(!e.commit){console.log(g.dim(" --no-commit: not writing.")),console.log(g.dim(` Draft kept at ${k} (prompt only; no article file)`));return}let De=pe,ve={title:we,type:O.type||d,related:O.related?O.related.replace(/^\[|\]$/g,"").split(",").map(A=>A.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:O.tags?O.tags.replace(/^\[|\]$/g,"").split(",").map(A=>A.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:O.access||"public",created:O.created||new Date().toISOString().slice(0,10),lastUpdated:O.last_updated||new Date().toISOString().slice(0,10),sources:[`interview-${new Date().toISOString().slice(0,10)}`]};if(E==="edit"){let A=process.env.EDITOR||"vi",ae=_(v,`draft-${o().slice(0,8)}.md`);at(ae,C);try{rt(`${A} '${ae}'`,{stdio:"inherit"});let $o=Ut(ae,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if($o){let Le={};for(let Tt of $o[1].split(`
|
|
280
|
+
`)){let bo=Tt.match(/^(\w+):\s*(.+)$/);bo&&(Le[bo[1]]=bo[2].trim().replace(/^"(.*)"$/,"$1"))}De=$o[2],ve={...ve,title:Le.title||ve.title,type:Le.type||ve.type,access:Le.access||ve.access,related:Le.related?Le.related.replace(/^\[|\]$/g,"").split(",").map(Tt=>Tt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ve.related,tags:Le.tags?Le.tags.replace(/^\[|\]$/g,"").split(",").map(Tt=>Tt.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):ve.tags}}}catch(Se){console.log(g.red(` editor failed: ${Se.message}`));return}}if(!a.writeArticle(ke,ve,De,e.agent)){console.log(g.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(g.green(` \u2713 ${ke} saved.`));let wo=a.extractWikilinks(De),Dt=new Map;for(let A of a.listArticles(e.agent))Dt.set(A.meta.title.toLowerCase(),!0);let an=wo.filter(A=>!Dt.has(A.toLowerCase()));if(an.length){console.log(),console.log(g.bold(" Gaps referenced but not yet covered:"));for(let A of an.slice(0,8))console.log(g.dim(` - ${A}`));console.log(g.dim(` Run \`agentx wiki interview --agent ${e.agent} --topic "<title>"\` for any of these.`))}});Z.command("quiz").description("reverse interview \u2014 ask the wiki questions and patch cited articles with corrections, additions, or links").option("--dir <path>","wiki directory").option("--agent <id>","which agent's wiki to quiz (required)").option("--selector-model <m>","candidate-selection model","haiku").option("--synth-model <m>","answer synthesis model","sonnet").option("--patch-model <m>","article patch model","sonnet").option("--rounds <n>","stop after N rounds","20").option("--script <path>","non-interactive: question line + /verdict line per entry, entries separated by blank lines").option("--no-commit","show proposed patches but don't write").option("--out <path>","write a session transcript as markdown").action(async e=>{let t=await import("node:readline/promises"),{randomUUID:o}=await import("node:crypto"),{agenticQuery:n}=await import("./query-HZYYRCLU.js");if(!e.agent){console.log(g.red(" --agent <id> is required."));return}let s=ue(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(u){console.log(g.red(` can't open wiki for agent "${e.agent}": ${u.message}`));return}let r=null;if(e.script){let h=Ut(e.script,"utf-8").split(/\n\s*\n/).map(y=>y.trim()).filter(Boolean);r=[];for(let y of h){let w=y.split(/\r?\n/).filter(S=>S.trim());if(w.length<2)continue;let b=w[0].replace(/^Q:\s*/i,"").trim(),$=w.slice(1).join(" ").trim();b&&$&&r.push({q:b,verdict:$})}}let a=r?null:t.createInterface({input:process.stdin,output:process.stdout}),c=async u=>a?(await a.question(u)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),p=e.commit!==!1;console.log(),console.log(g.bold(" Wiki Quiz")),console.log(g.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${p?"commit":"dry-run"} \xB7 ${r?`scripted (${r.length})`:"interactive"}`)),console.log(g.dim(" Verdicts: /ok /correct <note> /add <note> /link <url> /skip /done")),console.log();let d=[],m=0;for(let u=0;u<l;u++){let h,y;if(r){let ce=r[u];if(!ce)break;h=ce.q,y=ce.verdict,console.log(g.cyan(` [${u+1}] Q: `)+h)}else{if(h=await c(g.cyan(` [${u+1}] Q: `)),!h||h==="/done"||h==="/abort")break;y=""}process.stdout.write(g.dim(" querying... "));let w;try{w=await n(h,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(ce){console.log(g.red(`failed: ${ce.message?.slice(0,120)}`));continue}if(console.log(g.dim("done")),w.status!=="ok")console.log(g.yellow(` (status: ${w.status}${w.error?" \u2014 "+w.error:""})`));else{let ce=w.citations.map(ke=>`${ke.title} [${ke.type||"?"}]`).join(" \xB7 ");console.log(),console.log(g.dim(" A: ")+w.answer.replace(/\n/g,`
|
|
281
|
+
`)),console.log(g.dim(" citations: "+ce))}r||(y=await c(g.cyan(" verdict > "))),console.log(g.dim(" verdict: ")+y);let b={q:h,answer:w.answer,citations:w.citations,verdict:y},$=y.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!$){console.log(g.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(b);continue}let S=$[1].toLowerCase(),v=($[2]||"").trim();if(d.push(b),S==="/ok"||S==="/skip")continue;if(!v){console.log(g.yellow(` ${S} without note \u2014 skipping.`));continue}let k=w.citations[0];if(!k){console.log(g.yellow(" no cited article to patch."));continue}let C=i.readArticle(k.path);if(!C){console.log(g.red(` can't read ${k.path} to patch.`));continue}console.log(g.dim(` patching ${k.title} (${k.path})...`));let j=br(C.content,S,v,C.meta.title,C.meta.type),L=_(i.baseDir,"_tmp");Pe(L,{recursive:!0});let W=_(L,`quiz-patch-${o().slice(0,8)}.txt`);at(W,j);let O="";try{let ce=`cat '${W}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ke=rt(ce,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let De=JSON.parse(ke);O=String(De.result||De.content||"")}catch{O=ke}let E=O.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);E&&(O=E[1].trim()),O=O.trim()}catch(ce){console.log(g.red(` patch failed: ${ce.message?.slice(0,120)}`));continue}if(!O||O.length<20){console.log(g.yellow(" patch returned nothing usable."));continue}let pe=C.content.split(`
|
|
282
|
+
`).length,we=O.split(`
|
|
283
|
+
`).length;if(console.log(g.dim(` diff: ${pe} \u2192 ${we} lines (${we-pe>=0?"+":""}${we-pe})`)),!p){console.log(g.dim(" (--no-commit: patch not written)")),b.patched=k.path+" (dry)";continue}if(!i.writeArticle(k.path,{...C.meta,lastUpdated:new Date().toISOString().slice(0,10)},O,e.agent)){console.log(g.red(" write failed (permission?)"));continue}m++,b.patched=k.path,console.log(g.green(` \u2713 patched ${k.path}`))}if(a&&a.close(),m>0&&p&&i.rebuildIndex(),console.log(),console.log(g.bold(` Session done: ${d.length} rounds, ${m} patches applied.`)),e.out){let u=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${m} patches_`,""];for(let h=0;h<d.length;h++){let y=d[h];u.push(`## ${h+1}. Q: ${y.q}`,"",`**A:** ${y.answer}`,"",`**Citations:** ${y.citations.map(w=>`\`${w.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${y.verdict}\``+(y.patched?` \u2192 patched \`${y.patched}\``:""),"")}at(e.out,u.join(`
|
|
284
|
+
`)),console.log(g.dim(` Transcript written to ${e.out}`))}});Z.command("edit <agent> <titleOrPath>").description("open an article in $EDITOR (resolves by title or path), rebuild catalog on exit").option("--dir <path>","wiki directory").option("--editor <cmd>","override $EDITOR for this run").action((e,t,o)=>{let n=ue(o.dir),s;try{s=n.getAgentWiki(e)}catch(l){console.log(g.red(` can't open wiki for agent "${e}": ${l.message}`));return}let i=fs(s,t,e);if(!i){console.log(g.yellow(` no article matches "${t}" in ${e}'s wiki.`)),console.log(g.dim(` Tip: ${g.green("agentx wiki status")} lists agents; ${g.green(`agentx wiki search "term" --agent ${e}`)} finds by content.`));return}let r=_(s.baseDir,i),a=o.editor||process.env.EDITOR||"vi";console.log(g.dim(` opening ${i} in ${a}...`));try{rt(`${a} '${r}'`,{stdio:"inherit"})}catch(l){console.log(g.red(` editor exited with error: ${l.message?.slice(0,150)}`));return}let c=s.readArticle(i);if(c){let l=new Set,p=s.extractWikilinks(c.content).filter(u=>l.has(u)?!1:(l.add(u),!0)),d=c.meta.related||[];(p.some(u=>!d.includes(u))||d.some(u=>!p.includes(u)))&&(s.writeArticle(i,{...c.meta,related:p.length?p:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(g.dim(` (synced frontmatter.related from body: ${p.length} wikilink${p.length===1?"":"s"})`)))}try{s.rebuildIndex(),console.log(g.green(` \u2713 ${i} saved. Catalog rebuilt.`))}catch(l){console.log(g.yellow(` saved, but catalog rebuild failed: ${l.message?.slice(0,100)}`))}});Z.command("patch <agent> <titleOrPath> <instruction>").description("LLM-patch an article from a free-form instruction; shows diff + confirms before writing").option("--dir <path>","wiki directory").option("--patch-model <m>","patch model","sonnet").option("--yes","skip confirmation and write immediately").option("--no-commit","show the patched body but don't write").action(async(e,t,o,n)=>{let s=await import("node:readline/promises"),{randomUUID:i}=await import("node:crypto"),r=ue(n.dir),a;try{a=r.getAgentWiki(e)}catch(k){console.log(g.red(` can't open wiki for agent "${e}": ${k.message}`));return}let c=fs(a,t,e);if(!c){console.log(g.yellow(` no article matches "${t}" in ${e}'s wiki.`));return}let l=a.readArticle(c);if(!l){console.log(g.red(` can't read ${c}.`));return}let p=$r(l.content,l.meta.title,l.meta.type,o),d=_(a.baseDir,"_tmp");Pe(d,{recursive:!0});let m=_(d,`patch-${i().slice(0,8)}.txt`);at(m,p),console.log(),console.log(g.dim(` Target: ${l.meta.title} (${c})`)),console.log(g.dim(` Patching with ${n.patchModel}...`));let u="";try{let k=`cat '${m}' | claude -p - --output-format json --max-turns 1 --model ${n.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,C=rt(k,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let L=JSON.parse(C);u=String(L.result||L.content||"")}catch{u=C}let j=u.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);j&&(u=j[1].trim()),u=u.trim()}catch(k){console.log(g.red(` patch failed: ${k.message?.slice(0,150)}`));return}if(!u||u.length<20){console.log(g.yellow(" patch returned nothing usable."));return}let h=l.content.split(`
|
|
285
|
+
`).length,y=u.split(`
|
|
286
|
+
`).length;if(console.log(),console.log(g.bold(" === Patched preview ===")),console.log(g.dim(` diff: ${h} \u2192 ${y} lines (${y-h>=0?"+":""}${y-h})`)),console.log(),console.log(u),console.log(),!n.commit){console.log(g.dim(" --no-commit: preview only, not written."));return}let w=!!n.yes;if(!w){let k=s.createInterface({input:process.stdin,output:process.stdout}),C=(await k.question(g.cyan(" apply? [y/N] "))).trim().toLowerCase();k.close(),w=C==="y"||C==="yes"}if(!w){console.log(g.dim(" aborted."));return}let b=new Set,$=a.extractWikilinks(u).filter(k=>b.has(k)?!1:(b.add(k),!0));if(!a.writeArticle(c,{...l.meta,related:$.length?$:void 0,lastUpdated:new Date().toISOString().slice(0,10)},u,e)){console.log(g.red(" write failed (permission?)"));return}a.rebuildIndex();let v=(l.meta.related||[]).filter(k=>!$.includes(k));v.length&&console.log(g.dim(` (pruned stale related: ${v.slice(0,3).join(", ")}${v.length>3?", \u2026":""})`)),console.log(g.green(` \u2713 ${c} patched.`))});function fs(e,t,o){let n=t.trim(),s=e.listArticles(o),i=n.toLowerCase(),r=s.find(l=>l.meta.title.toLowerCase()===i);if(r)return r.path;if(n.includes("/")||n.endsWith(".md")){let l=n.endsWith(".md")?n:`${n}.md`,p=s.find(d=>d.path===l||d.path===n);if(p)return p.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let p=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return p===a||p.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function $r(e,t,o,n){return["You are editing a single wiki article to incorporate an operator instruction.","",`## Article: "${t}" (type: ${o||"untyped"})`,"","<article-body>",e,"</article-body>","","## Operator instruction",n,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the instruction requires changing them.","- Make the MINIMUM edit that satisfies the instruction \u2014 don't rewrite untouched sections.","- If the instruction is ambiguous or can't be applied, return the original body unchanged."].join(`
|
|
287
|
+
`)}function br(e,t,o,n,s){let i={"/correct":`The operator says the article contains an error:
|
|
288
|
+
|
|
289
|
+
${o}
|
|
290
|
+
|
|
291
|
+
Edit the article to correct ONLY this mistake. Do not rewrite untouched sections. Keep the existing prose style. If the correction invalidates a larger passage, revise the minimum that must change.`,"/add":`The operator wants to add this detail:
|
|
292
|
+
|
|
293
|
+
${o}
|
|
294
|
+
|
|
295
|
+
Incorporate it into the most relevant existing section, or create a short new section if nothing fits. Keep the prose encyclopedic and under 100 additional words.`,"/link":`The operator wants to add this resource:
|
|
296
|
+
|
|
297
|
+
${o}
|
|
298
|
+
|
|
299
|
+
Add it as a Markdown link in the most relevant section, or append a "## References" section at the end if none exists. If it looks like a URL, use it as-is; otherwise treat it as a wikilink target and use [[${o}]].`};return["You are editing a single wiki article to incorporate operator feedback.","",`## Article: "${n}" (type: ${s||"untyped"})`,"","<article-body>",e,"</article-body>","","## Edit instruction",i[t]||`Make a minimal edit per: ${o}`,"","## Rules","- Output ONLY the modified article body (content between the --- frontmatter markers).","- Do NOT output frontmatter (title, type, tags, etc.) \u2014 the serializer handles that.","- Do NOT wrap the output in code fences.",`- Do NOT prepend any preamble like "Here's the updated article:".`,"- Preserve existing wikilinks, markdown formatting, and section structure unless the edit requires changing them.","- If no meaningful edit can be made from the operator's feedback, return the original body unchanged."].join(`
|
|
300
|
+
`)}Z.command("prune").description("collapse legacy flat/unified mode dirs into graph/ (dedup by title; losers archived)").option("--dir <path>","wiki directory").option("--agent <id>","prune only this agent's wiki").option("--commit","execute moves + archives (default: dry-run)").action(async e=>{let t=ue(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=!!e.commit,s=e.dir?_(e.dir):_(process.cwd(),".agentx/wiki"),i="graph",r=["flat","unified"];console.log(),console.log(g.bold(n?" Pruning (commit)":" Pruning (dry-run)")),console.log(g.dim(` Canonical: ${i}/ \xB7 Legacy to collapse: ${r.join("/, ")}/`));let a=0,c=0,l=0,p=0;for(let d of o){let m=_(s,"agents",d);if(!Ce(m))continue;let u=_(m,i),h=r.map($=>({mode:$,dir:_(m,$)})).filter($=>Ce($.dir));if(h.length===0)continue;let y=new Map;Fo(u,$=>{let S=gs(u,$);if(S.startsWith("_")||S.startsWith("raw/")||S.includes("_tmp/"))return;let v=ps(Ut($,"utf-8"));v?.meta.title&&y.set(v.meta.title.trim().toLowerCase(),{relPath:S,type:v.meta.type,lastUpdated:v.meta.lastUpdated||""})});let w=[];for(let $ of h)Fo($.dir,S=>{let v=gs($.dir,S);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let k=ps(Ut(S,"utf-8"));k?.meta.title&&w.push({mode:$.mode,relPath:v,absPath:S,title:k.meta.title.trim(),type:k.meta.type,lastUpdated:k.meta.lastUpdated||""})});if(a+=w.length,w.length===0)continue;console.log();let b=h.map($=>$.mode).join("+");console.log(g.bold(` ${g.cyan(d)}: ${w.length} legacy article(s) across ${b}`));for(let $ of w){let S=$.title.toLowerCase(),v=y.get(S),k;v?!v.type&&$.type||!!v.type==!!$.type&&$.lastUpdated&&v.lastUpdated&&$.lastUpdated>v.lastUpdated?k="upgrade":k="archive":k="promote";let C=$.type?g.magenta(`[${$.type}]`):g.yellow("[untyped]"),j=k==="promote"?g.green("\u2192 promote "):k==="upgrade"?g.cyan("\u27F3 upgrade "):g.dim("\u2717 archive "),L=$.relPath.length>46?$.relPath.slice(0,43)+"...":$.relPath.padEnd(46);if(console.log(` ${j} ${C} ${g.dim($.mode+"/")}${L}`),k==="upgrade"&&console.log(g.dim(` (replaces ${v.relPath}, old version kept under _versions/)`)),!n){k==="promote"?c++:k==="upgrade"?l++:p++;continue}try{if(k==="promote"){let W=_(u,$.relPath);Ce(W)?(console.log(g.yellow(` ! target path already exists, archiving instead: ${$.relPath}`)),us(m,$),p++):(Pe(ms(W),{recursive:!0}),ao($.absPath,W),y.set(S,{relPath:$.relPath,type:$.type,lastUpdated:$.lastUpdated}),c++)}else if(k==="upgrade"){let W=_(u,v.relPath);if(Ce(W)){let O=_(m,"_versions",v.relPath.replace(/\.md$/,""));Pe(O,{recursive:!0});let pe=new Date().toISOString().replace(/[:.]/g,"-");ao(W,_(O,`${pe}.md`))}Pe(ms(W),{recursive:!0}),ao($.absPath,W),y.set(S,{relPath:v.relPath,type:$.type,lastUpdated:$.lastUpdated}),l++}else us(m,$),p++}catch(W){console.log(g.red(` ! ${k} failed: ${W.message?.slice(0,120)}`))}}if(n){for(let $ of h)try{wr($.dir,{recursive:!0,force:!0})}catch{}try{t.getAgentWiki(d).rebuildIndex()}catch($){console.log(g.dim(` (catalog rebuild skipped: ${$.message?.slice(0,80)})`))}}}console.log(),console.log(g.dim(` Legacy scanned: ${a}`)),n?(console.log(g.green(` Promoted: ${c} \xB7 Upgraded canonical: ${l} \xB7 Archived: ${p}`)),console.log(g.dim(" Archived losers preserved under <agent>/_versions/. Legacy mode dirs deleted."))):(console.log(g.dim(` Would: promote ${c} \xB7 upgrade ${l} \xB7 archive ${p}`)),console.log(g.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function Fo(e,t){if(Ce(e))for(let o of yr(e,{withFileTypes:!0})){let n=_(e,o.name);o.isDirectory()?Fo(n,t):o.isFile()&&o.name.endsWith(".md")&&t(n)}}function ps(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let o={};for(let n of t[1].split(`
|
|
301
|
+
`)){let s=n.match(/^(\w+):\s*(.+)$/);if(!s)continue;let i=s[1]==="last_updated"?"lastUpdated":s[1];o[i]=s[2].trim().replace(/^"(.*)"$/,"$1")}return{meta:o}}function us(e,t){let o=_(e,"_versions",`legacy-${t.mode}`,t.relPath.replace(/\.md$/,""));Pe(o,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");ao(t.absPath,_(o,`${n}.md`))}Z.command("migrate").description("backfill type + related on legacy articles (one-shot)").option("--dir <path>","wiki directory").option("--agent <id>","migrate only this agent's articles").option("--commit","write changes (default: dry-run, reports what would change)").option("--batch <n>","articles per LLM call","10").option("--max <n>","cap articles this run (for spot-checks)").option("--model <m>","classifier model","sonnet").action(async e=>{let t=ue(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=Math.max(1,parseInt(e.batch)||10),s=e.max?parseInt(e.max):1/0,i=!!e.commit;console.log(),console.log(g.bold(i?" Migrating (commit)":" Migrating (dry-run)")),console.log(g.dim(` Batch size: ${n} \xB7 Model: ${e.model}`)),console.log();let r=0,a=0,c=0;for(let l of o){let p=t.getAgentWiki(l),d=p.listArticles(l),m=d.filter(b=>!b.meta.type);if(r+=d.length,a+=m.length,m.length===0){console.log(` ${g.cyan(l)}: ${g.green("all typed")} (${d.length} articles)`);continue}let u=Math.max(0,s-c),h=Math.min(m.length,u);if(h===0){console.log(g.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(g.bold(` ${g.cyan(l)}: ${h}/${m.length} untyped articles`));let y=p.baseDir,w=_(y,"_tmp");Pe(w,{recursive:!0});for(let b=0;b<h;b+=n){let $=m.slice(b,Math.min(b+n,h)),S=vr($),v=_(w,"migrate-prompt.txt");at(v,S);let k;try{let C=`cat '${v}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,j=rt(C,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),L=JSON.parse(j),O=String(L.result||L.content||"").match(/\[[\s\S]*\]/);if(!O)throw new Error("no JSON array in classifier response");k=JSON.parse(O[0])}catch(C){console.log(g.red(` LLM classify failed: ${C.message?.slice(0,150)}`));continue}for(let C of $){let j=k.find(Me=>Me.path===C.path),L=kr(j?.type);if(!j||!L){console.log(g.yellow(` ? ${C.path}: unclassified${j?` (got "${j.type}")`:""}`));continue}let W=p.extractWikilinks(C.content),O={...C.meta,type:L.type,related:W.length?W:void 0,lastUpdated:new Date().toISOString().slice(0,10)},pe=W.length?g.dim(` \u2192 ${W.slice(0,3).join(", ")}${W.length>3?", \u2026":""}`):"",we=L.alias?g.dim(` (from "${L.alias}")`):"";console.log(` ${g.green("+")} ${g.magenta("["+L.type+"]")}${we} ${C.path}${pe}`),i&&(p.writeArticle(C.path,O,C.content,l),c++)}}i&&p.rebuildIndex()}console.log(),console.log(g.dim(` Scanned ${r} articles; ${a} needed migration`)),console.log(i?g.green(` Applied ${c} patches.`):g.dim(" Dry-run \u2014 add --commit to write changes.")),console.log()});function kr(e){if(!e)return null;let t=String(e).trim().toLowerCase().replace(/^[\s"'`]+|[\s"'`]+$/g,"");if(!t)return null;let n={person:"person",project:"project",place:"place",concept:"concept",event:"event",decision:"decision",pattern:"pattern",people:"person",projects:"project",places:"place",concepts:"concept",events:"event",decisions:"decision",patterns:"pattern",agent:"project",bot:"project",service:"project",product:"project",tool:"project",repo:"project",repository:"project",app:"project",application:"project",team:"project",organization:"project",company:"project",issue:"event",mr:"event","merge-request":"event",merge_request:"event",ticket:"event",incident:"event",deploy:"event",deployment:"event",launch:"event",release:"event",process:"pattern",procedure:"pattern",workflow:"pattern",runbook:"pattern",recipe:"pattern",template:"pattern",sop:"pattern",infrastructure:"place",infra:"place",server:"place",environment:"place",env:"place",location:"place",host:"place",decisionrecord:"decision",adr:"decision","decision-record":"decision"}[t];return n?n===t?{type:n}:{type:n,alias:t}:null}function vr(e){let t=e.map((o,n)=>{let s=o.content.replace(/\s+/g," ").slice(0,400),i=(o.meta.tags||[]).slice(0,8).join(", ");return`${n+1}. path: "${o.path}"
|
|
302
|
+
title: "${o.meta.title}"
|
|
303
|
+
tags: [${i}]
|
|
304
|
+
body: ${s}${o.content.length>400?"\u2026":""}`}).join(`
|
|
305
|
+
|
|
306
|
+
`);return`Classify each of these ${e.length} wiki articles into EXACTLY ONE type from this closed set (no synonyms, no plurals, no new values):
|
|
307
|
+
|
|
308
|
+
person | project | place | concept | event | decision | pattern
|
|
309
|
+
|
|
310
|
+
What each type means:
|
|
311
|
+
- person: an individual human (team member, stakeholder, contact)
|
|
312
|
+
- project: a named initiative, repo, product, service, bot, agent, team, or org
|
|
313
|
+
- place: a physical or logical location (office, server, environment, infrastructure)
|
|
314
|
+
- concept: a recurring idea, philosophy, methodology, or thinking pattern
|
|
315
|
+
- event: a specific dated thing that happened (incident, deploy, launch, GitLab issue, MR)
|
|
316
|
+
- decision: a specific choice made and why (architecture decision, policy, ADR)
|
|
317
|
+
- pattern: a reusable workflow, template, recipe, procedure, runbook, or SOP
|
|
318
|
+
|
|
319
|
+
Explicit mappings (you WILL be tempted to volunteer these \u2014 don't; use the right-hand value):
|
|
320
|
+
- "agent" / "bot" / "service" / "repo" / "team" \u2192 project
|
|
321
|
+
- "issue" / "MR" / "ticket" / "incident" / "deploy" \u2192 event
|
|
322
|
+
- "process" / "procedure" / "runbook" / "workflow" \u2192 pattern
|
|
323
|
+
- "infrastructure" / "server" / "environment" \u2192 place
|
|
324
|
+
- "ADR" / "decision record" \u2192 decision
|
|
325
|
+
|
|
326
|
+
Rules:
|
|
327
|
+
- Return EXACTLY one type per article, by path, from the 7 allowed values above.
|
|
328
|
+
- Do not invent new types. Do not return plurals. Do not return synonyms.
|
|
329
|
+
- If the title is a person's name, it's person. If it's a repo/product/bot name, it's project. If it's dated + past tense, it's event.
|
|
330
|
+
- If you genuinely cannot decide, pick "concept" as the fallback.
|
|
331
|
+
- Output ONLY valid JSON, no markdown fencing, no prose.
|
|
332
|
+
|
|
333
|
+
Articles:
|
|
334
|
+
|
|
335
|
+
${t}
|
|
336
|
+
|
|
337
|
+
Output (JSON array, one entry per input article, same order):
|
|
338
|
+
[
|
|
339
|
+
{"path": "path/to/article.md", "type": "project"},
|
|
340
|
+
...
|
|
341
|
+
]`}Z.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ue(e.dir).getSharedStore().listEntries();e.agent&&(n=n.filter(s=>s.agentId===e.agent)),console.log(),console.log(g.bold(` ${n.length} raw entries`)),console.log();for(let s of n.slice(-20))console.log(` ${g.dim(s.date)} ${g.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);n.length>20&&console.log(g.dim(` ... showing last 20 of ${n.length}`)),console.log()});Z.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 t=e.dir||_(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-BLOKGMER.js");n=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(g.bold(" AgentX Wiki Server")),console.log(),console.log(` ${g.green(">")} http://localhost:${o}`),e.agent?console.log(` Agent: ${g.cyan(e.agent)}`):console.log(` Mode: ${g.cyan("Hub")} (all agents)`),n.length>0&&console.log(` Mesh: ${g.cyan(n.length+" peer(s)")} \u2014 ${n.join(", ")}`),console.log(g.dim(` Wiki: ${t}`)),console.log(g.dim(" Press Ctrl+C to stop")),console.log(),Dn(t,o,e.agent,n,e.mode)});Z.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,t)=>{let{agenticQuery:o}=await import("./query-HZYYRCLU.js"),n=ue(t.dir),s=t.agent?[t.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),p=_(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(p)){i=c;break}}catch{}}if(!i){console.log(g.yellow(" No agent has a catalog yet. Run `agentx wiki status` or migrate first."));return}let r=n.getAgentWiki(i),a=await o(e,r,i,{selectorModel:t.selectorModel,synthModel:t.synthModel,maxCandidates:parseInt(t.maxCandidates),maxHops:parseInt(t.maxHops),maxArticles:parseInt(t.maxArticles)});if(t.json){console.log(JSON.stringify(a,null,2));return}if(console.log(),console.log(g.bold(` Q: ${e}`)),console.log(g.dim(` agent: ${i} \xB7 status: ${a.status} \xB7 walked: ${a.walked.length}`)),console.log(),a.status!=="ok"){console.log(g.yellow(` (no answer) ${a.error||a.status}`));return}if(console.log(a.answer),console.log(),a.citations.length){console.log(g.dim(" Citations:"));for(let c of a.citations){let l=c.type?g.magenta(` [${c.type}]`):"";console.log(g.dim(` - ${c.title}${l} (${c.path})`))}console.log()}if(t.trace&&a.trace){if(console.log(g.dim(` selector: ${a.trace.selectorMs}ms synthesis: ${a.trace.synthesisMs}ms`)),console.log(g.dim(` candidates: ${a.candidates.map(c=>c.title).join(" | ")||"(none)"}`)),a.walked.length>a.candidates.length){let c=a.walked.filter(l=>!a.candidates.some(p=>p.path===l.path));console.log(g.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});Z.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,t)=>{let o=ue(t.dir,t.mode),n=t.agent?[t.agent]:o.listAgents();console.log();let s=0;for(let i of n){let a=o.getAgentWiki(i).findRelevant(e,void 0,10);if(a.length>0){console.log(g.bold(` ${g.cyan(i)}:`));for(let c of a)console.log(` ${c.meta.title} [${(c.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(g.dim(` ${c.path} \u2014 ${c.content.slice(0,100)}...`));s+=a.length}}s===0&&console.log(g.dim(" No matching articles")),console.log()});Z.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 t=ue(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=_(process.cwd(),".agentx/graph");if(!Ce(n)){console.log(g.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Ve({baseDir:n}),i=s.loadIndex(),r=new Map;for(let[d,m]of Object.entries(i.entries))r.set(d,m.path);if(r.size===0){console.log(g.yellow(" Graph index is empty \u2014 nothing to look up."));return}console.log(g.dim(` Loaded ${r.size} fingerprint -> path entries from .agentx/graph/index.json`));let a=0,c=0,l=0,p=0;for(let d of o){let m=t.getAgentWiki(d),u=m.listArticles(d),h=t.getSharedStore().listEntries(),y=new Map(h.map(S=>[S.id,S])),w=0,b=0,$=0;for(let S of u){if(a++,S.meta.graphPath?.length||!S.meta.sources?.length)continue;w++,c++;let v=new Map;for(let C of S.meta.sources){let j=y.get(C);if(!j)continue;let L=String(j.meta?.sender??""),W=s.fingerprint({text:j.content,channel:j.source,sender:L}),O=r.get(W);if(!O?.length)continue;let pe=O.join("/"),we=v.get(pe);we?we.n++:v.set(pe,{path:O,n:1})}if(v.size===0)continue;b++,l++;let k;for(let C of v.values())(!k||C.n>k.n)&&(k=C);k&&(e.dryRun||(m.writeArticle(S.path,{...S.meta,graphPath:k.path},S.content,d),$++,p++))}console.log(` ${g.cyan(d)}: ${g.bold(u.length)} articles \xB7 ${w} eligible \xB7 ${b} matched \xB7 ${g.green($)} written`)}console.log(),console.log(g.bold(` Total: ${a} articles, ${c} missing graphPath, ${l} matched (${Math.round(l/Math.max(1,c)*100)}%), ${p} written`)),e.dryRun&&console.log(g.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});Z.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 o=ue(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-BLOKGMER.js");n=(r().mesh?.peers||[]).map(c=>c.url)}catch{console.log(g.red(" No --peer specified and no daemon config found")),console.log(g.dim(" Usage: agentx wiki sync --peer http://100.67.108.119:19900"));return}if(n.length===0){console.log(g.dim(" No mesh peers configured"));return}let s=new Set(o.listEntries().map(r=>r.id)),i=0;for(let r of n){console.log(),console.log(g.bold(` Syncing from ${r}...`));try{let a=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(12e4)});if(!a.ok){console.log(g.red(` HTTP ${a.status}`));continue}let c=await a.json(),l=c.entries||[],p=c.nodeId||"unknown";console.log(g.dim(` Node: ${p} \u2014 ${l.length} entries`));let d=0;for(let m of l)s.has(m.id)||(e.dryRun||(o.addEntry({id:m.id,date:m.date,agentId:m.agentId,source:`${m.source}@${p}`,sourceContext:m.sourceContext,content:m.content}),s.add(m.id)),d++);d>0?console.log(g.green(` ${d} new entries${e.dryRun?" (dry run)":" synced"}`)):console.log(g.dim(" Already up to date")),i+=d;try{let m=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(m.ok){let u=await m.json();for(let h of u.agents||[])h.totalEntries>0&&console.log(g.dim(` ${h.agentId}: ${h.totalEntries} entries, ${h.totalArticles} articles`))}}catch{}}catch(a){a.cause?.code==="ECONNREFUSED"?console.log(g.red(" Connection refused")):console.log(g.red(` ${a.message}`))}}console.log(),i>0&&!e.dryRun?console.log(g.green(` ${i} entries synced.`)):i>0?console.log(g.dim(` ${i} entries would be synced (dry run)`)):console.log(g.dim(" All peers up to date")),console.log()});Z.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 t=e.dir||_(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new ko(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),m=l.getAgentEntries(o),u=l.getUnabsorbedEntries(o),h=new Set,y=0,w=new Set;for(let $ of d.articles){for(let S of $.tags||[])h.add(S);y+=$.tags?.length||0;for(let S of $.sources||[])w.add(S)}let b=new Set(d.articles.map($=>$.path.includes("/")?$.path.split("/")[0]:"/"));return{mode:c,label:Uo(c),articles:d.articles.length,entries:m.length,unabsorbed:u.length,uniqueTags:h.size,avgTags:d.articles.length>0?(y/d.articles.length).toFixed(1):"0",dirs:b.size,coverage:w.size,articleList:d.articles}});console.log(),console.log(g.bold(` Wiki Compare: ${o}`)),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,l]of r){let p=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${p.join(" ")}`)}console.log();let a=(c,l)=>{let p=Math.max(...s.map(m=>m[c])),d=s.filter(m=>m[c]===p).map(m=>m.label);p>0&&console.log(g.dim(` Best ${l}: ${d.join(", ")} (${p})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});Z.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,t)=>{let o=t.dir?_(process.cwd(),t.dir):_(process.cwd(),".agentx/wiki");Ce(o)||(console.log(g.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?_(process.cwd(),e):_(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=_(o,".."),r=o.split("/").pop()||"wiki",a=["-C",i,"-czf",s];t.includeRaw||a.push("--exclude="+r+"/raw"),a.push(r),console.log(g.dim(` tar ${a.join(" ")}`));let{spawnSync:c}=await import("child_process"),l=c("tar",a,{stdio:"inherit"});l.status!==0&&(console.log(g.red(` tar exited with ${l.status}`)),process.exit(l.status||1));let{statSync:p}=await import("fs"),d=Ce(s)?p(s).size:0;console.log(),console.log(g.green(` \u2713 wrote ${s} (${xr(d)})`)),console.log(g.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Z.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,t)=>{let o=_(process.cwd(),e);Ce(o)||(console.log(g.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?_(process.cwd(),t.dir):_(process.cwd(),".agentx/wiki");Ce(n)&&!t.force&&(console.log(g.yellow(` ${n} already exists.`)),console.log(g.yellow(" Re-run with --force to overwrite (existing files where the archive has them; others stay).")),process.exit(1));let s=_(n,".."),{mkdirSync:i}=await import("fs");i(s,{recursive:!0});let r=["-C",s,"-xzf",o];console.log(g.dim(` tar ${r.join(" ")}`));let{spawnSync:a}=await import("child_process"),c=a("tar",r,{stdio:"inherit"});c.status!==0&&(console.log(g.red(` tar exited with ${c.status}`)),process.exit(c.status||1)),console.log(),console.log(g.green(` \u2713 restored to ${n}`)),console.log(g.dim(" Restart the daemon (or POST /reload) for the wiki hub to pick up the new content.")),console.log()});function xr(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 Sr}from"commander";import N from"chalk";import{resolve as Bo}from"path";import{existsSync as jr}from"fs";var Bt=new Sr().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Bt.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 t=R();if(!t.graph?.enabled){console.log(N.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(N.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(N.red(` agent "${o}" not in config`));return}let n=(e.daemonUrl||t.dashboard?.daemonUrl||"http://localhost:18800").replace(/\/+$/,""),s=Math.max(1,parseInt(e.max)||20),i=new Ve({baseDir:Bo(process.cwd(),t.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(N.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(N.bold(` Graph review \u2014 ${r.length} pending`)),console.log(N.dim(` Reviewer: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,p=0,d=0,m=0;for(let h=0;h<r.length;h++){let y=r[h],w=cn(y.path,c)||y.path.join(" \u203A ");process.stdout.write(` [${h+1}/${r.length}] ${N.cyan(y.msgHash.slice(0,8))} ${N.dim(w)} ... `);let b=Cr(y,a,c),$=null;try{$=await Er(n,o,b,t.dashboard?.token)}catch(k){m++,console.log(N.red(`ERR ${k.message?.slice(0,80)}`));continue}if(!$||!$.decision){m++,console.log(N.red("ERR no decision"));continue}let S=String($.decision).toLowerCase().trim(),v=($.reason||"").toString().slice(0,180);if(S==="approve")if(console.log(N.green("APPROVE")+" "+N.dim(v)),e.dryRun)l++;else try{Ir(i,y,a,c,o),i.updateClassificationStatus(y.msgHash,{status:"approved",reviewer:o,reviewReason:v}),l++}catch(k){console.log(N.yellow(` (commit failed, staying pending: ${k.message?.slice(0,100)})`)),m++}else S==="reject"?(console.log(N.red("REJECT")+" "+N.dim(v)),e.dryRun||i.updateClassificationStatus(y.msgHash,{status:"rejected",reviewer:o,reviewReason:v}),p++):(console.log(N.yellow("SKIP")+" "+N.dim(v||S)),d++)}console.log();let u=e.dryRun?"would":"did";console.log(N.dim(` Summary: ${u} approve ${l}, ${u} reject ${p}, ${d} skipped, ${m} errors.`)),e.dryRun&&(l>0||p>0)&&console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Bt.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 t=R();if(!t.graph){console.log(N.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=Bo(process.cwd(),t.graph.baseDir);if(!jr(o)){console.log(N.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-QO7SLKIM.js"),s=new Ve({baseDir:o,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(N.dim(" "),...a)});console.log(),console.log(N.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(N.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(N.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Bt.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 t=R();if(!t.graph?.enabled){console.log(N.yellow(" graph.enabled is false on this node \u2014 nothing to sync INTO."));return}let o=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 Ve({baseDir:Bo(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(j=>j.id));console.log(),console.log(N.bold(` graph pull \u2190 ${o}`));let l,p,d;try{let j=await fetch(`${o}/graph/schema`,{headers:s});if(!j.ok)throw new Error(`schema HTTP ${j.status}`);l=(await j.json()).schema;let W=await fetch(`${o}/graph/nodes`,{headers:s});if(!W.ok)throw new Error(`nodes HTTP ${W.status}`);p=(await W.json()).nodes||[];let O=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!O.ok)throw new Error(`classifications HTTP ${O.status}`);d=(await O.json()).classifications||[]}catch(j){console.log(N.red(` fetch failed: ${j.message}`));return}let m=r.levels.map(j=>j.id).join(","),u=l?.levels?.map(j=>j.id).join(","),h=m===u;h?console.log(N.dim(` schema matches (${r.levels.length} levels)`)):(console.log(N.yellow(" \u26A0 schema levels differ:")),console.log(N.dim(` local: ${m}`)),console.log(N.dim(` peer: ${u}`)),a.length===0&&!e.dryRun?(console.log(N.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(N.yellow(" keeping local schema; node import may fail if levels disagree")));let y=h?r:l,w=new Map;y.levels.forEach((j,L)=>w.set(j.id,L));let b=[...p].sort((j,L)=>(w.get(j.level)??99)-(w.get(L.level)??99)),$=0,S=0,v=0;for(let j of b){if(c.has(j.id)){S++;continue}if(e.dryRun){$++,c.add(j.id);continue}try{i.addNode({...j,createdBy:j.createdBy?`${j.createdBy} (sync)`:`sync:${o}`}),c.add(j.id),$++}catch(L){v++,console.log(N.yellow(` skip node ${j.id}: ${L.message?.slice(0,100)}`))}}console.log(N.dim(` nodes: +${$} added \xB7 ${S} already-present \xB7 ${v} failed`));let k=0,C=0;for(let j of d)if(!(!j.msgHash||!Array.isArray(j.path))){if(i.getFingerprint(j.msgHash)){C++;continue}if(e.dryRun){k++;continue}i.setFingerprint(j.msgHash,{path:j.path,leaf:j.leaf||{}}),k++}console.log(N.dim(` fingerprints: +${k} cached \xB7 ${C} already-present`)),console.log(),e.dryRun?console.log(N.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(N.green(` \u2713 pulled from ${o}`)),console.log()});function Cr(e,t,o){let n={};for(let r of o)(n[r.level]||=[]).push(`${r.id}${r.axes?.name?` (${r.axes.name})`:""}`);let s=t.levels.map(r=>` ${r.id}: [${(n[r.id]||[]).slice(0,10).join(", ")||"(none yet)"}]`).join(`
|
|
342
|
+
`),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(`
|
|
343
|
+
`)}async function Er(e,t,o,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:t,message:o,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 Ar((c?.content||"").toString())}finally{clearTimeout(r)}}function Ir(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function Ar(e){if(!e)return null;try{return JSON.parse(e)}catch{}let t=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(t)try{return JSON.parse(t[1])}catch{}let o=e.indexOf("{");if(o<0)return null;let n=0;for(let s=o;s<e.length;s++)if(e[s]==="{")n++;else if(e[s]==="}"&&(n--,n===0))try{return JSON.parse(e.slice(o,s+1))}catch{return null}return null}import{Command as Dr}from"commander";import se from"chalk";import{existsSync as qo,mkdirSync as Or,readFileSync as hs,readdirSync as Rr,writeFileSync as ys}from"fs";import{resolve as Jo,relative as zo}from"path";import{z as de}from"zod";var xt=de.object({id:de.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:de.string().min(1),trigger:de.string().min(1,"procedures must describe when they apply"),inputs:de.array(de.string()).default([]),expected:de.string().optional(),kpis:de.array(de.string()).default([]),owner:de.string().optional(),tags:de.array(de.string()).default([]),created:de.string().optional(),updated:de.string().optional(),related:de.array(de.string()).default([])});function ws(e){let t=e.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!t)return{meta:{},body:e};let o={};for(let n of t[1].split(`
|
|
344
|
+
`)){let s=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(!s)continue;let i=s[1],r=s[2].trim();if(r.startsWith("[")&&r.endsWith("]")){try{o[i]=JSON.parse(r);continue}catch{}o[i]=r.slice(1,-1).split(",").map(a=>a.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean);continue}r.startsWith('"')&&r.endsWith('"')&&(r=r.slice(1,-1)),o[i]=r}return{meta:o,body:t[2]}}function $s(e){let t=["---"];return t.push(`id: ${e.id}`),t.push(`title: "${e.title.replace(/"/g,'\\"')}"`),t.push(`trigger: "${e.trigger.replace(/"/g,'\\"')}"`),e.inputs?.length&&t.push(`inputs: ${JSON.stringify(e.inputs)}`),e.expected&&t.push(`expected: "${e.expected.replace(/"/g,'\\"')}"`),e.kpis?.length&&t.push(`kpis: ${JSON.stringify(e.kpis)}`),e.owner&&t.push(`owner: ${e.owner}`),e.tags?.length&&t.push(`tags: ${JSON.stringify(e.tags)}`),e.related?.length&&t.push(`related: ${JSON.stringify(e.related)}`),e.created&&t.push(`created: ${e.created}`),e.updated&&t.push(`updated: ${e.updated}`),t.push("---"),t.join(`
|
|
345
|
+
`)}var ct=class{baseDir;constructor(t={}){this.baseDir=t.baseDir??Jo(process.cwd(),".agentx/procedures"),Or(this.baseDir,{recursive:!0})}pathFor(t){return Jo(this.baseDir,`${t}.md`)}list(){if(!qo(this.baseDir))return[];let t=[];for(let o of Rr(this.baseDir,{withFileTypes:!0})){if(!o.isFile()||!o.name.endsWith(".md")||o.name.startsWith("_"))continue;let n=Jo(this.baseDir,o.name),s=hs(n,"utf-8"),{meta:i,body:r}=ws(s),a=xt.safeParse({...i,inputs:i.inputs||[],kpis:i.kpis||[],tags:i.tags||[],related:i.related||[]});a.success&&t.push({meta:a.data,body:r.trim(),path:zo(this.baseDir,n)})}return t.sort((o,n)=>o.meta.id.localeCompare(n.meta.id))}get(t){let o=this.pathFor(t);if(!qo(o))return null;let n=hs(o,"utf-8"),{meta:s,body:i}=ws(n),r=xt.safeParse({...s,inputs:s.inputs||[],kpis:s.kpis||[],tags:s.tags||[],related:s.related||[]});return r.success?{meta:r.data,body:i.trim(),path:zo(this.baseDir,o)}:null}add(t,o){let n=xt.parse({...t,created:t.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),s=this.pathFor(n.id);if(qo(s))throw new Error(`Procedure already exists: ${n.id}`);return ys(s,$s(n)+`
|
|
346
|
+
|
|
347
|
+
`+o.trim()+`
|
|
348
|
+
`),{meta:n,body:o.trim(),path:zo(this.baseDir,s)}}update(t,o,n){let s=this.get(t);if(!s)throw new Error(`Procedure not found: ${t}`);let i=xt.parse({...s.meta,...o,id:s.meta.id,updated:new Date().toISOString().slice(0,10)}),r=n!==void 0?n:s.body;return ys(this.pathFor(t),$s(i)+`
|
|
349
|
+
|
|
350
|
+
`+r.trim()+`
|
|
351
|
+
`),{meta:i,body:r.trim(),path:s.path}}};var qt=new Dr().name("procedure").description("procedures (SOPs) \u2014 list, add, show \xB7 delta extraction coming later");qt.command("list").description("list all procedures with their trigger line").action(()=>{let t=new ct().list();if(!t.length){console.log(se.dim(" no procedures yet. Add one with: agentx procedure add"));return}console.log();for(let o of t)console.log(` ${se.cyan(o.meta.id)} ${se.bold(o.meta.title)}`),console.log(` ${se.dim("trigger:")} ${o.meta.trigger}`),o.meta.kpis?.length&&console.log(` ${se.dim("kpis:")} ${o.meta.kpis.join(", ")}`);console.log(),console.log(se.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});qt.command("add").description("add a new procedure (non-interactive; pass all fields as flags)").requiredOption("--id <id>","procedure id (lower-kebab, e.g. deploy-clawd)").requiredOption("--title <t>","human-readable title").requiredOption("--trigger <t>","when this procedure applies (one sentence)").option("--input <i...>","required input (repeatable)",(e,t=[])=>[...t,e]).option("--expected <t>","expected output / success criterion").option("--kpi <k...>","KPI (repeatable)",(e,t=[])=>[...t,e]).option("--owner <id>","owning agent or person").option("--tag <t...>","tag (repeatable)",(e,t=[])=>[...t,e]).option("--related <r...>","related procedure id or wiki article title (repeatable)",(e,t=[])=>[...t,e]).option("--steps <md>","markdown body \u2014 usually numbered steps").action(e=>{let t=new ct,o=e.steps?String(e.steps):`## Steps
|
|
352
|
+
|
|
353
|
+
1. (fill in)
|
|
354
|
+
|
|
355
|
+
## Notes
|
|
356
|
+
|
|
357
|
+
`;try{let n=t.add({id:e.id,title:e.title,trigger:e.trigger,inputs:e.input||[],expected:e.expected,kpis:e.kpi||[],owner:e.owner,tags:e.tag||[],related:e.related||[]},o);console.log(se.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(se.dim(` ${t.baseDir}/${n.path}`))}catch(n){console.log(se.red(` add failed: ${n.message}`)),process.exit(1)}});qt.command("show <id>").description("show a single procedure").action(e=>{let o=new ct().get(e);o||(console.log(se.yellow(` no procedure matches "${e}". Try: agentx procedure list`)),process.exit(1)),console.log(),console.log(se.bold(` ${o.meta.title}`)+se.dim(` (${o.meta.id})`)),console.log(se.dim(` trigger: ${o.meta.trigger}`)),o.meta.inputs?.length&&console.log(se.dim(` inputs: ${o.meta.inputs.join(", ")}`)),o.meta.expected&&console.log(se.dim(` expected: ${o.meta.expected}`)),o.meta.kpis?.length&&console.log(se.dim(` kpis: ${o.meta.kpis.join(", ")}`)),o.meta.owner&&console.log(se.dim(` owner: ${o.meta.owner}`)),o.meta.related?.length&&console.log(se.dim(` related: ${o.meta.related.join(", ")}`)),console.log(),console.log(o.body),console.log()});import{Command as Tr}from"commander";import D from"chalk";import{resolve as _r}from"path";import{existsSync as Nr,readFileSync as Pr}from"fs";var Re=new Tr().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Re.command("list").description("list all workflows with their trigger + state count").action(()=>{let t=new Vt().list();if(!t.length){console.log(D.dim(" no workflows yet. Add one by writing .agentx/workflows/<id>.json"));return}console.log();for(let o of t){let s=o.nodes.find(r=>r.type.startsWith("trigger."))?.config??{},i=[s.filter?.project,s.filter?.repo,s.filter?.chat].filter(Boolean).join(" / ");console.log(` ${D.cyan(o.id)} ${D.bold(o.title)} ${D.dim(`v${o.version}`)}`),console.log(` ${D.dim("trigger:")} ${s.source??"?"}${i?` ${D.dim(i)}`:""}`),console.log(` ${D.dim("nodes: ")} ${o.nodes.length} (${o.nodes.map(r=>r.type).join(", ")})`)}console.log(),console.log(D.dim(` ${t.length} workflow${t.length===1?"":"s"}.`))});Re.command("show <id>").description("show a single workflow's full definition").option("--format <fmt>","output format: json (default) or yaml","json").action((e,t)=>{let n=new Vt().get(e);n||(console.log(D.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=t.format.toLowerCase();s==="yaml"||s==="yml"?console.log(vn(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(D.red(` unknown format "${t.format}" \u2014 use json or yaml`)),process.exit(1))});Re.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=_r(process.cwd(),e);Nr(i)||(console.log(D.red(` file not found: ${i}`)),process.exit(1));try{let r=Pr(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?kn(r,{filePath:e}):JSON.parse(r),l=wn.safeParse(c);if(!l.success){console.log(D.red(` \u2717 ${i}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let p=$n(l.data);if(p.length){console.log(D.yellow(` ! ${i} (lint)`));for(let d of p)console.log(` ${d}`);process.exit(1)}console.log(D.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof bn?r.message:`parse error: ${r?.message??r}`;console.log(D.red(` ${a}`)),process.exit(1)}return}let o=new Vt().validateAll(),n=0,s=0;for(let i of o)if(i.isValid)console.log(D.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(D.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(D.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Re.command("runs [id]").description("list recent runs (optionally filtered to a single workflow)").option("--limit <n>","max runs to show","20").option("--node <id>",'home-node id for this daemon (defaults to WF_NODE_ID env or "local")').action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local",n=new _t({nodeId:o}).list({workflowId:e,limit:Number(t.limit)});if(!n.length){console.log(D.dim(` no runs yet${e?` for "${e}"`:""}.`));return}console.log();for(let s of n){let i=s.history.at(-1),r=s.pending[0]??(s.status==="completed"?"\u2205":"\u2014"),a=s.status==="running"?D.cyan:s.status==="failed"?D.red:D.green;console.log(` ${D.dim(s.id.slice(0,8))} ${D.bold(s.workflowId)} ${a(r)} ${D.dim(s.status)}`),console.log(` ${D.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${D.dim("home: ")} ${s.homeNode}`),console.log(` ${D.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${D.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(D.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Re.command("run <id>").description("manually trigger a workflow (trigger.manual by default; add --force for any)").option("--input <json>","JSON object merged into the trigger event payload").option("--force","fire even if the trigger isn't `trigger.manual` (uses a synthesized event)",!1).option("--daemon <url>","daemon API base URL","http://127.0.0.1:18800").action(async(e,t)=>{let o={};if(t.input)try{o=JSON.parse(t.input)}catch{console.log(D.red(" --input must be valid JSON")),process.exit(1)}let n=`${String(t.daemon).replace(/\/$/,"")}/workflows/${encodeURIComponent(e)}/run`;try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:o,force:!!t.force})});if(!s.ok){let r=await s.text();console.log(D.red(` run failed (${s.status}): ${r.slice(0,300)}`)),s.status===409&&console.log(D.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let i=await s.json();console.log(D.green(` \u2713 run started: ${i.runId||"(unknown id)"}${i.force?D.dim(` (forced, source=${i.source})`):""}`))}catch(s){console.log(D.red(` request to daemon failed: ${s.message}`)),process.exit(1)}});Re.command("pause <runId>").description("pause an active run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new _t({nodeId:o}).setStatus(e,"paused")||(console.log(D.yellow(` no such run: ${e}`)),process.exit(1)),console.log(D.green(` \u2713 paused ${e}`))});Re.command("resume <runId>").description("resume a paused run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new _t({nodeId:o}).setStatus(e,"running")||(console.log(D.yellow(` no such run: ${e}`)),process.exit(1)),console.log(D.green(` \u2713 resumed ${e}`))});Re.command("cancel <runId>").description("cancel an active run").option("--node <id>","home-node id").action((e,t)=>{let o=t.node||process.env.WF_NODE_ID||"local";new _t({nodeId:o}).setStatus(e,"canceled")||(console.log(D.yellow(` no such run: ${e}`)),process.exit(1)),console.log(D.green(` \u2713 canceled ${e}`))});import{Command as Mr}from"commander";import U from"chalk";import bs from"prompts";function co(){let e=R(),[t,o]=(e.node?.bind||"127.0.0.1:18800").split(":");return`http://${t||"127.0.0.1"}:${o||18800}`}async function lo(e,t){let o=await fetch(e,t);if(!o.ok){let n=await o.text().catch(()=>"");throw new Error(`HTTP ${o.status}: ${n.slice(0,200)||o.statusText}`)}return await o.json()}var Jt=new Mr().name("task").description("workflow user-tasks \u2014 list, show, submit (the terminal inbox)");Jt.command("list").description("list open user-tasks awaiting submission").option("--actor <id>","filter to tasks assigned to this actor id").option("--json","machine-readable JSON output").action(async e=>{try{let t=e.actor?`?actor=${encodeURIComponent(String(e.actor))}`:"",n=(await lo(`${co()}/api/workflows/tasks${t}`)).tasks||[];if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(U.dim(" No open tasks.")),console.log();return}console.log(),console.log(U.bold(` ${n.length} open task${n.length===1?"":"s"}`)),console.log();for(let s of n){let i=s.dueAt?U.yellow(` \xB7 due ${s.dueAt.slice(0,16).replace("T"," ")}`):"",r=s.form?.fields?.length||0;console.log(` ${U.bold(s.id)}${i}`),console.log(` ${s.title}`),console.log(U.dim(` workflow=${s.workflowId} node=${s.nodeId} assignee=${s.assignee} fields=${r}`))}console.log(),console.log(U.dim(" agentx task show <id> to see form details")),console.log(U.dim(" agentx task submit <id> to fill it in")),console.log()}catch(t){console.log(U.red(` ${t.message}`)),process.exitCode=1}});Jt.command("show <id>").description("show a single user-task with its form definition").option("--json","machine-readable JSON output").action(async(e,t)=>{try{let n=(await lo(`${co()}/api/workflows/tasks/${encodeURIComponent(e)}`)).task;if(t.json){console.log(JSON.stringify(n,null,2));return}console.log(),console.log(U.bold(` ${n.title}`)),n.description&&console.log(U.dim(` ${n.description}`)),console.log(),console.log(U.dim(` id=${n.id} workflow=${n.workflowId} node=${n.nodeId}`)),console.log(U.dim(` assignee=${n.assignee} status=${n.status}`)),n.dueAt&&console.log(U.yellow(` due ${n.dueAt}`)),console.log();let s=n.form?.fields||[];if(s.length===0)console.log(U.dim(" (no fields)"));else{console.log(U.bold(" Fields:"));for(let i of s){let r=i.required?U.red("*"):" ",a=i.options?.length?U.dim(` [${i.options.join("|")}]`):"",c=i.hint?U.dim(` \u2014 ${i.hint}`):"";console.log(` ${r} ${U.cyan(i.key)} (${i.type})${a}${c}`)}}console.log(),console.log(U.dim(` agentx task submit ${n.id} to fill it in`)),console.log()}catch(o){console.log(U.red(` ${o.message}`)),process.exitCode=1}});Jt.command("submit <id>").description("fill in and submit a user-task form interactively (or via --json)").option("--as <actor>","submitted-by id (defaults to terminal user)",process.env.USER||"cli").option("--json <body>","non-interactive: pass {action,values} as a JSON string").option("--secondary","click the secondary action instead of primary (e.g. reject)").action(async(e,t)=>{try{let n=(await lo(`${co()}/api/workflows/tasks/${encodeURIComponent(e)}`)).task;if(n.status!=="open"){console.log(U.yellow(` task is ${n.status} \u2014 nothing to submit`));return}let s=t.secondary?"secondary":"primary",i={};if(t.json)try{let c=JSON.parse(t.json);c&&typeof c=="object"&&(i=c.values&&typeof c.values=="object"?c.values:c,c.action==="secondary"&&(s="secondary"))}catch(c){console.log(U.red(` --json parse failed: ${c.message}`)),process.exitCode=1;return}else{console.log(),console.log(U.bold(` ${n.title}`)),n.description&&console.log(U.dim(` ${n.description}`)),console.log();for(let c of n.form?.fields||[]){let l=Lr(c.type),p=`${c.label}${c.required?U.red(" *"):""}${c.hint?U.dim(` (${c.hint})`):""}`,d=c.defaultValue!==void 0?c.defaultValue:void 0,m=c.options?.map(y=>({title:y,value:y})),u={type:l,name:c.key,message:p,...d!==void 0?{initial:d}:{},...m?{choices:m}:{},validate:y=>c.required&&(y==null||y==="")?`${c.label} is required`:!0},h=await bs(u,{onCancel:()=>process.exit(130)});i[c.key]=h[c.key]}if(!t.secondary&&n.form?.secondaryAction){let c=n.form.submitLabel||"Submit",l=n.form.secondaryAction.label;(await bs({type:"select",name:"action",message:"Action",choices:[{title:c,value:"primary"},{title:l,value:"secondary"}]},{onCancel:()=>process.exit(130)})).action==="secondary"&&(s="secondary")}}let r={submission:{action:s,values:i},submittedBy:t.as},a=await lo(`${co()}/api/workflows/tasks/${encodeURIComponent(e)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if("error"in a){if(console.log(U.red(` ${a.error}`)),a.fieldErrors)for(let[c,l]of Object.entries(a.fieldErrors))console.log(U.red(` ${c}: ${l}`));process.exitCode=1;return}console.log(),console.log(U.green(` Submitted (action=${s}). runId=${a.runId}`)),console.log()}catch(o){console.log(U.red(` ${o.message}`)),process.exitCode=1}});function Lr(e){switch(e){case"long-text":return"text";case"number":return"number";case"boolean":return"confirm";case"date":return"text";case"select":return"select";case"multi-select":return"multiselect";case"file":return"text";default:return"text"}}import{Command as Wr}from"commander";import z from"chalk";function St(e){let{summary:t,backupPath:o}=ut(n=>e(n));console.log(z.green(`
|
|
358
|
+
\u2713 ${t}`)),o&&console.log(z.dim(` Backup: ${o}`)),console.log(z.dim(` Restart the daemon (or POST /reload) for the change to take effect.
|
|
359
|
+
`))}function go(){try{return R().business||{}}catch{return{}}}var jt=new Wr().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");jt.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let t=go();if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t||!t.enabled){console.log(),console.log(z.yellow(" business block not enabled (or missing).")),console.log(z.dim(" Add a `business` key to agentx.json to opt in.")),console.log();return}let o=t.orgChart||{},n=t.projects||[],s=t.contactMap||[];console.log(),console.log(z.bold(" Org chart"));let i=Object.entries(o);if(i.length===0)console.log(z.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?z.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?z.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${z.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(z.bold(` Projects (${n.length})`)),n.length===0)console.log(z.dim(" (empty)"));else for(let r of n){let a=r.pm?z.dim(` \xB7 pm=${r.pm}`):"",c=r.client?z.dim(` \xB7 client=${r.client}`):"";console.log(` ${z.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(z.bold(` Contact map (${s.length})`)),s.length===0)console.log(z.dim(" (empty)"));else for(let r of s){let a=r.chatId?`chatId=${r.chatId}`:r.username?`username=${r.username}`:r.senderId?`senderId=${r.senderId}`:"?",c=r.channel?`${r.channel}/`:"";console.log(` ${z.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?z.dim(` (${r.displayName})`):""}`)}console.log()});var Go=jt.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");Go.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let t=go(),o=Object.entries(t.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(o),null,2));return}if(o.length===0){console.log(z.dim(" no entries"));return}for(let[n,s]of o)console.log(` ${z.cyan(n)} ${s.role}${s.reportsTo?z.dim(` \u2192 ${s.reportsTo}`):""}`)});Go.command("add <agentId>").description("add or update an orgChart entry for an agent").requiredOption("--role <role>","role title (e.g. 'PM', 'Coder', 'DevOps')").option("--reports-to <agentId>","manager's agentId").option("--start <hh:mm>","schedule start","09:00").option("--end <hh:mm>","schedule end","17:00").option("--days <csv>","working days (mon,tue,wed,thu,fri)","mon,tue,wed,thu,fri").option("--utilization <0..1>","target utilization","0.8").action((e,t)=>{let o=String(t.days).split(",").map(n=>n.trim()).filter(Boolean);St(n=>(n.business=n.business||{},n.business.orgChart=n.business.orgChart||{},n.business.orgChart[e]={role:t.role,...t.reportsTo?{reportsTo:t.reportsTo}:{},schedule:{days:o,start:t.start,end:t.end},utilizationTarget:parseFloat(t.utilization)||.8},`orgChart entry "${e}" upserted (role=${t.role}${t.reportsTo?`, reports to ${t.reportsTo}`:""})`))});Go.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{St(t=>{if(!t.business?.orgChart||!(e in t.business.orgChart))throw new Error(`no orgChart entry for "${e}"`);return delete t.business.orgChart[e],`orgChart entry "${e}" removed`})});var Ho=jt.command("project").description("manage business.projects \u2014 id, pm, client");Ho.command("list").description("list projects").option("--json","JSON output").action(e=>{let o=go().projects||[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(z.dim(" no projects"));return}for(let n of o)console.log(` ${z.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});Ho.command("add <id>").description("add or update a project entry").option("--pm <agentId>","PM responsible for this project (drives PM gate)").option("--client <name>","client this project belongs to (drives activity-graph attribution)").action((e,t)=>{St(o=>{o.business=o.business||{},o.business.projects=o.business.projects||[];let n=o.business.projects.findIndex(i=>i.id===e),s={id:e,...t.pm?{pm:t.pm}:{},...t.client?{client:t.client}:{}};return n>=0?o.business.projects[n]={...o.business.projects[n],...s}:o.business.projects.push(s),n>=0?`project "${e}" updated`:`project "${e}" added`})});Ho.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{St(t=>{let o=t.business?.projects||[],n=o.length;if(t.business.projects=o.filter(s=>s.id!==e),t.business.projects.length===n)throw new Error(`no project "${e}"`);return`project "${e}" removed`})});var Yo=jt.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");Yo.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let o=go().contactMap||[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(z.dim(" no entries"));return}for(let n of o){let s=n.chatId?`chatId=${n.chatId}`:n.username?`username=${n.username}`:n.senderId?`senderId=${n.senderId}`:"?";console.log(` ${n.channel?n.channel+"/":""}${z.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});Yo.command("add").description("add a contactMap entry").requiredOption("--client <name>","client this contact belongs to").option("--channel <name>","telegram | whatsapp | slack | discord").option("--chat-id <id>","native chat id (e.g. -100\u2026, JID)").option("--username <handle>","sender username/handle").option("--sender-id <id>","numeric sender id (when username is unstable)").option("--project <id>","project this traffic should attribute to").option("--display-name <name>","display-name override for the initiator pill").action(e=>{!e.chatId&&!e.username&&!e.senderId&&(console.log(z.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),St(t=>{t.business=t.business||{},t.business.contactMap=t.business.contactMap||[];let o={client:e.client};e.channel&&(o.channel=e.channel),e.chatId&&(o.chatId=e.chatId),e.username&&(o.username=e.username),e.senderId&&(o.senderId=e.senderId),e.project&&(o.project=e.project),e.displayName&&(o.displayName=e.displayName),t.business.contactMap.push(o);let n=e.chatId||e.username||e.senderId;return`contact ${e.channel?e.channel+"/":""}${n} \u2192 ${e.client}${e.project?"/"+e.project:""} added`})});Yo.command("remove").alias("rm").description("remove a contactMap entry by matching field(s)").option("--channel <name>").option("--chat-id <id>").option("--username <handle>").option("--sender-id <id>").action(e=>{St(t=>{let o=t.business?.contactMap||[],n=o.length;if(t.business.contactMap=o.filter(s=>!!(e.channel&&s.channel!==e.channel||e.chatId&&s.chatId!==e.chatId||e.username&&s.username!==e.username||e.senderId&&s.senderId!==e.senderId)),t.business.contactMap.length===n)throw new Error("no matching contact entry");return`${n-t.business.contactMap.length} contact entry/entries removed`})});import{Command as Fr}from"commander";import ge from"chalk";var Ur={today:"day",day:"day",week:"week","this-week":"week",month:"month","this-month":"month"};function Ko(e){let t=Ur[e.toLowerCase()];if(!t)throw new Error(`Unknown plan tier "${e}". Use: today | week | month.`);return t}function mo(){let t=R().business?.standup?.plansDir||".agentx/plans";return new En(t)}var Ct=new Fr().name("plan").description("set / read / list day-week-month plans that drive the standup-tick");Ct.command("set <tier>").description("write a plan for today | week | month (priorities-as-bullets)").option("-p, --priority <text...>","bullet line \u2014 repeat for multiple priorities").option("-m, --markdown <md>","raw markdown body (overrides --priority)").option("-f, --file <path>","read markdown from a file").action(async(e,t)=>{let o=Ko(e),n=mo(),s;if(t.file){let{readFileSync:a}=await import("fs");s=a(t.file,"utf-8")}else t.markdown?s=t.markdown:t.priority?.length?s=t.priority.map(a=>`- ${a}`).join(`
|
|
360
|
+
`):(console.error(ge.red(" Provide --priority, --markdown, or --file.")),process.exit(1));let i=n.write(o,s);console.log(ge.green(` \u2713 ${o} plan saved \u2192 ${i.path}`));let r=So(s);if(r.length){console.log(ge.dim(` ${r.length} bullet${r.length===1?"":"s"}:`));for(let a of r)console.log(ge.dim(` \u2022 ${a}`))}});Ct.command("show [tier]").description("print the plan that the next standup will use (default: resolve day\u2192week\u2192month)").action(async e=>{let t=mo();if(e){let n=Ko(e),s=t.read(n);if(!s){console.log(ge.dim(` No ${n} plan set.`));return}ks(s.tier,s.date,s.content);return}let o=t.resolve();if(!o){console.log(ge.yellow(" No plan set at any tier.")),console.log(ge.dim(" The next standup-tick will post a 'no plan today' notice and dispatch no agent.")),console.log(ge.dim(' Set one with: agentx plan set today --priority "\u2026"'));return}ks(o.tier,o.date,o.content)});Ct.command("list").description("recent plans across all tiers").option("-n, --limit <n>","max rows","20").action(async e=>{let o=mo().list(parseInt(e.limit,10)||20);if(!o.length){console.log(ge.dim(" No plans yet."));return}for(let n of o)console.log(` ${ge.cyan(n.tier.padEnd(5))} ${ge.bold(n.date.padEnd(11))} ${ge.dim(n.path)}`)});Ct.command("clear <tier>").description("remove the plan for today | week | month").action(async e=>{let t=Ko(e),n=mo().read(t);if(!n){console.log(ge.dim(` No ${t} plan to clear.`));return}let{unlinkSync:s}=await import("fs");s(n.path),console.log(ge.green(` \u2713 ${t} plan cleared (${n.path})`))});function ks(e,t,o){console.log(ge.cyan(` ${e} plan \u2014 ${t}`)),console.log();for(let s of o.split(`
|
|
361
|
+
`))console.log(` ${s}`);console.log();let n=So(o);n.length&&console.log(ge.dim(` ${n.length} bullet${n.length===1?"":"s"} extracted as priorities.`))}import{Command as Br}from"commander";import be from"chalk";function qr(){try{return R().notifications||{}}catch{return{}}}function po(e){let{summary:t,backupPath:o}=ut(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(be.green(`
|
|
362
|
+
\u2713 ${t}`)),o&&console.log(be.dim(` Backup: ${o}`)),console.log(be.dim(` Restart the daemon (or POST /reload) for the change to take effect.
|
|
363
|
+
`))}var Et=new Br().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");Et.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let t=qr();if(e.json){console.log(JSON.stringify(t,null,2));return}if(console.log(),t.destination){let n=t.destination.accountId?` \xB7 account=${t.destination.accountId}`:"";console.log(` destination ${be.cyan(t.destination.channel+":"+t.destination.chatId)}${be.dim(n)}`)}else console.log(` destination ${be.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${t.longTaskThreshold??30}s ${be.dim("(0 disables long-task pings)")}`);let o=t.on||{};console.log(` on.taskComplete ${o.taskComplete===!1?be.dim("off"):"on"}`),console.log(` on.taskError ${o.taskError===!1?be.dim("off"):"on"}`),console.log(` on.taskQueued ${o.taskQueued?"on":be.dim("off")}`),console.log()});Et.command("route").description("set the destination channel/chatId for notifications").requiredOption("--channel <name>","telegram | whatsapp | slack | discord").requiredOption("--chat-id <id>","native chat id (e.g. -100\u2026, JID, channel id)").option("--account-id <id>","channel account id when the channel is multi-account (telegram with multiple bots)").option("--clear","clear the destination instead of setting it").action(e=>{if(e.clear){po(t=>(delete t.destination,"notifications destination cleared"));return}po(t=>(t.destination={channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}},`notifications destination \u2192 ${e.channel}:${e.chatId}${e.accountId?` (account=${e.accountId})`:""}`))});Et.command("event <name> <state>").description("toggle an event: name in {taskComplete, taskError, taskQueued}; state in {on, off}").action((e,t)=>{let o=["taskComplete","taskError","taskQueued"];o.includes(e)||(console.log(be.red(` unknown event "${e}". Pick from: ${o.join(", ")}`)),process.exit(1));let n=t.toLowerCase();["on","off","true","false","1","0"].includes(n)||(console.log(be.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";po(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});Et.command("threshold <seconds>").description("set the long-task threshold in seconds (0 disables long-task pings)").action(e=>{let t=parseInt(e,10);(!Number.isFinite(t)||t<0)&&(console.log(be.red(" threshold must be a non-negative integer")),process.exit(1)),po(o=>(o.longTaskThreshold=t,`longTaskThreshold = ${t}s`))});import{Command as Jr}from"commander";import He from"chalk";import{readdirSync as Vo,statSync as vs,unlinkSync as zr,rmSync as Gr,existsSync as xs}from"fs";import{resolve as Ss,join as js}from"path";var Cs=[{dir:".agentx/sessions",label:"Per-day session JSON"},{dir:".agentx/drift",label:"Drift snapshots",recursive:!0},{dir:".agentx/router",label:"Router-decision logs",recursive:!0},{dir:".agentx/patterns",label:"Self-improving pattern store",recursive:!0}];function Qo(e,t){if(!xs(e))return[];let o=[];for(let n of Vo(e,{withFileTypes:!0})){let s=js(e,n.name);n.isFile()?o.push(s):n.isDirectory()&&t&&o.push(...Qo(s,!0))}return o}var fo=new Jr().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");fo.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let t of Cs){let o=Ss(process.cwd(),t.dir),n=Qo(o,!!t.recursive),s=0,i=null;for(let a of n)try{let c=vs(a);s+=c.size,(i===null||c.mtimeMs<i)&&(i=c.mtimeMs)}catch{}e+=s;let r=i!==null?`${Math.round((Date.now()-i)/864e5)}d`:"\u2014";console.log(` ${He.cyan(t.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${uo(s).padStart(10)} oldest=${r}`)}console.log(He.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${uo(e).padStart(10)} total`)),console.log(),console.log(He.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});fo.command("prune").description("delete files older than --days from each retention target").option("--days <n>","max age in days; everything older is deleted","30").option("--dry-run","list candidates, don't delete").option("--target <name>","limit to one target dir (e.g. .agentx/sessions)").action(e=>{let t=parseInt(e.days,10);(!Number.isFinite(t)||t<1)&&(console.log(He.red(" --days must be a positive integer")),process.exit(1));let o=Date.now()-t*864e5,n=e.target,s=0,i=0;console.log(),console.log(He.bold(` Pruning files older than ${t}d (${new Date(o).toISOString().slice(0,10)})${e.dryRun?He.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of Cs){if(n&&r.dir!==n)continue;let a=Ss(process.cwd(),r.dir),c=Qo(a,!!r.recursive),l=0,p=0;for(let m of c)try{let u=vs(m);if(u.mtimeMs<o&&(p+=u.size,l++,!e.dryRun))try{zr(m)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{Es(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${He.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${uo(p)})`),s+=l,i+=p}console.log(),console.log(He.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${uo(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function Es(e){if(xs(e))for(let t of Vo(e,{withFileTypes:!0})){if(!t.isDirectory())continue;let o=js(e,t.name);Es(o);try{Vo(o).length===0&&Gr(o,{recursive:!1})}catch{}}}function uo(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 Hr}from"commander";import B from"chalk";var lt=new Hr().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");lt.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let o=new pt().list();if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(),console.log(B.dim(" No actions yet. Add one with `agentx actions add` or `agentx actions create`.")),console.log();return}console.log();for(let n of o){let s=n.inputs?.length?B.dim(` (${n.inputs.length} input${n.inputs.length===1?"":"s"})`):"",i=n.kind==="shell"?`shell: ${n.command.slice(0,50)}`:`${n.method} ${n.url.slice(0,50)}`;console.log(` ${B.cyan(n.id.padEnd(24))} ${n.title}${s}`),console.log(` ${" ".repeat(24)} ${B.dim(i)}`)}console.log()});lt.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,t)=>{let n=new pt().get(e);if(n||(console.log(B.red(` no action "${e}"`)),process.exit(1)),t.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),console.log(B.bold(` ${n.title}`)),n.description&&console.log(B.dim(` ${n.description}`)),console.log(),console.log(` id ${n.id}`),console.log(` kind ${n.kind}`),console.log(` timeout ${n.timeoutMs}ms`),n.kind==="shell"?(console.log(` command ${n.command}`),n.cwd&&console.log(` cwd ${n.cwd}`),n.env&&console.log(` env ${JSON.stringify(n.env)}`)):(console.log(` ${n.method.padEnd(9)} ${n.url}`),n.headers&&console.log(` headers ${JSON.stringify(n.headers)}`),n.body&&console.log(` body ${n.body.slice(0,200)}`)),n.inputs.length){console.log(),console.log(B.bold(" Inputs:"));for(let s of n.inputs){let i=s.required?B.red("*"):" ",r=s.defaultValue!==void 0?B.dim(` default=${JSON.stringify(s.defaultValue)}`):"",a=s.description?B.dim(` \u2014 ${s.description}`):"";console.log(` ${i} ${B.cyan(s.name)} (${s.type})${r}${a}`)}}console.log()});lt.command("add <id>").description("add (or replace) an action non-interactively").requiredOption("--title <text>").requiredOption("--kind <kind>","shell | http").option("--description <text>").option("--command <text>","[shell] templated shell command").option("--cwd <path>","[shell] working directory").option("--url <url>","[http] URL").option("--method <m>","[http] GET|POST|PUT|PATCH|DELETE","POST").option("--headers <json>","[http] headers as JSON object").option("--body <text>","[http] body template").option("--inputs <csv>","comma-separated list of name:type[!] (e.g. amount:number!,note:string)").option("--timeout <ms>","timeout in ms (default 30000)","30000").action((e,t)=>{let o=Yr(t.inputs),n={id:e,title:t.title,description:t.description,inputs:o,timeoutMs:parseInt(t.timeout,10)||3e4,kind:t.kind};if(t.kind==="shell")t.command||(console.log(B.red(" --command required for kind=shell")),process.exit(1)),n.command=t.command,t.cwd&&(n.cwd=t.cwd);else if(t.kind==="http"){if(t.url||(console.log(B.red(" --url required for kind=http")),process.exit(1)),n.url=t.url,n.method=t.method,t.headers)try{n.headers=JSON.parse(t.headers)}catch{console.log(B.red(" --headers must be valid JSON")),process.exit(1)}t.body&&(n.body=t.body)}else console.log(B.red(" --kind must be shell|http")),process.exit(1);let s=xn.safeParse(n);if(!s.success){console.log(B.red(" validation failed:"));for(let a of s.error.issues)console.log(B.red(` ${a.path.join(".")}: ${a.message}`));process.exit(1)}let r=new pt().save(s.data);console.log(B.green(`
|
|
364
|
+
\u2713 action "${r.id}" saved (${r.kind}).`)),console.log(B.dim(` Test: agentx actions run ${r.id}
|
|
365
|
+
`))});lt.command("remove <id>").alias("rm").description("delete an action").action(e=>{new pt().delete(e)||(console.log(B.red(` no action "${e}"`)),process.exit(1)),console.log(B.green(` \u2713 action "${e}" removed`))});lt.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,t)=>{let n=new pt().get(e);n||(console.log(B.red(` no action "${e}"`)),process.exit(1));let s={};for(let i of t.input||[]){let r=i.indexOf("=");r<0&&(console.log(B.red(` --input "${i}" must be key=value`)),process.exit(1)),s[i.slice(0,r)]=i.slice(r+1)}try{let i=await Sn(n,s);if(t.json){console.log(JSON.stringify(i,null,2));return}console.log(),console.log(` ${i.ok?B.green("\u2713 ok"):B.red("\u2717 failed")} status=${i.status} ${i.durationMs}ms`),console.log(),i.output&&(console.log(B.dim(" --- output ---")),console.log(i.output)),i.errors&&(console.log(B.dim(" --- errors ---")),console.log(B.red(i.errors))),console.log(),i.ok||process.exit(1)}catch(i){console.log(B.red(` ${i.message}`)),process.exit(1)}});function Yr(e){if(!e)return[];let t=[];for(let o of e.split(",").map(n=>n.trim()).filter(Boolean)){let n=o.endsWith("!"),s=n?o.slice(0,-1):o,i=s.indexOf(":"),r=i>=0?s.slice(0,i):s,a=i>=0?s.slice(i+1):"string";t.push({name:r,type:a,required:n})}return t}import{Command as Is}from"commander";import G from"chalk";var It=new Is().name("actor").description("manage actors (humans) that can be assigned to workflow userTasks");It.command("add").description("add a new actor").argument("<id>","actor id (e.g. alice; 'actor:' prefix is added if missing)").requiredOption("--name <name>","human-readable name").option("--email <email>","email address").option("--telegram <handle>","Telegram user id (numeric)").option("--whatsapp <phone>","WhatsApp phone in E.164 (no +)").option("--slack <memberId>","Slack member id").option("--discord <userId>","Discord user id").option("--timezone <tz>","IANA timezone, e.g. Africa/Tunis").option("--prefer <channel>","mark this channel as preferred for task notifications","").action((e,t)=>{let o=e.startsWith("actor:")?e:`actor:${e}`,n=new Ee;if(n.getActor(o)){console.error(G.red(` actor "${o}" already exists. Use 'actor remove' first.`)),process.exitCode=1;return}let s=[],i=(c,l)=>{l&&s.push({channel:c,handle:l,preferredForTasks:t.prefer===c||void 0})};if(i("telegram",t.telegram),i("whatsapp",t.whatsapp),i("slack",t.slack),i("discord",t.discord),t.email&&i("email",t.email),s.length===0){console.error(G.red(" at least one channel handle is required (--telegram, --whatsapp, --slack, --discord, --email)")),process.exitCode=1;return}let r={id:o,name:t.name,email:t.email,channels:s,timezone:t.timezone},a=n.saveActor(r);console.log(G.green(` \u2713 actor "${a.id}" saved (${a.channels.length} channel${a.channels.length===1?"":"s"})`))});It.command("list").description("list all actors").action(()=>{let t=new Ee().listActors();if(!t.length){console.log(G.dim(" no actors yet. Try: agentx actor add alice --name 'Alice' --telegram 12345"));return}console.log();for(let o of t){let n=o.channels.map(s=>`${s.channel}:${s.handle}${s.preferredForTasks?"*":""}`).join(", ");console.log(` ${G.cyan(o.id.padEnd(24))} ${G.bold(o.name)}`),console.log(` ${G.dim(n)}`)}console.log(),console.log(G.dim(` ${t.length} actor${t.length===1?"":"s"}. * = preferred for tasks.`))});It.command("show").description("print full JSON for an actor").argument("<id>","actor id (with or without 'actor:' prefix)").action(e=>{let t=e.startsWith("actor:")?e:`actor:${e}`,n=new Ee().getActor(t);if(!n){console.error(G.red(` actor "${t}" not found`)),process.exitCode=1;return}console.log(JSON.stringify(n,null,2))});It.command("remove").alias("rm").description("remove an actor (does not clean up role memberships)").argument("<id>","actor id").action(e=>{let t=e.startsWith("actor:")?e:`actor:${e}`;if(!new Ee().deleteActor(t)){console.error(G.red(` actor "${t}" not found`)),process.exitCode=1;return}console.log(G.green(` \u2713 actor "${t}" removed`))});var dt=new Is().name("role").description("manage roles (groups of actors) for workflow userTasks");dt.command("create").description("create a new role").argument("<id>","role id (e.g. reviewers; 'role:' prefix is added if missing)").requiredOption("--name <name>","human-readable name").option("--strategy <strategy>","first-available | round-robin | all | manager-of","first-available").action((e,t)=>{let o=e.startsWith("role:")?e:`role:${e}`,n=new Ee;if(n.getRole(o)){console.error(G.red(` role "${o}" already exists`)),process.exitCode=1;return}let s=t.strategy,i=n.saveRole({id:o,name:t.name,members:[],assignmentStrategy:s,rotationCursor:0});console.log(G.green(` \u2713 role "${i.id}" created (strategy: ${i.assignmentStrategy})`))});dt.command("grant").description("add an actor (or nested role) to a role's members").argument("<roleId>","target role").argument("<memberId>","actor:<id> or role:<id>").action((e,t)=>{let o=e.startsWith("role:")?e:`role:${e}`,n=new Ee,s=n.getRole(o);if(!s){console.error(G.red(` role "${o}" not found`)),process.exitCode=1;return}let i=t.startsWith("actor:")?{actor:t}:t.startsWith("role:")?{role:t}:null;if(!i){console.error(G.red(" member must be 'actor:<id>' or 'role:<id>'")),process.exitCode=1;return}if(s.members.some(a=>JSON.stringify(a)===JSON.stringify(i))){console.log(G.dim(" already a member"));return}let r=n.saveRole({...s,members:[...s.members,i]});console.log(G.green(` \u2713 ${t} granted to ${o} (${r.members.length} member${r.members.length===1?"":"s"})`))});dt.command("revoke").description("remove an actor or nested role from a role").argument("<roleId>","target role").argument("<memberId>","actor:<id> or role:<id>").action((e,t)=>{let o=e.startsWith("role:")?e:`role:${e}`,n=new Ee,s=n.getRole(o);if(!s){console.error(G.red(` role "${o}" not found`)),process.exitCode=1;return}let i=s.members.length,r=s.members.filter(a=>"actor"in a?a.actor!==t:a.role!==t);if(r.length===i){console.log(G.dim(` "${t}" was not a member`));return}n.saveRole({...s,members:r}),console.log(G.green(` \u2713 ${t} revoked from ${o}`))});dt.command("list").description("list all roles with member counts").action(()=>{let t=new Ee().listRoles();if(!t.length){console.log(G.dim(" no roles yet. Try: agentx role create reviewers --name 'Reviewers'"));return}console.log();for(let o of t){console.log(` ${G.cyan(o.id.padEnd(24))} ${G.bold(o.name)} ${G.dim(o.assignmentStrategy)}`);for(let n of o.members){let s="actor"in n?n.actor:n.role;console.log(` ${G.dim("\u2022")} ${s}`)}}console.log(),console.log(G.dim(` ${t.length} role${t.length===1?"":"s"}.`))});dt.command("show").description("print full JSON for a role, including resolved members").argument("<id>","role id").action(e=>{let t=e.startsWith("role:")?e:`role:${e}`,o=new Ee,n=o.getRole(t);if(!n){console.error(G.red(` role "${t}" not found`)),process.exitCode=1;return}let s=o.resolveMembers({kind:"role",id:n.id});console.log(JSON.stringify({...n,_resolvedActors:s},null,2))});import{Command as Kr}from"commander";import q from"chalk";var As=new Kr().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 t=typeof e.node=="string"?e.node:"",o=typeof e.token=="string"?e.token:"";if(!t||!o)try{let r=R(e.config);t||(t=r.dashboard?.daemonUrl||""),o||(o=r.dashboard?.token||"")}catch{}t||(t="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=`${t.replace(/\/+$/,"")}/events${n.length?`?${n.join("&")}`:""}`;console.log(q.dim(` connecting to ${s}`));let i={Accept:"text/event-stream"};o&&(i.Authorization=`Bearer ${o}`);try{let r=await fetch(s,{headers:i});(!r.ok||!r.body)&&(console.error(q.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(q.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:p,value:d}=await a.read();if(p)break;l+=c.decode(d,{stream:!0});let m;for(;(m=l.indexOf(`
|
|
366
|
+
|
|
367
|
+
`))>=0;){let u=l.slice(0,m);l=l.slice(m+2),Vr(u)}}}catch(r){console.error(q.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function Vr(e){let t="message",o="";for(let i of e.split(`
|
|
368
|
+
`))i.startsWith("event: ")?t=i.slice(7):i.startsWith("data: ")&&(o=i.slice(6));if(!o)return;let n={};try{n=JSON.parse(o)}catch{console.log(`${t}: ${o}`);return}let s=n.at?q.dim(new Date(n.at).toLocaleTimeString()):"";switch(t){case"run":{let i=q.cyan(n.phase?.padEnd(9)??"run"),r=q.bold(n.workflowId??""),a=q.dim((n.runId??"").slice(0,8)),c=n.nodeId?q.yellow(n.nodeId):"",l=n.note?q.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=q.magenta(`task.${n.phase}`.padEnd(14)),r=q.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?q.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${q.cyan(a)} ${c}`);break}case"signal":{let i=q.green("signal".padEnd(9)),r=q.bold(n.name),a=q.dim(`(${n.scope})`),c=n.workflowId?q.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=q.blue("mesh".padEnd(9)),r=q.bold(n.peer),a=n.healthy?q.green("\u2713 healthy"):q.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${q.dim(n.delta??"")}`);break}case"channel":{let i=q.yellow("channel".padEnd(9)),r=n.direction==="in"?q.cyan("\u2190"):q.magenta("\u2192"),a=q.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?q.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(q.dim(`${s} status ${n.node??""} agents=${n.agents??0} active=${(n.active??[]).length} peers=${(n.mesh??[]).length}`));break}default:console.log(`${s} ${t} ${JSON.stringify(n)}`)}}import{Command as Qr}from"commander";import me from"chalk";import{readFileSync as Xr}from"fs";var ho=["user","feedback","project","reference"],gt=new Qr().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");gt.command("add").description("add a memory for an agent").requiredOption("--agent <id>","agent id").requiredOption("--type <type>","one of: user, feedback, project, reference").requiredOption("--name <slug>","short slug, unique per agent (e.g. deep-backend)").requiredOption("--description <line>","one-line hook shown in MEMORY.md").option("--body <text>","memory body (markdown); repeat --body or use --file").option("--file <path>","read body from a file (use '-' for stdin)").action(async e=>{if(!ho.includes(e.type)){console.error(me.red(` --type must be one of: ${ho.join(", ")}`)),process.exitCode=1;return}let t=e.body??"";if(e.file)if(e.file==="-")t=await Zr();else try{t=Xr(e.file,"utf-8")}catch(s){console.error(me.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!t.trim()){console.error(me.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new mt().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:t});console.log(me.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});gt.command("list").description("list memories for an agent").requiredOption("--agent <id>","agent id").option("--type <type>","filter by memory type").action(e=>{let o=new mt().list(e.agent);if(e.type){if(!ho.includes(e.type)){console.error(me.red(` --type must be one of: ${ho.join(", ")}`)),process.exitCode=1;return}o=o.filter(s=>s.type===e.type)}if(!o.length){console.log(me.dim(` no memories for agent "${e.agent}"${e.type?` of type "${e.type}"`:""}`));return}console.log();let n=null;for(let s of o)s.type!==n&&(console.log(me.bold(` ${s.type}`)),n=s.type),console.log(` ${me.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(me.dim(` ${o.length} memor${o.length===1?"y":"ies"} for ${e.agent}`))});gt.command("show").description("print the full body of a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,t)=>{let n=new mt().get(t.agent,e);if(!n){console.error(me.red(` no memory "${e}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(me.bold(`${n.type}/${n.name}`)+me.dim(` (${n.description})`)),console.log(me.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});gt.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,t)=>{if(!new mt().remove(t.agent,e)){console.error(me.red(` no memory "${e}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(me.green(` \u2713 memory "${e}" removed`))});gt.command("index").description("print the MEMORY.md index content an agent sees in its prompt").requiredOption("--agent <id>","agent id").action(e=>{let o=new mt().indexMarkdown(e.agent);if(!o){console.log(me.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(o)});async function Zr(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}import Xo from"chalk";import{Command as ea}from"commander";var Os=new ea().name("serve").description("run agentx as an MCP server for AI editors (Claude Code, Cursor, Windsurf, etc.)").option("--stdio","use stdio transport (default)",!0).option("-c, --cwd <cwd>","working directory",process.cwd()).action(async e=>{try{e.stdio!==!1?await dn():(Te.error("Only stdio transport is currently supported."),Te.info(`Usage: ${Xo.green("agentx serve --stdio")} or configure in your MCP client.`),Te.break(),Te.info("Add to Claude Code:"),Te.info(Xo.dim(" claude mcp add agentx -- npx agentx serve --stdio")),Te.break(),Te.info("Add to Cursor/MCP config:"),Te.info(Xo.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(t){In(t)}});import{Command as ta}from"commander";import fe from"chalk";var Zo=new ta().name("bench").description("benchmark harnesses (context strategies, ...)");Zo.command("context").description("run the same message under 'layered' vs 'planner' strategies and compare").requiredOption("--agent <id>","agent id to send the message to").requiredOption("--message <text>","the user message to bench").option("--channel <name>","channel label for the request context","bench").option("--chat-id <id>","chatId for session scoping","bench-harness").option("--sender <name>","sender label for the request context","bench").option("--runs <n>","number of runs per strategy (averaged)","1").option("--preview <chars>","how many response chars to print","280").option("--url <url>","daemon URL override (default: from agentx.json)").action(async e=>{let t=Math.max(1,parseInt(e.runs,10)||1),o=Math.max(0,parseInt(e.preview,10)||280),n=e.url||sa();console.log(),console.log(fe.bold(" Context-strategy benchmark")),console.log(fe.dim(` agent=${e.agent}, channel=${e.channel}, chatId=${e.chatId}, runs=${t}`)),console.log(fe.dim(` daemon=${n}`)),console.log();let s=await Rs(n,"layered",e,t),i=await Rs(n,"planner",e,t);na(s,i,o)});async function Rs(e,t,o,n){let s=0,i=0,r=0,a=0,c=0,l=0,p=0,d="",m;for(let h=0;h<n;h++){let y=Date.now();try{let b=await(await fetch(`${e}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:o.agent,message:o.message,contextStrategy:t,context:{channel:o.channel,chatId:o.chatId,sender:o.sender}}),signal:AbortSignal.timeout(6e5)})).json();if(b.error){p++,m=b.error;continue}s+=b.duration??Date.now()-y,i+=b.usage?.inputTokens??0,r+=b.usage?.outputTokens??0,a+=b.usage?.cacheReadTokens??0,c+=b.usage?.cacheCreateTokens??0,l+=oa(b.usage),d=b.content??""}catch(w){p++,m=w.message??String(w)}}let u=n-p||1;return{strategy:t,runs:n,errors:p,avgDurationMs:Math.round(s/u),avgInput:Math.round(i/u),avgOutput:Math.round(r/u),avgCacheRead:Math.round(a/u),avgCacheCreate:Math.round(c/u),avgTotalInput:Math.round((i+a+c)/u),avgCost:l/u,lastResponse:d,lastError:m}}function oa(e){if(!e)return 0;let t=3/1e6,o=15/1e6,n=.3/1e6,s=3.75/1e6;return(e.inputTokens??0)*t+(e.outputTokens??0)*o+(e.cacheReadTokens??0)*n+(e.cacheCreateTokens??0)*s}function na(e,t,o){let n=(a,c)=>a.length>=c?a:a+" ".repeat(c-a.length),s=a=>a.toLocaleString();console.log(fe.bold(" "+n("metric",22)+n("layered",18)+n("planner",18)+"delta")),console.log(fe.dim(" "+"-".repeat(74)));let i=[["input tokens",e.avgInput,t.avgInput,s],["output tokens",e.avgOutput,t.avgOutput,s],["cache read",e.avgCacheRead,t.avgCacheRead,s],["cache create",e.avgCacheCreate,t.avgCacheCreate,s],["total input",e.avgTotalInput,t.avgTotalInput,s],["est. cost ($)",e.avgCost,t.avgCost,a=>a.toFixed(4)],["duration (ms)",e.avgDurationMs,t.avgDurationMs,s]];for(let[a,c,l,p]of i){let d=l-c,m=c===0?0:d/c*100,u=d===0?fe.dim("\xB10"):d<0?fe.green(`${p(d)} (${m.toFixed(0)}%)`):fe.red(`+${p(d)} (+${m.toFixed(0)}%)`);console.log(" "+n(a,22)+n(p(c),18)+n(p(l),18)+u)}console.log(fe.dim(" "+"-".repeat(74))),(e.errors>0||t.errors>0)&&console.log(fe.yellow(` errors: layered=${e.errors} (${e.lastError??""}), planner=${t.errors} (${t.lastError??""})`)),console.log(),o>0&&(console.log(fe.bold(" Response preview (last run of each):")),console.log(fe.dim(" layered:")),console.log(" "+Ds(e.lastResponse,o).split(`
|
|
369
|
+
`).join(`
|
|
370
|
+
`)),console.log(fe.dim(" planner:")),console.log(" "+Ds(t.lastResponse,o).split(`
|
|
371
|
+
`).join(`
|
|
372
|
+
`)),console.log());let r=t.avgTotalInput-e.avgTotalInput;if(r<0){let a=e.avgTotalInput===0?0:Math.abs(r/e.avgTotalInput)*100;console.log(fe.green(` Planner saved ${s(Math.abs(r))} input tokens/run (${a.toFixed(0)}% less).`))}else r>0&&console.log(fe.yellow(` Planner used ${s(r)} MORE input tokens \u2014 investigate before enabling.`));console.log()}function Ds(e,t){return e?e.length>t?e.slice(0,t)+"\u2026":e:"(empty)"}function sa(){try{let e=R(),[t,o]=e.node.bind.split(":");return`http://${t||"127.0.0.1"}:${o||"19900"}`}catch{return"http://127.0.0.1:19900"}}import{Command as ia}from"commander";import ie from"chalk";var Ye=new ia().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Ye.command("list-chats").description("list chats observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").option("--group","groups only").option("--dm","DMs only").action(async e=>{try{let o=(await zt("/whatsapp/chats")).chats??[];if(e.group&&(o=o.filter(n=>n.isGroup)),e.dm&&(o=o.filter(n=>!n.isGroup)),e.format==="json"){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(ie.dim(" no chats cached yet"));return}console.log(),console.log(ie.bold(` ${o.length} chat${o.length===1?"":"s"}`)),console.log();for(let n of o){let s=n.isGroup?ie.cyan("group"):ie.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${ie.dim(n.jid.padEnd(40))} ${ie.dim(i)}`)}console.log()}catch(t){At(t)}});Ye.command("list-contacts").description("list contacts observed by the WhatsApp socket (cached, no live fetch)").option("--format <format>","output format: table | json","table").action(async e=>{try{let o=(await zt("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(ie.dim(" no contacts cached yet"));return}console.log(),console.log(ie.bold(` ${o.length} contact${o.length===1?"":"s"}`)),console.log();for(let n of o){let s=(n.name||n.pushName||n.phone||n.jid).padEnd(30),i=n.phone?`+${n.phone}`.padEnd(16):"\u2014".padEnd(16);console.log(` ${s} ${ie.dim(i)} ${ie.dim(n.jid)}`)}console.log()}catch(t){At(t)}});Ye.command("ingest-all").description("run a full ingest sweep against the configured allowlist (writes raw wiki entries)").option("--dry-run","compute entries without writing them \u2014 review before enabling").option("--agent <id>","owner agent for the entries (defaults to channels.whatsapp.defaultAgent)").option("--force","bypass the channels.whatsapp.ingest.enabled guard").action(async e=>{try{let t={dryRun:!!e.dryRun,force:!!e.force};e.agent&&(t.agent=e.agent);let o=await tn("/whatsapp/ingest",t);en(o,!!e.dryRun)}catch(t){At(t)}});Ye.command("ingest-contact <jid>").description("ingest one contact (skips scope allowlist for this JID only)").option("--dry-run","compute entries without writing them").option("--agent <id>","owner agent for the entries").action(async(e,t)=>{try{let o={dryRun:!!t.dryRun,force:!0,onlyJid:e,onlyKind:"contact"};t.agent&&(o.agent=t.agent);let n=await tn("/whatsapp/ingest",o);en(n,!!t.dryRun)}catch(o){At(o)}});Ye.command("ingest-chat <jid>").description("ingest one chat (DM or group) including message window if `--messages` is set").option("--dry-run","compute entries without writing them").option("--messages","include the bounded message window for this chat (overrides config mode)").option("--agent <id>","owner agent for the entries").action(async(e,t)=>{try{let o={dryRun:!!t.dryRun,force:!0,onlyJid:e};t.agent&&(o.agent=t.agent),t.messages&&(o.forceMode="messages");let n=await tn("/whatsapp/ingest",o);en(n,!!t.dryRun)}catch(o){At(o)}});Ye.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await zt("/whatsapp/state"),t=await zt("/whatsapp/chats"),o=await zt("/whatsapp/contacts");console.log(),console.log(ie.bold(" WhatsApp status")),console.log(),console.log(` connection: ${e.connection||"\u2014"}`),console.log(` cached chats: ${t.chats?.length??0}`),console.log(` cached contacts: ${o.contacts?.length??0}`),console.log()}catch(e){At(e)}});function en(e,t){if(console.log(),console.log(ie.bold(t?" Ingest (dry-run)":" Ingest report")),console.log(),console.log(` scanned: contacts=${e.scannedContacts}, groups=${e.scannedGroups}`),console.log(` wrote: contacts=${e.wroteContacts}, groups=${e.wroteGroups}, dm-windows=${e.wroteDmWindows}, group-windows=${e.wroteGroupWindows}`),e.skippedUnchanged&&console.log(` skipped: ${e.skippedUnchanged} unchanged`),e.errors?.length){console.log(ie.yellow(` errors: ${e.errors.length}`));for(let o of e.errors.slice(0,5))console.log(ie.yellow(` - [${o.kind}] ${o.jid}: ${o.message}`))}if(t&&e.dryRunEntries?.length){console.log(),console.log(ie.dim(" would-be entries:"));for(let o of e.dryRunEntries.slice(0,10))console.log(ie.dim(` - ${o.id} (${o.source}, ${o.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(ie.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function Ts(){try{let e=R(),[t,o]=e.node.bind.split(":");return`http://${t||"127.0.0.1"}:${o||"19900"}`}catch{return"http://127.0.0.1:19900"}}async function zt(e){let t=await fetch(`${Ts()}${e}`,{signal:AbortSignal.timeout(1e4)}),o=await t.json().catch(()=>({}));if(!t.ok)throw new Error(o.error||`HTTP ${t.status}`);return o}async function tn(e,t){let o=await fetch(`${Ts()}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(6e5)}),n=await o.json().catch(()=>({}));if(!o.ok)throw new Error(n.error||`HTTP ${o.status}`);return n}function At(e){console.error(ie.red(` ${e.message||e}`)),process.exit(1)}import{Command as ra}from"commander";import H from"chalk";import{existsSync as aa,mkdirSync as _s,writeFileSync as Gt}from"fs";import{join as Ot,resolve as ca}from"path";var Ht=new ra().name("plugin").description("manage agentx plugins (Move B)");Ht.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let t=R().plugins??[];if(console.log(),t.length===0){console.log(H.dim(" No plugins configured.")),console.log(H.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(H.bold(` Plugins configured: ${t.length}`)),console.log();for(let o of t)console.log(` ${H.cyan(o)}`);console.log(),console.log(H.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(H.red(` ${e.message}`)),process.exitCode=1}});Ht.command("init <name>").description("scaffold a new plugin package (npm-publishable, with manifest + setup hook)").option("--cwd <cwd>","directory to create the package under",process.cwd()).option("--description <text>","short package description").option("--force","overwrite an existing directory").action((e,t)=>{/^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(e)||(console.log(H.red(` invalid package name "${e}". Use lowercase letters, digits, hyphens; optional @scope/ prefix.`)),process.exit(1));let o=e.startsWith("@")?e.split("/")[1]:e,n=ca(t.cwd,o);aa(n)&&!t.force&&(console.log(H.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),_s(n,{recursive:!0}),_s(Ot(n,"src"),{recursive:!0});let s=t.description||`AgentX plugin: ${e}`;Gt(Ot(n,"package.json"),ma(e,s)),Gt(Ot(n,"tsconfig.json"),pa()),Gt(Ot(n,"src/index.ts"),ua(e)),Gt(Ot(n,"README.md"),fa(e,s)),Gt(Ot(n,".gitignore"),ha()),console.log(),console.log(H.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(H.bold(" Next steps:")),console.log(H.dim(` cd ${o}`)),console.log(H.dim(" pnpm install")),console.log(H.dim(" pnpm build")),console.log(H.dim(" pnpm link --global # for local testing")),console.log(H.dim(" # then in your agentx project:")),console.log(H.dim(` pnpm link --global ${e}`)),console.log(H.dim(` agentx config set plugins[0] "${e}"`)),console.log(H.dim(" agentx plugin doctor")),console.log()});Ht.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let t=R().plugins??[];if(console.log(),t.length===0){console.log(H.dim(" No plugins configured. Nothing to check.")),console.log();return}let o=0;for(let n of t){let s=await la(n);s.kind==="ok"?console.log(` ${H.green("\u2713")} ${H.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(o++,console.log(` ${H.red("\u2717")} ${H.cyan(n)} \u2014 ${s.reason}`))}console.log(),o>0&&(console.log(H.red(` ${o}/${t.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(H.red(` ${e.message}`)),process.exitCode=1}});async function la(e){let t;try{t=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let o=da(t);if(!ga(o))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=yn.safeParse(o.manifest);return n.success?{kind:"ok",manifestName:n.data.name,manifestVersion:n.data.version}:{kind:"fail",reason:`manifest invalid: ${n.error.issues.map(i=>i.message).join("; ")}`}}function da(e){if(e==null||typeof e!="object")return e;let t=e;if(t.default&&typeof t.default=="object"){let o=t.default;if(o.manifest&&typeof o.setup=="function")return o;if(o.default&&typeof o.default=="object"){let n=o.default;if(n.manifest&&typeof n.setup=="function")return n}}return t.manifest&&typeof t.setup=="function"?t:t.default??t}function ga(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function ma(e,t){return JSON.stringify({name:e,version:"0.1.0",description:t,main:"dist/index.js",types:"dist/index.d.ts",files:["dist"],scripts:{build:"tsc",prepublishOnly:"pnpm build"},keywords:["agentx","agentx-plugin"],license:"MIT",devDependencies:{typescript:"^5.4.0","@types/node":"^20.0.0"}},null,2)+`
|
|
373
|
+
`}function pa(){return JSON.stringify({compilerOptions:{target:"es2020",module:"commonjs",lib:["es2020"],declaration:!0,outDir:"dist",strict:!0,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:"node"},include:["src/**/*.ts"]},null,2)+`
|
|
374
|
+
`}function ua(e){return`// ${e} \u2014 AgentX plugin
|
|
375
|
+
//
|
|
376
|
+
// A plugin's default export is { manifest, setup }. The daemon calls
|
|
377
|
+
// setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
|
|
378
|
+
// registers a custom channel adapter; ctx.log() namespaces output.
|
|
379
|
+
|
|
380
|
+
const plugin = {
|
|
381
|
+
manifest: {
|
|
382
|
+
name: ${JSON.stringify(e)},
|
|
383
|
+
version: "0.1.0",
|
|
384
|
+
// agentxRange: "0.x", // optional \u2014 gate against the daemon's major.minor
|
|
385
|
+
},
|
|
386
|
+
|
|
387
|
+
setup(ctx: any) {
|
|
388
|
+
ctx.log("hello from", ${JSON.stringify(e)})
|
|
389
|
+
|
|
390
|
+
// Example: log every completed task.
|
|
391
|
+
ctx.on("task:completed", (payload: any) => {
|
|
392
|
+
ctx.log("task done:", payload.agentId, payload.durationMs + "ms")
|
|
393
|
+
})
|
|
394
|
+
|
|
395
|
+
// Example: register a no-op channel adapter.
|
|
396
|
+
// ctx.addChannel({
|
|
397
|
+
// name: "my-channel",
|
|
398
|
+
// start: async () => {},
|
|
399
|
+
// stop: async () => {},
|
|
400
|
+
// send: async (out) => { ctx.log("send:", out) },
|
|
401
|
+
// })
|
|
402
|
+
},
|
|
403
|
+
|
|
404
|
+
// Optional \u2014 only needed for resources you own (timers, sockets).
|
|
405
|
+
// Bus subscriptions are removed automatically.
|
|
406
|
+
// teardown() {},
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
export default plugin
|
|
410
|
+
`}function fa(e,t){return`# ${e}
|
|
411
|
+
|
|
412
|
+
${t}
|
|
413
|
+
|
|
414
|
+
## Install
|
|
415
|
+
|
|
416
|
+
\`\`\`bash
|
|
417
|
+
pnpm install ${e}
|
|
418
|
+
\`\`\`
|
|
419
|
+
|
|
420
|
+
## Use
|
|
421
|
+
|
|
422
|
+
Add to \`agentx.json\`:
|
|
423
|
+
|
|
424
|
+
\`\`\`json
|
|
425
|
+
{
|
|
426
|
+
"plugins": ["${e}"]
|
|
427
|
+
}
|
|
428
|
+
\`\`\`
|
|
429
|
+
|
|
430
|
+
Then verify the load:
|
|
431
|
+
|
|
432
|
+
\`\`\`bash
|
|
433
|
+
agentx plugin doctor
|
|
434
|
+
\`\`\`
|
|
435
|
+
|
|
436
|
+
Restart the daemon to activate.
|
|
437
|
+
`}function ha(){return`node_modules/
|
|
438
|
+
dist/
|
|
439
|
+
*.log
|
|
440
|
+
.env
|
|
441
|
+
`}import{Command as ya}from"commander";import re from"chalk";import{writeFileSync as wa,mkdirSync as $a,existsSync as yo,readFileSync as Ns,appendFileSync as Ps}from"fs";import{resolve as Rt,dirname as Ws}from"path";import{homedir as nn}from"os";var Fs=new ya().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:t}=await import("./program-GZOJIWTB.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=va(o);break;case"bash":s=Ea(o);break;case"fish":s=Ia(o);break;default:console.error(re.red(`unsupported shell: ${n}`)),console.error(re.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Rt(String(e.output)):ba(n);$a(Ws(i),{recursive:!0}),wa(i,s),console.log(re.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),ka(n,i,!!e.yes)});function ba(e){let t=nn();switch(e){case"zsh":return Rt(t,".zsh","completions","_agentx");case"bash":return Rt(t,".bash_completion.d","agentx.bash");case"fish":return Rt(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function ka(e,t,o){if(e==="zsh"){let n=Rt(nn(),".zshrc"),s=Ws(t),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=yo(n)?Ns(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(re.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&yo(n)){let p=["","# agentx completion"];c&&p.push(i),l&&p.push(r),Ps(n,p.join(`
|
|
442
|
+
`)+`
|
|
443
|
+
`),console.log(re.green("\u2713 Patched ~/.zshrc")),console.log(re.dim("Reload your shell: exec zsh"));return}console.log(re.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(re.cyan(` ${i}`)),l&&console.log(re.cyan(` ${r}`)),console.log(),console.log(re.dim("Then reload: exec zsh")),console.log(re.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Rt(nn(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((yo(n)?Ns(n,"utf-8"):"").includes(t)){console.log(re.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&yo(n)){Ps(n,`
|
|
444
|
+
# agentx completion
|
|
445
|
+
${s}
|
|
446
|
+
`),console.log(re.green("\u2713 Patched ~/.bashrc")),console.log(re.dim("Reload your shell: exec bash"));return}console.log(re.dim("Add this to ~/.bashrc:")),console.log(re.cyan(` ${s}`)),console.log(),console.log(re.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(re.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function ye(e){return e._name||e.name()||""}function Ke(e){return e.commands.filter(t=>{let o=ye(t);return!(!o||o==="help"||t._hidden)})}function Yt(e){return e.options.filter(t=>!t.hidden)}function va(e){let t=[];return t.push("#compdef agentx"),t.push(""),Us(e,[],t),t.push("compdef _agentx_root_completion agentx"),t.push(""),t.join(`
|
|
447
|
+
`)}function Ms(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function Us(e,t,o){let n=Ke(e),i=Yt(e).map(ja).filter(c=>!!c),r=Ms(t);if(o.push(`${r}() {`),o.push(" local -a commands"),o.push(" local -a options"),o.push(" "),i.length===0&&n.length===0){o.push(" return 0"),o.push("}"),o.push("");return}let a=[];for(let c of i)a.push(c);if(n.length>0){let c=n.map(Ca).join(" ");a.push(` "1: :_values 'command' ${c}"`),a.push(' "*::arg:->args"')}o.push(" _arguments -C \\");for(let c=0;c<a.length;c++){let l=c===a.length-1;o.push(`${a[c]}${l?"":" \\"}`)}if(n.length>0){o.push(""),o.push(" case $state in"),o.push(" (args)"),o.push(" case $line[1] in");for(let c of n){let l=Ms([...t,ye(c)]);o.push(` (${ye(c)}) ${l} ;;`)}o.push(" esac"),o.push(" ;;"),o.push(" esac")}o.push("}"),o.push("");for(let c of n)Us(c,[...t,ye(c)],o)}function xa(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Sa(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function ja(e){let t=e.short||void 0,o=e.long||void 0;if(!t&&!o)return null;let n=xa(e.description||"");return t&&o?` "(${o} ${t})"{${o},${t}}"[${n}]"`:` "${o||t}[${n}]"`}function Ca(e){let t=Sa(e.description()||"");return`'${ye(e)}[${t}]'`}function Ea(e){let t=Ke(e),o=[];o.push("# bash completion for agentx"),o.push("_agentx_complete() {"),o.push(" local cur prev words cword"),o.push(" COMPREPLY=()"),o.push(' cur="${COMP_WORDS[COMP_CWORD]}"'),o.push(' prev="${COMP_WORDS[COMP_CWORD-1]}"'),o.push(""),o.push(` local top="${t.map(ye).join(" ")}"`),o.push(""),o.push(" if [[ $COMP_CWORD -eq 1 ]]; then"),o.push(' COMPREPLY=( $(compgen -W "$top" -- "$cur") )'),o.push(" return 0"),o.push(" fi"),o.push(""),o.push(' local cmd="${COMP_WORDS[1]}"'),o.push(' local sub2="${COMP_WORDS[2]:-}"'),o.push(' case "$cmd" in');for(let n of t){let s=Ke(n).map(ye),i=Ls(n);if(o.push(` ${ye(n)})`),s.length>0){o.push(" if [[ $COMP_CWORD -eq 2 ]]; then"),o.push(` COMPREPLY=( $(compgen -W "${s.join(" ")} ${i}" -- "$cur") )`),o.push(" return 0"),o.push(" fi"),o.push(' case "$sub2" in');for(let r of Ke(n)){let a=Ls(r);o.push(` ${ye(r)})`),o.push(` COMPREPLY=( $(compgen -W "${a}" -- "$cur") )`),o.push(" return 0"),o.push(" ;;")}o.push(" esac")}else o.push(` COMPREPLY=( $(compgen -W "${i}" -- "$cur") )`);o.push(" ;;")}return o.push(" esac"),o.push("}"),o.push(""),o.push("complete -F _agentx_complete agentx"),o.push(""),o.join(`
|
|
448
|
+
`)}function Ls(e){let t=[];for(let o of Yt(e))o.long&&t.push(o.long),o.short&&t.push(o.short);return t.join(" ")}function Ia(e){let t=[];t.push("# fish completion for agentx"),t.push(""),t.push("complete -c agentx -f"),t.push(""),t.push("# top-level commands");for(let o of Ke(e)){let n=sn(o.description()||"");t.push(`complete -c agentx -n "__fish_use_subcommand" -a "${ye(o)}" -d "${n}"`)}t.push("");for(let o of Yt(e)){let n=on(o,["__fish_use_subcommand"]);n&&t.push(n)}t.push("");for(let o of Ke(e)){let n=ye(o);t.push(`# ${n}`);for(let s of Yt(o)){let i=on(s,[`__fish_seen_subcommand_from ${n}`]);i&&t.push(i)}for(let s of Ke(o)){let i=sn(s.description()||"");t.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Ke(o).map(ye).join(" ")}" -a "${ye(s)}" -d "${i}"`);for(let r of Yt(s)){let a=on(r,[`__fish_seen_subcommand_from ${ye(s)}`]);a&&t.push(a)}}t.push("")}return t.join(`
|
|
449
|
+
`)}function sn(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function on(e,t){let o=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!o&&!n)return null;let s=sn(e.description||""),r=["complete -c agentx",t.map(a=>`-n "${a}"`).join(" ")];return o&&r.push(`-s ${o}`),n&&r.push(`-l ${n}`),r.push(`-d "${s}"`),r.join(" ")}async function Am(){let e=await An(),t=new Aa().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");return t.addCommand(Ie).addCommand(Wn).addCommand(Pn).addCommand(yt).addCommand(Xt).addCommand(it).addCommand(wt).addCommand(ze).addCommand($t).addCommand(bt).addCommand(Mt).addCommand(Ne).addCommand(Je).addCommand(eo).addCommand(to).addCommand(ot).addCommand(Ao).addCommand(Oo).addCommand(Ue).addCommand(ro).addCommand(Ge).addCommand(Z).addCommand(Bt).addCommand(qt).addCommand(Re).addCommand(Jt).addCommand(jt).addCommand(Ct).addCommand(Et).addCommand(fo).addCommand(lt).addCommand(It).addCommand(dt).addCommand(As).addCommand(gt).addCommand(Pt).addCommand(Rn).addCommand(Os).addCommand(Zo).addCommand(Ye).addCommand(Ht).addCommand(Fs),t}export{Am as a};
|
|
450
|
+
//# sourceMappingURL=chunk-OPKQNLGX.js.map
|