agentix-cli 0.20.0 → 0.21.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.
Files changed (65) hide show
  1. package/dist/{agent-57MG4LBM.js → agent-I3ILI3MO.js} +2 -2
  2. package/dist/{board-dashboard-HXDOYGIG.js → board-dashboard-ASI6MDKX.js} +339 -97
  3. package/dist/board-dashboard-ASI6MDKX.js.map +1 -0
  4. package/dist/{chunk-WFHIIVLL.js → chunk-2B2DIQKD.js} +75 -51
  5. package/dist/chunk-2B2DIQKD.js.map +1 -0
  6. package/dist/{chunk-MBOLXKA2.js → chunk-5GDCJ2SF.js} +13 -6
  7. package/dist/chunk-5GDCJ2SF.js.map +1 -0
  8. package/dist/{chunk-23AUU4S2.js → chunk-5XZ73VM4.js} +38 -38
  9. package/dist/chunk-5XZ73VM4.js.map +1 -0
  10. package/dist/{chunk-DLVOHCTA.js → chunk-AANSVC5A.js} +2 -2
  11. package/dist/{chunk-TC3BSUP7.js → chunk-AGINLNAW.js} +2 -2
  12. package/dist/{chunk-6B74TO2J.js → chunk-BLRLUF2H.js} +2 -2
  13. package/dist/chunk-EQNM3TOF.js +15 -0
  14. package/dist/chunk-EQNM3TOF.js.map +1 -0
  15. package/dist/{chunk-WPPUOTY6.js → chunk-FUYZUGNQ.js} +2 -2
  16. package/dist/chunk-GSX4NK2N.js +2 -0
  17. package/dist/chunk-GSX4NK2N.js.map +1 -0
  18. package/dist/chunk-GV7S5BAX.js +2 -0
  19. package/dist/chunk-GV7S5BAX.js.map +1 -0
  20. package/dist/{chunk-7GVXCOLO.js → chunk-IFQQVDM6.js} +85 -83
  21. package/dist/chunk-IFQQVDM6.js.map +1 -0
  22. package/dist/{chunk-QW2OYR3N.js → chunk-K6MC66D6.js} +2 -2
  23. package/dist/chunk-SZDACK6O.js +2 -0
  24. package/dist/chunk-SZDACK6O.js.map +1 -0
  25. package/dist/cli.js +1 -1
  26. package/dist/cli.js.map +1 -1
  27. package/dist/{config-QXWKEQON.js → config-RWHSEE4N.js} +2 -2
  28. package/dist/config-mutator-JKCNCY2F.js +2 -0
  29. package/dist/doctor-KWN7NUFQ.js +2 -0
  30. package/dist/index.js +1 -1
  31. package/dist/program-JEKM7SCS.js +2 -0
  32. package/dist/{registry-HM4ELSXS.js → registry-EGKDMVSP.js} +2 -2
  33. package/dist/runner-BFYDWPUO.js +2 -0
  34. package/dist/scheduler-ED4FCI2Y.js +2 -0
  35. package/dist/scheduler-ED4FCI2Y.js.map +1 -0
  36. package/dist/store-I3HEWVLQ.js +2 -0
  37. package/dist/store-I3HEWVLQ.js.map +1 -0
  38. package/dist/types-Y6ZCZ52Z.js +2 -0
  39. package/dist/types-Y6ZCZ52Z.js.map +1 -0
  40. package/dist/web/workflow-editor.global.js +12 -10
  41. package/dist/web/workflow-editor.global.js.map +1 -1
  42. package/package.json +1 -1
  43. package/dist/board-dashboard-HXDOYGIG.js.map +0 -1
  44. package/dist/chunk-23AUU4S2.js.map +0 -1
  45. package/dist/chunk-7GVXCOLO.js.map +0 -1
  46. package/dist/chunk-E4ZZILAK.js +0 -15
  47. package/dist/chunk-E4ZZILAK.js.map +0 -1
  48. package/dist/chunk-MBOLXKA2.js.map +0 -1
  49. package/dist/chunk-WFHIIVLL.js.map +0 -1
  50. package/dist/config-mutator-53XGR2NT.js +0 -2
  51. package/dist/doctor-SEOUFHSL.js +0 -2
  52. package/dist/program-WWCXMRU2.js +0 -2
  53. package/dist/scheduler-XVFIK4XH.js +0 -2
  54. /package/dist/{agent-57MG4LBM.js.map → agent-I3ILI3MO.js.map} +0 -0
  55. /package/dist/{chunk-DLVOHCTA.js.map → chunk-AANSVC5A.js.map} +0 -0
  56. /package/dist/{chunk-TC3BSUP7.js.map → chunk-AGINLNAW.js.map} +0 -0
  57. /package/dist/{chunk-6B74TO2J.js.map → chunk-BLRLUF2H.js.map} +0 -0
  58. /package/dist/{chunk-WPPUOTY6.js.map → chunk-FUYZUGNQ.js.map} +0 -0
  59. /package/dist/{chunk-QW2OYR3N.js.map → chunk-K6MC66D6.js.map} +0 -0
  60. /package/dist/{config-QXWKEQON.js.map → config-RWHSEE4N.js.map} +0 -0
  61. /package/dist/{config-mutator-53XGR2NT.js.map → config-mutator-JKCNCY2F.js.map} +0 -0
  62. /package/dist/{doctor-SEOUFHSL.js.map → doctor-KWN7NUFQ.js.map} +0 -0
  63. /package/dist/{program-WWCXMRU2.js.map → program-JEKM7SCS.js.map} +0 -0
  64. /package/dist/{registry-HM4ELSXS.js.map → registry-EGKDMVSP.js.map} +0 -0
  65. /package/dist/{scheduler-XVFIK4XH.js.map → runner-BFYDWPUO.js.map} +0 -0
@@ -1,21 +1,21 @@
1
- import{b as pn}from"./chunk-WPPUOTY6.js";import{a as ct,b as mn,e as Jt,i as un}from"./chunk-WFHIIVLL.js";import{a as Vo,g as en,h as tn,i as uo,j as dn,k as gn}from"./chunk-6B74TO2J.js";import{a as on,b as nn,c as sn,d as rn,e as an,f as qt,g as Et,l as cn,m as mo,n as ln,o as po}from"./chunk-E4ZZILAK.js";import{b as xe}from"./chunk-EW27SCCC.js";import{c as Xo}from"./chunk-QW2OYR3N.js";import{a as re,b as Q,c as Ye,d as Zo}from"./chunk-DLVOHCTA.js";import{d as Qo,e as P,f as Ut}from"./chunk-MBOLXKA2.js";import{e as at}from"./chunk-23AUU4S2.js";import{b as Ko}from"./chunk-4MREHZP5.js";import{b as Ge,d as Ho,f as go}from"./chunk-7P5QRX5W.js";import{a as Ie}from"./chunk-VJUTQAPJ.js";import{a as ws}from"./chunk-4YCH6IZV.js";import{Command as Gr}from"commander";import{Command as $s}from"commander";import S from"chalk";import{existsSync as bs,readFileSync as ks}from"fs";var Se=new $s().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Se.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"),p=["dist/cli.js","daemon","start"];e.config&&p.push("-c",e.config),e.port&&p.push("--port",e.port);let d=l("node",p,{detached:!0,stdio:["ignore","ignore","ignore"],cwd:process.cwd()});d.unref();let{writeFileSync:m}=await import("fs");m("/tmp/agentx-daemon.pid",String(d.pid)),console.log(S.green(`Daemon started in background (PID: ${d.pid})`)),console.log(S.dim(" Logs: tail -f /tmp/agentx-daemon.log")),console.log(S.dim(" Stop: agentx daemon stop"));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{vs(i(process.cwd(),".env"))}catch{}await new uo(e.config).start()});function vs(e){if(!bs(e))return;let t=ks(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}}Se.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(S.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(S.green("Daemon stopped"))}catch{console.log(S.yellow("No daemon process found"))}});Se.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=P(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(S.bold(` ${r.node.name}`)+S.dim(` (${r.node.id})`)),console.log(S.green(" Status: running")+S.dim(` \u2014 uptime ${xs(r.uptime)}`)),console.log(),console.log(S.bold(" Agents:"));for(let c of r.agents){let l=c.active>0?S.yellow(` [${c.active} active]`):"",p=c.errors>0?S.red(` (${c.errors} errors)`):"";console.log(` ${S.cyan(c.name)} ${S.dim(`(${c.tier})`)}${l}${p}`),console.log(S.dim(` ${c.workspace}`))}let a=r.crons.filter(c=>c.enabled);if(r.crons.length){console.log(),console.log(S.bold(` Crons: ${a.length} enabled / ${r.crons.length} total`));for(let c of r.crons){let l=c.enabled?S.green("\u25CF"):S.dim("\u25CB"),p=c.nextRun?S.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${p}`)}}if(r.mesh?.length){console.log(),console.log(S.bold(" Mesh:"));for(let c of r.mesh){let l=c.healthy?S.green("\u25CF"):S.red("\u25CF"),p=c.skills?.length?S.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${S.dim(c.peerUrl)}${p}`)}}console.log()}catch(t){if(t.cause?.code==="ECONNREFUSED"||t.name==="TimeoutError")console.log(S.red(" Daemon is not running")),console.log(S.dim(" Start with: agentx daemon start"));else try{let o=P(e.config),n=Ut(o);if(console.log(),console.log(S.bold(` ${o.node.name}`)+S.dim(` (${o.node.id})`)),console.log(S.yellow(" Status: stopped")),console.log(S.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(S.yellow(` \u26A0 ${s}`))}console.log()}catch(o){console.log(S.red(` ${o.message}`))}}});Se.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(S.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"})});Se.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(P(e.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(S.dim(` Connecting to ${n}...`)),console.log(S.dim(` Press Ctrl+C to stop
3
- `));try{let s=await fetch(n);if(!s.ok||!s.body){console.log(S.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)),h=new Date(m.time).toLocaleTimeString(),f=m.message?.replace(/^\[agentx\]\s*/,"")||"";f.includes("executing")?console.log(`${S.dim(h)} ${S.cyan("\u25B6")} ${f}`):f.includes("completed")?console.log(`${S.dim(h)} ${S.green("\u2713")} ${f}`):f.includes("error")||f.includes("Error")?console.log(`${S.dim(h)} ${S.red("\u2717")} ${f}`):f.includes("Routing")?console.log(`${S.dim(h)} ${S.yellow("\u2192")} ${f}`):f.includes("mention")?console.log(`${S.dim(h)} ${S.magenta("@")} ${f}`):f.includes("Skipping")?console.log(`${S.dim(h)} ${S.dim("\u2298")} ${S.dim(f)}`):console.log(`${S.dim(h)} ${f}`)}catch{}else d.startsWith("event: status")}}catch(s){console.log(S.red(` Connection failed: ${s.message}`)),console.log(S.dim(" Is the daemon running? Try: agentx daemon status"))}});Se.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=P(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(S.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(S.red(` Error: ${d.error}`)):(console.log(),console.log(d.content||d.response||"No response"),d.duration&&console.log(S.dim(`
5
- (${(d.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(S.red(` Failed: ${s.message}`)),console.log(S.dim(" Is the daemon running? Try: agentx daemon status"))}});Se.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(S.dim(" Running tests...")),o("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(S.green(" \u2713 Tests passed"))}catch{console.log(S.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(S.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(S.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(c).mtimeMs>3e5&&(console.log(S.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),o("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(S.green(" \u2713 Build complete")))}console.log(S.dim(` Deploying to ${t.user}@${e}:${t.path}...`));try{if(o(`rsync -avzL --delete ${n} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(S.green(" \u2713 Deploy complete")),t.restart){console.log(S.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(S.green(" Remote daemon restarted"))}}catch(i){console.log(S.red(` Deploy failed: ${i.message}`))}});Se.action(async e=>{await new uo(e.config).start()});function xs(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 Ss}from"commander";import ke from"chalk";import{existsSync as At,readFileSync as js,writeFileSync as hn,mkdirSync as fn}from"fs";import{hostname as yn}from"os";import{resolve as lt}from"path";var wn=new Ss().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let t=process.cwd(),o=lt(t,"agentx.json"),n=lt(t,".env"),s=lt(t,".agentx/sessions");if(console.log(),console.log(ke.bold(" agentx init")),console.log(),At(o)&&!e.force){console.log(ke.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[lt(t,"agentx.example.json"),lt(t,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(At(c)){r=js(c,"utf-8");break}r||(r=JSON.stringify({node:{id:yn().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:yn(),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)),hn(o,r),console.log(ke.green(" \u2713 Created agentx.json")),At(n)||(hn(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
6
- `)),console.log(ke.green(" \u2713 Created .env template"))),At(s)||(fn(s,{recursive:!0}),console.log(ke.green(" \u2713 Created .agentx/sessions/")));let a=lt(t,".claude");At(a)||(fn(a,{recursive:!0}),console.log(ke.green(" \u2713 Created .claude/"))),console.log(),console.log(ke.bold(" Next steps:")),console.log(` 1. Edit ${ke.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${ke.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${ke.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${ke.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Cs}from"commander";import He from"chalk";import{spawn as bn}from"child_process";import{existsSync as Es}from"fs";import{resolve as As}from"path";var kn=new Cs().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=mn(),o=e.port?parseInt(e.port,10):Is(),n=`http://127.0.0.1:${o}/setup`;if(console.log(),t.configExists?console.log(He.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(He.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(He.bold(` Opening ${n}`)),console.log(),await Rs(n).catch(()=>!1))console.log(He.dim(" Dashboard is already running.")),e.open!==!1&&$n(n);else{console.log(He.dim(` Starting dashboard server on port ${o} (Ctrl-C to quit)\u2026`));let i=Os(),r=bn(process.execPath,[i,"board","serve","--port",String(o)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&$n(n),await new Promise(a=>r.on("exit",()=>a()))}});function Is(){try{return P().dashboard.port||4202}catch{return 4202}}function Os(){let e=As(import.meta.dirname,"cli.js");return Es(e)?e:process.argv[1]||e}async function Rs(e){try{let t=await fetch(e,{method:"GET"});return t.ok||t.status===302}catch{return!1}}function $n(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let o=bn(t,[e],{stdio:"ignore",detached:!0});o.once("error",()=>{console.log(He.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),o.unref()}catch{console.log(He.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as Ds}from"commander";import ee from"chalk";var It=new Ds().name("token").description("scoped API tokens for external access (mesh peers, integrations)");It.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 Jt,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(ee.bold(" Token created.")),console.log(),console.log(` id: ${ee.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||ee.dim("never")}`),console.log(),console.log(ee.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${ee.green.bold(s)}`),console.log(),console.log(ee.dim(" Use it via the Authorization header:")),console.log(ee.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(t){console.log(ee.red(` ${t.message}`)),process.exit(1)}});It.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new Jt().list();if(e.length===0){console.log(ee.dim(`
1
+ import{a as gt,b as yn,f as Yt,j as $n}from"./chunk-2B2DIQKD.js";import{b as wn}from"./chunk-FUYZUGNQ.js";import{c as mn}from"./chunk-SZDACK6O.js";import{a as dt}from"./chunk-GV7S5BAX.js";import{e as gn}from"./chunk-GSX4NK2N.js";import{a as Zo,g as nn,h as sn,i as yo,j as hn,k as fn}from"./chunk-BLRLUF2H.js";import{a as rn,b as an,c as cn,d as ln,e as dn,f as Gt,g as It,l as pn,m as ho,n as un,o as fo}from"./chunk-EQNM3TOF.js";import{b as Se}from"./chunk-EW27SCCC.js";import{c as tn}from"./chunk-K6MC66D6.js";import{a as ae,b as X,c as He,d as on}from"./chunk-AANSVC5A.js";import{d as en,e as P,f as zt}from"./chunk-5GDCJ2SF.js";import{e as lt}from"./chunk-5XZ73VM4.js";import{b as Xo}from"./chunk-4MREHZP5.js";import{b as Ye,d as Qo,f as uo}from"./chunk-7P5QRX5W.js";import{a as Ie}from"./chunk-VJUTQAPJ.js";import{a as xs}from"./chunk-4YCH6IZV.js";import{Command as Zr}from"commander";import{Command as Ss}from"commander";import x from"chalk";import{existsSync as js,readFileSync as Cs}from"fs";var je=new Ss().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");je.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:h,writeFileSync:d,existsSync:m}=await import("fs"),p=process.argv[1];(!p||!m(p))&&(console.error(x.red(` Cannot resolve agentx CLI entrypoint (process.argv[1]=${p||"?"}).`)),console.error(x.dim(" Try running without --detach to see the underlying error.")),process.exit(1));let f=[p,"daemon","start"];e.config&&f.push("-c",e.config),e.port&&f.push("--port",e.port);let y="/tmp/agentx-daemon.log",w;try{w=h(y,"a")}catch($){console.error(x.red(` Failed to open ${y} for writing: ${$.message}`)),process.exit(1)}let b=l(process.execPath,f,{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{Es(i(process.cwd(),".env"))}catch{}await new yo(e.config).start()});function Es(e){if(!js(e))return;let t=Cs(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}}je.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"))}});je.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=P(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 ${As(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]`):"",h=c.errors>0?x.red(` (${c.errors} errors)`):"";console.log(` ${x.cyan(c.name)} ${x.dim(`(${c.tier})`)}${l}${h}`),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"),h=c.nextRun?x.dim(` next: ${new Date(c.nextRun).toLocaleTimeString()}`):"";console.log(` ${l} ${c.id}${h}`)}}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"),h=c.skills?.length?x.dim(` (${c.skills.length} agents)`):"";console.log(` ${l} ${c.peer} ${x.dim(c.peerUrl)}${h}`)}}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=P(e.config),n=zt(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}`))}}});je.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"})});je.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async e=>{let n=`http://${(P(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 h=a.split(`
4
+ `);a=h.pop()||"";for(let d of h)if(d.startsWith("data: "))try{let m=JSON.parse(d.slice(6)),p=new Date(m.time).toLocaleTimeString(),f=m.message?.replace(/^\[agentx\]\s*/,"")||"";f.includes("executing")?console.log(`${x.dim(p)} ${x.cyan("\u25B6")} ${f}`):f.includes("completed")?console.log(`${x.dim(p)} ${x.green("\u2713")} ${f}`):f.includes("error")||f.includes("Error")?console.log(`${x.dim(p)} ${x.red("\u2717")} ${f}`):f.includes("Routing")?console.log(`${x.dim(p)} ${x.yellow("\u2192")} ${f}`):f.includes("mention")?console.log(`${x.dim(p)} ${x.magenta("@")} ${f}`):f.includes("Skipping")?console.log(`${x.dim(p)} ${x.dim("\u2298")} ${x.dim(f)}`):console.log(`${x.dim(p)} ${f}`)}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."))}});je.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=P(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"))}});je.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}`))}});je.action(async e=>{await new yo(e.config).start()});function As(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 Os}from"commander";import ve from"chalk";import{existsSync as Rt,readFileSync as Is,writeFileSync as bn,mkdirSync as kn}from"fs";import{hostname as vn}from"os";import{resolve as mt}from"path";var xn=new Os().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async e=>{let t=process.cwd(),o=mt(t,"agentx.json"),n=mt(t,".env"),s=mt(t,".agentx/sessions");if(console.log(),console.log(ve.bold(" agentx init")),console.log(),Rt(o)&&!e.force){console.log(ve.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let i=[mt(t,"agentx.example.json"),mt(t,"node_modules/agentix-cli/agentx.example.json")],r;for(let c of i)if(Rt(c)){r=Is(c,"utf-8");break}r||(r=JSON.stringify({node:{id:vn().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:vn(),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)),bn(o,r),console.log(ve.green(" \u2713 Created agentx.json")),Rt(n)||(bn(n,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
6
+ `)),console.log(ve.green(" \u2713 Created .env template"))),Rt(s)||(kn(s,{recursive:!0}),console.log(ve.green(" \u2713 Created .agentx/sessions/")));let a=mt(t,".claude");Rt(a)||(kn(a,{recursive:!0}),console.log(ve.green(" \u2713 Created .claude/"))),console.log(),console.log(ve.bold(" Next steps:")),console.log(` 1. Edit ${ve.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${ve.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${ve.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${ve.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Rs}from"commander";import Ke from"chalk";import{spawn as jn}from"child_process";import{existsSync as Ds}from"fs";import{resolve as Ts}from"path";var Cn=new Rs().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=yn(),o=e.port?parseInt(e.port,10):_s(),n=`http://127.0.0.1:${o}/setup`;if(console.log(),t.configExists?console.log(Ke.dim(" Found agentx.json \u2014 the wizard will extend your current install.")):console.log(Ke.dim(" No agentx.json yet \u2014 the wizard will create one.")),console.log(Ke.bold(` Opening ${n}`)),console.log(),await Ns(n).catch(()=>!1))console.log(Ke.dim(" Dashboard is already running.")),e.open!==!1&&Sn(n);else{console.log(Ke.dim(` Starting dashboard server on port ${o} (Ctrl-C to quit)\u2026`));let i=Ps(),r=jn(process.execPath,[i,"board","serve","--port",String(o)],{stdio:"inherit",detached:!1});await new Promise(a=>setTimeout(a,1200)),e.open!==!1&&Sn(n),await new Promise(a=>r.on("exit",()=>a()))}});function _s(){try{return P().dashboard.port||4202}catch{return 4202}}function Ps(){let e=Ts(import.meta.dirname,"cli.js");return Ds(e)?e:process.argv[1]||e}async function Ns(e){try{let t=await fetch(e,{method:"GET"});return t.ok||t.status===302}catch{return!1}}function Sn(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let o=jn(t,[e],{stdio:"ignore",detached:!0});o.once("error",()=>{console.log(Ke.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}),o.unref()}catch{console.log(Ke.dim(` Couldn't auto-open the browser. Visit ${e} manually.`))}}import{Command as Ms}from"commander";import te from"chalk";var Dt=new Ms().name("token").description("scoped API tokens for external access (mesh peers, integrations)");Dt.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 Yt,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(te.bold(" Token created.")),console.log(),console.log(` id: ${te.cyan(i.id)}`),console.log(` name: ${i.name}`),console.log(` scopes: ${i.scopes.join(", ")}`),console.log(` expires: ${i.expiresAt||te.dim("never")}`),console.log(),console.log(te.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${te.green.bold(s)}`),console.log(),console.log(te.dim(" Use it via the Authorization header:")),console.log(te.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(t){console.log(te.red(` ${t.message}`)),process.exit(1)}});Dt.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let e=new Yt().list();if(e.length===0){console.log(te.dim(`
7
7
  No tokens issued.
8
- `));return}console.log();for(let t of e){let o=t.revokedAt?ee.red("revoked"):t.expiresAt&&Date.parse(t.expiresAt)<Date.now()?ee.red("expired"):ee.green("active");console.log(` ${ee.cyan(t.id)} ${o} ${t.name}`),console.log(ee.dim(` prefix: ${t.prefix}\u2026 scopes: ${t.scopes.join(", ")}`)),console.log(ee.dim(` created: ${t.createdAt}${t.expiresAt?` expires: ${t.expiresAt}`:""}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(ee.red(` ${e.message}`)),process.exit(1)}});It.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let t=new Jt().revoke(e);t||(console.log(ee.red(` Token ${e} not found.`)),process.exit(1)),console.log(ee.green(`
8
+ `));return}console.log();for(let t of e){let o=t.revokedAt?te.red("revoked"):t.expiresAt&&Date.parse(t.expiresAt)<Date.now()?te.red("expired"):te.green("active");console.log(` ${te.cyan(t.id)} ${o} ${t.name}`),console.log(te.dim(` prefix: ${t.prefix}\u2026 scopes: ${t.scopes.join(", ")}`)),console.log(te.dim(` created: ${t.createdAt}${t.expiresAt?` expires: ${t.expiresAt}`:""}${t.lastUsedAt?` last used: ${t.lastUsedAt}`:""}`))}console.log()}catch(e){console.log(te.red(` ${e.message}`)),process.exit(1)}});Dt.command("revoke <id>").description("immediately invalidate a token").action(e=>{try{let t=new Yt().revoke(e);t||(console.log(te.red(` Token ${e} not found.`)),process.exit(1)),console.log(te.green(`
9
9
  \u2713 Revoked ${e} (${t.name})
10
- `))}catch(t){console.log(ee.red(` ${t.message}`)),process.exit(1)}});import{Command as Oe}from"commander";import u from"chalk";import $e from"prompts";import{readFileSync as Ne,writeFileSync as dt,existsSync as G,mkdirSync as je,cpSync as ho,readdirSync as yo}from"fs";import{resolve as R,join as Pe}from"path";function X(){let e=R(process.cwd(),"agentx.json");if(!G(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ne(e,"utf-8"))}function me(e){return re(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(u.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(u.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(u.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var gt=new Oe().name("agent").description("manage agents \u2014 add, list, remove");gt.command("list").alias("ls").description("list configured agents").action(()=>{let e=X();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${u.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(u.dim(` workspace: ${o.workspace}`)),n&&console.log(u.dim(` mentions: ${n}`))}console.log()});gt.command("add").description("add a new agent interactively").action(async()=>{let e=X(),t=await $e([{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:R(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:Pe(t.workspace,t.id);je(R(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-FPGN5VNY.js"),i=s(t.id,n,"19900",(...l)=>{console.log(u.dim(` ${l.join(" ")}`))}),r=R(process.cwd(),"src/wiki/SKILL.md"),a=R(import.meta.dirname,"../wiki/SKILL.md"),c=G(r)?r:a;G(c)&&(je(R(o,".claude/skills/wiki"),{recursive:!0}),ho(c,R(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await me(e),console.log(u.green(`
11
- Agent "${t.id}" added`)),console.log(u.dim(` Workspace: ${o}`)),console.log(u.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});gt.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=X();if(!t.agents?.[e]){console.log(u.red(` Agent "${e}" not found`));return}delete t.agents[e],await me(t),console.log(u.green(` Agent "${e}" removed from config (workspace preserved)`))});gt.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=X(),n=o.agents?.[e];if(n||(console.log(u.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log(u.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):u.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":u.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||u.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(u.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(u.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(u.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(u.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(u.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await me(o),console.log(u.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(u.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var zt=new Oe().name("channel").description("manage channels \u2014 add telegram/whatsapp/discord, list");zt.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=X();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(u.bold(" Telegram:"));for(let[i,r]of Object.entries(t.accounts||{}))console.log(` ${u.cyan(i)} -> agent: ${r.agentBinding}`)}else console.log(u.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(u.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(u.dim(" WhatsApp: disabled"));let n=e.channels?.discord;n?.enabled?(console.log(u.bold(" Discord:")),console.log(` agent: ${n.agentBinding||"(none)"}`)):console.log(u.dim(" Discord: disabled"));let s=e.channels?.gitlab;if(s?.enabled){console.log(u.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(u.dim(" GitLab: disabled"));console.log()});zt.command("add").description("add a channel (telegram, whatsapp, or discord)").action(async()=>{let e=X(),t=Object.keys(e.agents||{});if(!t.length){console.log(u.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 $e({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 $e([{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(u.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(u.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 me(e),console.log(u.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await $e([{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 $e([{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 me(e),je(R(process.cwd(),s.sessionDir),{recursive:!0}),console.log(u.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(u.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="discord"){let s=await $e([{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 me(e),console.log(u.green(` Discord added -> ${s.agentBinding}`))}if(n==="gitlab"){let s=await $e([{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 $e([{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 me(e),console.log(u.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(u.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(u.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(u.dim(` Secret token: ${s.webhookSecret}`)),console.log(u.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(u.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var mt=new Oe().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");mt.command("list").alias("ls").description("list cron jobs").action(()=>{let e=X();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?u.green("\u25CF"):u.dim("\u25CB");console.log(` ${n} ${u.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(u.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(u.dim(" No cron jobs configured")),console.log()});mt.command("add").description("add a cron job").action(async()=>{let e=X(),t=Object.keys(e.agents||{}),o=await $e([{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 me(e),console.log(u.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});mt.command("enable <id>").description("enable a cron job").action(async e=>{let t=X();if(!t.crons?.[e]){console.log(u.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!0,await me(t),console.log(u.green(` Cron "${e}" enabled`))});mt.command("disable <id>").description("disable a cron job").action(async e=>{let t=X();if(!t.crons?.[e]){console.log(u.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await me(t),console.log(u.green(` Cron "${e}" disabled`))});var pt=new Oe().name("mesh").description("manage mesh peers \u2014 add, list, remove");pt.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=X();if(console.log(),!e.mesh?.enabled)console.log(u.dim(" Mesh: disabled"));else{console.log(u.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=u.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=u.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${u.cyan(t.name)} ${u.dim(t.url)} ${o}`)}}console.log()});pt.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=X(),t=await $e([{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(u.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(u.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 me(e),console.log(u.green(` Peer "${t.name}" added`)),console.log()}});pt.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=X();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await me(t),console.log(u.green(` Peer "${e}" removed`)))});pt.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=X();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(u.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(u.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(u.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await me(t),console.log(u.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(u.dim(" Restart the daemon for the new cadence to take effect."))});var ut=new Oe().name("skill").description("manage skills \u2014 add to agent(s), list");ut.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=X(),n=R(e);if(!G(n)){console.log(u.red(` Skill not found: ${n}`));return}let s=G(Pe(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 $e({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(u.yellow(` Agent "${r}" not found, skipping`));continue}let c=R(a.workspace,".claude/skills",s);je(c,{recursive:!0}),G(Pe(n,"SKILL.md"))?ho(n,c,{recursive:!0}):n.endsWith(".md")&&ho(n,Pe(c,"SKILL.md")),console.log(u.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});ut.command("list").alias("ls").description("list skills per agent").action(()=>{let e=X();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=R(o.workspace,".claude/skills"),s=G(n)?yo(n).filter(i=>!i.startsWith(".")):[];console.log(` ${u.cyan(t)}: ${s.length?s.join(", "):u.dim("(none)")}`)}console.log()});ut.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]:[R(n,"src",e,"SKILL.md"),R(n,"skills",e,"SKILL.md")],i=s.find(k=>G(k));if(!i){console.log(u.red(` No SKILL.md found for "${e}". Searched:`));for(let k of s)console.log(u.dim(` ${k}`));return}let r=Ne(i,"utf-8"),a=o("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=P()}catch(k){console.log(u.red(` Can't load agentx.json: ${k.message}`));return}let p=Object.entries(l.agents||{}),d=t.agent?p.filter(([k])=>k===t.agent):p;if(d.length===0){console.log(u.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(u.bold(` Skill sync \u2014 ${e}`)),console.log(u.dim(` Source: ${i}`)),console.log(u.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(u.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let m=0,h=0,f=0,w=0;for(let[k,$]of d){let x=$.workspace;if(!x||!G(x)){console.log(` ${u.yellow("\u2717")} ${k.padEnd(22)} ${u.dim("(workspace missing: "+(x||"undefined")+")")}`),w++;continue}let v=R(x,".claude/skills",e),b=R(v,"SKILL.md");if(!G(b)){if(!t.allWorkspaces){console.log(` ${u.dim("\xB7")} ${k.padEnd(22)} ${u.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),w++;continue}t.dryRun||(je(v,{recursive:!0}),dt(b,r)),console.log(` ${u.green("+")} ${k.padEnd(22)} ${u.dim("\u2192 seeded v"+c)}`),m++;continue}let C=Ne(b,"utf-8");if(o("sha256").update(C).digest("hex").slice(0,12)===a){console.log(` ${u.dim("=")} ${k.padEnd(22)} ${u.dim("up to date (v"+c+")")}`),f++;continue}let M=(C.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||dt(b,r),console.log(` ${u.yellow("\u21BB")} ${k.padEnd(22)} ${u.dim(`v${M} \u2192 v${c}`)}`),h++}console.log();let y=t.dryRun?"would":"did";console.log(u.dim(` Summary: ${y} seed ${m}, ${y} update ${h}, ${f} already current, ${w} skipped.`)),t.dryRun&&(m>0||h>0)&&console.log(u.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});ut.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 h=X().agents?.[e.workspace];h||(console.log(u.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(R(h.workspace))}else if(e.allWorkspaces){let m=X();for(let h of Object.values(m.agents||{}))h?.workspace&&i.push(R(h.workspace))}else i.push(R(e.cwd));let r=R(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 h of d)m[h.verdict]++;console.log();for(let h of d){let f=h.verdict==="PASS"?u.green("PASS "):h.verdict==="REVIEW"?u.yellow("REVIEW "):u.red("FAILING");console.log(` ${f} ${u.bold(h.name)}${h.skill?.path?u.dim(` (${h.skill.path})`):""}`);for(let w of h.reasons)console.log(` ${u.dim("\xB7")} ${w}`)}console.log(),console.log(` ${u.green(`${m.PASS} PASS`)} ${u.yellow(`${m.REVIEW} REVIEW`)} ${u.red(`${m.FAILING} FAILING`)}`),console.log()}process.exit(d.some(m=>m.verdict==="FAILING")?1:0)});var Ot=new Oe().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Ot.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(u.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let o=R(t.cwd),n=R(o,"references/example"),s=R(o,"references/recipes/example.yaml");G(n)||(console.log(u.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=R(o,".agentx/references",e),r=R(o,".agentx/references/recipes");je(i,{recursive:!0}),je(r,{recursive:!0});let a=yo(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let m=Pe(i,d);if(G(m)&&!t.force){console.log(u.dim(` skip ${m} (exists; --force to overwrite)`)),l++;continue}let f=Ne(Pe(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);dt(m,f),console.log(u.green(` + ${m}`)),c++}let p=Pe(r,`${e}.yaml`);if(G(p)&&!t.force)console.log(u.dim(` skip ${p} (exists; --force to overwrite)`)),l++;else if(G(s)){let d=Ne(s,"utf-8").replaceAll("example.",`${e}.`);dt(p,d),console.log(u.green(` + ${p}`)),c++}console.log(),console.log(u.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(u.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(u.dim(" 2. agentx skill audit # verify references resolve")),console.log(u.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Ot.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(u.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=R(t.cwd),r=t.from?String(t.from).split(",").map(w=>w.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(u.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(u.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(u.dim(` Scanned skills: ${c.scannedSkills.join(", ")}`));let l=Object.fromEntries(Object.entries(c.byKind).map(([w,y])=>[w,y.length]));console.log(` Discovered: ssh=${l.ssh} gitlab=${l.gitlab} paths=${l.path} contacts=${l.contact}`);let p=s(c,e),d=R(t.referencesCwd||t.cwd),m=R(d,".agentx/references",e);if(!t.write){console.log(),console.log(u.dim(` Dry-run \u2014 would write to ${m}/`));for(let[w,y]of Object.entries(p))console.log(u.cyan(`
12
- --- ${w} ---`)),console.log(y.split(`
13
- `).slice(0,30).map(k=>` ${k}`).join(`
14
- `)),y.split(`
15
- `).length>30&&console.log(u.dim(` \u2026 (${y.split(`
16
- `).length-30} more lines truncated in preview)`));console.log(),console.log(u.dim(` Re-run with --write to commit these to ${m}/`)),console.log();return}je(m,{recursive:!0});let h=0,f=0;for(let[w,y]of Object.entries(p)){let k=Pe(m,w);if(G(k)&&!t.force){console.log(u.dim(` skip ${k} (exists; --force to overwrite)`)),f++;continue}dt(k,y),console.log(u.green(` + ${k}`)),h++}console.log(),console.log(u.dim(` ${h} written, ${f} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(u.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Ot.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(R(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(u.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(` ${u.cyan(s.id)} ${u.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(u.dim(` ${i}`))}console.log(),console.log(u.dim(` ${n.length} reference(s) loaded.`)),console.log()});var wo=new Oe().name("hook").description("manage hooks \u2014 add to agent workspace");wo.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=X().agents?.[e];if(!o){console.log(u.red(` Agent "${e}" not found`));return}let n=R(o.workspace,".claude/settings.json"),s=G(n)?JSON.parse(Ne(n,"utf-8")):{},i=await $e([{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),je(R(o.workspace,".claude"),{recursive:!0}),dt(n,JSON.stringify(s,null,2)),console.log(u.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var $o=new Oe().name("migrate").description("import configuration from OpenClaw or other tools");$o.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,R(process.env.HOME||"",".openclaw/openclaw.json"),R(process.env.HOME||"",".openclaw/clawdbot.json")].filter(Boolean),n;for(let h of o)if(h&&G(h)){n=h;break}if(!n){console.log(u.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(u.dim(` Reading: ${n}`));let s=JSON.parse(Ne(n,"utf-8")),i=G(R(process.cwd(),"agentx.json"))?X():{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 h of a)h.match?.channel==="telegram"&&(c[h.match.accountId]=h.agentId);r.find(h=>h.id==="main"||h.default)&&(c.default="main");let l=0;for(let h of r){if(h.workspace?.startsWith("/data"))continue;let f=h.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),w=h.groupChat?.mentionPatterns||[];if(w.some(y=>y===f)||w.push(f),i.agents[f]={name:h.name,workspace:h.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:w,maxConcurrent:h.id==="main"?2:1,systemPrompt:`You are ${h.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!t.dryRun){je(R(h.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:y}=await import("./workspace-setup-FPGN5VNY.js");y(f,i.agents[f])}}console.log(` ${u.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let p=s.channels?.telegram?.accounts||{},d=0;for(let[h,f]of Object.entries(p)){if(!f.botToken)continue;let y=c[h]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[h]={token:f.botToken,agentBinding:y},i.channels.telegram.enabled=!0,d++}console.log(` ${u.green(d)} Telegram accounts imported`);let m=R(n,"../cron/jobs.json");if(G(m)){let h=JSON.parse(Ne(m,"utf-8")),f=0;for(let w of h.jobs||[]){let y=w.name||w.id,k=w.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[y]={enabled:w.enabled||!1,schedule:w.schedule?.expr||"0 9 * * *",timezone:w.schedule?.tz||"UTC",agent:k,prompt:w.payload?.message||"",timeout:w.payload?.timeoutSeconds||600,onError:["log"]},f++}console.log(` ${u.green(f)} cron jobs imported`)}t.dryRun?(console.log(u.yellow(`
17
- Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await me(i),console.log(u.green(`
18
- Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Me=new Oe().name("config").description("validate and inspect configuration");Me.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=P(e.config);console.log(u.green(" \u2713 Config valid")),console.log(u.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(u.dim(` Bind: ${t.node.bind}`)),console.log(u.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(u.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(u.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(u.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(u.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`)),console.log(u.dim(` Discord: ${t.channels.discord?.enabled?"enabled":"disabled"}`));let n=Ut(t);if(n.length){console.log(),console.log(u.yellow(" Warnings:"));for(let s of n)console.log(u.yellow(` \u26A0 ${s}`))}else console.log(u.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(t.agents)){let r=i.workspace,a=G(R(r,".claude")),c=G(R(r,"CLAUDE.md")),l=G(R(r,".claude/settings.json")),p=G(R(r,".claude/skills"))?yo(R(r,".claude/skills")).filter(m=>!m.startsWith(".")).length:0,d=[a?u.green("\u2713"):u.red("\u2717"),".claude",c?u.green("\u2713"):u.yellow("\u25CB"),"CLAUDE.md",l?u.green("\u2713"):u.yellow("\u25CB"),"settings",`${p} skills`];console.log(` ${u.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(u.red(` \u2717 ${t.message}`))}console.log()});Me.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=P(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(u.red(t.message))}});function Ts(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 fo(e){return e===void 0?u.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Me.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-53XGR2NT.js"),{expandEnvVars:r}=await import("./config-QXWKEQON.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(u.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(fo(p))});Me.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-53XGR2NT.js"),r=Ts(t,!!o.string),a=await n(l=>{s(l,e,r)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(u.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);o.dryRun?console.log(u.yellow(` (dry-run) ${u.cyan(e)} would become: ${fo(c)}`)):(console.log(u.green(` \u2713 ${u.cyan(e)} = ${fo(c)}`)),a.reloaded?console.log(u.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(u.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Me.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-53XGR2NT.js"),i=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(i.success||(console.log(u.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(u.dim(` (no-op) ${u.cyan(e)} was not set`));return}t.dryRun?console.log(u.yellow(` (dry-run) ${u.cyan(e)} would be removed`)):(console.log(u.green(` \u2713 ${u.cyan(e)} removed`)),i.reloaded&&console.log(u.dim(" Daemon hot-reloaded.")))});Me.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=P(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(u.bold(" Governance flags")),console.log(),n&&(console.log(u.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?u.green:s==="shadow"?u.cyan:s==="off"?u.dim:u.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":u.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let p=a?u.green("active"):r?u.yellow("env=true but business.enabled=false \u2192 inactive"):u.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${p}`),console.log(u.dim(` business.enabled ${t?u.green("true"):u.dim("false")}`)),console.log(u.dim(` business.projects[] ${o}`)),console.log(),console.log(u.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(u.dim(" See: https://github.com/anis-marrouchi/agentx/blob/master/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as _s}from"commander";import Le from"chalk";import{resolve as We}from"path";import{existsSync as Ps}from"fs";var Re=new _s().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Ke(e){let t=We(e,".agentx/db.sqlite");Ps(t)||(console.log(Le.red(` No SQLite at ${t}`)),console.log(Le.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=en({path:t});return o||(console.log(Le.red(` Could not open ${t}`)),console.log(Le.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function Ve(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(Le.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])))}Re.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=Ke(We(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=`
10
+ `))}catch(t){console.log(te.red(` ${t.message}`)),process.exit(1)}});import{Command as Re}from"commander";import u from"chalk";import be from"prompts";import{readFileSync as Me,writeFileSync as pt,existsSync as Y,mkdirSync as Ce,cpSync as wo,readdirSync as bo}from"fs";import{resolve as R,join as Ne}from"path";function Z(){let e=R(process.cwd(),"agentx.json");if(!Y(e))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Me(e,"utf-8"))}function pe(e){return ae(t=>{for(let o of Object.keys(t))delete t[o];Object.assign(t,e)}).then(t=>{if(!t.success){console.error(u.red(` Config save failed: ${t.error}`));return}t.reloaded?console.error(u.dim(" (daemon hot-reloaded)")):t.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(t.reloadSkipped)&&console.error(u.dim(` (daemon reload skipped: ${t.reloadSkipped})`))})}var ut=new Re().name("agent").description("manage agents \u2014 add, list, remove");ut.command("list").alias("ls").description("list configured agents").action(()=>{let e=Z();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=o.mentions?.join(", ")||"";console.log(` ${u.cyan(t)} \u2014 ${o.name} (${o.tier})`),console.log(u.dim(` workspace: ${o.workspace}`)),n&&console.log(u.dim(` mentions: ${n}`))}console.log()});ut.command("add").description("add a new agent interactively").action(async()=>{let e=Z(),t=await be([{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:R(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:Ne(t.workspace,t.id);Ce(R(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-FPGN5VNY.js"),i=s(t.id,n,"19900",(...l)=>{console.log(u.dim(` ${l.join(" ")}`))}),r=R(process.cwd(),"src/wiki/SKILL.md"),a=R(import.meta.dirname,"../wiki/SKILL.md"),c=Y(r)?r:a;Y(c)&&(Ce(R(o,".claude/skills/wiki"),{recursive:!0}),wo(c,R(o,".claude/skills/wiki/SKILL.md"))),e.agents=e.agents||{},e.agents[t.id]=n,await pe(e),console.log(u.green(`
11
+ Agent "${t.id}" added`)),console.log(u.dim(` Workspace: ${o}`)),console.log(u.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});ut.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async e=>{let t=Z();if(!t.agents?.[e]){console.log(u.red(` Agent "${e}" not found`));return}delete t.agents[e],await pe(t),console.log(u.green(` Agent "${e}" removed from config (workspace preserved)`))});ut.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=Z(),n=o.agents?.[e];if(n||(console.log(u.red(` Agent "${e}" not found`)),process.exit(1)),t.show){console.log(),console.log(u.bold(` ${e}`)),console.log(` intents ${n.intents&&n.intents.length?n.intents.join(", "):u.dim("(any)")}`),console.log(` maxDelegationDepth ${n.maxDelegationDepth??5}`),console.log(` contextReferences ${n.contextReferences?"on":u.dim("off")}`),console.log(` contextStrategy ${n.contextStrategy||u.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(u.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(u.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(u.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(u.red(" --max-execution-minutes must be 1..240")),process.exit(1)),n.maxExecutionMinutes=i,s.push(`maxExecutionMinutes=${i}`)}s.length===0&&(console.log(u.yellow(" no changes \u2014 pass at least one flag, or use --show")),process.exit(1)),await pe(o),console.log(u.green(` \u2713 ${e}: ${s.join(", ")}`)),console.log(u.dim(" Restart the daemon (or POST /reload) for the change to take effect."))});var Ht=new Re().name("channel").description("manage channels \u2014 add telegram/whatsapp/discord, list");Ht.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=Z();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(u.bold(" Telegram:"));for(let[i,r]of Object.entries(t.accounts||{}))console.log(` ${u.cyan(i)} -> agent: ${r.agentBinding}`)}else console.log(u.dim(" Telegram: disabled"));let o=e.channels?.whatsapp;if(o?.enabled){console.log(u.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(u.dim(" WhatsApp: disabled"));let n=e.channels?.discord;n?.enabled?(console.log(u.bold(" Discord:")),console.log(` agent: ${n.agentBinding||"(none)"}`)):console.log(u.dim(" Discord: disabled"));let s=e.channels?.gitlab;if(s?.enabled){console.log(u.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(u.dim(" GitLab: disabled"));console.log()});Ht.command("add").description("add a channel (telegram, whatsapp, or discord)").action(async()=>{let e=Z(),t=Object.keys(e.agents||{});if(!t.length){console.log(u.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 be({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 be([{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(u.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(u.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 pe(e),console.log(u.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(n==="whatsapp"){let s=await be([{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 be([{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 pe(e),Ce(R(process.cwd(),s.sessionDir),{recursive:!0}),console.log(u.green(` WhatsApp enabled (${i.length} routes, default: ${s.defaultAgent})`)),console.log(u.dim(" Start daemon to scan QR code: agentx daemon start"))}if(n==="discord"){let s=await be([{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 pe(e),console.log(u.green(` Discord added -> ${s.agentBinding}`))}if(n==="gitlab"){let s=await be([{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 be([{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 pe(e),console.log(u.green(` GitLab enabled (${i.length} routes, webhook :${s.webhookPort})`)),console.log(u.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(u.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(u.dim(` Secret token: ${s.webhookSecret}`)),console.log(u.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(u.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var ht=new Re().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");ht.command("list").alias("ls").description("list cron jobs").action(()=>{let e=Z();console.log();for(let[t,o]of Object.entries(e.crons||{})){let n=o.enabled?u.green("\u25CF"):u.dim("\u25CB");console.log(` ${n} ${u.cyan(t)} \u2014 ${o.schedule} (${o.timezone})`),console.log(u.dim(` agent: ${o.agent} | timeout: ${o.timeout}s`))}Object.keys(e.crons||{}).length||console.log(u.dim(" No cron jobs configured")),console.log()});ht.command("add").description("add a cron job").action(async()=>{let e=Z(),t=Object.keys(e.agents||{}),o=await be([{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 pe(e),console.log(u.green(` Cron "${o.id}" added (${o.enabled?"enabled":"disabled"})`)),console.log())});ht.command("enable <id>").description("enable a cron job").action(async e=>{let t=Z();if(!t.crons?.[e]){console.log(u.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!0,await pe(t),console.log(u.green(` Cron "${e}" enabled`))});ht.command("disable <id>").description("disable a cron job").action(async e=>{let t=Z();if(!t.crons?.[e]){console.log(u.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,await pe(t),console.log(u.green(` Cron "${e}" disabled`))});var ft=new Re().name("mesh").description("manage mesh peers \u2014 add, list, remove");ft.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=Z();if(console.log(),!e.mesh?.enabled)console.log(u.dim(" Mesh: disabled"));else{console.log(u.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let o=u.red("unreachable");try{let s=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();o=u.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${u.cyan(t.name)} ${u.dim(t.url)} ${o}`)}}console.log()});ft.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=Z(),t=await be([{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(u.green(` Connected: ${n.name} (${n.skills?.length||0} agents)`))}catch{console.log(u.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 pe(e),console.log(u.green(` Peer "${t.name}" added`)),console.log()}});ft.command("remove <name>").alias("rm").description("remove a mesh peer").action(async e=>{let t=Z();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(o=>o.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),await pe(t),console.log(u.green(` Peer "${e}" removed`)))});ft.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=Z();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(u.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(u.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(u.yellow(" no changes \u2014 pass --interval and/or --timeout, or --show")),process.exit(1)),await pe(t),console.log(u.green(` \u2713 mesh.healthCheck: ${o.join(", ")}`)),console.log(u.dim(" Restart the daemon for the new cadence to take effect."))});var yt=new Re().name("skill").description("manage skills \u2014 add to agent(s), list");yt.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=Z(),n=R(e);if(!Y(n)){console.log(u.red(` Skill not found: ${n}`));return}let s=Y(Ne(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 be({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(u.yellow(` Agent "${r}" not found, skipping`));continue}let c=R(a.workspace,".claude/skills",s);Ce(c,{recursive:!0}),Y(Ne(n,"SKILL.md"))?wo(n,c,{recursive:!0}):n.endsWith(".md")&&wo(n,Ne(c,"SKILL.md")),console.log(u.green(` ${s} -> ${r} (${a.workspace})`))}console.log()});yt.command("list").alias("ls").description("list skills per agent").action(()=>{let e=Z();console.log();for(let[t,o]of Object.entries(e.agents||{})){let n=R(o.workspace,".claude/skills"),s=Y(n)?bo(n).filter(i=>!i.startsWith(".")):[];console.log(` ${u.cyan(t)}: ${s.length?s.join(", "):u.dim("(none)")}`)}console.log()});yt.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]:[R(n,"src",e,"SKILL.md"),R(n,"skills",e,"SKILL.md")],i=s.find(b=>Y(b));if(!i){console.log(u.red(` No SKILL.md found for "${e}". Searched:`));for(let b of s)console.log(u.dim(` ${b}`));return}let r=Me(i,"utf-8"),a=o("sha256").update(r).digest("hex").slice(0,12),c=(r.match(/^version:\s*(.+)$/m)?.[1]||"?").trim(),l;try{l=P()}catch(b){console.log(u.red(` Can't load agentx.json: ${b.message}`));return}let h=Object.entries(l.agents||{}),d=t.agent?h.filter(([b])=>b===t.agent):h;if(d.length===0){console.log(u.yellow(t.agent?` Agent "${t.agent}" not in config.`:" No agents in config."));return}console.log(),console.log(u.bold(` Skill sync \u2014 ${e}`)),console.log(u.dim(` Source: ${i}`)),console.log(u.dim(` Version: ${c} \xB7 hash ${a}`)),console.log(u.dim(` Mode: ${t.dryRun?"dry-run":"commit"}${t.allWorkspaces?" \xB7 seed missing":" \xB7 only-existing"}`)),console.log();let m=0,p=0,f=0,y=0;for(let[b,$]of d){let S=$.workspace;if(!S||!Y(S)){console.log(` ${u.yellow("\u2717")} ${b.padEnd(22)} ${u.dim("(workspace missing: "+(S||"undefined")+")")}`),y++;continue}let v=R(S,".claude/skills",e),k=R(v,"SKILL.md");if(!Y(k)){if(!t.allWorkspaces){console.log(` ${u.dim("\xB7")} ${b.padEnd(22)} ${u.dim("(skipped \u2014 no existing copy; use --all-workspaces to seed)")}`),y++;continue}t.dryRun||(Ce(v,{recursive:!0}),pt(k,r)),console.log(` ${u.green("+")} ${b.padEnd(22)} ${u.dim("\u2192 seeded v"+c)}`),m++;continue}let C=Me(k,"utf-8");if(o("sha256").update(C).digest("hex").slice(0,12)===a){console.log(` ${u.dim("=")} ${b.padEnd(22)} ${u.dim("up to date (v"+c+")")}`),f++;continue}let M=(C.match(/^version:\s*(.+)$/m)?.[1]||"?").trim();t.dryRun||pt(k,r),console.log(` ${u.yellow("\u21BB")} ${b.padEnd(22)} ${u.dim(`v${M} \u2192 v${c}`)}`),p++}console.log();let w=t.dryRun?"would":"did";console.log(u.dim(` Summary: ${w} seed ${m}, ${w} update ${p}, ${f} already current, ${y} skipped.`)),t.dryRun&&(m>0||p>0)&&console.log(u.dim(" Dry-run \u2014 rerun without --dry-run to write.")),console.log()});yt.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 p=Z().agents?.[e.workspace];p||(console.log(u.red(` Agent "${e.workspace}" not found in agentx.json`)),process.exit(1)),i.push(R(p.workspace))}else if(e.allWorkspaces){let m=Z();for(let p of Object.values(m.agents||{}))p?.workspace&&i.push(R(p.workspace))}else i.push(R(e.cwd));let r=R(e.referencesCwd||e.cwd),c=(await Promise.all(i.map(m=>t(m)))).flat(),[l,h]=await Promise.all([n(r),s(r)]),d=o({skills:c,references:l,recipes:h});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 p of d)m[p.verdict]++;console.log();for(let p of d){let f=p.verdict==="PASS"?u.green("PASS "):p.verdict==="REVIEW"?u.yellow("REVIEW "):u.red("FAILING");console.log(` ${f} ${u.bold(p.name)}${p.skill?.path?u.dim(` (${p.skill.path})`):""}`);for(let y of p.reasons)console.log(` ${u.dim("\xB7")} ${y}`)}console.log(),console.log(` ${u.green(`${m.PASS} PASS`)} ${u.yellow(`${m.REVIEW} REVIEW`)} ${u.red(`${m.FAILING} FAILING`)}`),console.log()}process.exit(d.some(m=>m.verdict==="FAILING")?1:0)});var Tt=new Re().name("references").alias("refs").description("manage the deterministic references registry \u2014 facts cited by skills and resolved into agent context");Tt.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(u.red(` Invalid namespace "${e}". Use lowercase letters, digits, and hyphens.`)),process.exit(1));let o=R(t.cwd),n=R(o,"references/example"),s=R(o,"references/recipes/example.yaml");Y(n)||(console.log(u.red(` Example template not found at ${n}. Are you running this from the agentx repo root?`)),process.exit(1));let i=R(o,".agentx/references",e),r=R(o,".agentx/references/recipes");Ce(i,{recursive:!0}),Ce(r,{recursive:!0});let a=bo(n).filter(d=>d.endsWith(".yaml")||d.endsWith(".yml")),c=0,l=0;for(let d of a){let m=Ne(i,d);if(Y(m)&&!t.force){console.log(u.dim(` skip ${m} (exists; --force to overwrite)`)),l++;continue}let f=Me(Ne(n,d),"utf-8").replace(/^namespace:\s*example\./m,`namespace: ${e}.`);pt(m,f),console.log(u.green(` + ${m}`)),c++}let h=Ne(r,`${e}.yaml`);if(Y(h)&&!t.force)console.log(u.dim(` skip ${h} (exists; --force to overwrite)`)),l++;else if(Y(s)){let d=Me(s,"utf-8").replaceAll("example.",`${e}.`);pt(h,d),console.log(u.green(` + ${h}`)),c++}console.log(),console.log(u.dim(` ${c} written, ${l} skipped. Edit the placeholders, then:`)),console.log(u.dim(" 1. set contextReferences: true on the relevant agents in agentx.json")),console.log(u.dim(" 2. agentx skill audit # verify references resolve")),console.log(u.dim(" 3. systemctl restart agentx # pick up the new registry")),console.log()});Tt.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(u.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=R(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(u.yellow(` No skills matched filter [${r.join(", ")}] under ${i}`)),console.log(u.dim(" Tip: pass --from <skill-name>,<other> to widen the filter.")),console.log();return}console.log(u.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 h=s(c,e),d=R(t.referencesCwd||t.cwd),m=R(d,".agentx/references",e);if(!t.write){console.log(),console.log(u.dim(` Dry-run \u2014 would write to ${m}/`));for(let[y,w]of Object.entries(h))console.log(u.cyan(`
12
+ --- ${y} ---`)),console.log(w.split(`
13
+ `).slice(0,30).map(b=>` ${b}`).join(`
14
+ `)),w.split(`
15
+ `).length>30&&console.log(u.dim(` \u2026 (${w.split(`
16
+ `).length-30} more lines truncated in preview)`));console.log(),console.log(u.dim(` Re-run with --write to commit these to ${m}/`)),console.log();return}Ce(m,{recursive:!0});let p=0,f=0;for(let[y,w]of Object.entries(h)){let b=Ne(m,y);if(Y(b)&&!t.force){console.log(u.dim(` skip ${b} (exists; --force to overwrite)`)),f++;continue}pt(b,w),console.log(u.green(` + ${b}`)),p++}console.log(),console.log(u.dim(` ${p} written, ${f} skipped. Review every card \u2014 flagged ones (tags include "needs-review") are best-effort guesses.`)),console.log(u.dim(" Then: agentx skill audit \u2192 set contextReferences: true on the relevant agents \u2192 systemctl restart agentx")),console.log()});Tt.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(R(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(u.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(` ${u.cyan(s.id)} ${u.dim(`(${s.kind})`)}`),console.log(` ${s.summary}`),i&&console.log(u.dim(` ${i}`))}console.log(),console.log(u.dim(` ${n.length} reference(s) loaded.`)),console.log()});var ko=new Re().name("hook").description("manage hooks \u2014 add to agent workspace");ko.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let o=Z().agents?.[e];if(!o){console.log(u.red(` Agent "${e}" not found`));return}let n=R(o.workspace,".claude/settings.json"),s=Y(n)?JSON.parse(Me(n,"utf-8")):{},i=await be([{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),Ce(R(o.workspace,".claude"),{recursive:!0}),pt(n,JSON.stringify(s,null,2)),console.log(u.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var vo=new Re().name("migrate").description("import configuration from OpenClaw or other tools");vo.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,R(process.env.HOME||"",".openclaw/openclaw.json"),R(process.env.HOME||"",".openclaw/clawdbot.json")].filter(Boolean),n;for(let p of o)if(p&&Y(p)){n=p;break}if(!n){console.log(u.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(u.dim(` Reading: ${n}`));let s=JSON.parse(Me(n,"utf-8")),i=Y(R(process.cwd(),"agentx.json"))?Z():{node:{id:"imported",name:"Imported",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{telegram:{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},whatsapp:{enabled:!1}},crons:{},mesh:{enabled:!1,peers:[]}},r=s.agents?.list||[],a=s.bindings||[],c={};for(let p of a)p.match?.channel==="telegram"&&(c[p.match.accountId]=p.agentId);r.find(p=>p.id==="main"||p.default)&&(c.default="main");let l=0;for(let p of r){if(p.workspace?.startsWith("/data"))continue;let f=p.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),y=p.groupChat?.mentionPatterns||[];if(y.some(w=>w===f)||y.push(f),i.agents[f]={name:p.name,workspace:p.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:y,maxConcurrent:p.id==="main"?2:1,systemPrompt:`You are ${p.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!t.dryRun){Ce(R(p.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-FPGN5VNY.js");w(f,i.agents[f])}}console.log(` ${u.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let h=s.channels?.telegram?.accounts||{},d=0;for(let[p,f]of Object.entries(h)){if(!f.botToken)continue;let w=c[p]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[p]={token:f.botToken,agentBinding:w},i.channels.telegram.enabled=!0,d++}console.log(` ${u.green(d)} Telegram accounts imported`);let m=R(n,"../cron/jobs.json");if(Y(m)){let p=JSON.parse(Me(m,"utf-8")),f=0;for(let y of p.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"]},f++}console.log(` ${u.green(f)} cron jobs imported`)}t.dryRun?(console.log(u.yellow(`
17
+ Dry run \u2014 nothing written`)),console.log(JSON.stringify(i,null,2))):(await pe(i),console.log(u.green(`
18
+ Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var Le=new Re().name("config").description("validate and inspect configuration");Le.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=P(e.config);console.log(u.green(" \u2713 Config valid")),console.log(u.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(u.dim(` Bind: ${t.node.bind}`)),console.log(u.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(u.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(u.dim(` Mesh peers: ${t.mesh.peers.length}`));let o=Object.keys(t.channels.telegram.accounts).length;console.log(u.dim(` Telegram: ${t.channels.telegram.enabled?`${o} accounts`:"disabled"}`)),console.log(u.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`)),console.log(u.dim(` Discord: ${t.channels.discord?.enabled?"enabled":"disabled"}`));let n=zt(t);if(n.length){console.log(),console.log(u.yellow(" Warnings:"));for(let s of n)console.log(u.yellow(` \u26A0 ${s}`))}else console.log(u.green(" \u2713 All workspaces valid"));console.log();for(let[s,i]of Object.entries(t.agents)){let r=i.workspace,a=Y(R(r,".claude")),c=Y(R(r,"CLAUDE.md")),l=Y(R(r,".claude/settings.json")),h=Y(R(r,".claude/skills"))?bo(R(r,".claude/skills")).filter(m=>!m.startsWith(".")).length:0,d=[a?u.green("\u2713"):u.red("\u2717"),".claude",c?u.green("\u2713"):u.yellow("\u25CB"),"CLAUDE.md",l?u.green("\u2713"):u.yellow("\u25CB"),"settings",`${h} skills`];console.log(` ${u.cyan(s)}: ${d.join(" ")}`)}}catch(t){console.log(u.red(` \u2717 ${t.message}`))}console.log()});Le.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=P(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(u.red(t.message))}});function Ls(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 $o(e){return e===void 0?u.dim("(unset)"):typeof e=="string"?e:JSON.stringify(e,null,2)}Le.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-JKCNCY2F.js"),{expandEnvVars:r}=await import("./config-RWHSEE4N.js"),a=t.config||s(process.cwd(),"agentx.json");n(a)||(console.log(u.red(` No config at ${a}`)),process.exit(1));let c=JSON.parse(o(a,"utf-8")),l=t.raw?c:r(c),h=i(l,e);t.json?console.log(JSON.stringify(h)):console.log($o(h))});Le.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-JKCNCY2F.js"),r=Ls(t,!!o.string),a=await n(l=>{s(l,e,r)},{configPath:o.config,dryRun:!!o.dryRun});a.success||(console.log(u.red(` \u2717 ${a.error}`)),process.exit(1));let c=i(a.after,e);o.dryRun?console.log(u.yellow(` (dry-run) ${u.cyan(e)} would become: ${$o(c)}`)):(console.log(u.green(` \u2713 ${u.cyan(e)} = ${$o(c)}`)),a.reloaded?console.log(u.dim(" Daemon hot-reloaded.")):a.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(a.reloadSkipped)&&console.log(u.dim(` (daemon reload skipped: ${a.reloadSkipped})`)))});Le.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-JKCNCY2F.js"),i=await o(a=>{n(a,e)!==void 0&&s(a,e)},{configPath:t.config,dryRun:!!t.dryRun});if(i.success||(console.log(u.red(` \u2717 ${i.error}`)),process.exit(1)),n(i.after,e)!==void 0){console.log(u.dim(` (no-op) ${u.cyan(e)} was not set`));return}t.dryRun?console.log(u.yellow(` (dry-run) ${u.cyan(e)} would be removed`)):(console.log(u.green(` \u2713 ${u.cyan(e)} removed`)),i.reloaded&&console.log(u.dim(" Daemon hot-reloaded.")))});Le.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=P(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(u.bold(" Governance flags")),console.log(),n&&(console.log(u.yellow(` Note: agentx.json couldn't be loaded \u2014 ${n}`)),console.log());let l=s==="authoritative"?u.green:s==="shadow"?u.cyan:s==="off"?u.dim:u.red;console.log(` INTENT_LEDGER_MODE ${l(s)}${c?"":u.red(" (invalid \u2014 must be off|shadow|authoritative)")}`);let h=a?u.green("active"):r?u.yellow("env=true but business.enabled=false \u2192 inactive"):u.dim("disabled");console.log(` INTENT_PM_GATE_ENABLED ${h}`),console.log(u.dim(` business.enabled ${t?u.green("true"):u.dim("false")}`)),console.log(u.dim(` business.projects[] ${o}`)),console.log(),console.log(u.dim(" These flags are read once at daemon startup. Flipping requires a restart.")),console.log(u.dim(" See: https://github.com/anis-marrouchi/agentx/blob/master/docs/architecture/research-rescue-plan.md")),console.log()});import{Command as Ws}from"commander";import We from"chalk";import{resolve as Fe}from"path";import{existsSync as Fs}from"fs";var De=new Ws().name("db").description("explore the operational SQLite store at .agentx/db.sqlite");function Ve(e){let t=Fe(e,".agentx/db.sqlite");Fs(t)||(console.log(We.red(` No SQLite at ${t}`)),console.log(We.dim(" Make sure the daemon has started since Move 2 shipped \u2014 the file is created on first boot.")),process.exit(1));let o=nn({path:t});return o||(console.log(We.red(` Could not open ${t}`)),console.log(We.dim(' If you see "NODE_MODULE_VERSION mismatch", run `pnpm rebuild better-sqlite3` under the daemon\'s Node version.')),process.exit(1)),o}function Qe(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(We.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])))}De.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=Ve(Fe(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
19
  SELECT agent_id, channel, status, duration_ms,
20
20
  input_tokens, output_tokens,
21
21
  substr(message_preview, 1, 60) AS message,
@@ -24,7 +24,7 @@ import{b as pn}from"./chunk-WPPUOTY6.js";import{a as ct,b as mn,e as Jt,i as un}
24
24
  ${o.length?"WHERE "+o.join(" AND "):""}
25
25
  ORDER BY started_at DESC
26
26
  LIMIT @limit
27
- `,i=t.prepare(s).all({...n,limit:Number(e.limit)});Ve(i,!!e.json)});Re.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=Ke(We(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?`
27
+ `,i=t.prepare(s).all({...n,limit:Number(e.limit)});Qe(i,!!e.json)});De.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=Ve(Fe(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
28
  SELECT agent_id, reason, COUNT(*) AS n,
29
29
  ROUND(AVG(last_turn_input_tokens)) AS avg_input_tokens,
30
30
  MAX(last_turn_input_tokens) AS max_input_tokens
@@ -38,14 +38,14 @@ import{b as pn}from"./chunk-WPPUOTY6.js";import{a as ct,b as mn,e as Jt,i as un}
38
38
  ${s}
39
39
  ORDER BY rotated_at DESC
40
40
  LIMIT @limit
41
- `,r=t.prepare(i).all({...n,limit:Number(e.limit)});Ve(r,!!e.json)});Re.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=Ke(We(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=`
41
+ `,r=t.prepare(i).all({...n,limit:Number(e.limit)});Qe(r,!!e.json)});De.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=Ve(Fe(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
42
  SELECT day, agent_id, model, tasks,
43
43
  input_tokens AS in_tok, output_tokens AS out_tok,
44
44
  cache_read_tokens AS cache_read, cache_create_tokens AS cache_create
45
45
  FROM usage_daily
46
46
  ${o.length?"WHERE "+o.join(" AND "):""}
47
47
  ORDER BY day DESC, agent_id
48
- `,i=t.prepare(s).all(n);Ve(i,!!e.json)});Re.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=Ke(We(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?`
48
+ `,i=t.prepare(s).all(n);Qe(i,!!e.json)});De.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=Ve(Fe(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
49
  SELECT channel, kind, deciding_stage, COUNT(*) AS n
50
50
  FROM route_traces
51
51
  ${s}
@@ -58,7 +58,7 @@ import{b as pn}from"./chunk-WPPUOTY6.js";import{a as ct,b as mn,e as Jt,i as un}
58
58
  ${s}
59
59
  ORDER BY at DESC
60
60
  LIMIT @limit
61
- `,r=t.prepare(i).all({...n,limit:Number(e.limit)});Ve(r,!!e.json)});Re.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=Ke(We(e.cwd)),o=["status = 'error'"],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent);let s=`
61
+ `,r=t.prepare(i).all({...n,limit:Number(e.limit)});Qe(r,!!e.json)});De.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=Ve(Fe(e.cwd)),o=["status = 'error'"],n={};e.agent&&(o.push("agent_id = @agent"),n.agent=e.agent);let s=`
62
62
  SELECT agent_id, channel, duration_ms,
63
63
  substr(error, 1, 120) AS error,
64
64
  started_at
@@ -66,12 +66,12 @@ import{b as pn}from"./chunk-WPPUOTY6.js";import{a as ct,b as mn,e as Jt,i as un}
66
66
  WHERE ${o.join(" AND ")}
67
67
  ORDER BY started_at DESC
68
68
  LIMIT @limit
69
- `,i=t.prepare(s).all({...n,limit:Number(e.limit)});Ve(i,!!e.json)});Re.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let t=Ke(We(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}));Ve(n,!!e.json)});Re.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=Ke(We(t.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(Le.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(Le.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=o.prepare(e).all();Ve(n,!!t.json)}catch(n){console.log(Le.red(` ${n.message}`)),process.exit(1)}});import{Command as Ls}from"commander";import _ from"chalk";import{mkdtempSync as Ws}from"fs";import{tmpdir as Fs}from"os";import{resolve as xn,join as Sn}from"path";import{existsSync as Bs}from"fs";import Us from"better-sqlite3";function vn(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(f){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${f?.message??f}`})}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=Ns(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},h=Xo(e,m,d,()=>l.decidedAt);a+=1,(h.outcome!==l.outcome||h.agentId!==l.agentId)&&r.push({eventId:p.id,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:h.agentId,outcome:h.outcome},reason:Ms(l,h)})}return{eventsCount:t.length,decisionsCount:a,divergences:r,skipped:[]}}function Ns(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Ms(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 Fe=new Ls().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function ht(e){let t=xn(e.cwd??process.cwd()),o=xn(t,e.path??".agentx/intent/ledger.sqlite");Bs(o)||(console.log(_.red(` No ledger at ${o}`)),console.log(_.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 Us(o,{readonly:!0})}catch(n){console.log(_.red(` Could not open ${o}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(_.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Qe(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(_.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 qs(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 Gt(e){if(!e)return;let t=qs(e);if(t===null){let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(_.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-t}Fe.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=ht(e),o=Gt(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(`
69
+ `,i=t.prepare(s).all({...n,limit:Number(e.limit)});Qe(i,!!e.json)});De.command("tables").description("list tables + row counts").option("--cwd <cwd>","working directory",process.cwd()).option("--json","emit JSON").action(e=>{let t=Ve(Fe(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}));Qe(n,!!e.json)});De.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=Ve(Fe(t.cwd));/^\s*(insert|update|delete|drop|alter|create|attach|vacuum|pragma)\b/i.test(e)&&(console.log(We.red(" Refusing to run a write/DDL statement via `agentx db query`.")),console.log(We.dim(" Use `sqlite3 .agentx/db.sqlite` directly if you really mean it.")),process.exit(2));try{let n=o.prepare(e).all();Qe(n,!!t.json)}catch(n){console.log(We.red(` ${n.message}`)),process.exit(1)}});import{Command as qs}from"commander";import _ from"chalk";import{mkdtempSync as Js}from"fs";import{tmpdir as zs}from"os";import{resolve as An,join as On}from"path";import{existsSync as Gs}from"fs";import Ys from"better-sqlite3";function En(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(f){r.push({eventId:c.resolution.decisionEventId,decidedBy:c.resolution.decisionDecidedBy,expected:{agentId:null,outcome:"resolved"},actual:{agentId:null,outcome:"resolution-failed"},reason:`recordResolution threw: ${f?.message??f}`})}continue}let l=c.decision,h=s.get(l.eventId);if(!h){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=Bs(l),m={id:h.id,ts:h.ts,source:h.source,sourceEventId:h.sourceEventId,project:h.project,subject:h.subject,intent:h.intent,rawJson:h.rawJson},p=tn(e,m,d,()=>l.decidedAt);a+=1,(p.outcome!==l.outcome||p.agentId!==l.agentId)&&r.push({eventId:h.id,decidedBy:l.decidedBy,expected:{agentId:l.agentId,outcome:l.outcome},actual:{agentId:p.agentId,outcome:p.outcome},reason:Us(l,p)})}return{eventsCount:t.length,decisionsCount:a,divergences:r,skipped:[]}}function Bs(e){return{decidedBy:e.decidedBy,decide:()=>e.outcome==="deduped"?null:{agentId:e.agentId,outcome:e.outcome,reason:e.reason}}}function Us(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 Be=new qs().name("ledger").description("inspect the intent ledger (.agentx/intent/ledger.sqlite)");function wt(e){let t=An(e.cwd??process.cwd()),o=An(t,e.path??".agentx/intent/ledger.sqlite");Gs(o)||(console.log(_.red(` No ledger at ${o}`)),console.log(_.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 Ys(o,{readonly:!0})}catch(n){console.log(_.red(` Could not open ${o}: ${n.message}`)),/NODE_MODULE_VERSION/.test(n.message)&&console.log(_.dim(" Run `pnpm rebuild better-sqlite3` under the daemon's Node version.")),process.exit(1)}}function Xe(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(e.length===0){console.log(_.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 Hs(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 Kt(e){if(!e)return;let t=Hs(e);if(t===null){let o=Number(e);if(Number.isFinite(o)&&o>0)return o;console.log(_.red(` Invalid --since "${e}". Use a duration like "1h", "30m", "7d", or an ms epoch.`)),process.exit(1)}return Date.now()-t}Be.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=wt(e),o=Kt(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,h=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
70
  SELECT COUNT(*) as n FROM intent_decisions d
71
71
  LEFT JOIN intent_resolutions r
72
72
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
73
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(_.bold("Events by source")),Qe(r,!1),console.log(),console.log(_.bold(`Decisions: ${a}`)),Qe(c,!1),console.log(),console.log(_.bold(`Divergences: ${l}`)),Qe(p,!1),console.log(),console.log(_.bold(`In-flight (dispatched, no resolution): ${d}`))});Fe.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=ht(e),o=Gt(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(`
74
+ `).get().n;if(e.json){console.log(JSON.stringify({since:o??null,eventsBySource:r,totalDecisions:a,decisionsByOutcome:c,totalDivergences:l,divergencesBySource:h,inFlight:d},null,2));return}console.log(_.bold("Events by source")),Xe(r,!1),console.log(),console.log(_.bold(`Decisions: ${a}`)),Xe(c,!1),console.log(),console.log(_.bold(`Divergences: ${l}`)),Xe(h,!1),console.log(),console.log(_.bold(`In-flight (dispatched, no resolution): ${d}`))});Be.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=wt(e),o=Kt(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
75
  SELECT
76
76
  datetime(ts/1000, 'unixepoch') AS at,
77
77
  source,
@@ -85,7 +85,7 @@ import{b as pn}from"./chunk-WPPUOTY6.js";import{a as ct,b as mn,e as Jt,i as un}
85
85
  ${i}
86
86
  ORDER BY ts DESC
87
87
  LIMIT @limit
88
- `).all(s);Qe(r,!!e.json)});Fe.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=ht(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(`
88
+ `).all(s);Xe(r,!!e.json)});Be.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=wt(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
89
  SELECT
90
90
  datetime(d.decided_at/1000, 'unixepoch') AS dispatched_at,
91
91
  e.source,
@@ -101,7 +101,7 @@ import{b as pn}from"./chunk-WPPUOTY6.js";import{a as ct,b as mn,e as Jt,i as un}
101
101
  WHERE ${o.join(" AND ")}
102
102
  ORDER BY d.decided_at DESC
103
103
  LIMIT @limit
104
- `).all(n);Qe(s,!!e.json)});Fe.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=ht(e),o=Gt(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(`
104
+ `).all(n);Xe(s,!!e.json)});Be.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=wt(e),o=Kt(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
105
  SELECT
106
106
  datetime(ts/1000, 'unixepoch') AS at,
107
107
  source,
@@ -112,7 +112,7 @@ import{b as pn}from"./chunk-WPPUOTY6.js";import{a as ct,b as mn,e as Jt,i as un}
112
112
  ${i}
113
113
  ORDER BY ts DESC
114
114
  LIMIT @limit
115
- `).all(s);Qe(r,!!e.json)});Fe.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=ht(t),n=null,s=null;if(t.bySubject){let d=e.indexOf(":");d<0&&(console.log(_.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(_.red(` no event with id ${e}`)),process.exit(1)),n=d.project,s=d.subject,(n===null||s===null)&&(console.log(_.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(_.dim(` project: ${n}`)),s&&console.log(_.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
115
+ `).all(s);Xe(r,!!e.json)});Be.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=wt(t),n=null,s=null;if(t.bySubject){let d=e.indexOf(":");d<0&&(console.log(_.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(_.red(` no event with id ${e}`)),process.exit(1)),n=d.project,s=d.subject,(n===null||s===null)&&(console.log(_.yellow(` event ${e} has no (project, subject) \u2014 lineage requires both`)),n&&console.log(_.dim(` project: ${n}`)),s&&console.log(_.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
116
  FROM intent_events WHERE project = ? AND subject = ? ORDER BY ts ASC`).all(n,s);if(i.length===0){console.log(_.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
117
  SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason,
118
118
  r.resolved_at, r.status AS resolution_status, r.duration_ms, r.result_summary
@@ -121,13 +121,13 @@ import{b as pn}from"./chunk-WPPUOTY6.js";import{a as ct,b as mn,e as Jt,i as un}
121
121
  ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by
122
122
  WHERE d.event_id IN (${a})
123
123
  ORDER BY d.decided_at ASC
124
- `).all(c);if(t.json){let d=i.map(m=>({event:m,decisions:l.filter(h=>h.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(_.bold(` Lineage for ${_.cyan(n+":"+s)}`)),console.log(_.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(` ${_.dim(m)} ${_.bold(d.id)} ${_.dim(`(${d.source}/${d.intent})`)}`);let h=l.filter(f=>f.event_id===d.id);if(h.length===0){console.log(_.dim(" (no decisions yet)"));continue}for(let f of h){let w=f.outcome==="dispatched"?_.green(f.outcome):f.outcome==="dropped"?_.dim(f.outcome):_.yellow(f.outcome),y=f.agent_id?_.cyan(f.agent_id):_.dim("-"),k=f.reason?_.dim(` \u2014 ${f.reason.slice(0,60)}`):"";if(console.log(` ${_.dim(f.decided_by)} \u2192 ${w} ${y}${k}`),f.resolution_status){let $=f.resolution_status==="ok"?_.green(f.resolution_status):_.red(f.resolution_status),x=f.duration_ms?`${(f.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${_.dim("resolved")} ${$} ${_.dim(x)}`)}else f.outcome==="dispatched"&&console.log(` ${_.yellow("(in-flight, no resolution)")}`)}}console.log()});Fe.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=ht(e),o=Gt(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(`
124
+ `).all(c);if(t.json){let d=i.map(m=>({event:m,decisions:l.filter(p=>p.event_id===m.id)}));console.log(JSON.stringify({project:n,subject:s,lineage:d},null,2));return}let h=new Set;for(let d of l)d.outcome==="dispatched"&&d.agent_id&&h.add(d.agent_id);console.log(),console.log(_.bold(` Lineage for ${_.cyan(n+":"+s)}`)),console.log(_.dim(` ${i.length} event(s), ${l.length} decision(s), ${h.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(` ${_.dim(m)} ${_.bold(d.id)} ${_.dim(`(${d.source}/${d.intent})`)}`);let p=l.filter(f=>f.event_id===d.id);if(p.length===0){console.log(_.dim(" (no decisions yet)"));continue}for(let f of p){let y=f.outcome==="dispatched"?_.green(f.outcome):f.outcome==="dropped"?_.dim(f.outcome):_.yellow(f.outcome),w=f.agent_id?_.cyan(f.agent_id):_.dim("-"),b=f.reason?_.dim(` \u2014 ${f.reason.slice(0,60)}`):"";if(console.log(` ${_.dim(f.decided_by)} \u2192 ${y} ${w}${b}`),f.resolution_status){let $=f.resolution_status==="ok"?_.green(f.resolution_status):_.red(f.resolution_status),S=f.duration_ms?`${(f.duration_ms/1e3).toFixed(1)}s`:"-";console.log(` ${_.dim("resolved")} ${$} ${_.dim(S)}`)}else f.outcome==="dispatched"&&console.log(` ${_.yellow("(in-flight, no resolution)")}`)}}console.log()});Be.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=wt(e),o=Kt(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
125
  SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
126
126
  FROM intent_events
127
127
  ${n.length?"WHERE "+n.join(" AND "):""}
128
128
  ORDER BY ts ASC
129
129
  ${i}
130
- `).all(s).map(f=>({id:f.id,ts:f.ts,source:f.source,sourceEventId:f.source_event_id,project:f.project,subject:f.subject,intent:f.intent,rawJson:f.raw_json}));if(r.length===0){console.log(_.dim(" (no events match filter)"));return}let a=new Set(r.map(f=>f.id)),c=r.map((f,w)=>`@id${w}`).join(", "),l=Object.fromEntries(r.map((f,w)=>[`id${w}`,f.id])),p=t.prepare(`
130
+ `).all(s).map(f=>({id:f.id,ts:f.ts,source:f.source,sourceEventId:f.source_event_id,project:f.project,subject:f.subject,intent:f.intent,rawJson:f.raw_json}));if(r.length===0){console.log(_.dim(" (no events match filter)"));return}let a=new Set(r.map(f=>f.id)),c=r.map((f,y)=>`@id${y}`).join(", "),l=Object.fromEntries(r.map((f,y)=>[`id${y}`,f.id])),h=t.prepare(`
131
131
  SELECT event_id, decided_at, decided_by, agent_id, outcome, reason
132
132
  FROM intent_decisions
133
133
  WHERE event_id IN (${c})
@@ -135,23 +135,23 @@ import{b as pn}from"./chunk-WPPUOTY6.js";import{a as ct,b as mn,e as Jt,i as un}
135
135
  SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary
136
136
  FROM intent_resolutions
137
137
  WHERE decision_event_id IN (${c})
138
- `).all(l).map(f=>({decisionEventId:f.decision_event_id,decisionDecidedBy:f.decision_decided_by,resolvedAt:f.resolved_at,status:f.status,durationMs:f.duration_ms,resultSummary:f.result_summary})),m=Ws(Sn(Fs(),"agentx-ledger-replay-")),h=new Ko({path:Sn(m,"target.sqlite")});try{let f=vn(h,r,p,d);if(e.json){console.log(JSON.stringify(f,null,2));return}console.log(_.bold(`Replayed ${f.eventsCount} events, ${f.decisionsCount} decisions, ${d.length} resolutions`)),f.divergences.length===0?console.log(_.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(_.red(` \u2717 ${f.divergences.length} divergences`)),Qe(f.divergences.map(w=>({event_id:w.eventId,decided_by:w.decidedBy,recorded:`${w.expected.outcome}/${w.expected.agentId??"-"}`,replayed:`${w.actual.outcome}/${w.actual.agentId??"-"}`,reason:w.reason.slice(0,80)})),!1))}finally{h.close()}});import{Command as Js}from"commander";import W from"chalk";import ft from"prompts";var Xe=new Js().name("backlog").description("manage the local backlog used by business workSource=backlog");function Rt(e){let t=P(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new cn(n)}}function zs(e){return e?W.cyan(`${e.type}:${e.project}#${e.iid}`):W.dim("manual")}function Gs(e){return{todo:W.gray("todo"),doing:W.yellow("doing"),blocked:W.red("blocked"),done:W.green("done")}[e]}Xe.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}=Rt(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(W.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?W.magenta(`@${n.assignee}`):W.dim("unassigned");console.log(` ${Gs(n.status).padEnd(7)} ${zs(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(W.dim(` ${n.source.url}`))}console.log(),console.log(W.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});Xe.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=Rt(o.config);n.store.findById(e)||(console.error(W.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:t,status:"doing"});if(console.log(W.green(` claimed: ${i.title} -> ${t}`)),i.source){let r=ln([t],i.source,n.config),a=await po(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(W.dim(" sync:"),...c));console.log(a.ok?W.dim(` synced -> ${a.url??i.source.type}`):W.yellow(` sync failed: ${a.error}`))}});Xe.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=Rt(t.config);o.store.findById(e)||(console.error(W.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(W.green(` done: ${s.title}`)),s.source){let i=await po(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...r)=>console.log(W.dim(" sync:"),...r));console.log(i.ok?W.dim(` synced -> ${i.url??s.source.type}`):W.yellow(` sync failed: ${i.error}`))}});Xe.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}=Rt(t.config);o.remove(e)||(console.error(W.red(` item ${e} not found`)),process.exit(1)),console.log(W.green(` removed ${e}`))});Xe.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=Rt(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(W.red(" no source configured \u2014 set channels.gitlab.token or channels.github.token in agentx.json")),process.exit(1));let s=e.source;if(!s){let y=[o&&{title:"GitLab",value:"gitlab"},n&&{title:"GitHub",value:"github"}].filter(Boolean);if(s=(await ft({type:"select",name:"source",message:"Source",choices:y})).source,!s)return}s==="gitlab"&&!o&&(console.error(W.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(W.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let y=s==="gitlab"?Hs(t.config):Ks(t.config);y.length?(i=(await ft({type:"autocomplete",name:"project",message:"Project (type to filter, or pick + then Enter for custom)",choices:[...y.map($=>({title:$,value:$})),{title:"(custom \u2014 type below)",value:"__CUSTOM__"}]})).project,i==="__CUSTOM__"&&(i=(await ft({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await ft({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await ft({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(W.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await Vs(t.config,i,a):await Qs(t.config,i,a);if(!c.length){console.log(W.yellow(" no open issues matched"));return}console.log(W.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,p=new Set(t.store.list().map(y=>y.id)),d=c.map(y=>{let k=mo({type:s,project:l,iid:y.iid,url:y.url}),$=p.has(k),x=y.labels.length?` [${y.labels.slice(0,3).join(",")}]`:"";return{title:`#${y.iid} ${y.title}${x}${$?W.dim(" (already imported)"):""}`,value:y,disabled:$}}),h=(await ft({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!h.length){console.log(W.dim(" nothing selected"));return}let f=h.map(y=>{let k={type:s,host:s==="gitlab"?Ys(t.config):void 0,project:l,iid:y.iid,url:y.url};return{id:mo(k),title:y.title,description:y.description,assignee:e.assignee||y.assignee,labels:y.labels,milestone:y.milestone,status:"todo",source:k,importedAt:new Date().toISOString()}}),w=t.store.addMany(f);console.log(W.green(` imported ${w.length} item${w.length===1?"":"s"}`));for(let y of w)console.log(W.dim(` ${y.id} \u2014 ${y.title}`))});function Ys(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Hs(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 Ks(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 Vs(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 Qs(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(jn)}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(jn):[]}function jn(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 ei}from"commander";import N from"chalk";import{existsSync as ti,readFileSync as oi}from"fs";import{resolve as ni}from"path";import si from"prompts";import Xs from"cronstrue";var bo={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},Yt={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 Ce(e){try{return Xs.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function Zs(e){if(/\b(noon|midday)\b/.test(e))return Yt.noon;if(/\bmidnight\b/.test(e))return Yt.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 ko(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:Ce(`*/${d} * * * *`),matched:o[0]}}if(/\bevery\s+minute\b/.test(t))return{cron:"* * * * *",human:Ce("* * * * *"),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:Ce(`0 */${d} * * *`),matched:o[0]}}if(/\b(every hour|hourly)\b/.test(t))return{cron:"0 * * * *",human:Ce("0 * * * *"),matched:"every hour"};let n=Zs(t),s=null;for(let[d,m]of Object.entries(Yt))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 h=i||{h:9,m:0},f=`${h.m} ${h.h} ${m} * *`;return{cron:f,human:Ce(f),matched:r[0]}}let a=[],c=Object.keys(bo).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(bo))if(new RegExp(`\\b${m}s?\\b`).test(d)){let h=bo[m];a.includes(h)||a.push(h)}}if(a.length){let d=i||{h:9,m:0};a.sort((f,w)=>f-w);let m=a.join(","),h=`${d.m} ${d.h} * * ${m}`;return{cron:h,human:Ce(h),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:Ce(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:Ce(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:Ce(m),matched:s&&Object.entries(Yt).find(([,h])=>h===s)?.[0]||"daily"}}if(n){let d=`${n.m} ${n.h} * * *`;return{cron:d,human:Ce(d),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function Cn(e,t){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${t}`}function En(e){let t=e||ni(process.cwd(),"agentx.json");return ti(t)||(console.log(N.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(oi(t,"utf-8"))}function ii(e){return e?e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t==="log"||t==="notify"||t==="disable"):["log"]}async function ri(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(N.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await si([{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(N.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Be=new ei().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Be.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){Be.help();return}t.agent||(console.log(N.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(N.red(' --do "<prompt>" is required')),process.exit(1));let o=ko(e);o||(console.log(N.red(` Couldn't parse: "${e}"`)),console.log(N.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(N.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(N.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=En(t.config),s=Qo(n);n.agents?.[t.agent]||(console.log(N.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(N.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=ii(t.onError),r=await ri(t.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=t.id||Cn(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 re(d=>Q(d,`crons.${a}`,c),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(N.red(` \u2717 ${l.error}`)),process.exit(1));let p=t.dryRun?"would add":"Added";console.log(N.green(` \u2713 ${p} cron ${N.cyan(a)}`)),console.log(N.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(N.dim(` Agent: ${t.agent}`)),r&&console.log(N.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(N.dim(` On error: ${i.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(N.dim(" Daemon hot-reloaded."))});Be.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=En(e.config).crons||{},n=Object.entries(o);if(!n.length){console.log(N.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?N.green("\u25CF"):N.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${N.cyan(s.padEnd(32))} ${N.dim(i.schedule.padEnd(14))} ${N.dim("\u2192")} ${i.agent}`),console.log(N.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(N.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,t]of[["on",!0],["off",!1]])Be.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await re(s=>{if(!Ye(s,`crons.${o}`))throw new Error(`cron "${o}" not found`);Q(s,`crons.${o}.enabled`,t)});n.success||(console.log(N.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(N.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(N.dim(" Daemon hot-reloaded."))});Be.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await re(o=>{if(!Ye(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);Zo(o,`crons.${e}`)});t.success||(console.log(N.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(N.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(N.dim(" Daemon hot-reloaded."))});Be.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=ko(t);o||(console.log(N.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(N.green(` "${t}"`)),console.log(N.dim(` \u2192 ${o.cron}`)),console.log(N.dim(` \u2192 ${o.human}`))});import{Command as Di}from"commander";import et from"chalk";import U from"chalk";import Dt from"prompts";import{readFileSync as ai,writeFileSync as ci,existsSync as li}from"fs";import{resolve as An}from"path";var di=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function gi(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function vo(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function In(e=".env"){let t=An(e);if(!li(t))return[];let o=ai(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(di);i?n.push({kind:"kv",key:i[1],value:gi(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function mi(e){return e.map(t=>t.kind==="kv"?`${t.key}=${vo(t.value)}`:t.raw).join(`
138
+ `).all(l).map(f=>({decisionEventId:f.decision_event_id,decisionDecidedBy:f.decision_decided_by,resolvedAt:f.resolved_at,status:f.status,durationMs:f.duration_ms,resultSummary:f.result_summary})),m=Js(On(zs(),"agentx-ledger-replay-")),p=new Xo({path:On(m,"target.sqlite")});try{let f=En(p,r,h,d);if(e.json){console.log(JSON.stringify(f,null,2));return}console.log(_.bold(`Replayed ${f.eventsCount} events, ${f.decisionsCount} decisions, ${d.length} resolutions`)),f.divergences.length===0?console.log(_.green(" \u2713 0 divergences \u2014 ledger mechanics are deterministic on this snapshot")):(console.log(_.red(` \u2717 ${f.divergences.length} divergences`)),Xe(f.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{p.close()}});import{Command as Ks}from"commander";import W from"chalk";import $t from"prompts";var Ze=new Ks().name("backlog").description("manage the local backlog used by business workSource=backlog");function _t(e){let t=P(e),o=t.business?.workSource,n=o?.type==="backlog"?o.path:".agentx/backlog.md";return{config:t,storePath:n,store:new pn(n)}}function Vs(e){return e?W.cyan(`${e.type}:${e.project}#${e.iid}`):W.dim("manual")}function Qs(e){return{todo:W.gray("todo"),doing:W.yellow("doing"),blocked:W.red("blocked"),done:W.green("done")}[e]}Ze.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}=_t(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(W.dim(" (no items)"));return}console.log();for(let n of o){let s=n.assignee?W.magenta(`@${n.assignee}`):W.dim("unassigned");console.log(` ${Qs(n.status).padEnd(7)} ${Vs(n.source)} ${s} ${n.title}`),n.source?.url&&console.log(W.dim(` ${n.source.url}`))}console.log(),console.log(W.dim(` ${o.length} item${o.length===1?"":"s"} \u2014 ${t.jsonPath()}`))});Ze.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=_t(o.config);n.store.findById(e)||(console.error(W.red(` item ${e} not found`)),process.exit(1));let i=n.store.update(e,{assignee:t,status:"doing"});if(console.log(W.green(` claimed: ${i.title} -> ${t}`)),i.source){let r=un([t],i.source,n.config),a=await fo(i,{assigneeUsernames:r,addLabels:["Doing"],removeLabels:["To Do"]},n.config,(...c)=>console.log(W.dim(" sync:"),...c));console.log(a.ok?W.dim(` synced -> ${a.url??i.source.type}`):W.yellow(` sync failed: ${a.error}`))}});Ze.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=_t(t.config);o.store.findById(e)||(console.error(W.red(` item ${e} not found`)),process.exit(1));let s=o.store.update(e,{status:"done"});if(console.log(W.green(` done: ${s.title}`)),s.source){let i=await fo(s,{addLabels:["Done"],removeLabels:["Doing"],state:t.close?"closed":void 0,note:t.note},o.config,(...r)=>console.log(W.dim(" sync:"),...r));console.log(i.ok?W.dim(` synced -> ${i.url??s.source.type}`):W.yellow(` sync failed: ${i.error}`))}});Ze.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}=_t(t.config);o.remove(e)||(console.error(W.red(` item ${e} not found`)),process.exit(1)),console.log(W.green(` removed ${e}`))});Ze.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=_t(e.config),o=!!t.config.channels.gitlab?.token,n=!!t.config.channels.github?.token;!o&&!n&&(console.error(W.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 $t({type:"select",name:"source",message:"Source",choices:w})).source,!s)return}s==="gitlab"&&!o&&(console.error(W.red(" channels.gitlab.token not configured")),process.exit(1)),s==="github"&&!n&&(console.error(W.red(" channels.github.token not configured")),process.exit(1));let i=e.project;if(!i){let w=s==="gitlab"?Zs(t.config):ei(t.config);w.length?(i=(await $t({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 $t({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p)):i=(await $t({type:"text",name:"p",message:s==="gitlab"?"Group/path":"owner/repo"})).p}if(!i)return;let a=((await $t({type:"text",name:"search",message:"Search filter (optional \u2014 leave empty for all open)"})).search||"").trim();console.log(W.dim(` fetching open issues from ${s}:${i}${a?` (search: ${a})`:""}\u2026`));let c=s==="gitlab"?await ti(t.config,i,a):await oi(t.config,i,a);if(!c.length){console.log(W.yellow(" no open issues matched"));return}console.log(W.dim(` ${c.length} open issue${c.length===1?"":"s"}`));let l=i,h=new Set(t.store.list().map(w=>w.id)),d=c.map(w=>{let b=ho({type:s,project:l,iid:w.iid,url:w.url}),$=h.has(b),S=w.labels.length?` [${w.labels.slice(0,3).join(",")}]`:"";return{title:`#${w.iid} ${w.title}${S}${$?W.dim(" (already imported)"):""}`,value:w,disabled:$}}),p=(await $t({type:"autocompleteMultiselect",name:"selected",message:"Pick issues to import (space to toggle, Enter to confirm)",instructions:!1,choices:d,min:1})).selected||[];if(!p.length){console.log(W.dim(" nothing selected"));return}let f=p.map(w=>{let b={type:s,host:s==="gitlab"?Xs(t.config):void 0,project:l,iid:w.iid,url:w.url};return{id:ho(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(f);console.log(W.green(` imported ${y.length} item${y.length===1?"":"s"}`));for(let w of y)console.log(W.dim(` ${w.id} \u2014 ${w.title}`))});function Xs(e){let t=e.channels.gitlab?.host;if(t)return t.replace(/^https?:\/\//,"").replace(/\/+$/,"")}function Zs(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 ei(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 ti(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(In)}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(In):[]}function In(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 ii}from"commander";import N from"chalk";import{existsSync as ri,readFileSync as ai}from"fs";import{resolve as ci}from"path";import li from"prompts";import ni from"cronstrue";var xo={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},Vt={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 Ee(e){try{return ni.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function si(e){if(/\b(noon|midday)\b/.test(e))return Vt.noon;if(/\bmidnight\b/.test(e))return Vt.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 So(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:Ee(`*/${d} * * * *`),matched:o[0]}}if(/\bevery\s+minute\b/.test(t))return{cron:"* * * * *",human:Ee("* * * * *"),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:Ee(`0 */${d} * * *`),matched:o[0]}}if(/\b(every hour|hourly)\b/.test(t))return{cron:"0 * * * *",human:Ee("0 * * * *"),matched:"every hour"};let n=si(t),s=null;for(let[d,m]of Object.entries(Vt))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 p=i||{h:9,m:0},f=`${p.m} ${p.h} ${m} * *`;return{cron:f,human:Ee(f),matched:r[0]}}let a=[],c=Object.keys(xo).join("|"),l=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${c})s?(?:\\s*(?:,|and|&)\\s*(?:${c})s?)*)\\b`),h=t.match(l);if(h){let d=h[1];for(let m of Object.keys(xo))if(new RegExp(`\\b${m}s?\\b`).test(d)){let p=xo[m];a.includes(p)||a.push(p)}}if(a.length){let d=i||{h:9,m:0};a.sort((f,y)=>f-y);let m=a.join(","),p=`${d.m} ${d.h} * * ${m}`;return{cron:p,human:Ee(p),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:Ee(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:Ee(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:Ee(m),matched:s&&Object.entries(Vt).find(([,p])=>p===s)?.[0]||"daily"}}if(n){let d=`${n.m} ${n.h} * * *`;return{cron:d,human:Ee(d),matched:`at ${n.h}:${String(n.m).padStart(2,"0")}`}}return null}function Rn(e,t){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${t}`}function Dn(e){let t=e||ci(process.cwd(),"agentx.json");return ri(t)||(console.log(N.red(` No config at ${t}. Run: agentx init`)),process.exit(1)),JSON.parse(ai(t,"utf-8"))}function di(e){return e?e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t==="log"||t==="notify"||t==="disable"):["log"]}async function gi(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(N.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:i,accountId:r}=await li([{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(N.red(` Unrecognized --notify value: ${e} (use "me" or "channel:chatId[:account]")`))}var Ue=new ii().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Ue.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){Ue.help();return}t.agent||(console.log(N.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!t.do&&!t.id&&(console.log(N.red(' --do "<prompt>" is required')),process.exit(1));let o=So(e);o||(console.log(N.red(` Couldn't parse: "${e}"`)),console.log(N.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(N.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(N.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let n=Dn(t.config),s=en(n);n.agents?.[t.agent]||(console.log(N.red(` Agent "${t.agent}" not found in agentx.json`)),console.log(N.dim(` Available: ${Object.keys(n.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let i=di(t.onError),r=await gi(t.notify,s);r&&!i.includes("notify")&&i.push("notify");let a=t.id||Rn(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 ae(d=>X(d,`crons.${a}`,c),{configPath:t.config,dryRun:!!t.dryRun});l.success||(console.log(N.red(` \u2717 ${l.error}`)),process.exit(1));let h=t.dryRun?"would add":"Added";console.log(N.green(` \u2713 ${h} cron ${N.cyan(a)}`)),console.log(N.dim(` Schedule: ${o.cron} (${o.human}, ${t.timezone})`)),console.log(N.dim(` Agent: ${t.agent}`)),r&&console.log(N.dim(` Notify: ${r.channel} ${r.chatId}`)),i.length&&console.log(N.dim(` On error: ${i.join(", ")}`)),!t.dryRun&&l.reloaded&&console.log(N.dim(" Daemon hot-reloaded."))});Ue.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=Dn(e.config).crons||{},n=Object.entries(o);if(!n.length){console.log(N.dim(" No scheduled jobs"));return}console.log();for(let[s,i]of n){let r=i.enabled?N.green("\u25CF"):N.dim("\u25CB"),a=i.schedule;try{a=(await import("cronstrue")).default.toString(i.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${N.cyan(s.padEnd(32))} ${N.dim(i.schedule.padEnd(14))} ${N.dim("\u2192")} ${i.agent}`),console.log(N.dim(` ${a} (${i.timezone||"UTC"})`)),i.notify&&console.log(N.dim(` notify: ${i.notify.channel} ${i.notify.chatId}`))}console.log()});for(let[e,t]of[["on",!0],["off",!1]])Ue.command(`${e} <id>`).description(`${t?"enable":"disable"} a scheduled job`).action(async o=>{let n=await ae(s=>{if(!He(s,`crons.${o}`))throw new Error(`cron "${o}" not found`);X(s,`crons.${o}.enabled`,t)});n.success||(console.log(N.red(` \u2717 ${n.error}`)),process.exit(1)),console.log(N.green(` \u2713 ${o} ${t?"enabled":"disabled"}`)),n.reloaded&&console.log(N.dim(" Daemon hot-reloaded."))});Ue.command("remove <id>").alias("rm").description("remove a scheduled job").action(async e=>{let t=await ae(o=>{if(!He(o,`crons.${e}`))throw new Error(`cron "${e}" not found`);on(o,`crons.${e}`)});t.success||(console.log(N.red(` \u2717 ${t.error}`)),process.exit(1)),console.log(N.green(` \u2713 ${e} removed`)),t.reloaded&&console.log(N.dim(" Daemon hot-reloaded."))});Ue.command("parse <when...>").description("preview a natural-language parse without writing anything").action(e=>{let t=e.join(" "),o=So(t);o||(console.log(N.red(` \u2717 could not parse: "${t}"`)),process.exit(1)),console.log(N.green(` "${t}"`)),console.log(N.dim(` \u2192 ${o.cron}`)),console.log(N.dim(` \u2192 ${o.human}`))});import{Command as Mi}from"commander";import tt from"chalk";import q from"chalk";import Pt from"prompts";import{readFileSync as mi,writeFileSync as pi,existsSync as ui}from"fs";import{resolve as Tn}from"path";var hi=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function fi(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function jo(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function _n(e=".env"){let t=Tn(e);if(!ui(t))return[];let o=mi(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(hi);i?n.push({kind:"kv",key:i[1],value:fi(i[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function yi(e){return e.map(t=>t.kind==="kv"?`${t.key}=${jo(t.value)}`:t.raw).join(`
139
139
  `)+`
140
- `}function Ze(e,t,o=".env"){let n=An(o),s=In(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${vo(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${vo(t)}`})),ci(n,mi(s))}function xo(e,t=".env"){return In(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var On="https://t.me/BotFather";async function pi(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 ui(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 Rn(e={}){console.log(),console.log(U.bold(" Connect Telegram")),console.log(),console.log(U.dim(` 1. Open ${On}`)),console.log(U.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(U.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await Dt({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(t)try{let{spawn:$}=await import("child_process"),x=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";$(x,[On],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await Dt({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(U.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await pi(o.trim());n||(console.log(U.red("\u2717 invalid or revoked")),process.exit(1)),console.log(U.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(U.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(U.red(" No agents configured. Run: agentx agent add")),process.exit(1));let p=e.agent;p||(p=(await Dt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(x=>({title:x,value:x})),initial:0})).agent),p||(console.log(U.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},m=e.account||p;d[m]&&d[m].agentBinding!==p&&(m=(await Dt({type:"text",name:"account",message:`Account "${m}" is already in use. Pick a different label:`,initial:`${p}-2`,validate:x=>/^[a-z0-9-]+$/i.test(x)||"lowercase letters, digits, hyphens only"})).account),m||(console.log(U.red(" Aborted")),process.exit(1));let h=`TG_${m.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Ze(h,o.trim()),process.env[h]=o.trim();let f=await re($=>{Q($,"channels.telegram.enabled",!0),Q($,`channels.telegram.accounts.${m}`,{token:`\${${h}}`,agentBinding:p});let x=Ye($,`agents.${p}.mentions`)||[],v=`@${n.username}`;x.includes(v)||(x.push(v),Q($,`agents.${p}.mentions`,x))},{configPath:e.configPath});if(f.success||(console.log(U.red(` \u2717 ${f.error}`)),process.exit(1)),console.log(),console.log(U.green(` \u2713 Bot @${n.username} bound to agent "${p}"`)),console.log(U.dim(` Token stored in .env as ${h}`)),console.log(U.dim(` Mentions updated to include @${n.username}`)),f.reloaded?console.log(U.dim(" Daemon hot-reloaded.")):console.log(U.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:w}=await Dt({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!w)return;console.log(),console.log(U.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(U.dim(" Waiting up to 90s..."));let y=await ui(o.trim(),9e4);if(!y){console.log(U.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(U.dim(" agentx config set notifications.destination.channel telegram")),console.log(U.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(U.dim(` agentx config set notifications.destination.accountId ${m}`));return}let k=await re($=>{Q($,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:m})},{configPath:e.configPath});if(!k.success){console.log(U.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(U.green(" \u2713 Default --notify target set")),console.log(U.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(U.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(U.dim(" Daemon hot-reloaded."))}import K from"chalk";import Ht from"prompts";import{spawn as hi}from"child_process";var Dn="https://discord.com/developers/applications",fi="67584";async function yi(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 Tn(e){try{let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";hi(t,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}async function _n(e={}){console.log(),console.log(K.bold(" Connect Discord")),console.log(),console.log(K.dim(" 1. Open the Discord Developer Portal")),console.log(K.dim(` ${Dn}`)),console.log(K.dim(" 2. New Application \u2192 Bot \u2192 Reset Token \u2192 copy the token")),console.log(K.dim(" 3. Under Bot \u2192 Privileged Gateway Intents,")),console.log(K.dim(" enable 'MESSAGE CONTENT INTENT'")),console.log();let{openBrowser:t}=await Ht({type:"confirm",name:"openBrowser",message:"Open the Developer Portal in your browser?",initial:!0});t&&Tn(Dn);let{token:o}=await Ht({type:"password",name:"token",message:"Paste the bot token:",validate:y=>y.trim().length>20||"that looks too short for a Discord token"});o||(console.log(K.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await yi(o.trim());n||(console.log(K.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(K.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(K.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(K.red(" No agents configured. Run: agentx agent add")),process.exit(1));let d=e.agent;d||(d=(await Ht({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:p.map(k=>({title:k,value:k})),initial:0})).agent),d||(console.log(K.red(" Aborted")),process.exit(1));let m="DISCORD_BOT_TOKEN";Ze(m,o.trim()),process.env[m]=o.trim();let h=await re(y=>{Q(y,"channels.discord.enabled",!0),Q(y,"channels.discord.token",`\${${m}}`),Q(y,"channels.discord.agentBinding",d)},{configPath:e.configPath});h.success||(console.log(K.red(` \u2717 ${h.error}`)),process.exit(1)),console.log(),console.log(K.green(` \u2713 Discord bot ${s} bound to agent "${d}"`)),console.log(K.dim(` Token stored in .env as ${m}`)),h.reloaded?console.log(K.dim(" Daemon hot-reloaded.")):console.log(K.dim(" Restart the daemon to start Discord polling.")),console.log(),console.log(K.bold(" Install the bot to a server")),console.log();let f=`https://discord.com/oauth2/authorize?client_id=${n.id}&scope=bot&permissions=${fi}`;console.log(` ${K.cyan(f)}`),console.log();let{openInstall:w}=await Ht({type:"confirm",name:"openInstall",message:"Open the install URL in your browser now?",initial:!0});w&&Tn(f),console.log(),console.log(K.dim(" After you pick a server, the bot will come online on the next daemon restart.")),console.log(K.dim(" Mention the bot in any channel to route messages to the agent."))}import Y from"chalk";import So from"prompts";import{existsSync as Co,mkdirSync as wi,readdirSync as $i,readFileSync as Pn}from"fs";import{resolve as jo}from"path";var bi=".agentx/whatsapp-sessions";function ki(){let e=jo(process.cwd(),".agentx/daemon.pid");if(!Co(e))return!1;try{let t=parseInt(Pn(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function vi(e){if(!Co(e))return!1;try{return $i(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function xi(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Y.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Y.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;wi(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(Y.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}p(!1)},12e4);l.ev.on("connection.update",async h=>{if(h.qr){t(Y.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:f}=await import("qrcode-terminal");f.generate(h.qr,{small:!0})}catch{t(` QR: ${h.qr}`)}t("")}if(h.connection==="open"){clearTimeout(m),t(Y.green(" \u2713 Paired"));try{l.end(void 0)}catch{}p(!0)}h.connection==="close"&&!h.qr&&h.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(m),t(Y.red(" \u2717 Authorization failed \u2014 rescan required")),p(!1))})})}async function Nn(e={}){if(console.log(),console.log(Y.bold(" Connect WhatsApp")),console.log(),ki()){console.log(Y.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Y.dim(" agentx daemon stop")),console.log();let{cont:l}=await So({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Y.red(" Aborted")),process.exit(1))}let t=e.configPath||jo(process.cwd(),"agentx.json");Co(t)||(console.log(Y.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Pn(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||bi,s=jo(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log(Y.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await So({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(p=>({title:p,value:p})),initial:0})).agent),r||(console.log(Y.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(vi(s)&&a){let{keep:l}=await So({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(Y.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await xi(s,p=>console.log(p))||(console.log(Y.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await re(l=>{Q(l,"channels.whatsapp.enabled",!0),Q(l,"channels.whatsapp.sessionDir",n),Q(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(Y.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Y.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(Y.dim(` Session: ${n}`)),console.log(Y.dim(" Start the daemon to begin receiving:")),console.log(Y.dim(" agentx daemon start")),console.log(Y.dim(" Add routes later with:")),console.log(Y.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Si}from"crypto";import Z from"chalk";import Mn from"prompts";var Kt="agentx-mesh:",Vt="//join/";function ji(e){return Buffer.from(e,"utf-8").toString("base64url")}function Ci(e){return Buffer.from(e,"base64url").toString("utf-8")}function Ei(e){return`${Kt}${Vt}${ji(JSON.stringify(e))}`}function Ai(e){if(!e.startsWith(`${Kt}${Vt}`))throw new Error(`Not a mesh invite link \u2014 expected ${Kt}${Vt}\u2026`);let t=e.slice(Kt.length+Vt.length),o=JSON.parse(Ci(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 Ii(){return Si(32).toString("hex")}function Oi(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function Ri(e){return e?.node?.name||e?.node?.id||"node"}async function Ln(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(Z.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=xo("MESH_TOKEN");r||(r=Ii(),Ze("MESH_TOKEN",r),console.log(Z.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Oi(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Mn({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(Z.red(" Aborted")),process.exit(1)),a=d}let l=await re(d=>{Q(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Z.red(` \u2717 ${l.error}`)),process.exit(1));let p=Ei({url:a,token:r,name:Ri(i),version:1});console.log(),console.log(Z.bold(" Mesh invite")),console.log(),console.log(` ${Z.cyan(p)}`),console.log(),console.log(Z.dim(" Run on the other node:")),console.log(Z.dim(` agentx connect mesh join "${p}"`)),console.log(),console.log(Z.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Wn(e,t={}){let o;try{o=Ai(e)}catch(i){console.log(Z.red(` \u2717 ${i.message}`)),process.exit(1)}let n=xo("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await Mn({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(Z.red(" Aborted (keeping existing .env)")),process.exit(1))}Ze("MESH_TOKEN",o.token);let s=await re(i=>{Q(i,"mesh.enabled",!0);let r=Ye(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),Q(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(Z.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Z.green(" \u2713 Joined mesh")),console.log(Z.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Z.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Z.dim(" Daemon hot-reloaded.")):console.log(Z.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(Z.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Z.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(Z.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var tt=new Di().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");tt.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 Rn({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});tt.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 _n({agent:e.agent,configPath:e.config})});tt.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 Nn({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var Fn=tt.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Fn.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 Ln({url:e.url,configPath:e.config})});Fn.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 Wn(e,{configPath:t.config})});tt.action(()=>{console.log(),console.log(et.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${et.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${et.cyan("agentx connect discord")} \u2014 pair a Discord bot, emit install URL`),console.log(` ${et.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${et.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${et.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(et.dim(" GitLab connect is the next slice.")),console.log()});import{Command as Ti}from"commander";import he from"chalk";var Qt=new Ti().name("usage").description("token usage analysis and reporting");Qt.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=P(),[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(he.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(he.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${he.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: ${he.red(String(s.totalErrors))}`),console.log(),console.log(he.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(` ${he.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${he.dim(p)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(he.red(" Daemon not running. Start with: agentx daemon start")):console.log(he.red(` ${e.message}`))}});Qt.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(he.red(` Script not found: ${s}`)),console.log(he.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(he.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(he.red(" Analysis failed. Is Python 3 installed?"))}});import{Command as _i}from"commander";import H from"chalk";var Ue=new _i().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ue.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=Pi(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-HXDOYGIG.js");o(t)}catch(t){console.log(H.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(H.dim(t.stack)),process.exit(1)}});function Pi(e,t){try{let o=P();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(H.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(H.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
141
- `)),{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}}}}Ue.command("list").description("list configured boards").action(()=>{try{let e=P();if(!e.boards?.length){console.log(H.dim(`
140
+ `}function et(e,t,o=".env"){let n=Tn(o),s=_n(n),i=s.findIndex(r=>r.kind==="kv"&&r.key===e);i>=0?s[i]={kind:"kv",key:e,value:t,raw:`${e}=${jo(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${jo(t)}`})),pi(n,yi(s))}function Co(e,t=".env"){return _n(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var Pn="https://t.me/BotFather";async function wi(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 $i(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 Nn(e={}){console.log(),console.log(q.bold(" Connect Telegram")),console.log(),console.log(q.dim(` 1. Open ${Pn}`)),console.log(q.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(q.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:t}=await Pt({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,[Pn],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:o}=await Pt({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(q.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await wi(o.trim());n||(console.log(q.red("\u2717 invalid or revoked")),process.exit(1)),console.log(q.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(q.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(q.red(" No agents configured. Run: agentx agent add")),process.exit(1));let h=e.agent;h||(h=(await Pt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(S=>({title:S,value:S})),initial:0})).agent),h||(console.log(q.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},m=e.account||h;d[m]&&d[m].agentBinding!==h&&(m=(await Pt({type:"text",name:"account",message:`Account "${m}" is already in use. Pick a different label:`,initial:`${h}-2`,validate:S=>/^[a-z0-9-]+$/i.test(S)||"lowercase letters, digits, hyphens only"})).account),m||(console.log(q.red(" Aborted")),process.exit(1));let p=`TG_${m.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;et(p,o.trim()),process.env[p]=o.trim();let f=await ae($=>{X($,"channels.telegram.enabled",!0),X($,`channels.telegram.accounts.${m}`,{token:`\${${p}}`,agentBinding:h});let S=He($,`agents.${h}.mentions`)||[],v=`@${n.username}`;S.includes(v)||(S.push(v),X($,`agents.${h}.mentions`,S))},{configPath:e.configPath});if(f.success||(console.log(q.red(` \u2717 ${f.error}`)),process.exit(1)),console.log(),console.log(q.green(` \u2713 Bot @${n.username} bound to agent "${h}"`)),console.log(q.dim(` Token stored in .env as ${p}`)),console.log(q.dim(` Mentions updated to include @${n.username}`)),f.reloaded?console.log(q.dim(" Daemon hot-reloaded.")):console.log(q.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:y}=await Pt({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(q.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(q.dim(" Waiting up to 90s..."));let w=await $i(o.trim(),9e4);if(!w){console.log(q.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(q.dim(" agentx config set notifications.destination.channel telegram")),console.log(q.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(q.dim(` agentx config set notifications.destination.accountId ${m}`));return}let b=await ae($=>{X($,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:m})},{configPath:e.configPath});if(!b.success){console.log(q.red(` \u2717 failed to save destination: ${b.error}`));return}console.log(q.green(" \u2713 Default --notify target set")),console.log(q.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(q.dim(" From now on, --notify me resolves to this chat.")),b.reloaded&&console.log(q.dim(" Daemon hot-reloaded."))}import V from"chalk";import Qt from"prompts";import{spawn as bi}from"child_process";var Mn="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 Ln(e){try{let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";bi(t,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}async function Wn(e={}){console.log(),console.log(V.bold(" Connect Discord")),console.log(),console.log(V.dim(" 1. Open the Discord Developer Portal")),console.log(V.dim(` ${Mn}`)),console.log(V.dim(" 2. New Application \u2192 Bot \u2192 Reset Token \u2192 copy the token")),console.log(V.dim(" 3. Under Bot \u2192 Privileged Gateway Intents,")),console.log(V.dim(" enable 'MESSAGE CONTENT INTENT'")),console.log();let{openBrowser:t}=await Qt({type:"confirm",name:"openBrowser",message:"Open the Developer Portal in your browser?",initial:!0});t&&Ln(Mn);let{token:o}=await Qt({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(V.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await vi(o.trim());n||(console.log(V.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(V.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(V.red(` No agentx.json at ${c}. Run: agentx init`)),process.exit(1));let l=JSON.parse(i(c,"utf-8")),h=Object.keys(l.agents||{});h.length===0&&(console.log(V.red(" No agents configured. Run: agentx agent add")),process.exit(1));let d=e.agent;d||(d=(await Qt({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:h.map(b=>({title:b,value:b})),initial:0})).agent),d||(console.log(V.red(" Aborted")),process.exit(1));let m="DISCORD_BOT_TOKEN";et(m,o.trim()),process.env[m]=o.trim();let p=await ae(w=>{X(w,"channels.discord.enabled",!0),X(w,"channels.discord.token",`\${${m}}`),X(w,"channels.discord.agentBinding",d)},{configPath:e.configPath});p.success||(console.log(V.red(` \u2717 ${p.error}`)),process.exit(1)),console.log(),console.log(V.green(` \u2713 Discord bot ${s} bound to agent "${d}"`)),console.log(V.dim(` Token stored in .env as ${m}`)),p.reloaded?console.log(V.dim(" Daemon hot-reloaded.")):console.log(V.dim(" Restart the daemon to start Discord polling.")),console.log(),console.log(V.bold(" Install the bot to a server")),console.log();let f=`https://discord.com/oauth2/authorize?client_id=${n.id}&scope=bot&permissions=${ki}`;console.log(` ${V.cyan(f)}`),console.log();let{openInstall:y}=await Qt({type:"confirm",name:"openInstall",message:"Open the install URL in your browser now?",initial:!0});y&&Ln(f),console.log(),console.log(V.dim(" After you pick a server, the bot will come online on the next daemon restart.")),console.log(V.dim(" Mention the bot in any channel to route messages to the agent."))}import H from"chalk";import Eo from"prompts";import{existsSync as Oo,mkdirSync as xi,readdirSync as Si,readFileSync as Fn}from"fs";import{resolve as Ao}from"path";var ji=".agentx/whatsapp-sessions";function Ci(){let e=Ao(process.cwd(),".agentx/daemon.pid");if(!Oo(e))return!1;try{let t=parseInt(Fn(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function Ei(e){if(!Oo(e))return!1;try{return Si(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function Ai(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(H.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(H.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;xi(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(h=>{let m=setTimeout(()=>{t(H.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}h(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(H.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:f}=await import("qrcode-terminal");f.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(m),t(H.green(" \u2713 Paired"));try{l.end(void 0)}catch{}h(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(m),t(H.red(" \u2717 Authorization failed \u2014 rescan required")),h(!1))})})}async function Bn(e={}){if(console.log(),console.log(H.bold(" Connect WhatsApp")),console.log(),Ci()){console.log(H.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(H.dim(" agentx daemon stop")),console.log();let{cont:l}=await Eo({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(H.red(" Aborted")),process.exit(1))}let t=e.configPath||Ao(process.cwd(),"agentx.json");Oo(t)||(console.log(H.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(Fn(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||ji,s=Ao(process.cwd(),n),i=Object.keys(o.agents||{});i.length===0&&(console.log(H.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=e.agent;r||(r=(await Eo({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:i.map(h=>({title:h,value:h})),initial:0})).agent),r||(console.log(H.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Ei(s)&&a){let{keep:l}=await Eo({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(H.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Ai(s,h=>console.log(h))||(console.log(H.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ae(l=>{X(l,"channels.whatsapp.enabled",!0),X(l,"channels.whatsapp.sessionDir",n),X(l,"channels.whatsapp.defaultAgent",r)},{configPath:e.configPath});c.success||(console.log(H.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(H.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(H.dim(` Session: ${n}`)),console.log(H.dim(" Start the daemon to begin receiving:")),console.log(H.dim(" agentx daemon start")),console.log(H.dim(" Add routes later with:")),console.log(H.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Oi}from"crypto";import ee from"chalk";import Un from"prompts";var Xt="agentx-mesh:",Zt="//join/";function Ii(e){return Buffer.from(e,"utf-8").toString("base64url")}function Ri(e){return Buffer.from(e,"base64url").toString("utf-8")}function Di(e){return`${Xt}${Zt}${Ii(JSON.stringify(e))}`}function Ti(e){if(!e.startsWith(`${Xt}${Zt}`))throw new Error(`Not a mesh invite link \u2014 expected ${Xt}${Zt}\u2026`);let t=e.slice(Xt.length+Zt.length),o=JSON.parse(Ri(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 _i(){return Oi(32).toString("hex")}function Pi(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function Ni(e){return e?.node?.name||e?.node?.id||"node"}async function qn(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(ee.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let i=JSON.parse(t(s,"utf-8")),r=Co("MESH_TOKEN");r||(r=_i(),et("MESH_TOKEN",r),console.log(ee.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Pi(i);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await Un({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(ee.red(" Aborted")),process.exit(1)),a=d}let l=await ae(d=>{X(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(ee.red(` \u2717 ${l.error}`)),process.exit(1));let h=Di({url:a,token:r,name:Ni(i),version:1});console.log(),console.log(ee.bold(" Mesh invite")),console.log(),console.log(` ${ee.cyan(h)}`),console.log(),console.log(ee.dim(" Run on the other node:")),console.log(ee.dim(` agentx connect mesh join "${h}"`)),console.log(),console.log(ee.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Jn(e,t={}){let o;try{o=Ti(e)}catch(i){console.log(ee.red(` \u2717 ${i.message}`)),process.exit(1)}let n=Co("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:i}=await Un({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});i||(console.log(ee.red(" Aborted (keeping existing .env)")),process.exit(1))}et("MESH_TOKEN",o.token);let s=await ae(i=>{X(i,"mesh.enabled",!0);let r=He(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),X(i,"mesh.peers",r)},{configPath:t.configPath});s.success||(console.log(ee.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(ee.green(" \u2713 Joined mesh")),console.log(ee.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(ee.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(ee.dim(" Daemon hot-reloaded.")):console.log(ee.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let i=await fetch(`${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(ee.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(ee.yellow(` Peer returned HTTP ${i.status} \u2014 double-check the URL`))}catch(i){console.log(ee.yellow(` Could not reach ${o.url} right now (${i?.cause?.code||i.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var ot=new Mi().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");ot.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 Nn({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});ot.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 Wn({agent:e.agent,configPath:e.config})});ot.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 Bn({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var zn=ot.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");zn.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 qn({url:e.url,configPath:e.config})});zn.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 Jn(e,{configPath:t.config})});ot.action(()=>{console.log(),console.log(tt.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${tt.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${tt.cyan("agentx connect discord")} \u2014 pair a Discord bot, emit install URL`),console.log(` ${tt.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${tt.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${tt.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(tt.dim(" GitLab connect is the next slice.")),console.log()});import{Command as Li}from"commander";import fe from"chalk";var eo=new Li().name("usage").description("token usage analysis and reporting");eo.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=P(),[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(fe.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(fe.dim(" No tasks recorded yet")),console.log();return}let i=a=>a.toLocaleString();console.log(` Total: ${fe.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: ${fe.red(String(s.totalErrors))}`),console.log(),console.log(fe.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),h=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${fe.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${fe.dim(h)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(fe.red(" Daemon not running. Start with: agentx daemon start")):console.log(fe.red(` ${e.message}`))}});eo.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(fe.red(` Script not found: ${s}`)),console.log(fe.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(fe.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(fe.red(" Analysis failed. Is Python 3 installed?"))}});import{Command as Wi}from"commander";import K from"chalk";var qe=new Wi().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");qe.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=Fi(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-ASI6MDKX.js");o(t)}catch(t){console.log(K.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(K.dim(t.stack)),process.exit(1)}});function Fi(e,t){try{let o=P();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(K.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(K.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
141
+ `)),{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}}}}qe.command("list").description("list configured boards").action(()=>{try{let e=P();if(!e.boards?.length){console.log(K.dim(`
142
142
  No boards configured.
143
- `));return}console.log();for(let t of e.boards){console.log(` ${H.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(H.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(H.dim(` primary label: ${t.primaryToolLabel}`)),console.log(H.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(H.red(` ${e.message}`)),process.exit(1)}});Ue.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{Tt(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(H.red(` ${o.message}`)),process.exit(1)}});Ue.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{Tt(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(H.red(` ${o.message}`)),process.exit(1)}});var Eo=Ue.command("column").description("manage a board's columns (add / remove / edit / list)");Eo.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(ws("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(H.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(` ${H.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${H.dim(i)}`)}}catch(t){console.log(H.red(` ${t.message}`)),process.exit(1)}});Eo.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{Tt(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(H.red(` ${n.message}`)),process.exit(1)}});Eo.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Tt(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(H.red(` ${o.message}`)),process.exit(1)}});Ue.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Tt(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(H.red(` ${t.message}`)),process.exit(1)}});function Tt(e){let{summary:t,backupPath:o}=ct(n=>e(n));console.log(H.green(`
143
+ `));return}console.log();for(let t of e.boards){console.log(` ${K.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(K.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(K.dim(` primary label: ${t.primaryToolLabel}`)),console.log(K.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(K.red(` ${e.message}`)),process.exit(1)}});qe.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{Nt(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(K.red(` ${o.message}`)),process.exit(1)}});qe.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{Nt(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(K.red(` ${o.message}`)),process.exit(1)}});var Io=qe.command("column").description("manage a board's columns (add / remove / edit / list)");Io.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(xs("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(K.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(` ${K.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${K.dim(i)}`)}}catch(t){console.log(K.red(` ${t.message}`)),process.exit(1)}});Io.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{Nt(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(K.red(` ${n.message}`)),process.exit(1)}});Io.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Nt(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(K.red(` ${o.message}`)),process.exit(1)}});qe.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Nt(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(K.red(` ${t.message}`)),process.exit(1)}});function Nt(e){let{summary:t,backupPath:o}=gt(n=>e(n));console.log(K.green(`
144
144
  \u2713 ${t}
145
- `)),o&&console.log(H.dim(` Backup: ${o}`)),console.log(H.dim(` Restart the dashboard to pick up the change if not auto-reloading.
146
- `))}import{Command as Mi}from"commander";import g from"chalk";function Bn(e,t,o,n,s,i){return Ni(t,o,n,s,i)}function Ni(e,t,o,n,s){let i=t?`
145
+ `)),o&&console.log(K.dim(` Backup: ${o}`)),console.log(K.dim(` Restart the dashboard to pick up the change if not auto-reloading.
146
+ `))}import{Command as Ui}from"commander";import g from"chalk";function Gn(e,t,o,n,s,i){return Bi(t,o,n,s,i)}function Bi(e,t,o,n,s){let i=t?`
147
147
  ## Worldview
148
148
 
149
149
  ${t}
150
- `:"",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?"":`
150
+ `:"",r=new Map;for(let c of o){let l=c.type||"untyped",h=r.get(l)||[];h.push(c),r.set(l,h)}let a=o.length===0?"":`
151
151
  ## Existing Articles (the current catalog)
152
152
 
153
153
  `+Array.from(r.entries()).sort().map(([c,l])=>`**${c}**
154
- `+l.sort((p,d)=>p.title.localeCompare(d.title)).map(p=>`- [[${p.title}]] \u2014 ${p.path}`).join(`
154
+ `+l.sort((h,d)=>h.title.localeCompare(d.title)).map(h=>`- [[${h.title}]] \u2014 ${h.path}`).join(`
155
155
  `)).join(`
156
156
 
157
157
  `)+`
@@ -250,35 +250,35 @@ After compiling, populate a \`gaps\` array: wikilink targets you referenced but
250
250
 
251
251
  ENTRIES (${s}):
252
252
 
253
- ${n}`}import{resolve as D,relative as Un,dirname as qn}from"path";import{execSync as ot}from"child_process";import{writeFileSync as nt,mkdirSync as De,readFileSync as _t,readdirSync as Li,renameSync as Xt,rmSync as Wi,existsSync as ve}from"fs";function de(e,t){return new go(e||D(process.cwd(),".agentx/wiki"),void 0,t||"graph")}function Io(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var V=new Mi().name("wiki").description("wiki knowledge base management");V.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=de(e.dir,t),n=o.summary(),i=o.getSharedStore().listEntries().length;console.log(),console.log(g.bold(` Wiki Hub Status [${Io(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())});V.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=de(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()});V.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=de(e.dir,t),n=e.agent?[e.agent]:o.listAgents(),s=parseInt(e.max),i=(()=>{try{let d=D(process.cwd(),".agentx/graph");return ve(d)?new Ge({baseDir:d}):null}catch{return null}})(),r=new Map;if(i)try{let d=i.loadIndex();for(let[m,h]of Object.entries(d.entries))r.set(m,h.path)}catch{}let a=d=>{let m=d.meta?.intentPath;if(Array.isArray(m)&&m.every(w=>typeof w=="string")&&m.length>0)return m;if(!i||r.size===0)return;let h=String(d.meta?.sender??""),f=i.fingerprint({text:d.content,channel:d.source,sender:h});return r.get(f)},c=(d,m)=>{let h=new Map;for(let w of d){let y=m.find(v=>v.id===w);if(!y)continue;let k=a(y);if(!k?.length)continue;let $=k.join("/"),x=h.get($);x?x.n++:h.set($,{path:k,n:1})}if(h.size===0)return;let f;for(let w of h.values())(!f||w.n>f.n)&&(f=w);return f?.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 h=o.getAgentWiki(d),f=h.rebuildIndex(),w=h.getWorldview()||o.getSharedStore().getWorldview()||"",y=m.map(v=>`--- ENTRY ${v.id} [${v.date} ${v.agentId} via ${v.source}] ---
253
+ ${n}`}import{resolve as D,relative as Yn,dirname as Hn}from"path";import{execSync as nt}from"child_process";import{writeFileSync as st,mkdirSync as Te,readFileSync as Mt,readdirSync as qi,renameSync as to,rmSync as Ji,existsSync as xe}from"fs";function ge(e,t){return new uo(e||D(process.cwd(),".agentx/wiki"),void 0,t||"graph")}function Do(e){return e==="graph"?"Knowledge Graph":e==="flat"?"Karpathy Flat":"Unified"}var Q=new Ui().name("wiki").description("wiki knowledge base management");Q.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=ge(e.dir,t),n=o.summary(),i=o.getSharedStore().listEntries().length;console.log(),console.log(g.bold(` Wiki Hub Status [${Do(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())});Q.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=ge(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()});Q.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=ge(e.dir,t),n=e.agent?[e.agent]:o.listAgents(),s=parseInt(e.max),i=(()=>{try{let d=D(process.cwd(),".agentx/graph");return xe(d)?new Ye({baseDir:d}):null}catch{return null}})(),r=new Map;if(i)try{let d=i.loadIndex();for(let[m,p]of Object.entries(d.entries))r.set(m,p.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 p=String(d.meta?.sender??""),f=i.fingerprint({text:d.content,channel:d.source,sender:p});return r.get(f)},c=(d,m)=>{let p=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=p.get($);S?S.n++:p.set($,{path:b,n:1})}if(p.size===0)return;let f;for(let y of p.values())(!f||y.n>f.n)&&(f=y);return f?.path},l=0,h=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 p=o.getAgentWiki(d),f=p.rebuildIndex(),y=p.getWorldview()||o.getSharedStore().getWorldview()||"",w=m.map(v=>`--- ENTRY ${v.id} [${v.date} ${v.agentId} via ${v.source}] ---
254
254
  ${v.content}
255
255
  --- END ENTRY ---`).join(`
256
256
 
257
- `),k=Bn(t,d,w,f.articles,y,m.length);console.log(g.dim(` Mode: ${Io(t)}`));let $=D(h.baseDir,"_tmp");De($,{recursive:!0});let x=D($,"absorb-prompt.txt");nt(x,k),console.log(g.dim(" Compiling with Claude..."));try{let v;try{v=ot(`cat '${x}' | 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 b=v;try{let E=JSON.parse(v);b=E.result||E.content||"",b||(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=[],M=b.indexOf("{"),L=b.indexOf("["),I=M>=0&&(L<0||M<L)?M:L;if(I===-1){console.log(g.red(" No JSON found in response")),console.log(g.dim(b.slice(0,500)));continue}let le=b[I],ue=le==="{"?"}":"]",Te=0,ie=-1;for(let E=I;E<b.length;E++)if(b[E]===le)Te++;else if(b[E]===ue&&(Te--,Te===0)){ie=E+1;break}if(ie===-1){console.log(g.red(" Unbalanced JSON"));continue}let ye=b.slice(I,ie);try{let E=JSON.parse(ye);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: ${ye.slice(0,300)}`));continue}for(let E of C){let Ae=new Date().toISOString().slice(0,10),we=c(E.sources||[],m);h.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:Ae,lastUpdated:Ae,sources:E.sources||[],graphPath:we},E.content,d);let Go=E.type?g.magenta(`[${E.type}]`)+" ":"",ao=Array.isArray(E.related)&&E.related.length?` \u2192 ${E.related.slice(0,3).join(", ")}${E.related.length>3?", \u2026":""}`:"";console.log(` ${g.green("+")} ${Go}${E.path}: ${E.title}${g.dim(ao)}`);let jt=(E.tags||[]).slice(0,4).join(", ");jt&&console.log(g.dim(` tags: ${jt}`)),we?.length&&(console.log(g.dim(` graphPath: ${we.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}`))}h.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()});V.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",D(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=de(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=[],h=o(d).sort().reverse();for(let y of h){let k=r(d,y),$=[];try{$=o(k).filter(x=>x.endsWith(".json")).sort().reverse()}catch{continue}for(let x of $){if(m.length>=p)break;try{let v=JSON.parse(n(r(k,x),"utf-8")),b=v.message||v.task?.message;typeof b=="string"&&b.trim().length>10&&m.push({id:v.id||x.replace(".json",""),message:b.trim(),ts:v.at||v.timestamp||y})}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 f=[`# 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 y=0;y<m.length;y++){let k=m[y];process.stdout.write(g.dim(` [${y+1}/${m.length}] querying... `));let x=l.findRelevant(k.message,c,3).map(b=>`- **${b.meta.title}** [${b.meta.type||"?"}] (${b.path})`).join(`
258
- `)||"_(none returned)_",v;try{let b=await t(k.message,l,c,{selectorModel:e.selectorModel,synthModel:e.synthModel});if(b.status!=="ok")v=`_(status: ${b.status}${b.error?" \u2014 "+b.error:""})_`;else{let C=b.citations.map(j=>`\`${j.title}\` [${j.type||"?"}]`).join(", ");v=`**Answer:**
257
+ `),b=Gn(t,d,y,f.articles,w,m.length);console.log(g.dim(` Mode: ${Do(t)}`));let $=D(p.baseDir,"_tmp");Te($,{recursive:!0});let S=D($,"absorb-prompt.txt");st(S,b),console.log(g.dim(" Compiling with Claude..."));try{let v;try{v=nt(`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=[],M=k.indexOf("{"),L=k.indexOf("["),O=M>=0&&(L<0||M<L)?M:L;if(O===-1){console.log(g.red(" No JSON found in response")),console.log(g.dim(k.slice(0,500)));continue}let de=k[O],he=de==="{"?"}":"]",_e=0,re=-1;for(let E=O;E<k.length;E++)if(k[E]===de)_e++;else if(k[E]===he&&(_e--,_e===0)){re=E+1;break}if(re===-1){console.log(g.red(" Unbalanced JSON"));continue}let we=k.slice(O,re);try{let E=JSON.parse(we);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: ${we.slice(0,300)}`));continue}for(let E of C){let Oe=new Date().toISOString().slice(0,10),$e=c(E.sources||[],m);p.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:Oe,lastUpdated:Oe,sources:E.sources||[],graphPath:$e},E.content,d);let Ko=E.type?g.magenta(`[${E.type}]`)+" ":"",go=Array.isArray(E.related)&&E.related.length?` \u2192 ${E.related.slice(0,3).join(", ")}${E.related.length>3?", \u2026":""}`:"";console.log(` ${g.green("+")} ${Ko}${E.path}: ${E.title}${g.dim(go)}`);let At=(E.tags||[]).slice(0,4).join(", ");At&&console.log(g.dim(` tags: ${At}`)),$e?.length&&(console.log(g.dim(` graphPath: ${$e.join(" \u203A ")}`)),h++),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}`))}p.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(h/l*100):0;console.log(g.dim(` ${h}/${l} carry graphPath (${d}%) \u2014 wiki retrieval graph weight is now non-zero for those`))}console.log()});Q.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",D(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=ge(e.dir),c=e.agent;if(!c){console.log(g.red(" --agent <id> is required"));return}let l=a.getAgentWiki(c),h=parseInt(e.n),d=i(e.history,c);if(!s(d)){console.log(g.yellow(` no task-history at ${d}`));return}let m=[],p=o(d).sort().reverse();for(let w of p){let b=r(d,w),$=[];try{$=o(b).filter(S=>S.endsWith(".json")).sort().reverse()}catch{continue}for(let S of $){if(m.length>=h)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>=h)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 f=[`# 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(`
258
+ `)||"_(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:**
259
259
 
260
- ${b.answer}
260
+ ${k.answer}
261
261
 
262
- **Citations:** ${C}`}}catch(b){v=`_(error: ${b.message})_`}console.log(g.dim("done")),f.push(`## ${y+1}. ${k.id}`,"",`> ${k.message.replace(/\n/g," ").slice(0,400)}${k.message.length>400?"\u2026":""}`,"","### OLD \u2014 BM25 preload (top 3)","",x,"","### NEW \u2014 agentic query","",v,"","| Path | Rating 0\u20132 | Notes |","|---|---|---|","| OLD | | |","| NEW | | |","")}let w=f.join(`
263
- `);e.out?((await import("fs")).writeFileSync(e.out,w),console.log(),console.log(g.green(` Wrote ${w.length} bytes to ${e.out}`))):(console.log(),console.log(w))});V.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?_t(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=de(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 se=s[i++]??"";return process.stdout.write(A+g.dim(`[scripted] ${se.slice(0,80)}${se.length>80?"\u2026":""}`)+`
264
- `),se.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 h={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?"]},f=h[d]||h.concept;console.log(),console.log(g.bold(` Topic: ${g.cyan(p)} \xB7 Type: ${g.magenta(d)}`)),console.log(g.dim(` ${f.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let w=[],y=!1;for(let A=0;A<f.length;A++){let se=f[A],be=await l(` ${g.dim(`[${A+1}/${f.length}]`)} ${se}
265
- ${g.green(">")} `);if(be==="/abort"){y=!0;break}if(be==="/done")break;be!=="/skip"&&be&&w.push({q:se,a:be})}if(!y){let A=await l(`
262
+ **Citations:** ${C}`}}catch(k){v=`_(error: ${k.message})_`}console.log(g.dim("done")),f.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=f.join(`
263
+ `);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))});Q.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?Mt(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=ge(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 ie=s[i++]??"";return process.stdout.write(A+g.dim(`[scripted] ${ie.slice(0,80)}${ie.length>80?"\u2026":""}`)+`
264
+ `),ie.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 h=e.topic||"";if(!h&&(h=await l(g.cyan(" Topic? ")+g.dim("(a person, a procedure, a past event, \u2026) ")),!h||h==="/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 p={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?"]},f=p[d]||p.concept;console.log(),console.log(g.bold(` Topic: ${g.cyan(h)} \xB7 Type: ${g.magenta(d)}`)),console.log(g.dim(` ${f.length} questions. Skip with empty answer. /done to stop early.`)),console.log();let y=[],w=!1;for(let A=0;A<f.length;A++){let ie=f[A],ke=await l(` ${g.dim(`[${A+1}/${f.length}]`)} ${ie}
265
+ ${g.green(">")} `);if(ke==="/abort"){w=!0;break}if(ke==="/done")break;ke!=="/skip"&&ke&&y.push({q:ie,a:ke})}if(!w){let A=await l(`
266
266
  ${g.dim("Anything else worth capturing?")}
267
- ${g.green(">")} `);A&&A!=="/abort"&&A!=="/done"&&w.push({q:"Anything else worth capturing?",a:A})}if(y||w.length===0){console.log(g.yellow(`
267
+ ${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(`
268
268
  Nothing captured. Exiting.`)),c?.close();return}let $=a.listArticles(e.agent).slice(0,40).map(A=>`- ${A.meta.title} [${A.meta.type||"?"}]`).join(`
269
- `),x=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${p}`,`**Type:** ${d}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...w.map(A=>`
269
+ `),S=["You are compiling one Farzapedia-style wiki article from an operator interview transcript.","",`**Topic:** ${h}`,`**Type:** ${d}`,`**Owning agent:** ${e.agent}`,"","## Transcript",...y.map(A=>`
270
270
  Q: ${A.q}
271
271
  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(`
272
- `),v=D(a.baseDir,"_tmp");De(v,{recursive:!0});let b=D(v,`interview-${o().slice(0,8)}.txt`);nt(b,x),console.log(),console.log(g.dim(` Synthesizing draft with ${e.model}...`));let C="";try{let A=`cat '${b}' | claude -p - --output-format json --max-turns 1 --model ${e.model} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,se=ot(A,{encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let be=JSON.parse(se);C=String(be.result||be.content||"")}catch{C=se}}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 M=C.indexOf("---");M>0&&(C=C.slice(M));let L=C.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!L){console.log(g.red(" LLM output is not a valid frontmatter+body article:")),console.log(C.slice(0,600)),c?.close();return}let I={};for(let A of L[1].split(`
273
- `)){let se=A.match(/^(\w+):\s*(.+)$/);se&&(I[se[1]]=se[2].trim().replace(/^"(.*)"$/,"$1"))}let le=L[2],ue=I.title||p,Te=ue.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),ye=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${Te}.md`;console.log(),console.log(g.bold(" === Draft preview ===")),console.log(g.dim(` Path: ${ye}`)),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 ${b} (prompt only; no article file)`));return}let Ae=le,we={title:ue,type:I.type||d,related:I.related?I.related.replace(/^\[|\]$/g,"").split(",").map(A=>A.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):void 0,tags:I.tags?I.tags.replace(/^\[|\]$/g,"").split(",").map(A=>A.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[],owner:e.agent,access:I.access||"public",created:I.created||new Date().toISOString().slice(0,10),lastUpdated:I.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",se=D(v,`draft-${o().slice(0,8)}.md`);nt(se,C);try{ot(`${A} '${se}'`,{stdio:"inherit"});let co=_t(se,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(co){let _e={};for(let Ct of co[1].split(`
274
- `)){let lo=Ct.match(/^(\w+):\s*(.+)$/);lo&&(_e[lo[1]]=lo[2].trim().replace(/^"(.*)"$/,"$1"))}Ae=co[2],we={...we,title:_e.title||we.title,type:_e.type||we.type,access:_e.access||we.access,related:_e.related?_e.related.replace(/^\[|\]$/g,"").split(",").map(Ct=>Ct.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):we.related,tags:_e.tags?_e.tags.replace(/^\[|\]$/g,"").split(",").map(Ct=>Ct.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):we.tags}}}catch(be){console.log(g.red(` editor failed: ${be.message}`));return}}if(!a.writeArticle(ye,we,Ae,e.agent)){console.log(g.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(g.green(` \u2713 ${ye} saved.`));let ao=a.extractWikilinks(Ae),jt=new Map;for(let A of a.listArticles(e.agent))jt.set(A.meta.title.toLowerCase(),!0);let Yo=ao.filter(A=>!jt.has(A.toLowerCase()));if(Yo.length){console.log(),console.log(g.bold(" Gaps referenced but not yet covered:"));for(let A of Yo.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.`))}});V.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=de(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(h){console.log(g.red(` can't open wiki for agent "${e.agent}": ${h.message}`));return}let r=null;if(e.script){let f=_t(e.script,"utf-8").split(/\n\s*\n/).map(w=>w.trim()).filter(Boolean);r=[];for(let w of f){let y=w.split(/\r?\n/).filter(x=>x.trim());if(y.length<2)continue;let k=y[0].replace(/^Q:\s*/i,"").trim(),$=y.slice(1).join(" ").trim();k&&$&&r.push({q:k,verdict:$})}}let a=r?null:t.createInterface({input:process.stdin,output:process.stdout}),c=async h=>a?(await a.question(h)).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 h=0;h<l;h++){let f,w;if(r){let ie=r[h];if(!ie)break;f=ie.q,w=ie.verdict,console.log(g.cyan(` [${h+1}] Q: `)+f)}else{if(f=await c(g.cyan(` [${h+1}] Q: `)),!f||f==="/done"||f==="/abort")break;w=""}process.stdout.write(g.dim(" querying... "));let y;try{y=await n(f,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(ie){console.log(g.red(`failed: ${ie.message?.slice(0,120)}`));continue}if(console.log(g.dim("done")),y.status!=="ok")console.log(g.yellow(` (status: ${y.status}${y.error?" \u2014 "+y.error:""})`));else{let ie=y.citations.map(ye=>`${ye.title} [${ye.type||"?"}]`).join(" \xB7 ");console.log(),console.log(g.dim(" A: ")+y.answer.replace(/\n/g,`
275
- `)),console.log(g.dim(" citations: "+ie))}r||(w=await c(g.cyan(" verdict > "))),console.log(g.dim(" verdict: ")+w);let k={q:f,answer:y.answer,citations:y.citations,verdict:w},$=w.match(/^(\/ok|\/correct|\/add|\/link|\/skip)(?:\s+(.+))?$/i);if(!$){console.log(g.yellow(" (verdict not recognised \u2014 treating as /skip)")),d.push(k);continue}let x=$[1].toLowerCase(),v=($[2]||"").trim();if(d.push(k),x==="/ok"||x==="/skip")continue;if(!v){console.log(g.yellow(` ${x} without note \u2014 skipping.`));continue}let b=y.citations[0];if(!b){console.log(g.yellow(" no cited article to patch."));continue}let C=i.readArticle(b.path);if(!C){console.log(g.red(` can't read ${b.path} to patch.`));continue}console.log(g.dim(` patching ${b.title} (${b.path})...`));let j=Bi(C.content,x,v,C.meta.title,C.meta.type),M=D(i.baseDir,"_tmp");De(M,{recursive:!0});let L=D(M,`quiz-patch-${o().slice(0,8)}.txt`);nt(L,j);let I="";try{let ie=`cat '${L}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,ye=ot(ie,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Ae=JSON.parse(ye);I=String(Ae.result||Ae.content||"")}catch{I=ye}let E=I.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);E&&(I=E[1].trim()),I=I.trim()}catch(ie){console.log(g.red(` patch failed: ${ie.message?.slice(0,120)}`));continue}if(!I||I.length<20){console.log(g.yellow(" patch returned nothing usable."));continue}let le=C.content.split(`
276
- `).length,ue=I.split(`
277
- `).length;if(console.log(g.dim(` diff: ${le} \u2192 ${ue} lines (${ue-le>=0?"+":""}${ue-le})`)),!p){console.log(g.dim(" (--no-commit: patch not written)")),k.patched=b.path+" (dry)";continue}if(!i.writeArticle(b.path,{...C.meta,lastUpdated:new Date().toISOString().slice(0,10)},I,e.agent)){console.log(g.red(" write failed (permission?)"));continue}m++,k.patched=b.path,console.log(g.green(` \u2713 patched ${b.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 h=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${m} patches_`,""];for(let f=0;f<d.length;f++){let w=d[f];h.push(`## ${f+1}. Q: ${w.q}`,"",`**A:** ${w.answer}`,"",`**Citations:** ${w.citations.map(y=>`\`${y.title}\``).join(", ")||"_(none)_"}`,"",`**Verdict:** \`${w.verdict}\``+(w.patched?` \u2192 patched \`${w.patched}\``:""),"")}nt(e.out,h.join(`
278
- `)),console.log(g.dim(` Transcript written to ${e.out}`))}});V.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=de(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=Gn(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=D(s.baseDir,i),a=o.editor||process.env.EDITOR||"vi";console.log(g.dim(` opening ${i} in ${a}...`));try{ot(`${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(h=>l.has(h)?!1:(l.add(h),!0)),d=c.meta.related||[];(p.some(h=>!d.includes(h))||d.some(h=>!p.includes(h)))&&(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)}`))}});V.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=de(n.dir),a;try{a=r.getAgentWiki(e)}catch(b){console.log(g.red(` can't open wiki for agent "${e}": ${b.message}`));return}let c=Gn(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=Fi(l.content,l.meta.title,l.meta.type,o),d=D(a.baseDir,"_tmp");De(d,{recursive:!0});let m=D(d,`patch-${i().slice(0,8)}.txt`);nt(m,p),console.log(),console.log(g.dim(` Target: ${l.meta.title} (${c})`)),console.log(g.dim(` Patching with ${n.patchModel}...`));let h="";try{let b=`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=ot(b,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let M=JSON.parse(C);h=String(M.result||M.content||"")}catch{h=C}let j=h.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);j&&(h=j[1].trim()),h=h.trim()}catch(b){console.log(g.red(` patch failed: ${b.message?.slice(0,150)}`));return}if(!h||h.length<20){console.log(g.yellow(" patch returned nothing usable."));return}let f=l.content.split(`
279
- `).length,w=h.split(`
280
- `).length;if(console.log(),console.log(g.bold(" === Patched preview ===")),console.log(g.dim(` diff: ${f} \u2192 ${w} lines (${w-f>=0?"+":""}${w-f})`)),console.log(),console.log(h),console.log(),!n.commit){console.log(g.dim(" --no-commit: preview only, not written."));return}let y=!!n.yes;if(!y){let b=s.createInterface({input:process.stdin,output:process.stdout}),C=(await b.question(g.cyan(" apply? [y/N] "))).trim().toLowerCase();b.close(),y=C==="y"||C==="yes"}if(!y){console.log(g.dim(" aborted."));return}let k=new Set,$=a.extractWikilinks(h).filter(b=>k.has(b)?!1:(k.add(b),!0));if(!a.writeArticle(c,{...l.meta,related:$.length?$:void 0,lastUpdated:new Date().toISOString().slice(0,10)},h,e)){console.log(g.red(" write failed (permission?)"));return}a.rebuildIndex();let v=(l.meta.related||[]).filter(b=>!$.includes(b));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 Gn(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 Fi(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(`
281
- `)}function Bi(e,t,o,n,s){let i={"/correct":`The operator says the article contains an error:
272
+ `),v=D(a.baseDir,"_tmp");Te(v,{recursive:!0});let k=D(v,`interview-${o().slice(0,8)}.txt`);st(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"`,ie=nt(A,{encoding:"utf-8",timeout:18e4,maxBuffer:4*1024*1024});try{let ke=JSON.parse(ie);C=String(ke.result||ke.content||"")}catch{C=ie}}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 M=C.indexOf("---");M>0&&(C=C.slice(M));let L=C.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!L){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 L[1].split(`
273
+ `)){let ie=A.match(/^(\w+):\s*(.+)$/);ie&&(O[ie[1]]=ie[2].trim().replace(/^"(.*)"$/,"$1"))}let de=L[2],he=O.title||h,_e=he.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),we=`${{person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"}[d]||d+"s"}/${_e}.md`;console.log(),console.log(g.bold(" === Draft preview ===")),console.log(g.dim(` Path: ${we}`)),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 Oe=de,$e={title:he,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",ie=D(v,`draft-${o().slice(0,8)}.md`);st(ie,C);try{nt(`${A} '${ie}'`,{stdio:"inherit"});let mo=Mt(ie,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(mo){let Pe={};for(let Ot of mo[1].split(`
274
+ `)){let po=Ot.match(/^(\w+):\s*(.+)$/);po&&(Pe[po[1]]=po[2].trim().replace(/^"(.*)"$/,"$1"))}Oe=mo[2],$e={...$e,title:Pe.title||$e.title,type:Pe.type||$e.type,access:Pe.access||$e.access,related:Pe.related?Pe.related.replace(/^\[|\]$/g,"").split(",").map(Ot=>Ot.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.related,tags:Pe.tags?Pe.tags.replace(/^\[|\]$/g,"").split(",").map(Ot=>Ot.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):$e.tags}}}catch(ke){console.log(g.red(` editor failed: ${ke.message}`));return}}if(!a.writeArticle(we,$e,Oe,e.agent)){console.log(g.red(" write failed (permission?)"));return}a.rebuildIndex(),console.log(g.green(` \u2713 ${we} saved.`));let go=a.extractWikilinks(Oe),At=new Map;for(let A of a.listArticles(e.agent))At.set(A.meta.title.toLowerCase(),!0);let Vo=go.filter(A=>!At.has(A.toLowerCase()));if(Vo.length){console.log(),console.log(g.bold(" Gaps referenced but not yet covered:"));for(let A of Vo.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.`))}});Q.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=ge(e.dir),i;try{i=s.getAgentWiki(e.agent)}catch(p){console.log(g.red(` can't open wiki for agent "${e.agent}": ${p.message}`));return}let r=null;if(e.script){let f=Mt(e.script,"utf-8").split(/\n\s*\n/).map(y=>y.trim()).filter(Boolean);r=[];for(let y of f){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 p=>a?(await a.question(p)).trim():"",l=Math.min(parseInt(e.rounds)||20,r?.length??999),h=e.commit!==!1;console.log(),console.log(g.bold(" Wiki Quiz")),console.log(g.dim(` Agent: ${e.agent} \xB7 Rounds: ${l} \xB7 ${h?"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 p=0;p<l;p++){let f,y;if(r){let re=r[p];if(!re)break;f=re.q,y=re.verdict,console.log(g.cyan(` [${p+1}] Q: `)+f)}else{if(f=await c(g.cyan(` [${p+1}] Q: `)),!f||f==="/done"||f==="/abort")break;y=""}process.stdout.write(g.dim(" querying... "));let w;try{w=await n(f,i,e.agent,{selectorModel:e.selectorModel,synthModel:e.synthModel})}catch(re){console.log(g.red(`failed: ${re.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 re=w.citations.map(we=>`${we.title} [${we.type||"?"}]`).join(" \xB7 ");console.log(),console.log(g.dim(" A: ")+w.answer.replace(/\n/g,`
275
+ `)),console.log(g.dim(" citations: "+re))}r||(y=await c(g.cyan(" verdict > "))),console.log(g.dim(" verdict: ")+y);let b={q:f,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=Gi(C.content,S,v,C.meta.title,C.meta.type),M=D(i.baseDir,"_tmp");Te(M,{recursive:!0});let L=D(M,`quiz-patch-${o().slice(0,8)}.txt`);st(L,j);let O="";try{let re=`cat '${L}' | claude -p - --output-format json --max-turns 1 --model ${e.patchModel} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,we=nt(re,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let Oe=JSON.parse(we);O=String(Oe.result||Oe.content||"")}catch{O=we}let E=O.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);E&&(O=E[1].trim()),O=O.trim()}catch(re){console.log(g.red(` patch failed: ${re.message?.slice(0,120)}`));continue}if(!O||O.length<20){console.log(g.yellow(" patch returned nothing usable."));continue}let de=C.content.split(`
276
+ `).length,he=O.split(`
277
+ `).length;if(console.log(g.dim(` diff: ${de} \u2192 ${he} lines (${he-de>=0?"+":""}${he-de})`)),!h){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&&h&&i.rebuildIndex(),console.log(),console.log(g.bold(` Session done: ${d.length} rounds, ${m} patches applied.`)),e.out){let p=[`# Wiki Quiz \u2014 ${e.agent}`,"",`_Generated ${new Date().toISOString()} \xB7 ${d.length} rounds \xB7 ${m} patches_`,""];for(let f=0;f<d.length;f++){let y=d[f];p.push(`## ${f+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}\``:""),"")}st(e.out,p.join(`
278
+ `)),console.log(g.dim(` Transcript written to ${e.out}`))}});Q.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=ge(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=Qn(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=D(s.baseDir,i),a=o.editor||process.env.EDITOR||"vi";console.log(g.dim(` opening ${i} in ${a}...`));try{nt(`${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,h=s.extractWikilinks(c.content).filter(p=>l.has(p)?!1:(l.add(p),!0)),d=c.meta.related||[];(h.some(p=>!d.includes(p))||d.some(p=>!h.includes(p)))&&(s.writeArticle(i,{...c.meta,related:h.length?h:void 0,lastUpdated:new Date().toISOString().slice(0,10)},c.content,e),console.log(g.dim(` (synced frontmatter.related from body: ${h.length} wikilink${h.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)}`))}});Q.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=ge(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=Qn(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 h=zi(l.content,l.meta.title,l.meta.type,o),d=D(a.baseDir,"_tmp");Te(d,{recursive:!0});let m=D(d,`patch-${i().slice(0,8)}.txt`);st(m,h),console.log(),console.log(g.dim(` Target: ${l.meta.title} (${c})`)),console.log(g.dim(` Patching with ${n.patchModel}...`));let p="";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=nt(k,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024});try{let M=JSON.parse(C);p=String(M.result||M.content||"")}catch{p=C}let j=p.trim().match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```\s*$/);j&&(p=j[1].trim()),p=p.trim()}catch(k){console.log(g.red(` patch failed: ${k.message?.slice(0,150)}`));return}if(!p||p.length<20){console.log(g.yellow(" patch returned nothing usable."));return}let f=l.content.split(`
279
+ `).length,y=p.split(`
280
+ `).length;if(console.log(),console.log(g.bold(" === Patched preview ===")),console.log(g.dim(` diff: ${f} \u2192 ${y} lines (${y-f>=0?"+":""}${y-f})`)),console.log(),console.log(p),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(p).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)},p,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 Qn(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`,h=s.find(d=>d.path===l||d.path===n);if(h)return h.path}let a=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),c=s.find(l=>{let h=l.meta.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return h===a||h.includes(a)||l.path.toLowerCase().includes(a)});return c?c.path:null}function zi(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(`
281
+ `)}function Gi(e,t,o,n,s){let i={"/correct":`The operator says the article contains an error:
282
282
 
283
283
  ${o}
284
284
 
@@ -291,8 +291,8 @@ Incorporate it into the most relevant existing section, or create a short new se
291
291
  ${o}
292
292
 
293
293
  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(`
294
- `)}V.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=de(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=!!e.commit,s=e.dir?D(e.dir):D(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=D(s,"agents",d);if(!ve(m))continue;let h=D(m,i),f=r.map($=>({mode:$,dir:D(m,$)})).filter($=>ve($.dir));if(f.length===0)continue;let w=new Map;Ao(h,$=>{let x=Un(h,$);if(x.startsWith("_")||x.startsWith("raw/")||x.includes("_tmp/"))return;let v=Jn(_t($,"utf-8"));v?.meta.title&&w.set(v.meta.title.trim().toLowerCase(),{relPath:x,type:v.meta.type,lastUpdated:v.meta.lastUpdated||""})});let y=[];for(let $ of f)Ao($.dir,x=>{let v=Un($.dir,x);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let b=Jn(_t(x,"utf-8"));b?.meta.title&&y.push({mode:$.mode,relPath:v,absPath:x,title:b.meta.title.trim(),type:b.meta.type,lastUpdated:b.meta.lastUpdated||""})});if(a+=y.length,y.length===0)continue;console.log();let k=f.map($=>$.mode).join("+");console.log(g.bold(` ${g.cyan(d)}: ${y.length} legacy article(s) across ${k}`));for(let $ of y){let x=$.title.toLowerCase(),v=w.get(x),b;v?!v.type&&$.type||!!v.type==!!$.type&&$.lastUpdated&&v.lastUpdated&&$.lastUpdated>v.lastUpdated?b="upgrade":b="archive":b="promote";let C=$.type?g.magenta(`[${$.type}]`):g.yellow("[untyped]"),j=b==="promote"?g.green("\u2192 promote "):b==="upgrade"?g.cyan("\u27F3 upgrade "):g.dim("\u2717 archive "),M=$.relPath.length>46?$.relPath.slice(0,43)+"...":$.relPath.padEnd(46);if(console.log(` ${j} ${C} ${g.dim($.mode+"/")}${M}`),b==="upgrade"&&console.log(g.dim(` (replaces ${v.relPath}, old version kept under _versions/)`)),!n){b==="promote"?c++:b==="upgrade"?l++:p++;continue}try{if(b==="promote"){let L=D(h,$.relPath);ve(L)?(console.log(g.yellow(` ! target path already exists, archiving instead: ${$.relPath}`)),zn(m,$),p++):(De(qn(L),{recursive:!0}),Xt($.absPath,L),w.set(x,{relPath:$.relPath,type:$.type,lastUpdated:$.lastUpdated}),c++)}else if(b==="upgrade"){let L=D(h,v.relPath);if(ve(L)){let I=D(m,"_versions",v.relPath.replace(/\.md$/,""));De(I,{recursive:!0});let le=new Date().toISOString().replace(/[:.]/g,"-");Xt(L,D(I,`${le}.md`))}De(qn(L),{recursive:!0}),Xt($.absPath,L),w.set(x,{relPath:v.relPath,type:$.type,lastUpdated:$.lastUpdated}),l++}else zn(m,$),p++}catch(L){console.log(g.red(` ! ${b} failed: ${L.message?.slice(0,120)}`))}}if(n){for(let $ of f)try{Wi($.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 Ao(e,t){if(ve(e))for(let o of Li(e,{withFileTypes:!0})){let n=D(e,o.name);o.isDirectory()?Ao(n,t):o.isFile()&&o.name.endsWith(".md")&&t(n)}}function Jn(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let o={};for(let n of t[1].split(`
295
- `)){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 zn(e,t){let o=D(e,"_versions",`legacy-${t.mode}`,t.relPath.replace(/\.md$/,""));De(o,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");Xt(t.absPath,D(o,`${n}.md`))}V.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=de(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(k=>!k.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 h=Math.max(0,s-c),f=Math.min(m.length,h);if(f===0){console.log(g.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(g.bold(` ${g.cyan(l)}: ${f}/${m.length} untyped articles`));let w=p.baseDir,y=D(w,"_tmp");De(y,{recursive:!0});for(let k=0;k<f;k+=n){let $=m.slice(k,Math.min(k+n,f)),x=qi($),v=D(y,"migrate-prompt.txt");nt(v,x);let b;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=ot(C,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),M=JSON.parse(j),I=String(M.result||M.content||"").match(/\[[\s\S]*\]/);if(!I)throw new Error("no JSON array in classifier response");b=JSON.parse(I[0])}catch(C){console.log(g.red(` LLM classify failed: ${C.message?.slice(0,150)}`));continue}for(let C of $){let j=b.find(Te=>Te.path===C.path),M=Ui(j?.type);if(!j||!M){console.log(g.yellow(` ? ${C.path}: unclassified${j?` (got "${j.type}")`:""}`));continue}let L=p.extractWikilinks(C.content),I={...C.meta,type:M.type,related:L.length?L:void 0,lastUpdated:new Date().toISOString().slice(0,10)},le=L.length?g.dim(` \u2192 ${L.slice(0,3).join(", ")}${L.length>3?", \u2026":""}`):"",ue=M.alias?g.dim(` (from "${M.alias}")`):"";console.log(` ${g.green("+")} ${g.magenta("["+M.type+"]")}${ue} ${C.path}${le}`),i&&(p.writeArticle(C.path,I,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 Ui(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 qi(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}"
294
+ `)}Q.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=ge(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=!!e.commit,s=e.dir?D(e.dir):D(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,h=0;for(let d of o){let m=D(s,"agents",d);if(!xe(m))continue;let p=D(m,i),f=r.map($=>({mode:$,dir:D(m,$)})).filter($=>xe($.dir));if(f.length===0)continue;let y=new Map;Ro(p,$=>{let S=Yn(p,$);if(S.startsWith("_")||S.startsWith("raw/")||S.includes("_tmp/"))return;let v=Kn(Mt($,"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 f)Ro($.dir,S=>{let v=Yn($.dir,S);if(v.startsWith("_")||v.startsWith("raw/")||v.includes("_tmp/"))return;let k=Kn(Mt(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=f.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 "),M=$.relPath.length>46?$.relPath.slice(0,43)+"...":$.relPath.padEnd(46);if(console.log(` ${j} ${C} ${g.dim($.mode+"/")}${M}`),k==="upgrade"&&console.log(g.dim(` (replaces ${v.relPath}, old version kept under _versions/)`)),!n){k==="promote"?c++:k==="upgrade"?l++:h++;continue}try{if(k==="promote"){let L=D(p,$.relPath);xe(L)?(console.log(g.yellow(` ! target path already exists, archiving instead: ${$.relPath}`)),Vn(m,$),h++):(Te(Hn(L),{recursive:!0}),to($.absPath,L),y.set(S,{relPath:$.relPath,type:$.type,lastUpdated:$.lastUpdated}),c++)}else if(k==="upgrade"){let L=D(p,v.relPath);if(xe(L)){let O=D(m,"_versions",v.relPath.replace(/\.md$/,""));Te(O,{recursive:!0});let de=new Date().toISOString().replace(/[:.]/g,"-");to(L,D(O,`${de}.md`))}Te(Hn(L),{recursive:!0}),to($.absPath,L),y.set(S,{relPath:v.relPath,type:$.type,lastUpdated:$.lastUpdated}),l++}else Vn(m,$),h++}catch(L){console.log(g.red(` ! ${k} failed: ${L.message?.slice(0,120)}`))}}if(n){for(let $ of f)try{Ji($.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: ${h}`)),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 ${h}`)),console.log(g.dim(" Dry-run \u2014 add --commit to execute"))),console.log()});function Ro(e,t){if(xe(e))for(let o of qi(e,{withFileTypes:!0})){let n=D(e,o.name);o.isDirectory()?Ro(n,t):o.isFile()&&o.name.endsWith(".md")&&t(n)}}function Kn(e){let t=e.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let o={};for(let n of t[1].split(`
295
+ `)){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 Vn(e,t){let o=D(e,"_versions",`legacy-${t.mode}`,t.relPath.replace(/\.md$/,""));Te(o,{recursive:!0});let n=new Date().toISOString().replace(/[:.]/g,"-");to(t.absPath,D(o,`${n}.md`))}Q.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=ge(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 h=t.getAgentWiki(l),d=h.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 p=Math.max(0,s-c),f=Math.min(m.length,p);if(f===0){console.log(g.dim(` ${l}: skipped (--max reached)`));continue}console.log(),console.log(g.bold(` ${g.cyan(l)}: ${f}/${m.length} untyped articles`));let y=h.baseDir,w=D(y,"_tmp");Te(w,{recursive:!0});for(let b=0;b<f;b+=n){let $=m.slice(b,Math.min(b+n,f)),S=Hi($),v=D(w,"migrate-prompt.txt");st(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=nt(C,{encoding:"utf-8",timeout:12e4,maxBuffer:4*1024*1024}),M=JSON.parse(j),O=String(M.result||M.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(_e=>_e.path===C.path),M=Yi(j?.type);if(!j||!M){console.log(g.yellow(` ? ${C.path}: unclassified${j?` (got "${j.type}")`:""}`));continue}let L=h.extractWikilinks(C.content),O={...C.meta,type:M.type,related:L.length?L:void 0,lastUpdated:new Date().toISOString().slice(0,10)},de=L.length?g.dim(` \u2192 ${L.slice(0,3).join(", ")}${L.length>3?", \u2026":""}`):"",he=M.alias?g.dim(` (from "${M.alias}")`):"";console.log(` ${g.green("+")} ${g.magenta("["+M.type+"]")}${he} ${C.path}${de}`),i&&(h.writeArticle(C.path,O,C.content,l),c++)}}i&&h.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 Yi(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 Hi(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}"
296
296
  title: "${o.meta.title}"
297
297
  tags: [${i}]
298
298
  body: ${s}${o.content.length>400?"\u2026":""}`}).join(`
@@ -332,36 +332,38 @@ Output (JSON array, one entry per input article, same order):
332
332
  [
333
333
  {"path": "path/to/article.md", "type": "project"},
334
334
  ...
335
- ]`}V.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=de(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()});V.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||D(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-QXWKEQON.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(),un(t,o,e.agent,n,e.mode)});V.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=de(t.dir),s=t.agent?[t.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),p=D(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()}});V.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=de(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()});V.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=de(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=D(process.cwd(),".agentx/graph");if(!ve(n)){console.log(g.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Ge({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),h=m.listArticles(d),f=t.getSharedStore().listEntries(),w=new Map(f.map(x=>[x.id,x])),y=0,k=0,$=0;for(let x of h){if(a++,x.meta.graphPath?.length||!x.meta.sources?.length)continue;y++,c++;let v=new Map;for(let C of x.meta.sources){let j=w.get(C);if(!j)continue;let M=String(j.meta?.sender??""),L=s.fingerprint({text:j.content,channel:j.source,sender:M}),I=r.get(L);if(!I?.length)continue;let le=I.join("/"),ue=v.get(le);ue?ue.n++:v.set(le,{path:I,n:1})}if(v.size===0)continue;k++,l++;let b;for(let C of v.values())(!b||C.n>b.n)&&(b=C);b&&(e.dryRun||(m.writeArticle(x.path,{...x.meta,graphPath:b.path},x.content,d),$++,p++))}console.log(` ${g.cyan(d)}: ${g.bold(h.length)} articles \xB7 ${y} eligible \xB7 ${k} 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()});V.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=de(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-QXWKEQON.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 h=await m.json();for(let f of h.agents||[])f.totalEntries>0&&console.log(g.dim(` ${f.agentId}: ${f.totalEntries} entries, ${f.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()});V.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||D(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new go(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),m=l.getAgentEntries(o),h=l.getUnabsorbedEntries(o),f=new Set,w=0,y=new Set;for(let $ of d.articles){for(let x of $.tags||[])f.add(x);w+=$.tags?.length||0;for(let x of $.sources||[])y.add(x)}let k=new Set(d.articles.map($=>$.path.includes("/")?$.path.split("/")[0]:"/"));return{mode:c,label:Io(c),articles:d.articles.length,entries:m.length,unabsorbed:h.length,uniqueTags:f.size,avgTags:d.articles.length>0?(w/d.articles.length).toFixed(1):"0",dirs:k.size,coverage:y.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()});V.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?D(process.cwd(),t.dir):D(process.cwd(),".agentx/wiki");ve(o)||(console.log(g.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?D(process.cwd(),e):D(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=D(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=ve(s)?p(s).size:0;console.log(),console.log(g.green(` \u2713 wrote ${s} (${Ji(d)})`)),console.log(g.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});V.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=D(process.cwd(),e);ve(o)||(console.log(g.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?D(process.cwd(),t.dir):D(process.cwd(),".agentx/wiki");ve(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=D(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 Ji(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 zi}from"commander";import T from"chalk";import{resolve as Oo}from"path";import{existsSync as Gi}from"fs";var Pt=new zi().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Pt.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=P();if(!t.graph?.enabled){console.log(T.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(T.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(T.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 Ge({baseDir:Oo(process.cwd(),t.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(T.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(T.bold(` Graph review \u2014 ${r.length} pending`)),console.log(T.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 f=0;f<r.length;f++){let w=r[f],y=Ho(w.path,c)||w.path.join(" \u203A ");process.stdout.write(` [${f+1}/${r.length}] ${T.cyan(w.msgHash.slice(0,8))} ${T.dim(y)} ... `);let k=Yi(w,a,c),$=null;try{$=await Hi(n,o,k,t.dashboard?.token)}catch(b){m++,console.log(T.red(`ERR ${b.message?.slice(0,80)}`));continue}if(!$||!$.decision){m++,console.log(T.red("ERR no decision"));continue}let x=String($.decision).toLowerCase().trim(),v=($.reason||"").toString().slice(0,180);if(x==="approve")if(console.log(T.green("APPROVE")+" "+T.dim(v)),e.dryRun)l++;else try{Ki(i,w,a,c,o),i.updateClassificationStatus(w.msgHash,{status:"approved",reviewer:o,reviewReason:v}),l++}catch(b){console.log(T.yellow(` (commit failed, staying pending: ${b.message?.slice(0,100)})`)),m++}else x==="reject"?(console.log(T.red("REJECT")+" "+T.dim(v)),e.dryRun||i.updateClassificationStatus(w.msgHash,{status:"rejected",reviewer:o,reviewReason:v}),p++):(console.log(T.yellow("SKIP")+" "+T.dim(v||x)),d++)}console.log();let h=e.dryRun?"would":"did";console.log(T.dim(` Summary: ${h} approve ${l}, ${h} reject ${p}, ${d} skipped, ${m} errors.`)),e.dryRun&&(l>0||p>0)&&console.log(T.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Pt.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=P();if(!t.graph){console.log(T.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=Oo(process.cwd(),t.graph.baseDir);if(!Gi(o)){console.log(T.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-QO7SLKIM.js"),s=new Ge({baseDir:o,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(T.dim(" "),...a)});console.log(),console.log(T.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(T.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(T.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(T.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Pt.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=P();if(!t.graph?.enabled){console.log(T.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 Ge({baseDir:Oo(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(j=>j.id));console.log(),console.log(T.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 L=await fetch(`${o}/graph/nodes`,{headers:s});if(!L.ok)throw new Error(`nodes HTTP ${L.status}`);p=(await L.json()).nodes||[];let I=await fetch(`${o}/graph/classifications?status=approved&limit=${n}`,{headers:s});if(!I.ok)throw new Error(`classifications HTTP ${I.status}`);d=(await I.json()).classifications||[]}catch(j){console.log(T.red(` fetch failed: ${j.message}`));return}let m=r.levels.map(j=>j.id).join(","),h=l?.levels?.map(j=>j.id).join(","),f=m===h;f?console.log(T.dim(` schema matches (${r.levels.length} levels)`)):(console.log(T.yellow(" \u26A0 schema levels differ:")),console.log(T.dim(` local: ${m}`)),console.log(T.dim(` peer: ${h}`)),a.length===0&&!e.dryRun?(console.log(T.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(T.yellow(" keeping local schema; node import may fail if levels disagree")));let w=f?r:l,y=new Map;w.levels.forEach((j,M)=>y.set(j.id,M));let k=[...p].sort((j,M)=>(y.get(j.level)??99)-(y.get(M.level)??99)),$=0,x=0,v=0;for(let j of k){if(c.has(j.id)){x++;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(M){v++,console.log(T.yellow(` skip node ${j.id}: ${M.message?.slice(0,100)}`))}}console.log(T.dim(` nodes: +${$} added \xB7 ${x} already-present \xB7 ${v} failed`));let b=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){b++;continue}i.setFingerprint(j.msgHash,{path:j.path,leaf:j.leaf||{}}),b++}console.log(T.dim(` fingerprints: +${b} cached \xB7 ${C} already-present`)),console.log(),e.dryRun?console.log(T.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(T.green(` \u2713 pulled from ${o}`)),console.log()});function Yi(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(`
335
+ ]`}Q.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(e=>{let n=ge(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()});Q.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||D(process.cwd(),".agentx/wiki"),o=parseInt(e.port),n=e.peer||[];if(n.length===0)try{let{loadDaemonConfig:s}=await import("./config-RWHSEE4N.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(),$n(t,o,e.agent,n,e.mode)});Q.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=ge(t.dir),s=t.agent?[t.agent]:n.listAgents(),i=null;for(let c of s){let l=n.getAgentWiki(c),h=D(l.baseDir,"_index.md");try{if((await import("fs")).existsSync(h)){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(h=>h.path===l.path));console.log(g.dim(` followed: ${c.map(l=>`${l.title}@h${l.hop}`).join(" | ")}`))}console.log()}});Q.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=ge(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()});Q.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=ge(e.dir),o=e.agent?[e.agent]:t.listAgents(),n=D(process.cwd(),".agentx/graph");if(!xe(n)){console.log(g.red(` No graph store at ${n} \u2014 nothing to backfill against.`));return}let s=new Ye({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,h=0;for(let d of o){let m=t.getAgentWiki(d),p=m.listArticles(d),f=t.getSharedStore().listEntries(),y=new Map(f.map(S=>[S.id,S])),w=0,b=0,$=0;for(let S of p){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 M=String(j.meta?.sender??""),L=s.fingerprint({text:j.content,channel:j.source,sender:M}),O=r.get(L);if(!O?.length)continue;let de=O.join("/"),he=v.get(de);he?he.n++:v.set(de,{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),$++,h++))}console.log(` ${g.cyan(d)}: ${g.bold(p.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)}%), ${h} written`)),e.dryRun&&console.log(g.dim(" Dry-run \u2014 re-run without --dry-run to commit.")),console.log()});Q.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=ge(e.dir).getSharedStore(),n=[];if(e.peer)n=[e.peer];else try{let{loadDaemonConfig:r}=await import("./config-RWHSEE4N.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||[],h=c.nodeId||"unknown";console.log(g.dim(` Node: ${h} \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}@${h}`,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 p=await m.json();for(let f of p.agents||[])f.totalEntries>0&&console.log(g.dim(` ${f.agentId}: ${f.totalEntries} entries, ${f.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()});Q.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||D(process.cwd(),".agentx/wiki"),o=e.agent,s=["flat","graph","unified"].map(c=>{let l=new uo(t,void 0,c),d=l.getAgentWiki(o).rebuildIndex(),m=l.getAgentEntries(o),p=l.getUnabsorbedEntries(o),f=new Set,y=0,w=new Set;for(let $ of d.articles){for(let S of $.tags||[])f.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:Do(c),articles:d.articles.length,entries:m.length,unabsorbed:p.length,uniqueTags:f.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 h=s.map(d=>l(d).padEnd(i));console.log(` ${c.padEnd(20)} ${h.join(" ")}`)}console.log();let a=(c,l)=>{let h=Math.max(...s.map(m=>m[c])),d=s.filter(m=>m[c]===h).map(m=>m.label);h>0&&console.log(g.dim(` Best ${l}: ${d.join(", ")} (${h})`))};a("uniqueTags","tag richness"),a("articles","article count"),a("coverage","entry coverage"),console.log()});Q.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?D(process.cwd(),t.dir):D(process.cwd(),".agentx/wiki");xe(o)||(console.log(g.red(` Wiki dir not found: ${o}`)),process.exit(1));let n=new Date().toISOString().slice(0,10),s=e?D(process.cwd(),e):D(process.cwd(),`agentx-wiki-${n}.tar.gz`),i=D(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:h}=await import("fs"),d=xe(s)?h(s).size:0;console.log(),console.log(g.green(` \u2713 wrote ${s} (${Ki(d)})`)),console.log(g.dim(` Restore on another node: agentx wiki import ${s}`)),console.log()});Q.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=D(process.cwd(),e);xe(o)||(console.log(g.red(` archive not found: ${o}`)),process.exit(1));let n=t.dir?D(process.cwd(),t.dir):D(process.cwd(),".agentx/wiki");xe(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=D(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 Ki(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 Vi}from"commander";import T from"chalk";import{resolve as To}from"path";import{existsSync as Qi}from"fs";var Lt=new Vi().name("graph").description("intent knowledge graph \u2014 review, inspect, manage");Lt.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=P();if(!t.graph?.enabled){console.log(T.yellow(" graph.enabled is false \u2014 nothing to review"));return}let o=e.agent||t.graph.reviewAgent||t.graph.draftAgent;if(!o){console.log(T.red(" no review agent. Set graph.reviewAgent in agentx.json or pass --agent <id>."));return}if(!t.agents?.[o]){console.log(T.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 Ye({baseDir:To(process.cwd(),t.graph.baseDir)}),r=i.listPendingClassifications(s);if(r.length===0){console.log(T.dim(" no pending classifications \u2014 nothing to review"));return}let a=i.loadSchema(),c=i.loadNodes().nodes;console.log(),console.log(T.bold(` Graph review \u2014 ${r.length} pending`)),console.log(T.dim(` Reviewer: ${o} \xB7 daemon: ${n} \xB7 ${e.dryRun?"dry-run":"commit"}`)),console.log();let l=0,h=0,d=0,m=0;for(let f=0;f<r.length;f++){let y=r[f],w=Qo(y.path,c)||y.path.join(" \u203A ");process.stdout.write(` [${f+1}/${r.length}] ${T.cyan(y.msgHash.slice(0,8))} ${T.dim(w)} ... `);let b=Xi(y,a,c),$=null;try{$=await Zi(n,o,b,t.dashboard?.token)}catch(k){m++,console.log(T.red(`ERR ${k.message?.slice(0,80)}`));continue}if(!$||!$.decision){m++,console.log(T.red("ERR no decision"));continue}let S=String($.decision).toLowerCase().trim(),v=($.reason||"").toString().slice(0,180);if(S==="approve")if(console.log(T.green("APPROVE")+" "+T.dim(v)),e.dryRun)l++;else try{er(i,y,a,c,o),i.updateClassificationStatus(y.msgHash,{status:"approved",reviewer:o,reviewReason:v}),l++}catch(k){console.log(T.yellow(` (commit failed, staying pending: ${k.message?.slice(0,100)})`)),m++}else S==="reject"?(console.log(T.red("REJECT")+" "+T.dim(v)),e.dryRun||i.updateClassificationStatus(y.msgHash,{status:"rejected",reviewer:o,reviewReason:v}),h++):(console.log(T.yellow("SKIP")+" "+T.dim(v||S)),d++)}console.log();let p=e.dryRun?"would":"did";console.log(T.dim(` Summary: ${p} approve ${l}, ${p} reject ${h}, ${d} skipped, ${m} errors.`)),e.dryRun&&(l>0||h>0)&&console.log(T.dim(" Dry-run \u2014 omit --dry-run to apply.")),console.log()});Lt.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=P();if(!t.graph){console.log(T.yellow(" graph block missing from agentx.json \u2014 nothing to migrate"));return}let o=To(process.cwd(),t.graph.baseDir);if(!Qi(o)){console.log(T.yellow(` ${o} does not exist \u2014 nothing to migrate`));return}let{migrateV2:n}=await import("./migrate-v2-QO7SLKIM.js"),s=new Ye({baseDir:o,log:()=>{}}),i=n(s,{dryRun:!!e.dryRun,log:(...a)=>console.log(T.dim(" "),...a)});console.log(),console.log(T.bold(" Pattern hits:"));let r=Object.entries(i.patternHits).sort((a,c)=>c[1]-a[1]);r.length===0&&console.log(T.dim(" (none)"));for(let[a,c]of r)console.log(` ${a.padEnd(28)} ${c}`);console.log(),e.dryRun?console.log(T.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(T.green(` Done. Backups: ${i.backups.length} file(s).`)),console.log()});Lt.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=P();if(!t.graph?.enabled){console.log(T.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 Ye({baseDir:To(process.cwd(),t.graph.baseDir)}),r=i.loadSchema(),a=i.loadNodes().nodes,c=new Set(a.map(j=>j.id));console.log(),console.log(T.bold(` graph pull \u2190 ${o}`));let l,h,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 L=await fetch(`${o}/graph/nodes`,{headers:s});if(!L.ok)throw new Error(`nodes HTTP ${L.status}`);h=(await L.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(T.red(` fetch failed: ${j.message}`));return}let m=r.levels.map(j=>j.id).join(","),p=l?.levels?.map(j=>j.id).join(","),f=m===p;f?console.log(T.dim(` schema matches (${r.levels.length} levels)`)):(console.log(T.yellow(" \u26A0 schema levels differ:")),console.log(T.dim(` local: ${m}`)),console.log(T.dim(` peer: ${p}`)),a.length===0&&!e.dryRun?(console.log(T.dim(" local is empty \u2014 adopting peer schema")),i.saveSchema(l)):console.log(T.yellow(" keeping local schema; node import may fail if levels disagree")));let y=f?r:l,w=new Map;y.levels.forEach((j,M)=>w.set(j.id,M));let b=[...h].sort((j,M)=>(w.get(j.level)??99)-(w.get(M.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(M){v++,console.log(T.yellow(` skip node ${j.id}: ${M.message?.slice(0,100)}`))}}console.log(T.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(T.dim(` fingerprints: +${k} cached \xB7 ${C} already-present`)),console.log(),e.dryRun?console.log(T.dim(" Dry-run \u2014 omit --dry-run to apply.")):console.log(T.green(` \u2713 pulled from ${o}`)),console.log()});function Xi(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(`
336
336
  `),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(`
337
- `)}async function Hi(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 Vi((c?.content||"").toString())}finally{clearTimeout(r)}}function Ki(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function Vi(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 Zi}from"commander";import te from"chalk";import{existsSync as Ro,mkdirSync as Qi,readFileSync as Yn,readdirSync as Xi,writeFileSync as Hn}from"fs";import{resolve as Do,relative as To}from"path";import{z as ae}from"zod";var yt=ae.object({id:ae.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:ae.string().min(1),trigger:ae.string().min(1,"procedures must describe when they apply"),inputs:ae.array(ae.string()).default([]),expected:ae.string().optional(),kpis:ae.array(ae.string()).default([]),owner:ae.string().optional(),tags:ae.array(ae.string()).default([]),created:ae.string().optional(),updated:ae.string().optional(),related:ae.array(ae.string()).default([])});function Kn(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(`
338
- `)){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 Vn(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(`
339
- `)}var st=class{baseDir;constructor(t={}){this.baseDir=t.baseDir??Do(process.cwd(),".agentx/procedures"),Qi(this.baseDir,{recursive:!0})}pathFor(t){return Do(this.baseDir,`${t}.md`)}list(){if(!Ro(this.baseDir))return[];let t=[];for(let o of Xi(this.baseDir,{withFileTypes:!0})){if(!o.isFile()||!o.name.endsWith(".md")||o.name.startsWith("_"))continue;let n=Do(this.baseDir,o.name),s=Yn(n,"utf-8"),{meta:i,body:r}=Kn(s),a=yt.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:To(this.baseDir,n)})}return t.sort((o,n)=>o.meta.id.localeCompare(n.meta.id))}get(t){let o=this.pathFor(t);if(!Ro(o))return null;let n=Yn(o,"utf-8"),{meta:s,body:i}=Kn(n),r=yt.safeParse({...s,inputs:s.inputs||[],kpis:s.kpis||[],tags:s.tags||[],related:s.related||[]});return r.success?{meta:r.data,body:i.trim(),path:To(this.baseDir,o)}:null}add(t,o){let n=yt.parse({...t,created:t.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),s=this.pathFor(n.id);if(Ro(s))throw new Error(`Procedure already exists: ${n.id}`);return Hn(s,Vn(n)+`
337
+ `)}async function Zi(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 tr((c?.content||"").toString())}finally{clearTimeout(r)}}function er(e,t,o,n,s){e.commitNodesAlongPath(t.path,t.proposedAxes||{},o,s),e.setFingerprint(t.msgHash,{path:t.path,leaf:t.leaf||{}})}function tr(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 sr}from"commander";import oe from"chalk";import{existsSync as _o,mkdirSync as or,readFileSync as Xn,readdirSync as nr,writeFileSync as Zn}from"fs";import{resolve as Po,relative as No}from"path";import{z as ce}from"zod";var bt=ce.object({id:ce.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"procedure id must be lower-kebab"),title:ce.string().min(1),trigger:ce.string().min(1,"procedures must describe when they apply"),inputs:ce.array(ce.string()).default([]),expected:ce.string().optional(),kpis:ce.array(ce.string()).default([]),owner:ce.string().optional(),tags:ce.array(ce.string()).default([]),created:ce.string().optional(),updated:ce.string().optional(),related:ce.array(ce.string()).default([])});function es(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(`
338
+ `)){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 ts(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(`
339
+ `)}var it=class{baseDir;constructor(t={}){this.baseDir=t.baseDir??Po(process.cwd(),".agentx/procedures"),or(this.baseDir,{recursive:!0})}pathFor(t){return Po(this.baseDir,`${t}.md`)}list(){if(!_o(this.baseDir))return[];let t=[];for(let o of nr(this.baseDir,{withFileTypes:!0})){if(!o.isFile()||!o.name.endsWith(".md")||o.name.startsWith("_"))continue;let n=Po(this.baseDir,o.name),s=Xn(n,"utf-8"),{meta:i,body:r}=es(s),a=bt.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:No(this.baseDir,n)})}return t.sort((o,n)=>o.meta.id.localeCompare(n.meta.id))}get(t){let o=this.pathFor(t);if(!_o(o))return null;let n=Xn(o,"utf-8"),{meta:s,body:i}=es(n),r=bt.safeParse({...s,inputs:s.inputs||[],kpis:s.kpis||[],tags:s.tags||[],related:s.related||[]});return r.success?{meta:r.data,body:i.trim(),path:No(this.baseDir,o)}:null}add(t,o){let n=bt.parse({...t,created:t.created||new Date().toISOString().slice(0,10),updated:new Date().toISOString().slice(0,10)}),s=this.pathFor(n.id);if(_o(s))throw new Error(`Procedure already exists: ${n.id}`);return Zn(s,ts(n)+`
340
340
 
341
341
  `+o.trim()+`
342
- `),{meta:n,body:o.trim(),path:To(this.baseDir,s)}}update(t,o,n){let s=this.get(t);if(!s)throw new Error(`Procedure not found: ${t}`);let i=yt.parse({...s.meta,...o,id:s.meta.id,updated:new Date().toISOString().slice(0,10)}),r=n!==void 0?n:s.body;return Hn(this.pathFor(t),Vn(i)+`
342
+ `),{meta:n,body:o.trim(),path:No(this.baseDir,s)}}update(t,o,n){let s=this.get(t);if(!s)throw new Error(`Procedure not found: ${t}`);let i=bt.parse({...s.meta,...o,id:s.meta.id,updated:new Date().toISOString().slice(0,10)}),r=n!==void 0?n:s.body;return Zn(this.pathFor(t),ts(i)+`
343
343
 
344
344
  `+r.trim()+`
345
- `),{meta:i,body:r.trim(),path:s.path}}};var Nt=new Zi().name("procedure").description("procedures (SOPs) \u2014 list, add, show \xB7 delta extraction coming later");Nt.command("list").description("list all procedures with their trigger line").action(()=>{let t=new st().list();if(!t.length){console.log(te.dim(" no procedures yet. Add one with: agentx procedure add"));return}console.log();for(let o of t)console.log(` ${te.cyan(o.meta.id)} ${te.bold(o.meta.title)}`),console.log(` ${te.dim("trigger:")} ${o.meta.trigger}`),o.meta.kpis?.length&&console.log(` ${te.dim("kpis:")} ${o.meta.kpis.join(", ")}`);console.log(),console.log(te.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});Nt.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 st,o=e.steps?String(e.steps):`## Steps
345
+ `),{meta:i,body:r.trim(),path:s.path}}};var Wt=new sr().name("procedure").description("procedures (SOPs) \u2014 list, add, show \xB7 delta extraction coming later");Wt.command("list").description("list all procedures with their trigger line").action(()=>{let t=new it().list();if(!t.length){console.log(oe.dim(" no procedures yet. Add one with: agentx procedure add"));return}console.log();for(let o of t)console.log(` ${oe.cyan(o.meta.id)} ${oe.bold(o.meta.title)}`),console.log(` ${oe.dim("trigger:")} ${o.meta.trigger}`),o.meta.kpis?.length&&console.log(` ${oe.dim("kpis:")} ${o.meta.kpis.join(", ")}`);console.log(),console.log(oe.dim(` ${t.length} procedure${t.length===1?"":"s"}.`))});Wt.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 it,o=e.steps?String(e.steps):`## Steps
346
346
 
347
347
  1. (fill in)
348
348
 
349
349
  ## Notes
350
350
 
351
- `;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(te.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(te.dim(` ${t.baseDir}/${n.path}`))}catch(n){console.log(te.red(` add failed: ${n.message}`)),process.exit(1)}});Nt.command("show <id>").description("show a single procedure").action(e=>{let o=new st().get(e);o||(console.log(te.yellow(` no procedure matches "${e}". Try: agentx procedure list`)),process.exit(1)),console.log(),console.log(te.bold(` ${o.meta.title}`)+te.dim(` (${o.meta.id})`)),console.log(te.dim(` trigger: ${o.meta.trigger}`)),o.meta.inputs?.length&&console.log(te.dim(` inputs: ${o.meta.inputs.join(", ")}`)),o.meta.expected&&console.log(te.dim(` expected: ${o.meta.expected}`)),o.meta.kpis?.length&&console.log(te.dim(` kpis: ${o.meta.kpis.join(", ")}`)),o.meta.owner&&console.log(te.dim(` owner: ${o.meta.owner}`)),o.meta.related?.length&&console.log(te.dim(` related: ${o.meta.related.join(", ")}`)),console.log(),console.log(o.body),console.log()});import{Command as er}from"commander";import O from"chalk";import{resolve as tr}from"path";import{existsSync as or,readFileSync as nr}from"fs";var Ee=new er().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Ee.command("list").description("list all workflows with their trigger + state count").action(()=>{let t=new qt().list();if(!t.length){console.log(O.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(` ${O.cyan(o.id)} ${O.bold(o.title)} ${O.dim(`v${o.version}`)}`),console.log(` ${O.dim("trigger:")} ${s.source??"?"}${i?` ${O.dim(i)}`:""}`),console.log(` ${O.dim("nodes: ")} ${o.nodes.length} (${o.nodes.map(r=>r.type).join(", ")})`)}console.log(),console.log(O.dim(` ${t.length} workflow${t.length===1?"":"s"}.`))});Ee.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 qt().get(e);n||(console.log(O.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=t.format.toLowerCase();s==="yaml"||s==="yml"?console.log(an(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(O.red(` unknown format "${t.format}" \u2014 use json or yaml`)),process.exit(1))});Ee.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=tr(process.cwd(),e);or(i)||(console.log(O.red(` file not found: ${i}`)),process.exit(1));try{let r=nr(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?rn(r,{filePath:e}):JSON.parse(r),l=on.safeParse(c);if(!l.success){console.log(O.red(` \u2717 ${i}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let p=nn(l.data);if(p.length){console.log(O.yellow(` ! ${i} (lint)`));for(let d of p)console.log(` ${d}`);process.exit(1)}console.log(O.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof sn?r.message:`parse error: ${r?.message??r}`;console.log(O.red(` ${a}`)),process.exit(1)}return}let o=new qt().validateAll(),n=0,s=0;for(let i of o)if(i.isValid)console.log(O.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(O.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(O.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Ee.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 Et({nodeId:o}).list({workflowId:e,limit:Number(t.limit)});if(!n.length){console.log(O.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"?O.cyan:s.status==="failed"?O.red:O.green;console.log(` ${O.dim(s.id.slice(0,8))} ${O.bold(s.workflowId)} ${a(r)} ${O.dim(s.status)}`),console.log(` ${O.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${O.dim("home: ")} ${s.homeNode}`),console.log(` ${O.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${O.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(O.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Ee.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(O.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(O.red(` run failed (${s.status}): ${r.slice(0,300)}`)),s.status===409&&console.log(O.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let i=await s.json();console.log(O.green(` \u2713 run started: ${i.runId||"(unknown id)"}${i.force?O.dim(` (forced, source=${i.source})`):""}`))}catch(s){console.log(O.red(` request to daemon failed: ${s.message}`)),process.exit(1)}});Ee.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 Et({nodeId:o}).setStatus(e,"paused")||(console.log(O.yellow(` no such run: ${e}`)),process.exit(1)),console.log(O.green(` \u2713 paused ${e}`))});Ee.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 Et({nodeId:o}).setStatus(e,"running")||(console.log(O.yellow(` no such run: ${e}`)),process.exit(1)),console.log(O.green(` \u2713 resumed ${e}`))});Ee.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 Et({nodeId:o}).setStatus(e,"canceled")||(console.log(O.yellow(` no such run: ${e}`)),process.exit(1)),console.log(O.green(` \u2713 canceled ${e}`))});import{Command as sr}from"commander";import F from"chalk";import Qn from"prompts";function Zt(){let e=P(),[t,o]=(e.node?.bind||"127.0.0.1:18800").split(":");return`http://${t||"127.0.0.1"}:${o||18800}`}async function eo(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 Mt=new sr().name("task").description("workflow user-tasks \u2014 list, show, submit (the terminal inbox)");Mt.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 eo(`${Zt()}/api/workflows/tasks${t}`)).tasks||[];if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(F.dim(" No open tasks.")),console.log();return}console.log(),console.log(F.bold(` ${n.length} open task${n.length===1?"":"s"}`)),console.log();for(let s of n){let i=s.dueAt?F.yellow(` \xB7 due ${s.dueAt.slice(0,16).replace("T"," ")}`):"",r=s.form?.fields?.length||0;console.log(` ${F.bold(s.id)}${i}`),console.log(` ${s.title}`),console.log(F.dim(` workflow=${s.workflowId} node=${s.nodeId} assignee=${s.assignee} fields=${r}`))}console.log(),console.log(F.dim(" agentx task show <id> to see form details")),console.log(F.dim(" agentx task submit <id> to fill it in")),console.log()}catch(t){console.log(F.red(` ${t.message}`)),process.exitCode=1}});Mt.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 eo(`${Zt()}/api/workflows/tasks/${encodeURIComponent(e)}`)).task;if(t.json){console.log(JSON.stringify(n,null,2));return}console.log(),console.log(F.bold(` ${n.title}`)),n.description&&console.log(F.dim(` ${n.description}`)),console.log(),console.log(F.dim(` id=${n.id} workflow=${n.workflowId} node=${n.nodeId}`)),console.log(F.dim(` assignee=${n.assignee} status=${n.status}`)),n.dueAt&&console.log(F.yellow(` due ${n.dueAt}`)),console.log();let s=n.form?.fields||[];if(s.length===0)console.log(F.dim(" (no fields)"));else{console.log(F.bold(" Fields:"));for(let i of s){let r=i.required?F.red("*"):" ",a=i.options?.length?F.dim(` [${i.options.join("|")}]`):"",c=i.hint?F.dim(` \u2014 ${i.hint}`):"";console.log(` ${r} ${F.cyan(i.key)} (${i.type})${a}${c}`)}}console.log(),console.log(F.dim(` agentx task submit ${n.id} to fill it in`)),console.log()}catch(o){console.log(F.red(` ${o.message}`)),process.exitCode=1}});Mt.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 eo(`${Zt()}/api/workflows/tasks/${encodeURIComponent(e)}`)).task;if(n.status!=="open"){console.log(F.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(F.red(` --json parse failed: ${c.message}`)),process.exitCode=1;return}else{console.log(),console.log(F.bold(` ${n.title}`)),n.description&&console.log(F.dim(` ${n.description}`)),console.log();for(let c of n.form?.fields||[]){let l=ir(c.type),p=`${c.label}${c.required?F.red(" *"):""}${c.hint?F.dim(` (${c.hint})`):""}`,d=c.defaultValue!==void 0?c.defaultValue:void 0,m=c.options?.map(w=>({title:w,value:w})),h={type:l,name:c.key,message:p,...d!==void 0?{initial:d}:{},...m?{choices:m}:{},validate:w=>c.required&&(w==null||w==="")?`${c.label} is required`:!0},f=await Qn(h,{onCancel:()=>process.exit(130)});i[c.key]=f[c.key]}if(!t.secondary&&n.form?.secondaryAction){let c=n.form.submitLabel||"Submit",l=n.form.secondaryAction.label;(await Qn({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 eo(`${Zt()}/api/workflows/tasks/${encodeURIComponent(e)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if("error"in a){if(console.log(F.red(` ${a.error}`)),a.fieldErrors)for(let[c,l]of Object.entries(a.fieldErrors))console.log(F.red(` ${c}: ${l}`));process.exitCode=1;return}console.log(),console.log(F.green(` Submitted (action=${s}). runId=${a.runId}`)),console.log()}catch(o){console.log(F.red(` ${o.message}`)),process.exitCode=1}});function ir(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 rr}from"commander";import q from"chalk";function wt(e){let{summary:t,backupPath:o}=ct(n=>e(n));console.log(q.green(`
352
- \u2713 ${t}`)),o&&console.log(q.dim(` Backup: ${o}`)),console.log(q.dim(` Restart the daemon (or POST /reload) for the change to take effect.
353
- `))}function to(){try{return P().business||{}}catch{return{}}}var $t=new rr().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");$t.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let t=to();if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t||!t.enabled){console.log(),console.log(q.yellow(" business block not enabled (or missing).")),console.log(q.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(q.bold(" Org chart"));let i=Object.entries(o);if(i.length===0)console.log(q.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?q.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?q.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${q.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(q.bold(` Projects (${n.length})`)),n.length===0)console.log(q.dim(" (empty)"));else for(let r of n){let a=r.pm?q.dim(` \xB7 pm=${r.pm}`):"",c=r.client?q.dim(` \xB7 client=${r.client}`):"";console.log(` ${q.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(q.bold(` Contact map (${s.length})`)),s.length===0)console.log(q.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(` ${q.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?q.dim(` (${r.displayName})`):""}`)}console.log()});var _o=$t.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");_o.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let t=to(),o=Object.entries(t.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(o),null,2));return}if(o.length===0){console.log(q.dim(" no entries"));return}for(let[n,s]of o)console.log(` ${q.cyan(n)} ${s.role}${s.reportsTo?q.dim(` \u2192 ${s.reportsTo}`):""}`)});_o.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);wt(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}`:""})`))});_o.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{wt(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 Po=$t.command("project").description("manage business.projects \u2014 id, pm, client");Po.command("list").description("list projects").option("--json","JSON output").action(e=>{let o=to().projects||[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(q.dim(" no projects"));return}for(let n of o)console.log(` ${q.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});Po.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)=>{wt(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`})});Po.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{wt(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 No=$t.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");No.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let o=to().contactMap||[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(q.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+"/":""}${q.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});No.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(q.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),wt(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`})});No.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=>{wt(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 ar}from"commander";import fe from"chalk";function cr(){try{return P().notifications||{}}catch{return{}}}function oo(e){let{summary:t,backupPath:o}=ct(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(fe.green(`
354
- \u2713 ${t}`)),o&&console.log(fe.dim(` Backup: ${o}`)),console.log(fe.dim(` Restart the daemon (or POST /reload) for the change to take effect.
355
- `))}var bt=new ar().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");bt.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let t=cr();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 ${fe.cyan(t.destination.channel+":"+t.destination.chatId)}${fe.dim(n)}`)}else console.log(` destination ${fe.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${t.longTaskThreshold??30}s ${fe.dim("(0 disables long-task pings)")}`);let o=t.on||{};console.log(` on.taskComplete ${o.taskComplete===!1?fe.dim("off"):"on"}`),console.log(` on.taskError ${o.taskError===!1?fe.dim("off"):"on"}`),console.log(` on.taskQueued ${o.taskQueued?"on":fe.dim("off")}`),console.log()});bt.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){oo(t=>(delete t.destination,"notifications destination cleared"));return}oo(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})`:""}`))});bt.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(fe.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(fe.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";oo(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});bt.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(fe.red(" threshold must be a non-negative integer")),process.exit(1)),oo(o=>(o.longTaskThreshold=t,`longTaskThreshold = ${t}s`))});import{Command as lr}from"commander";import qe from"chalk";import{readdirSync as Mo,statSync as Xn,unlinkSync as dr,rmSync as gr,existsSync as Zn}from"fs";import{resolve as es,join as ts}from"path";var os=[{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 Lo(e,t){if(!Zn(e))return[];let o=[];for(let n of Mo(e,{withFileTypes:!0})){let s=ts(e,n.name);n.isFile()?o.push(s):n.isDirectory()&&t&&o.push(...Lo(s,!0))}return o}var so=new lr().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");so.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let t of os){let o=es(process.cwd(),t.dir),n=Lo(o,!!t.recursive),s=0,i=null;for(let a of n)try{let c=Xn(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(` ${qe.cyan(t.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${no(s).padStart(10)} oldest=${r}`)}console.log(qe.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${no(e).padStart(10)} total`)),console.log(),console.log(qe.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});so.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(qe.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(qe.bold(` Pruning files older than ${t}d (${new Date(o).toISOString().slice(0,10)})${e.dryRun?qe.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of os){if(n&&r.dir!==n)continue;let a=es(process.cwd(),r.dir),c=Lo(a,!!r.recursive),l=0,p=0;for(let m of c)try{let h=Xn(m);if(h.mtimeMs<o&&(p+=h.size,l++,!e.dryRun))try{dr(m)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{ns(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${qe.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${no(p)})`),s+=l,i+=p}console.log(),console.log(qe.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${no(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function ns(e){if(Zn(e))for(let t of Mo(e,{withFileTypes:!0})){if(!t.isDirectory())continue;let o=ts(e,t.name);ns(o);try{Mo(o).length===0&&gr(o,{recursive:!1})}catch{}}}function no(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 ss}from"commander";import J from"chalk";var kt=new ss().name("actor").description("manage actors (humans) that can be assigned to workflow userTasks");kt.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 xe;if(n.getActor(o)){console.error(J.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(J.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(J.green(` \u2713 actor "${a.id}" saved (${a.channels.length} channel${a.channels.length===1?"":"s"})`))});kt.command("list").description("list all actors").action(()=>{let t=new xe().listActors();if(!t.length){console.log(J.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(` ${J.cyan(o.id.padEnd(24))} ${J.bold(o.name)}`),console.log(` ${J.dim(n)}`)}console.log(),console.log(J.dim(` ${t.length} actor${t.length===1?"":"s"}. * = preferred for tasks.`))});kt.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 xe().getActor(t);if(!n){console.error(J.red(` actor "${t}" not found`)),process.exitCode=1;return}console.log(JSON.stringify(n,null,2))});kt.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 xe().deleteActor(t)){console.error(J.red(` actor "${t}" not found`)),process.exitCode=1;return}console.log(J.green(` \u2713 actor "${t}" removed`))});var it=new ss().name("role").description("manage roles (groups of actors) for workflow userTasks");it.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 xe;if(n.getRole(o)){console.error(J.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(J.green(` \u2713 role "${i.id}" created (strategy: ${i.assignmentStrategy})`))});it.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 xe,s=n.getRole(o);if(!s){console.error(J.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(J.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(J.dim(" already a member"));return}let r=n.saveRole({...s,members:[...s.members,i]});console.log(J.green(` \u2713 ${t} granted to ${o} (${r.members.length} member${r.members.length===1?"":"s"})`))});it.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 xe,s=n.getRole(o);if(!s){console.error(J.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(J.dim(` "${t}" was not a member`));return}n.saveRole({...s,members:r}),console.log(J.green(` \u2713 ${t} revoked from ${o}`))});it.command("list").description("list all roles with member counts").action(()=>{let t=new xe().listRoles();if(!t.length){console.log(J.dim(" no roles yet. Try: agentx role create reviewers --name 'Reviewers'"));return}console.log();for(let o of t){console.log(` ${J.cyan(o.id.padEnd(24))} ${J.bold(o.name)} ${J.dim(o.assignmentStrategy)}`);for(let n of o.members){let s="actor"in n?n.actor:n.role;console.log(` ${J.dim("\u2022")} ${s}`)}}console.log(),console.log(J.dim(` ${t.length} role${t.length===1?"":"s"}.`))});it.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 xe,n=o.getRole(t);if(!n){console.error(J.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 mr}from"commander";import B from"chalk";var is=new mr().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=P(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(B.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(B.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(B.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(`
351
+ `;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(oe.green(` \u2713 procedure added: ${n.meta.id}`)),console.log(oe.dim(` ${t.baseDir}/${n.path}`))}catch(n){console.log(oe.red(` add failed: ${n.message}`)),process.exit(1)}});Wt.command("show <id>").description("show a single procedure").action(e=>{let o=new it().get(e);o||(console.log(oe.yellow(` no procedure matches "${e}". Try: agentx procedure list`)),process.exit(1)),console.log(),console.log(oe.bold(` ${o.meta.title}`)+oe.dim(` (${o.meta.id})`)),console.log(oe.dim(` trigger: ${o.meta.trigger}`)),o.meta.inputs?.length&&console.log(oe.dim(` inputs: ${o.meta.inputs.join(", ")}`)),o.meta.expected&&console.log(oe.dim(` expected: ${o.meta.expected}`)),o.meta.kpis?.length&&console.log(oe.dim(` kpis: ${o.meta.kpis.join(", ")}`)),o.meta.owner&&console.log(oe.dim(` owner: ${o.meta.owner}`)),o.meta.related?.length&&console.log(oe.dim(` related: ${o.meta.related.join(", ")}`)),console.log(),console.log(o.body),console.log()});import{Command as ir}from"commander";import I from"chalk";import{resolve as rr}from"path";import{existsSync as ar,readFileSync as cr}from"fs";var Ae=new ir().name("workflow").description("workflow definitions \u2014 list, show, validate, manage runs");Ae.command("list").description("list all workflows with their trigger + state count").action(()=>{let t=new Gt().list();if(!t.length){console.log(I.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(` ${I.cyan(o.id)} ${I.bold(o.title)} ${I.dim(`v${o.version}`)}`),console.log(` ${I.dim("trigger:")} ${s.source??"?"}${i?` ${I.dim(i)}`:""}`),console.log(` ${I.dim("nodes: ")} ${o.nodes.length} (${o.nodes.map(r=>r.type).join(", ")})`)}console.log(),console.log(I.dim(` ${t.length} workflow${t.length===1?"":"s"}.`))});Ae.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 Gt().get(e);n||(console.log(I.yellow(` no workflow matches "${e}". Try: agentx workflow list`)),process.exit(1));let s=t.format.toLowerCase();s==="yaml"||s==="yml"?console.log(dn(n)):s==="json"?console.log(JSON.stringify(n,null,2)):(console.log(I.red(` unknown format "${t.format}" \u2014 use json or yaml`)),process.exit(1))});Ae.command("validate [file]").description("validate all workflows in .agentx/workflows (or a single file)").action(e=>{if(e){let i=rr(process.cwd(),e);ar(i)||(console.log(I.red(` file not found: ${i}`)),process.exit(1));try{let r=cr(i,"utf-8"),c=/\.(ya?ml)$/i.test(e)?ln(r,{filePath:e}):JSON.parse(r),l=rn.safeParse(c);if(!l.success){console.log(I.red(` \u2717 ${i}`));for(let d of l.error.issues)console.log(` ${d.path.join(".")||"<root>"}: ${d.message}`);process.exit(1)}let h=an(l.data);if(h.length){console.log(I.yellow(` ! ${i} (lint)`));for(let d of h)console.log(` ${d}`);process.exit(1)}console.log(I.green(` \u2713 ${l.data.id} \u2014 valid`))}catch(r){let a=r instanceof cn?r.message:`parse error: ${r?.message??r}`;console.log(I.red(` ${a}`)),process.exit(1)}return}let o=new Gt().validateAll(),n=0,s=0;for(let i of o)if(i.isValid)console.log(I.green(` \u2713 ${i.workflow.id}`)),n++;else{let r=i.workflow?.id||i.id;console.log(I.red(` \u2717 ${r}`));for(let a of i.issues)console.log(` ${a}`);s++}console.log(),console.log(I.dim(` ${n} valid, ${s} invalid.`)),s>0&&process.exit(1)});Ae.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 It({nodeId:o}).list({workflowId:e,limit:Number(t.limit)});if(!n.length){console.log(I.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"?I.cyan:s.status==="failed"?I.red:I.green;console.log(` ${I.dim(s.id.slice(0,8))} ${I.bold(s.workflowId)} ${a(r)} ${I.dim(s.status)}`),console.log(` ${I.dim("entity: ")} ${s.entityRef.backend}:${s.entityRef.id}`),console.log(` ${I.dim("home: ")} ${s.homeNode}`),console.log(` ${I.dim("updated: ")} ${s.updatedAt}`),i&&console.log(` ${I.dim("last: ")} ${i.nodeId} (${i.status})`)}console.log(),console.log(I.dim(` ${n.length} run${n.length===1?"":"s"}.`))});Ae.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(I.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(I.red(` run failed (${s.status}): ${r.slice(0,300)}`)),s.status===409&&console.log(I.dim(" hint: pass --force to fire non-manual workflows for testing")),process.exit(1)}let i=await s.json();console.log(I.green(` \u2713 run started: ${i.runId||"(unknown id)"}${i.force?I.dim(` (forced, source=${i.source})`):""}`))}catch(s){console.log(I.red(` request to daemon failed: ${s.message}`)),process.exit(1)}});Ae.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 It({nodeId:o}).setStatus(e,"paused")||(console.log(I.yellow(` no such run: ${e}`)),process.exit(1)),console.log(I.green(` \u2713 paused ${e}`))});Ae.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 It({nodeId:o}).setStatus(e,"running")||(console.log(I.yellow(` no such run: ${e}`)),process.exit(1)),console.log(I.green(` \u2713 resumed ${e}`))});Ae.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 It({nodeId:o}).setStatus(e,"canceled")||(console.log(I.yellow(` no such run: ${e}`)),process.exit(1)),console.log(I.green(` \u2713 canceled ${e}`))});import{Command as lr}from"commander";import F from"chalk";import os from"prompts";function oo(){let e=P(),[t,o]=(e.node?.bind||"127.0.0.1:18800").split(":");return`http://${t||"127.0.0.1"}:${o||18800}`}async function no(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 Ft=new lr().name("task").description("workflow user-tasks \u2014 list, show, submit (the terminal inbox)");Ft.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 no(`${oo()}/api/workflows/tasks${t}`)).tasks||[];if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(F.dim(" No open tasks.")),console.log();return}console.log(),console.log(F.bold(` ${n.length} open task${n.length===1?"":"s"}`)),console.log();for(let s of n){let i=s.dueAt?F.yellow(` \xB7 due ${s.dueAt.slice(0,16).replace("T"," ")}`):"",r=s.form?.fields?.length||0;console.log(` ${F.bold(s.id)}${i}`),console.log(` ${s.title}`),console.log(F.dim(` workflow=${s.workflowId} node=${s.nodeId} assignee=${s.assignee} fields=${r}`))}console.log(),console.log(F.dim(" agentx task show <id> to see form details")),console.log(F.dim(" agentx task submit <id> to fill it in")),console.log()}catch(t){console.log(F.red(` ${t.message}`)),process.exitCode=1}});Ft.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 no(`${oo()}/api/workflows/tasks/${encodeURIComponent(e)}`)).task;if(t.json){console.log(JSON.stringify(n,null,2));return}console.log(),console.log(F.bold(` ${n.title}`)),n.description&&console.log(F.dim(` ${n.description}`)),console.log(),console.log(F.dim(` id=${n.id} workflow=${n.workflowId} node=${n.nodeId}`)),console.log(F.dim(` assignee=${n.assignee} status=${n.status}`)),n.dueAt&&console.log(F.yellow(` due ${n.dueAt}`)),console.log();let s=n.form?.fields||[];if(s.length===0)console.log(F.dim(" (no fields)"));else{console.log(F.bold(" Fields:"));for(let i of s){let r=i.required?F.red("*"):" ",a=i.options?.length?F.dim(` [${i.options.join("|")}]`):"",c=i.hint?F.dim(` \u2014 ${i.hint}`):"";console.log(` ${r} ${F.cyan(i.key)} (${i.type})${a}${c}`)}}console.log(),console.log(F.dim(` agentx task submit ${n.id} to fill it in`)),console.log()}catch(o){console.log(F.red(` ${o.message}`)),process.exitCode=1}});Ft.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 no(`${oo()}/api/workflows/tasks/${encodeURIComponent(e)}`)).task;if(n.status!=="open"){console.log(F.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(F.red(` --json parse failed: ${c.message}`)),process.exitCode=1;return}else{console.log(),console.log(F.bold(` ${n.title}`)),n.description&&console.log(F.dim(` ${n.description}`)),console.log();for(let c of n.form?.fields||[]){let l=dr(c.type),h=`${c.label}${c.required?F.red(" *"):""}${c.hint?F.dim(` (${c.hint})`):""}`,d=c.defaultValue!==void 0?c.defaultValue:void 0,m=c.options?.map(y=>({title:y,value:y})),p={type:l,name:c.key,message:h,...d!==void 0?{initial:d}:{},...m?{choices:m}:{},validate:y=>c.required&&(y==null||y==="")?`${c.label} is required`:!0},f=await os(p,{onCancel:()=>process.exit(130)});i[c.key]=f[c.key]}if(!t.secondary&&n.form?.secondaryAction){let c=n.form.submitLabel||"Submit",l=n.form.secondaryAction.label;(await os({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 no(`${oo()}/api/workflows/tasks/${encodeURIComponent(e)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if("error"in a){if(console.log(F.red(` ${a.error}`)),a.fieldErrors)for(let[c,l]of Object.entries(a.fieldErrors))console.log(F.red(` ${c}: ${l}`));process.exitCode=1;return}console.log(),console.log(F.green(` Submitted (action=${s}). runId=${a.runId}`)),console.log()}catch(o){console.log(F.red(` ${o.message}`)),process.exitCode=1}});function dr(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 gr}from"commander";import J from"chalk";function kt(e){let{summary:t,backupPath:o}=gt(n=>e(n));console.log(J.green(`
352
+ \u2713 ${t}`)),o&&console.log(J.dim(` Backup: ${o}`)),console.log(J.dim(` Restart the daemon (or POST /reload) for the change to take effect.
353
+ `))}function so(){try{return P().business||{}}catch{return{}}}var vt=new gr().name("business").description("manage the business layer in agentx.json \u2014 orgChart, projects, contactMap");vt.command("show").description("print the current business config (orgChart, projects, contactMap)").option("--json","machine-readable JSON").action(e=>{let t=so();if(e.json){console.log(JSON.stringify(t,null,2));return}if(!t||!t.enabled){console.log(),console.log(J.yellow(" business block not enabled (or missing).")),console.log(J.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(J.bold(" Org chart"));let i=Object.entries(o);if(i.length===0)console.log(J.dim(" (empty)"));else for(let[r,a]of i){let c=a.reportsTo?J.dim(` \u2192 reports to ${a.reportsTo}`):"",l=a.schedule?J.dim(` \xB7 ${(a.schedule.days||[]).join(",")} ${a.schedule.start}\u2013${a.schedule.end}`):"";console.log(` ${J.cyan(r)} ${a.role}${c}${l}`)}if(console.log(),console.log(J.bold(` Projects (${n.length})`)),n.length===0)console.log(J.dim(" (empty)"));else for(let r of n){let a=r.pm?J.dim(` \xB7 pm=${r.pm}`):"",c=r.client?J.dim(` \xB7 client=${r.client}`):"";console.log(` ${J.cyan(r.id)}${a}${c}`)}if(console.log(),console.log(J.bold(` Contact map (${s.length})`)),s.length===0)console.log(J.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(` ${J.cyan(c+a)} \u2192 ${r.client}${r.project?`/${r.project}`:""}${r.displayName?J.dim(` (${r.displayName})`):""}`)}console.log()});var Mo=vt.command("orgchart").description("manage business.orgChart \u2014 agentId \u2192 { role, reportsTo, schedule }");Mo.command("list").description("list orgChart entries").option("--json","JSON output").action(e=>{let t=so(),o=Object.entries(t.orgChart||{});if(e.json){console.log(JSON.stringify(Object.fromEntries(o),null,2));return}if(o.length===0){console.log(J.dim(" no entries"));return}for(let[n,s]of o)console.log(` ${J.cyan(n)} ${s.role}${s.reportsTo?J.dim(` \u2192 ${s.reportsTo}`):""}`)});Mo.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);kt(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}`:""})`))});Mo.command("remove <agentId>").alias("rm").description("remove an orgChart entry").action(e=>{kt(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 Lo=vt.command("project").description("manage business.projects \u2014 id, pm, client");Lo.command("list").description("list projects").option("--json","JSON output").action(e=>{let o=so().projects||[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(J.dim(" no projects"));return}for(let n of o)console.log(` ${J.cyan(n.id)} ${n.pm?`pm=${n.pm}`:""} ${n.client?`client=${n.client}`:""}`.trimEnd())});Lo.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)=>{kt(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`})});Lo.command("remove <id>").alias("rm").description("remove a project entry").action(e=>{kt(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 Wo=vt.command("contact").description("manage business.contactMap \u2014 chatId/username/senderId \u2192 client/project");Wo.command("list").description("list contact map entries").option("--json","JSON output").action(e=>{let o=so().contactMap||[];if(e.json){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(J.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+"/":""}${J.cyan(s)} \u2192 ${n.client}${n.project?"/"+n.project:""}`)}});Wo.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(J.red(" one of --chat-id / --username / --sender-id is required")),process.exit(1)),kt(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`})});Wo.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=>{kt(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 mr}from"commander";import ye from"chalk";function pr(){try{return P().notifications||{}}catch{return{}}}function io(e){let{summary:t,backupPath:o}=gt(n=>(n.notifications=n.notifications||{},e(n.notifications)));console.log(ye.green(`
354
+ \u2713 ${t}`)),o&&console.log(ye.dim(` Backup: ${o}`)),console.log(ye.dim(` Restart the daemon (or POST /reload) for the change to take effect.
355
+ `))}var xt=new mr().name("notifications").description("manage notifications routing \u2014 destination, event toggles, long-task threshold");xt.command("show").description("print current notifications config").option("--json","JSON output").action(e=>{let t=pr();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 ${ye.cyan(t.destination.channel+":"+t.destination.chatId)}${ye.dim(n)}`)}else console.log(` destination ${ye.dim("(unset \u2014 notifications go to the daemon log only)")}`);console.log(` longTaskThreshold ${t.longTaskThreshold??30}s ${ye.dim("(0 disables long-task pings)")}`);let o=t.on||{};console.log(` on.taskComplete ${o.taskComplete===!1?ye.dim("off"):"on"}`),console.log(` on.taskError ${o.taskError===!1?ye.dim("off"):"on"}`),console.log(` on.taskQueued ${o.taskQueued?"on":ye.dim("off")}`),console.log()});xt.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){io(t=>(delete t.destination,"notifications destination cleared"));return}io(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})`:""}`))});xt.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(ye.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(ye.red(" state must be on|off")),process.exit(1));let s=n==="on"||n==="true"||n==="1";io(i=>(i.on=i.on||{},i.on[e]=s,`notifications.on.${e} = ${s}`))});xt.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(ye.red(" threshold must be a non-negative integer")),process.exit(1)),io(o=>(o.longTaskThreshold=t,`longTaskThreshold = ${t}s`))});import{Command as ur}from"commander";import Je from"chalk";import{readdirSync as Fo,statSync as ns,unlinkSync as hr,rmSync as fr,existsSync as ss}from"fs";import{resolve as is,join as rs}from"path";var as=[{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 Bo(e,t){if(!ss(e))return[];let o=[];for(let n of Fo(e,{withFileTypes:!0})){let s=rs(e,n.name);n.isFile()?o.push(s):n.isDirectory()&&t&&o.push(...Bo(s,!0))}return o}var ao=new ur().name("retention").description("prune old workspace state (sessions, drift, router traces, pattern store)");ao.command("show",{isDefault:!0}).description("show how much each retention target currently weighs").action(()=>{console.log();let e=0;for(let t of as){let o=is(process.cwd(),t.dir),n=Bo(o,!!t.recursive),s=0,i=null;for(let a of n)try{let c=ns(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(` ${Je.cyan(t.dir.padEnd(22))} ${String(n.length).padStart(5)} files ${ro(s).padStart(10)} oldest=${r}`)}console.log(Je.dim(` ${"".padEnd(22)} ${"".padStart(5)} ${ro(e).padStart(10)} total`)),console.log(),console.log(Je.dim(" Run `agentx retention prune --days 30` to delete files older than 30 days.")),console.log()});ao.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(Je.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(Je.bold(` Pruning files older than ${t}d (${new Date(o).toISOString().slice(0,10)})${e.dryRun?Je.yellow(" \u2014 DRY RUN"):""}`)),console.log();for(let r of as){if(n&&r.dir!==n)continue;let a=is(process.cwd(),r.dir),c=Bo(a,!!r.recursive),l=0,h=0;for(let m of c)try{let p=ns(m);if(p.mtimeMs<o&&(h+=p.size,l++,!e.dryRun))try{hr(m)}catch{}}catch{}if(r.recursive&&!e.dryRun)try{cs(a)}catch{}let d=e.dryRun?"would remove":"removed";console.log(` ${Je.cyan(r.dir.padEnd(22))} ${d} ${String(l).padStart(5)} files (${ro(h)})`),s+=l,i+=h}console.log(),console.log(Je.green(` \u2713 ${e.dryRun?"(dry-run)":""} ${s} files, ${ro(i)} ${e.dryRun?"would be reclaimed":"reclaimed"}`)),console.log()});function cs(e){if(ss(e))for(let t of Fo(e,{withFileTypes:!0})){if(!t.isDirectory())continue;let o=rs(e,t.name);cs(o);try{Fo(o).length===0&&fr(o,{recursive:!1})}catch{}}}function ro(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 yr}from"commander";import B from"chalk";var rt=new yr().name("actions").description("manage the action registry \u2014 reusable shell/http invocations");rt.command("list").description("list registered actions").option("--json","JSON output").action(e=>{let o=new dt().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()});rt.command("show <id>").description("show an action's full definition").option("--json","JSON output").action((e,t)=>{let n=new dt().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()});rt.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=wr(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=gn.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 dt().save(s.data);console.log(B.green(`
356
+ \u2713 action "${r.id}" saved (${r.kind}).`)),console.log(B.dim(` Test: agentx actions run ${r.id}
357
+ `))});rt.command("remove <id>").alias("rm").description("delete an action").action(e=>{new dt().delete(e)||(console.log(B.red(` no action "${e}"`)),process.exit(1)),console.log(B.green(` \u2713 action "${e}" removed`))});rt.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 dt().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 mn(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 wr(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 ls}from"commander";import z from"chalk";var St=new ls().name("actor").description("manage actors (humans) that can be assigned to workflow userTasks");St.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 Se;if(n.getActor(o)){console.error(z.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(z.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(z.green(` \u2713 actor "${a.id}" saved (${a.channels.length} channel${a.channels.length===1?"":"s"})`))});St.command("list").description("list all actors").action(()=>{let t=new Se().listActors();if(!t.length){console.log(z.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(` ${z.cyan(o.id.padEnd(24))} ${z.bold(o.name)}`),console.log(` ${z.dim(n)}`)}console.log(),console.log(z.dim(` ${t.length} actor${t.length===1?"":"s"}. * = preferred for tasks.`))});St.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 Se().getActor(t);if(!n){console.error(z.red(` actor "${t}" not found`)),process.exitCode=1;return}console.log(JSON.stringify(n,null,2))});St.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 Se().deleteActor(t)){console.error(z.red(` actor "${t}" not found`)),process.exitCode=1;return}console.log(z.green(` \u2713 actor "${t}" removed`))});var at=new ls().name("role").description("manage roles (groups of actors) for workflow userTasks");at.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 Se;if(n.getRole(o)){console.error(z.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(z.green(` \u2713 role "${i.id}" created (strategy: ${i.assignmentStrategy})`))});at.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 Se,s=n.getRole(o);if(!s){console.error(z.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(z.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(z.dim(" already a member"));return}let r=n.saveRole({...s,members:[...s.members,i]});console.log(z.green(` \u2713 ${t} granted to ${o} (${r.members.length} member${r.members.length===1?"":"s"})`))});at.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 Se,s=n.getRole(o);if(!s){console.error(z.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(z.dim(` "${t}" was not a member`));return}n.saveRole({...s,members:r}),console.log(z.green(` \u2713 ${t} revoked from ${o}`))});at.command("list").description("list all roles with member counts").action(()=>{let t=new Se().listRoles();if(!t.length){console.log(z.dim(" no roles yet. Try: agentx role create reviewers --name 'Reviewers'"));return}console.log();for(let o of t){console.log(` ${z.cyan(o.id.padEnd(24))} ${z.bold(o.name)} ${z.dim(o.assignmentStrategy)}`);for(let n of o.members){let s="actor"in n?n.actor:n.role;console.log(` ${z.dim("\u2022")} ${s}`)}}console.log(),console.log(z.dim(` ${t.length} role${t.length===1?"":"s"}.`))});at.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 Se,n=o.getRole(t);if(!n){console.error(z.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 $r}from"commander";import U from"chalk";var ds=new $r().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=P(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(U.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(U.red(` connect failed: HTTP ${r.status}`)),process.exit(1)),console.log(U.green(" connected \u2014 Ctrl-C to stop")),console.log("");let a=r.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:h,value:d}=await a.read();if(h)break;l+=c.decode(d,{stream:!0});let m;for(;(m=l.indexOf(`
356
358
 
357
- `))>=0;){let h=l.slice(0,m);l=l.slice(m+2),pr(h)}}}catch(r){console.error(B.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function pr(e){let t="message",o="";for(let i of e.split(`
358
- `))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?B.dim(new Date(n.at).toLocaleTimeString()):"";switch(t){case"run":{let i=B.cyan(n.phase?.padEnd(9)??"run"),r=B.bold(n.workflowId??""),a=B.dim((n.runId??"").slice(0,8)),c=n.nodeId?B.yellow(n.nodeId):"",l=n.note?B.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=B.magenta(`task.${n.phase}`.padEnd(14)),r=B.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?B.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${B.cyan(a)} ${c}`);break}case"signal":{let i=B.green("signal".padEnd(9)),r=B.bold(n.name),a=B.dim(`(${n.scope})`),c=n.workflowId?B.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=B.blue("mesh".padEnd(9)),r=B.bold(n.peer),a=n.healthy?B.green("\u2713 healthy"):B.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${B.dim(n.delta??"")}`);break}case"channel":{let i=B.yellow("channel".padEnd(9)),r=n.direction==="in"?B.cyan("\u2190"):B.magenta("\u2192"),a=B.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?B.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(B.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 ur}from"commander";import ce from"chalk";import{readFileSync as hr}from"fs";var io=["user","feedback","project","reference"],rt=new ur().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");rt.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(!io.includes(e.type)){console.error(ce.red(` --type must be one of: ${io.join(", ")}`)),process.exitCode=1;return}let t=e.body??"";if(e.file)if(e.file==="-")t=await fr();else try{t=hr(e.file,"utf-8")}catch(s){console.error(ce.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!t.trim()){console.error(ce.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new at().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:t});console.log(ce.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});rt.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 at().list(e.agent);if(e.type){if(!io.includes(e.type)){console.error(ce.red(` --type must be one of: ${io.join(", ")}`)),process.exitCode=1;return}o=o.filter(s=>s.type===e.type)}if(!o.length){console.log(ce.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(ce.bold(` ${s.type}`)),n=s.type),console.log(` ${ce.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(ce.dim(` ${o.length} memor${o.length===1?"y":"ies"} for ${e.agent}`))});rt.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 at().get(t.agent,e);if(!n){console.error(ce.red(` no memory "${e}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(ce.bold(`${n.type}/${n.name}`)+ce.dim(` (${n.description})`)),console.log(ce.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});rt.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,t)=>{if(!new at().remove(t.agent,e)){console.error(ce.red(` no memory "${e}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(ce.green(` \u2713 memory "${e}" removed`))});rt.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 at().indexMarkdown(e.agent);if(!o){console.log(ce.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(o)});async function fr(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}import Wo from"chalk";import{Command as yr}from"commander";var rs=new yr().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 Vo():(Ie.error("Only stdio transport is currently supported."),Ie.info(`Usage: ${Wo.green("agentx serve --stdio")} or configure in your MCP client.`),Ie.break(),Ie.info("Add to Claude Code:"),Ie.info(Wo.dim(" claude mcp add agentx -- npx agentx serve --stdio")),Ie.break(),Ie.info("Add to Cursor/MCP config:"),Ie.info(Wo.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(t){dn(t)}});import{Command as wr}from"commander";import ge from"chalk";var Fo=new wr().name("bench").description("benchmark harnesses (context strategies, ...)");Fo.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||kr();console.log(),console.log(ge.bold(" Context-strategy benchmark")),console.log(ge.dim(` agent=${e.agent}, channel=${e.channel}, chatId=${e.chatId}, runs=${t}`)),console.log(ge.dim(` daemon=${n}`)),console.log();let s=await as(n,"layered",e,t),i=await as(n,"planner",e,t);br(s,i,o)});async function as(e,t,o,n){let s=0,i=0,r=0,a=0,c=0,l=0,p=0,d="",m;for(let f=0;f<n;f++){let w=Date.now();try{let k=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(k.error){p++,m=k.error;continue}s+=k.duration??Date.now()-w,i+=k.usage?.inputTokens??0,r+=k.usage?.outputTokens??0,a+=k.usage?.cacheReadTokens??0,c+=k.usage?.cacheCreateTokens??0,l+=$r(k.usage),d=k.content??""}catch(y){p++,m=y.message??String(y)}}let h=n-p||1;return{strategy:t,runs:n,errors:p,avgDurationMs:Math.round(s/h),avgInput:Math.round(i/h),avgOutput:Math.round(r/h),avgCacheRead:Math.round(a/h),avgCacheCreate:Math.round(c/h),avgTotalInput:Math.round((i+a+c)/h),avgCost:l/h,lastResponse:d,lastError:m}}function $r(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 br(e,t,o){let n=(a,c)=>a.length>=c?a:a+" ".repeat(c-a.length),s=a=>a.toLocaleString();console.log(ge.bold(" "+n("metric",22)+n("layered",18)+n("planner",18)+"delta")),console.log(ge.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,h=d===0?ge.dim("\xB10"):d<0?ge.green(`${p(d)} (${m.toFixed(0)}%)`):ge.red(`+${p(d)} (+${m.toFixed(0)}%)`);console.log(" "+n(a,22)+n(p(c),18)+n(p(l),18)+h)}console.log(ge.dim(" "+"-".repeat(74))),(e.errors>0||t.errors>0)&&console.log(ge.yellow(` errors: layered=${e.errors} (${e.lastError??""}), planner=${t.errors} (${t.lastError??""})`)),console.log(),o>0&&(console.log(ge.bold(" Response preview (last run of each):")),console.log(ge.dim(" layered:")),console.log(" "+cs(e.lastResponse,o).split(`
359
+ `))>=0;){let p=l.slice(0,m);l=l.slice(m+2),br(p)}}}catch(r){console.error(U.red(` disconnected: ${r.message||r}`)),process.exit(1)}});function br(e){let t="message",o="";for(let i of e.split(`
360
+ `))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?U.dim(new Date(n.at).toLocaleTimeString()):"";switch(t){case"run":{let i=U.cyan(n.phase?.padEnd(9)??"run"),r=U.bold(n.workflowId??""),a=U.dim((n.runId??"").slice(0,8)),c=n.nodeId?U.yellow(n.nodeId):"",l=n.note?U.dim(`\u2014 ${n.note}`):"";console.log(`${s} ${i} ${r} ${a} ${c} ${l}`);break}case"task":{let i=U.magenta(`task.${n.phase}`.padEnd(14)),r=U.bold(n.workflowId??""),a=Array.isArray(n.assignedTo)?n.assignedTo.join(","):"",c=n.title?U.dim(`"${n.title}"`):"";console.log(`${s} ${i} ${r} ${U.cyan(a)} ${c}`);break}case"signal":{let i=U.green("signal".padEnd(9)),r=U.bold(n.name),a=U.dim(`(${n.scope})`),c=n.workflowId?U.dim(n.workflowId):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"mesh":{let i=U.blue("mesh".padEnd(9)),r=U.bold(n.peer),a=n.healthy?U.green("\u2713 healthy"):U.red("\u2717 lost");console.log(`${s} ${i} ${r} ${a} ${U.dim(n.delta??"")}`);break}case"channel":{let i=U.yellow("channel".padEnd(9)),r=n.direction==="in"?U.cyan("\u2190"):U.magenta("\u2192"),a=U.bold(`${n.channel}:${n.chatId??""}`),c=n.textPreview?U.dim(n.textPreview):"";console.log(`${s} ${i} ${r} ${a} ${c}`);break}case"status":{console.log(U.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 kr}from"commander";import le from"chalk";import{readFileSync as vr}from"fs";var co=["user","feedback","project","reference"],ct=new kr().name("memory").description("audit + edit agent-memory (per-agent experiential notes)");ct.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(!co.includes(e.type)){console.error(le.red(` --type must be one of: ${co.join(", ")}`)),process.exitCode=1;return}let t=e.body??"";if(e.file)if(e.file==="-")t=await xr();else try{t=vr(e.file,"utf-8")}catch(s){console.error(le.red(` could not read --file: ${s.message}`)),process.exitCode=1;return}if(!t.trim()){console.error(le.red(" memory body is required (use --body or --file)")),process.exitCode=1;return}let n=new lt().save({agentId:e.agent,type:e.type,name:e.name,description:e.description,body:t});console.log(le.green(` \u2713 memory "${n.name}" saved (${n.type}) for agent ${e.agent}`))});ct.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 lt().list(e.agent);if(e.type){if(!co.includes(e.type)){console.error(le.red(` --type must be one of: ${co.join(", ")}`)),process.exitCode=1;return}o=o.filter(s=>s.type===e.type)}if(!o.length){console.log(le.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(le.bold(` ${s.type}`)),n=s.type),console.log(` ${le.cyan(s.name.padEnd(28))} ${s.description}`);console.log(),console.log(le.dim(` ${o.length} memor${o.length===1?"y":"ies"} for ${e.agent}`))});ct.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 lt().get(t.agent,e);if(!n){console.error(le.red(` no memory "${e}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(le.bold(`${n.type}/${n.name}`)+le.dim(` (${n.description})`)),console.log(le.dim(` updated ${n.updatedAt}`)),console.log(),console.log(n.body)});ct.command("remove").alias("rm").description("remove a memory").requiredOption("--agent <id>","agent id").argument("<name>","memory name (slug)").action((e,t)=>{if(!new lt().remove(t.agent,e)){console.error(le.red(` no memory "${e}" for agent "${t.agent}"`)),process.exitCode=1;return}console.log(le.green(` \u2713 memory "${e}" removed`))});ct.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 lt().indexMarkdown(e.agent);if(!o){console.log(le.dim(` (no memories \u2014 MEMORY.md is empty for agent "${e.agent}")`));return}console.log(o)});async function xr(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}import Uo from"chalk";import{Command as Sr}from"commander";var gs=new Sr().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 Zo():(Ie.error("Only stdio transport is currently supported."),Ie.info(`Usage: ${Uo.green("agentx serve --stdio")} or configure in your MCP client.`),Ie.break(),Ie.info("Add to Claude Code:"),Ie.info(Uo.dim(" claude mcp add agentx -- npx agentx serve --stdio")),Ie.break(),Ie.info("Add to Cursor/MCP config:"),Ie.info(Uo.dim(JSON.stringify({mcpServers:{agentx:{command:"npx",args:["agentx","serve","--stdio"]}}},null,2))))}catch(t){hn(t)}});import{Command as jr}from"commander";import me from"chalk";var qo=new jr().name("bench").description("benchmark harnesses (context strategies, ...)");qo.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||Ar();console.log(),console.log(me.bold(" Context-strategy benchmark")),console.log(me.dim(` agent=${e.agent}, channel=${e.channel}, chatId=${e.chatId}, runs=${t}`)),console.log(me.dim(` daemon=${n}`)),console.log();let s=await ms(n,"layered",e,t),i=await ms(n,"planner",e,t);Er(s,i,o)});async function ms(e,t,o,n){let s=0,i=0,r=0,a=0,c=0,l=0,h=0,d="",m;for(let f=0;f<n;f++){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){h++,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+=Cr(b.usage),d=b.content??""}catch(w){h++,m=w.message??String(w)}}let p=n-h||1;return{strategy:t,runs:n,errors:h,avgDurationMs:Math.round(s/p),avgInput:Math.round(i/p),avgOutput:Math.round(r/p),avgCacheRead:Math.round(a/p),avgCacheCreate:Math.round(c/p),avgTotalInput:Math.round((i+a+c)/p),avgCost:l/p,lastResponse:d,lastError:m}}function Cr(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 Er(e,t,o){let n=(a,c)=>a.length>=c?a:a+" ".repeat(c-a.length),s=a=>a.toLocaleString();console.log(me.bold(" "+n("metric",22)+n("layered",18)+n("planner",18)+"delta")),console.log(me.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,h]of i){let d=l-c,m=c===0?0:d/c*100,p=d===0?me.dim("\xB10"):d<0?me.green(`${h(d)} (${m.toFixed(0)}%)`):me.red(`+${h(d)} (+${m.toFixed(0)}%)`);console.log(" "+n(a,22)+n(h(c),18)+n(h(l),18)+p)}console.log(me.dim(" "+"-".repeat(74))),(e.errors>0||t.errors>0)&&console.log(me.yellow(` errors: layered=${e.errors} (${e.lastError??""}), planner=${t.errors} (${t.lastError??""})`)),console.log(),o>0&&(console.log(me.bold(" Response preview (last run of each):")),console.log(me.dim(" layered:")),console.log(" "+ps(e.lastResponse,o).split(`
359
361
  `).join(`
360
- `)),console.log(ge.dim(" planner:")),console.log(" "+cs(t.lastResponse,o).split(`
362
+ `)),console.log(me.dim(" planner:")),console.log(" "+ps(t.lastResponse,o).split(`
361
363
  `).join(`
362
- `)),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(ge.green(` Planner saved ${s(Math.abs(r))} input tokens/run (${a.toFixed(0)}% less).`))}else r>0&&console.log(ge.yellow(` Planner used ${s(r)} MORE input tokens \u2014 investigate before enabling.`));console.log()}function cs(e,t){return e?e.length>t?e.slice(0,t)+"\u2026":e:"(empty)"}function kr(){try{let e=P(),[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 vr}from"commander";import oe from"chalk";var Je=new vr().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");Je.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 Lt("/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(oe.dim(" no chats cached yet"));return}console.log(),console.log(oe.bold(` ${o.length} chat${o.length===1?"":"s"}`)),console.log();for(let n of o){let s=n.isGroup?oe.cyan("group"):oe.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${oe.dim(n.jid.padEnd(40))} ${oe.dim(i)}`)}console.log()}catch(t){vt(t)}});Je.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 Lt("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(oe.dim(" no contacts cached yet"));return}console.log(),console.log(oe.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} ${oe.dim(i)} ${oe.dim(n.jid)}`)}console.log()}catch(t){vt(t)}});Je.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 Uo("/whatsapp/ingest",t);Bo(o,!!e.dryRun)}catch(t){vt(t)}});Je.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 Uo("/whatsapp/ingest",o);Bo(n,!!t.dryRun)}catch(o){vt(o)}});Je.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 Uo("/whatsapp/ingest",o);Bo(n,!!t.dryRun)}catch(o){vt(o)}});Je.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await Lt("/whatsapp/state"),t=await Lt("/whatsapp/chats"),o=await Lt("/whatsapp/contacts");console.log(),console.log(oe.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){vt(e)}});function Bo(e,t){if(console.log(),console.log(oe.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(oe.yellow(` errors: ${e.errors.length}`));for(let o of e.errors.slice(0,5))console.log(oe.yellow(` - [${o.kind}] ${o.jid}: ${o.message}`))}if(t&&e.dryRunEntries?.length){console.log(),console.log(oe.dim(" would-be entries:"));for(let o of e.dryRunEntries.slice(0,10))console.log(oe.dim(` - ${o.id} (${o.source}, ${o.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(oe.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function ls(){try{let e=P(),[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 Lt(e){let t=await fetch(`${ls()}${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 Uo(e,t){let o=await fetch(`${ls()}${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 vt(e){console.error(oe.red(` ${e.message||e}`)),process.exit(1)}import{Command as xr}from"commander";import z from"chalk";import{existsSync as Sr,mkdirSync as ds,writeFileSync as Wt}from"fs";import{join as xt,resolve as jr}from"path";var Ft=new xr().name("plugin").description("manage agentx plugins (Move B)");Ft.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let t=P().plugins??[];if(console.log(),t.length===0){console.log(z.dim(" No plugins configured.")),console.log(z.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(z.bold(` Plugins configured: ${t.length}`)),console.log();for(let o of t)console.log(` ${z.cyan(o)}`);console.log(),console.log(z.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(z.red(` ${e.message}`)),process.exitCode=1}});Ft.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(z.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=jr(t.cwd,o);Sr(n)&&!t.force&&(console.log(z.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),ds(n,{recursive:!0}),ds(xt(n,"src"),{recursive:!0});let s=t.description||`AgentX plugin: ${e}`;Wt(xt(n,"package.json"),Ir(e,s)),Wt(xt(n,"tsconfig.json"),Or()),Wt(xt(n,"src/index.ts"),Rr(e)),Wt(xt(n,"README.md"),Dr(e,s)),Wt(xt(n,".gitignore"),Tr()),console.log(),console.log(z.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(z.bold(" Next steps:")),console.log(z.dim(` cd ${o}`)),console.log(z.dim(" pnpm install")),console.log(z.dim(" pnpm build")),console.log(z.dim(" pnpm link --global # for local testing")),console.log(z.dim(" # then in your agentx project:")),console.log(z.dim(` pnpm link --global ${e}`)),console.log(z.dim(` agentx config set plugins[0] "${e}"`)),console.log(z.dim(" agentx plugin doctor")),console.log()});Ft.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let t=P().plugins??[];if(console.log(),t.length===0){console.log(z.dim(" No plugins configured. Nothing to check.")),console.log();return}let o=0;for(let n of t){let s=await Cr(n);s.kind==="ok"?console.log(` ${z.green("\u2713")} ${z.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(o++,console.log(` ${z.red("\u2717")} ${z.cyan(n)} \u2014 ${s.reason}`))}console.log(),o>0&&(console.log(z.red(` ${o}/${t.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(z.red(` ${e.message}`)),process.exitCode=1}});async function Cr(e){let t;try{t=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let o=Er(t);if(!Ar(o))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=tn.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 Er(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 Ar(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Ir(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)+`
363
- `}function Or(){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)+`
364
- `}function Rr(e){return`// ${e} \u2014 AgentX plugin
364
+ `)),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(me.green(` Planner saved ${s(Math.abs(r))} input tokens/run (${a.toFixed(0)}% less).`))}else r>0&&console.log(me.yellow(` Planner used ${s(r)} MORE input tokens \u2014 investigate before enabling.`));console.log()}function ps(e,t){return e?e.length>t?e.slice(0,t)+"\u2026":e:"(empty)"}function Ar(){try{let e=P(),[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 Or}from"commander";import ne from"chalk";var ze=new Or().name("whatsapp").description("list WhatsApp chats/contacts and ingest them into the wiki as a data source");ze.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 Bt("/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(ne.dim(" no chats cached yet"));return}console.log(),console.log(ne.bold(` ${o.length} chat${o.length===1?"":"s"}`)),console.log();for(let n of o){let s=n.isGroup?ne.cyan("group"):ne.dim("dm"),i=n.lastMessageAt?new Date(n.lastMessageAt*1e3).toISOString().slice(0,16).replace("T"," "):"\u2014";console.log(` ${s} ${n.name.padEnd(30)} ${ne.dim(n.jid.padEnd(40))} ${ne.dim(i)}`)}console.log()}catch(t){jt(t)}});ze.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 Bt("/whatsapp/contacts")).contacts??[];if(e.format==="json"){console.log(JSON.stringify(o,null,2));return}if(o.length===0){console.log(ne.dim(" no contacts cached yet"));return}console.log(),console.log(ne.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} ${ne.dim(i)} ${ne.dim(n.jid)}`)}console.log()}catch(t){jt(t)}});ze.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 zo("/whatsapp/ingest",t);Jo(o,!!e.dryRun)}catch(t){jt(t)}});ze.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 zo("/whatsapp/ingest",o);Jo(n,!!t.dryRun)}catch(o){jt(o)}});ze.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 zo("/whatsapp/ingest",o);Jo(n,!!t.dryRun)}catch(o){jt(o)}});ze.command("status").description("show WhatsApp channel + ingest status").action(async()=>{try{let e=await Bt("/whatsapp/state"),t=await Bt("/whatsapp/chats"),o=await Bt("/whatsapp/contacts");console.log(),console.log(ne.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){jt(e)}});function Jo(e,t){if(console.log(),console.log(ne.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(ne.yellow(` errors: ${e.errors.length}`));for(let o of e.errors.slice(0,5))console.log(ne.yellow(` - [${o.kind}] ${o.jid}: ${o.message}`))}if(t&&e.dryRunEntries?.length){console.log(),console.log(ne.dim(" would-be entries:"));for(let o of e.dryRunEntries.slice(0,10))console.log(ne.dim(` - ${o.id} (${o.source}, ${o.content.length} bytes)`));e.dryRunEntries.length>10&&console.log(ne.dim(` \u2026and ${e.dryRunEntries.length-10} more`))}console.log()}function us(){try{let e=P(),[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 Bt(e){let t=await fetch(`${us()}${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 zo(e,t){let o=await fetch(`${us()}${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 jt(e){console.error(ne.red(` ${e.message||e}`)),process.exit(1)}import{Command as Ir}from"commander";import G from"chalk";import{existsSync as Rr,mkdirSync as hs,writeFileSync as Ut}from"fs";import{join as Ct,resolve as Dr}from"path";var qt=new Ir().name("plugin").description("manage agentx plugins (Move B)");qt.command("list",{isDefault:!0}).description("list plugins configured in agentx.json").action(()=>{try{let t=P().plugins??[];if(console.log(),t.length===0){console.log(G.dim(" No plugins configured.")),console.log(G.dim(' Add a plugin: edit agentx.json\'s `plugins: ["your-package"]` and pnpm install it.')),console.log();return}console.log(G.bold(` Plugins configured: ${t.length}`)),console.log();for(let o of t)console.log(` ${G.cyan(o)}`);console.log(),console.log(G.dim(" Run `agentx plugin doctor` to verify each plugin loads.")),console.log()}catch(e){console.log(G.red(` ${e.message}`)),process.exitCode=1}});qt.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(G.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=Dr(t.cwd,o);Rr(n)&&!t.force&&(console.log(G.red(` ${n} already exists. Use --force to overwrite.`)),process.exit(1)),hs(n,{recursive:!0}),hs(Ct(n,"src"),{recursive:!0});let s=t.description||`AgentX plugin: ${e}`;Ut(Ct(n,"package.json"),Nr(e,s)),Ut(Ct(n,"tsconfig.json"),Mr()),Ut(Ct(n,"src/index.ts"),Lr(e)),Ut(Ct(n,"README.md"),Wr(e,s)),Ut(Ct(n,".gitignore"),Fr()),console.log(),console.log(G.green(` \u2713 scaffolded plugin at ${n}`)),console.log(),console.log(G.bold(" Next steps:")),console.log(G.dim(` cd ${o}`)),console.log(G.dim(" pnpm install")),console.log(G.dim(" pnpm build")),console.log(G.dim(" pnpm link --global # for local testing")),console.log(G.dim(" # then in your agentx project:")),console.log(G.dim(` pnpm link --global ${e}`)),console.log(G.dim(` agentx config set plugins[0] "${e}"`)),console.log(G.dim(" agentx plugin doctor")),console.log()});qt.command("doctor").description("dynamic-import each configured plugin and report status").action(async()=>{try{let t=P().plugins??[];if(console.log(),t.length===0){console.log(G.dim(" No plugins configured. Nothing to check.")),console.log();return}let o=0;for(let n of t){let s=await Tr(n);s.kind==="ok"?console.log(` ${G.green("\u2713")} ${G.cyan(n)} \u2014 ${s.manifestName} v${s.manifestVersion}`):(o++,console.log(` ${G.red("\u2717")} ${G.cyan(n)} \u2014 ${s.reason}`))}console.log(),o>0&&(console.log(G.red(` ${o}/${t.length} plugin(s) failed`)),process.exitCode=1)}catch(e){console.log(G.red(` ${e.message}`)),process.exitCode=1}});async function Tr(e){let t;try{t=await import(e)}catch(s){return{kind:"fail",reason:`import failed: ${s?.message??s}`}}let o=_r(t);if(!Pr(o))return{kind:"fail",reason:"no default AgentXPlugin export (manifest/setup pair not found)"};let n=sn.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 _r(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 Pr(e){return!!e&&typeof e=="object"&&"manifest"in e&&"setup"in e&&typeof e.setup=="function"}function Nr(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)+`
365
+ `}function Mr(){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)+`
366
+ `}function Lr(e){return`// ${e} \u2014 AgentX plugin
365
367
  //
366
368
  // A plugin's default export is { manifest, setup }. The daemon calls
367
369
  // setup(ctx) once at boot. ctx.on() subscribes to the bus; ctx.addChannel()
@@ -397,7 +399,7 @@ const plugin = {
397
399
  }
398
400
 
399
401
  export default plugin
400
- `}function Dr(e,t){return`# ${e}
402
+ `}function Wr(e,t){return`# ${e}
401
403
 
402
404
  ${t}
403
405
 
@@ -424,17 +426,17 @@ agentx plugin doctor
424
426
  \`\`\`
425
427
 
426
428
  Restart the daemon to activate.
427
- `}function Tr(){return`node_modules/
429
+ `}function Fr(){return`node_modules/
428
430
  dist/
429
431
  *.log
430
432
  .env
431
- `}import{Command as _r}from"commander";import ne from"chalk";import{writeFileSync as Pr,mkdirSync as Nr,existsSync as ro,readFileSync as gs,appendFileSync as ms}from"fs";import{resolve as St,dirname as hs}from"path";import{homedir as Jo}from"os";var fs=new _r().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-WWCXMRU2.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Wr(o);break;case"bash":s=Jr(o);break;case"fish":s=zr(o);break;default:console.error(ne.red(`unsupported shell: ${n}`)),console.error(ne.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?St(String(e.output)):Mr(n);Nr(hs(i),{recursive:!0}),Pr(i,s),console.log(ne.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),Lr(n,i,!!e.yes)});function Mr(e){let t=Jo();switch(e){case"zsh":return St(t,".zsh","completions","_agentx");case"bash":return St(t,".bash_completion.d","agentx.bash");case"fish":return St(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function Lr(e,t,o){if(e==="zsh"){let n=St(Jo(),".zshrc"),s=hs(t),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=ro(n)?gs(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(ne.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&ro(n)){let p=["","# agentx completion"];c&&p.push(i),l&&p.push(r),ms(n,p.join(`
433
+ `}import{Command as Br}from"commander";import se from"chalk";import{writeFileSync as Ur,mkdirSync as qr,existsSync as lo,readFileSync as fs,appendFileSync as ys}from"fs";import{resolve as Et,dirname as bs}from"path";import{homedir as Yo}from"os";var ks=new Br().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-JEKM7SCS.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=Gr(o);break;case"bash":s=Qr(o);break;case"fish":s=Xr(o);break;default:console.error(se.red(`unsupported shell: ${n}`)),console.error(se.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let i=e.output?Et(String(e.output)):Jr(n);qr(bs(i),{recursive:!0}),Ur(i,s),console.log(se.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${i}`),console.log(),zr(n,i,!!e.yes)});function Jr(e){let t=Yo();switch(e){case"zsh":return Et(t,".zsh","completions","_agentx");case"bash":return Et(t,".bash_completion.d","agentx.bash");case"fish":return Et(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function zr(e,t,o){if(e==="zsh"){let n=Et(Yo(),".zshrc"),s=bs(t),i=`fpath=(${s} $fpath)`,r="autoload -U compinit && compinit",a=lo(n)?fs(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(se.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&lo(n)){let h=["","# agentx completion"];c&&h.push(i),l&&h.push(r),ys(n,h.join(`
432
434
  `)+`
433
- `),console.log(ne.green("\u2713 Patched ~/.zshrc")),console.log(ne.dim("Reload your shell: exec zsh"));return}console.log(ne.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(ne.cyan(` ${i}`)),l&&console.log(ne.cyan(` ${r}`)),console.log(),console.log(ne.dim("Then reload: exec zsh")),console.log(ne.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=St(Jo(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((ro(n)?gs(n,"utf-8"):"").includes(t)){console.log(ne.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&ro(n)){ms(n,`
435
+ `),console.log(se.green("\u2713 Patched ~/.zshrc")),console.log(se.dim("Reload your shell: exec zsh"));return}console.log(se.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(se.cyan(` ${i}`)),l&&console.log(se.cyan(` ${r}`)),console.log(),console.log(se.dim("Then reload: exec zsh")),console.log(se.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=Et(Yo(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((lo(n)?fs(n,"utf-8"):"").includes(t)){console.log(se.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&lo(n)){ys(n,`
434
436
  # agentx completion
435
437
  ${s}
436
- `),console.log(ne.green("\u2713 Patched ~/.bashrc")),console.log(ne.dim("Reload your shell: exec bash"));return}console.log(ne.dim("Add this to ~/.bashrc:")),console.log(ne.cyan(` ${s}`)),console.log(),console.log(ne.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(ne.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function pe(e){return e._name||e.name()||""}function ze(e){return e.commands.filter(t=>{let o=pe(t);return!(!o||o==="help"||t._hidden)})}function Bt(e){return e.options.filter(t=>!t.hidden)}function Wr(e){let t=[];return t.push("#compdef agentx"),t.push(""),ys(e,[],t),t.push("compdef _agentx_root_completion agentx"),t.push(""),t.join(`
437
- `)}function ps(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function ys(e,t,o){let n=ze(e),i=Bt(e).map(Ur).filter(c=>!!c),r=ps(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(qr).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=ps([...t,pe(c)]);o.push(` (${pe(c)}) ${l} ;;`)}o.push(" esac"),o.push(" ;;"),o.push(" esac")}o.push("}"),o.push("");for(let c of n)ys(c,[...t,pe(c)],o)}function Fr(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Br(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Ur(e){let t=e.short||void 0,o=e.long||void 0;if(!t&&!o)return null;let n=Fr(e.description||"");return t&&o?` "(${o} ${t})"{${o},${t}}"[${n}]"`:` "${o||t}[${n}]"`}function qr(e){let t=Br(e.description()||"");return`'${pe(e)}[${t}]'`}function Jr(e){let t=ze(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(pe).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=ze(n).map(pe),i=us(n);if(o.push(` ${pe(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 ze(n)){let a=us(r);o.push(` ${pe(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(`
438
- `)}function us(e){let t=[];for(let o of Bt(e))o.long&&t.push(o.long),o.short&&t.push(o.short);return t.join(" ")}function zr(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 ze(e)){let n=zo(o.description()||"");t.push(`complete -c agentx -n "__fish_use_subcommand" -a "${pe(o)}" -d "${n}"`)}t.push("");for(let o of Bt(e)){let n=qo(o,["__fish_use_subcommand"]);n&&t.push(n)}t.push("");for(let o of ze(e)){let n=pe(o);t.push(`# ${n}`);for(let s of Bt(o)){let i=qo(s,[`__fish_seen_subcommand_from ${n}`]);i&&t.push(i)}for(let s of ze(o)){let i=zo(s.description()||"");t.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${ze(o).map(pe).join(" ")}" -a "${pe(s)}" -d "${i}"`);for(let r of Bt(s)){let a=qo(r,[`__fish_seen_subcommand_from ${pe(s)}`]);a&&t.push(a)}}t.push("")}return t.join(`
439
- `)}function zo(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function qo(e,t){let o=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!o&&!n)return null;let s=zo(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 bg(){let e=await gn(),t=new Gr().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(Se).addCommand(kn).addCommand(wn).addCommand(gt).addCommand(zt).addCommand(tt).addCommand(mt).addCommand(Be).addCommand(pt).addCommand(ut).addCommand(Ot).addCommand(Re).addCommand(Fe).addCommand(Xe).addCommand(wo).addCommand($o).addCommand(Me).addCommand(Qt).addCommand(Ue).addCommand(V).addCommand(Pt).addCommand(Nt).addCommand(Ee).addCommand(Mt).addCommand($t).addCommand(bt).addCommand(so).addCommand(kt).addCommand(it).addCommand(is).addCommand(rt).addCommand(It).addCommand(pn).addCommand(rs).addCommand(Fo).addCommand(Je).addCommand(Ft).addCommand(fs),t}export{bg as a};
440
- //# sourceMappingURL=chunk-7GVXCOLO.js.map
438
+ `),console.log(se.green("\u2713 Patched ~/.bashrc")),console.log(se.dim("Reload your shell: exec bash"));return}console.log(se.dim("Add this to ~/.bashrc:")),console.log(se.cyan(` ${s}`)),console.log(),console.log(se.dim("Or rerun with --yes to auto-patch ~/.bashrc"));return}if(e==="fish"){console.log(se.dim("Fish auto-loads completions from this directory \u2014 start a new shell to pick it up."));return}}function ue(e){return e._name||e.name()||""}function Ge(e){return e.commands.filter(t=>{let o=ue(t);return!(!o||o==="help"||t._hidden)})}function Jt(e){return e.options.filter(t=>!t.hidden)}function Gr(e){let t=[];return t.push("#compdef agentx"),t.push(""),vs(e,[],t),t.push("compdef _agentx_root_completion agentx"),t.push(""),t.join(`
439
+ `)}function ws(e){return e.length===0?"_agentx_root_completion":`_agentx_${e.join("_").replace(/[^a-z0-9_]/gi,"_")}`}function vs(e,t,o){let n=Ge(e),i=Jt(e).map(Kr).filter(c=>!!c),r=ws(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(Vr).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=ws([...t,ue(c)]);o.push(` (${ue(c)}) ${l} ;;`)}o.push(" esac"),o.push(" ;;"),o.push(" esac")}o.push("}"),o.push("");for(let c of n)vs(c,[...t,ue(c)],o)}function Yr(e){return String(e||"").replace(/\r?\n/g," ").replace(/"/g,'\\"').replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Hr(e){return String(e||"").replace(/\r?\n/g," ").replace(/'/g,"'\\''").replace(/\[/g,"\\[").replace(/\]/g,"\\]")}function Kr(e){let t=e.short||void 0,o=e.long||void 0;if(!t&&!o)return null;let n=Yr(e.description||"");return t&&o?` "(${o} ${t})"{${o},${t}}"[${n}]"`:` "${o||t}[${n}]"`}function Vr(e){let t=Hr(e.description()||"");return`'${ue(e)}[${t}]'`}function Qr(e){let t=Ge(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(ue).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=Ge(n).map(ue),i=$s(n);if(o.push(` ${ue(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 Ge(n)){let a=$s(r);o.push(` ${ue(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(`
440
+ `)}function $s(e){let t=[];for(let o of Jt(e))o.long&&t.push(o.long),o.short&&t.push(o.short);return t.join(" ")}function Xr(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 Ge(e)){let n=Ho(o.description()||"");t.push(`complete -c agentx -n "__fish_use_subcommand" -a "${ue(o)}" -d "${n}"`)}t.push("");for(let o of Jt(e)){let n=Go(o,["__fish_use_subcommand"]);n&&t.push(n)}t.push("");for(let o of Ge(e)){let n=ue(o);t.push(`# ${n}`);for(let s of Jt(o)){let i=Go(s,[`__fish_seen_subcommand_from ${n}`]);i&&t.push(i)}for(let s of Ge(o)){let i=Ho(s.description()||"");t.push(`complete -c agentx -n "__fish_seen_subcommand_from ${n}; and not __fish_seen_subcommand_from ${Ge(o).map(ue).join(" ")}" -a "${ue(s)}" -d "${i}"`);for(let r of Jt(s)){let a=Go(r,[`__fish_seen_subcommand_from ${ue(s)}`]);a&&t.push(a)}}t.push("")}return t.join(`
441
+ `)}function Ho(e){return String(e||"").replace(/\r?\n/g," ").replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Go(e,t){let o=e.short?e.short.replace(/^-/,""):"",n=e.long?e.long.replace(/^--/,""):"";if(!o&&!n)return null;let s=Ho(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 _g(){let e=await fn(),t=new Zr().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(je).addCommand(Cn).addCommand(xn).addCommand(ut).addCommand(Ht).addCommand(ot).addCommand(ht).addCommand(Ue).addCommand(ft).addCommand(yt).addCommand(Tt).addCommand(De).addCommand(Be).addCommand(Ze).addCommand(ko).addCommand(vo).addCommand(Le).addCommand(eo).addCommand(qe).addCommand(Q).addCommand(Lt).addCommand(Wt).addCommand(Ae).addCommand(Ft).addCommand(vt).addCommand(xt).addCommand(ao).addCommand(rt).addCommand(St).addCommand(at).addCommand(ds).addCommand(ct).addCommand(Dt).addCommand(wn).addCommand(gs).addCommand(qo).addCommand(ze).addCommand(qt).addCommand(ks),t}export{_g as a};
442
+ //# sourceMappingURL=chunk-IFQQVDM6.js.map