agentix-cli 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -34
- package/dist/agent-LRSSVFDR.js +2 -0
- package/dist/board-dashboard-DAPHL6W2.js +4508 -0
- package/dist/board-dashboard-DAPHL6W2.js.map +1 -0
- package/dist/chunk-3XULOWYB.js +199 -0
- package/dist/chunk-3XULOWYB.js.map +1 -0
- package/dist/{chunk-ZRYBSI5G.js → chunk-7MBTMCKY.js} +2 -2
- package/dist/{chunk-XVYMZ4M7.js → chunk-AU37OREL.js} +5 -5
- package/dist/chunk-B4Q4X7D5.js +6 -0
- package/dist/chunk-B4Q4X7D5.js.map +1 -0
- package/dist/chunk-CXY2RYNI.js +11 -0
- package/dist/chunk-CXY2RYNI.js.map +1 -0
- package/dist/chunk-FIOB3MEX.js +2 -0
- package/dist/chunk-HLRVDCNH.js +5 -0
- package/dist/{chunk-NJR5WF5E.js.map → chunk-HLRVDCNH.js.map} +1 -1
- package/dist/chunk-IEVEMKAI.js +168 -0
- package/dist/chunk-IEVEMKAI.js.map +1 -0
- package/dist/{chunk-O72LPMBR.js → chunk-RB7265LO.js} +2 -2
- package/dist/chunk-RGUYBH77.js +7 -0
- package/dist/chunk-RGUYBH77.js.map +1 -0
- package/dist/chunk-WVNSWBCU.js +138 -0
- package/dist/chunk-WVNSWBCU.js.map +1 -0
- package/dist/cli.js +34 -24
- package/dist/cli.js.map +1 -1
- package/dist/{compaction-7I3E5QUO.js → compaction-JBZZ7I7Y.js} +4 -4
- package/dist/config-DCJYECL4.js +2 -0
- package/dist/config-mutator-6EJHSP3Y.js +2 -0
- package/dist/debug-3MEUO2P2.js +2 -0
- package/dist/{heal-OTGT5HHJ.js → heal-WKY5I4KB.js} +2 -2
- package/dist/index.d.ts +224 -1
- package/dist/index.js +11 -11
- package/dist/index.js.map +1 -1
- package/dist/loader-PTCXLJEX.js +2 -0
- package/dist/memory-extract-AD7KMRPC.js +2 -0
- package/dist/{providers-G3WZ4RVJ.js → providers-VUIWO3ZK.js} +2 -2
- package/dist/registry-5ND7GLFJ.js +2 -0
- package/dist/scheduler-FCXOXCN5.js +2 -0
- package/dist/{subagent-WV7QKQ3L.js → subagent-2SJHSSJS.js} +2 -2
- package/dist/{usage-dashboard-M7AFIGMJ.js → usage-dashboard-QX3CF6KK.js} +8 -8
- package/dist/usage-dashboard-QX3CF6KK.js.map +1 -0
- package/dist/whatsapp-state-6D6FHHD2.js +2 -0
- package/dist/whatsapp-state-6D6FHHD2.js.map +1 -0
- package/dist/workspace-setup-ZWTT42XT.js +2 -0
- package/dist/workspace-setup-ZWTT42XT.js.map +1 -0
- package/package.json +2 -1
- package/dist/agent-DW3NYIIL.js +0 -2
- package/dist/board-dashboard-6TKE6NMV.js +0 -1435
- package/dist/board-dashboard-6TKE6NMV.js.map +0 -1
- package/dist/chunk-4YCH6IZV.js +0 -2
- package/dist/chunk-DYOBFJLX.js +0 -11
- package/dist/chunk-DYOBFJLX.js.map +0 -1
- package/dist/chunk-ITZEVXZ4.js +0 -2
- package/dist/chunk-ITZEVXZ4.js.map +0 -1
- package/dist/chunk-M33CB2H4.js +0 -6
- package/dist/chunk-M33CB2H4.js.map +0 -1
- package/dist/chunk-NJR5WF5E.js +0 -5
- package/dist/chunk-RB73FZXJ.js +0 -133
- package/dist/chunk-RB73FZXJ.js.map +0 -1
- package/dist/chunk-UPT2UMF6.js +0 -159
- package/dist/chunk-UPT2UMF6.js.map +0 -1
- package/dist/config-7QJ2QJIC.js +0 -2
- package/dist/config-mutator-GAEVGHDD.js +0 -2
- package/dist/debug-N3B5NVJU.js +0 -2
- package/dist/loader-YQE6XJBT.js +0 -2
- package/dist/memory-extract-RGPUPMKU.js +0 -2
- package/dist/registry-YVAG4EO5.js +0 -2
- package/dist/usage-dashboard-M7AFIGMJ.js.map +0 -1
- package/dist/workspace-setup-QQTCJY4B.js +0 -2
- /package/dist/{agent-DW3NYIIL.js.map → agent-LRSSVFDR.js.map} +0 -0
- /package/dist/{chunk-ZRYBSI5G.js.map → chunk-7MBTMCKY.js.map} +0 -0
- /package/dist/{chunk-XVYMZ4M7.js.map → chunk-AU37OREL.js.map} +0 -0
- /package/dist/{chunk-4YCH6IZV.js.map → chunk-FIOB3MEX.js.map} +0 -0
- /package/dist/{chunk-O72LPMBR.js.map → chunk-RB7265LO.js.map} +0 -0
- /package/dist/{compaction-7I3E5QUO.js.map → compaction-JBZZ7I7Y.js.map} +0 -0
- /package/dist/{config-7QJ2QJIC.js.map → config-DCJYECL4.js.map} +0 -0
- /package/dist/{config-mutator-GAEVGHDD.js.map → config-mutator-6EJHSP3Y.js.map} +0 -0
- /package/dist/{debug-N3B5NVJU.js.map → debug-3MEUO2P2.js.map} +0 -0
- /package/dist/{heal-OTGT5HHJ.js.map → heal-WKY5I4KB.js.map} +0 -0
- /package/dist/{loader-YQE6XJBT.js.map → loader-PTCXLJEX.js.map} +0 -0
- /package/dist/{memory-extract-RGPUPMKU.js.map → memory-extract-AD7KMRPC.js.map} +0 -0
- /package/dist/{providers-G3WZ4RVJ.js.map → providers-VUIWO3ZK.js.map} +0 -0
- /package/dist/{registry-YVAG4EO5.js.map → registry-5ND7GLFJ.js.map} +0 -0
- /package/dist/{workspace-setup-QQTCJY4B.js.map → scheduler-FCXOXCN5.js.map} +0 -0
- /package/dist/{subagent-WV7QKQ3L.js.map → subagent-2SJHSSJS.js.map} +0 -0
package/dist/cli.js
CHANGED
|
@@ -1,19 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{a as at,b as it,e as Ae}from"./chunk-3XULOWYB.js";import{f as Ue,g as st}from"./chunk-WVNSWBCU.js";import"./chunk-6U2XOQHU.js";import{f as pe}from"./chunk-IEVEMKAI.js";import"./chunk-CXY2RYNI.js";import"./chunk-RB7265LO.js";import"./chunk-RGUYBH77.js";import{a as U,b as P,c as oe,d as ot}from"./chunk-HLRVDCNH.js";import{e as nt,f as N,g as Se,i as ne}from"./chunk-B4Q4X7D5.js";import"./chunk-QZP65I2H.js";import"./chunk-HI24KAEY.js";import"./chunk-M7HKBG3V.js";import"./chunk-DSYKYZMT.js";import"./chunk-7MBTMCKY.js";import"./chunk-QOYAX2FT.js";import{a as We}from"./chunk-FIOB3MEX.js";import{Command as no}from"commander";import{Command as Ut}from"commander";ne();import f from"chalk";var Y=new Ut().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");Y.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 t=>{if(t.detach){let{spawn:d}=await import("child_process"),p=["dist/cli.js","daemon","start"];t.config&&p.push("-c",t.config),t.port&&p.push("--port",t.port);let g=d("node",p,{detached:!0,stdio:["ignore","ignore","ignore"],cwd:process.cwd()});g.unref();let{writeFileSync:l}=await import("fs");l("/tmp/agentx-daemon.pid",String(g.pid)),console.log(f.green(`Daemon started in background (PID: ${g.pid})`)),console.log(f.dim(" Logs: tail -f /tmp/agentx-daemon.log")),console.log(f.dim(" Stop: agentx daemon stop"));return}let{readFileSync:e,writeFileSync:n,mkdirSync:o,existsSync:s}=await import("fs"),{resolve:a}=await import("path"),r=a(process.cwd(),".agentx");s(r)||o(r,{recursive:!0});let c=a(r,"daemon.pid");if(s(c)){let d=parseInt(e(c,"utf-8").trim(),10);if(d&&d!==process.pid)try{process.kill(d,0),console.error(`Another agentx daemon is already running (PID ${d}). Exiting.`),process.exit(0)}catch{}}n(c,String(process.pid)),await new Ue(t.config).start()});Y.command("stop").description("stop the running daemon").action(async()=>{let{readFileSync:t,existsSync:e,unlinkSync:n}=await import("fs"),{resolve:o}=await import("path"),s=[o(process.cwd(),".agentx/daemon.pid"),"/tmp/agentx-daemon.pid"];for(let r of s)if(e(r))try{let c=parseInt(t(r,"utf-8").trim(),10);process.kill(c,"SIGTERM"),await new Promise(i=>setTimeout(i,2e3));try{n(r)}catch{}console.log(f.green(`Daemon stopped (PID: ${c})`));return}catch{try{n(r)}catch{}}let{execSync:a}=await import("child_process");try{a("pkill -f 'node dist/cli.js daemon'",{stdio:"ignore"}),console.log(f.green("Daemon stopped"))}catch{console.log(f.yellow("No daemon process found"))}});Y.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 t=>{try{let e=N(t.config),[n,o]=e.node.bind.split(":"),s=`http://${n||"127.0.0.1"}:${o}/health`,r=await(await fetch(s,{signal:AbortSignal.timeout(3e3)})).json();if(t.json){console.log(JSON.stringify(r,null,2));return}console.log(),console.log(f.bold(` ${r.node.name}`)+f.dim(` (${r.node.id})`)),console.log(f.green(" Status: running")+f.dim(` \u2014 uptime ${Mt(r.uptime)}`)),console.log(),console.log(f.bold(" Agents:"));for(let i of r.agents){let d=i.active>0?f.yellow(` [${i.active} active]`):"",p=i.errors>0?f.red(` (${i.errors} errors)`):"";console.log(` ${f.cyan(i.name)} ${f.dim(`(${i.tier})`)}${d}${p}`),console.log(f.dim(` ${i.workspace}`))}let c=r.crons.filter(i=>i.enabled);if(r.crons.length){console.log(),console.log(f.bold(` Crons: ${c.length} enabled / ${r.crons.length} total`));for(let i of r.crons){let d=i.enabled?f.green("\u25CF"):f.dim("\u25CB"),p=i.nextRun?f.dim(` next: ${new Date(i.nextRun).toLocaleTimeString()}`):"";console.log(` ${d} ${i.id}${p}`)}}if(r.mesh?.length){console.log(),console.log(f.bold(" Mesh:"));for(let i of r.mesh){let d=i.healthy?f.green("\u25CF"):f.red("\u25CF"),p=i.skills?.length?f.dim(` (${i.skills.length} agents)`):"";console.log(` ${d} ${i.peer} ${f.dim(i.peerUrl)}${p}`)}}console.log()}catch(e){if(e.cause?.code==="ECONNREFUSED"||e.name==="TimeoutError")console.log(f.red(" Daemon is not running")),console.log(f.dim(" Start with: agentx daemon start"));else try{let n=N(t.config),o=Se(n);if(console.log(),console.log(f.bold(` ${n.node.name}`)+f.dim(` (${n.node.id})`)),console.log(f.yellow(" Status: stopped")),console.log(f.dim(` ${Object.keys(n.agents).length} agents, ${Object.keys(n.crons).length} crons configured`)),o.length){console.log();for(let s of o)console.log(f.yellow(` \u26A0 ${s}`))}console.log()}catch(n){console.log(f.red(` ${n.message}`))}}});Y.command("logs").description("tail daemon logs").option("-n, --lines <n>","number of lines","50").option("-f, --follow","follow log output",!1).action(async t=>{let{execSync:e,spawn:n}=await import("child_process"),o="/tmp/agentx-daemon.log",{existsSync:s}=await import("fs");if(!s(o)){console.log(f.yellow("No log file found at /tmp/agentx-daemon.log"));return}if(t.follow){let a=n("tail",["-f","-n",t.lines,o],{stdio:"inherit"});process.on("SIGINT",()=>{a.kill(),process.exit(0)})}else e(`tail -n ${t.lines} ${o}`,{stdio:"inherit"})});Y.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async t=>{let o=`http://${(N(t.config).node.bind||"127.0.0.1:18800").replace("0.0.0.0","127.0.0.1")}/events`;console.log(f.dim(` Connecting to ${o}...`)),console.log(f.dim(` Press Ctrl+C to stop
|
|
3
3
|
`));try{let s=await fetch(o);if(!s.ok||!s.body){console.log(f.red(` Failed: ${s.status}`));return}let a=s.body.getReader(),r=new TextDecoder,c="";for(;;){let{done:i,value:d}=await a.read();if(i)break;c+=r.decode(d,{stream:!0});let p=c.split(`
|
|
4
|
-
`);c=p.pop()||"";for(let g of p)if(g.startsWith("data: "))try{let l=JSON.parse(g.slice(6)),u=new Date(l.time).toLocaleTimeString(),h=l.message?.replace(/^\[agentx\]\s*/,"")||"";h.includes("executing")?console.log(`${f.dim(u)} ${f.cyan("\u25B6")} ${h}`):h.includes("completed")?console.log(`${f.dim(u)} ${f.green("\u2713")} ${h}`):h.includes("error")||h.includes("Error")?console.log(`${f.dim(u)} ${f.red("\u2717")} ${h}`):h.includes("Routing")?console.log(`${f.dim(u)} ${f.yellow("\u2192")} ${h}`):h.includes("mention")?console.log(`${f.dim(u)} ${f.magenta("@")} ${h}`):h.includes("Skipping")?console.log(`${f.dim(u)} ${f.dim("\u2298")} ${f.dim(h)}`):console.log(`${f.dim(u)} ${h}`)}catch{}else g.startsWith("event: status")}}catch(s){console.log(f.red(` Connection failed: ${s.message}`)),console.log(f.dim(" Is the daemon running? Try: agentx daemon status"))}});
|
|
5
|
-
(${(g.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(f.red(` Failed: ${s.message}`)),console.log(f.dim(" Is the daemon running? Try: agentx daemon status"))}});
|
|
6
|
-
`)),console.log(
|
|
7
|
-
Agent "${e.id}" added`)),console.log(m.dim(` Workspace: ${n}`)),console.log(m.dim(` Created: ${a.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});ge.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async t=>{let e=W();if(!e.agents?.[t]){console.log(m.red(` Agent "${t}" not found`));return}delete e.agents[t],await F(e),console.log(m.green(` Agent "${t}" removed from config (workspace preserved)`))});var ke=new X().name("channel").description("manage channels \u2014 add telegram/whatsapp/discord, list");ke.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let t=W();console.log();let e=t.channels?.telegram;if(e?.enabled){console.log(m.bold(" Telegram:"));for(let[a,r]of Object.entries(e.accounts||{}))console.log(` ${m.cyan(a)} -> agent: ${r.agentBinding}`)}else console.log(m.dim(" Telegram: disabled"));let n=t.channels?.whatsapp;if(n?.enabled){console.log(m.bold(" WhatsApp:")),console.log(` default agent: ${n.defaultAgent||"(none)"}`),console.log(` session: ${n.sessionDir||".agentx/whatsapp-sessions"}`);for(let a of n.routes||[]){let r=a.contact?`contact ${a.contact}`:`group "${a.group}"`;console.log(` ${r} -> agent: ${a.agent}`)}}else console.log(m.dim(" WhatsApp: disabled"));let o=t.channels?.discord;o?.enabled?(console.log(m.bold(" Discord:")),console.log(` agent: ${o.agentBinding||"(none)"}`)):console.log(m.dim(" Discord: disabled"));let s=t.channels?.gitlab;if(s?.enabled){console.log(m.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let a of s.routes||[])console.log(` ${a.project} -> agent: ${a.agent}`)}else console.log(m.dim(" GitLab: disabled"));console.log()});ke.command("add").description("add a channel (telegram, whatsapp, or discord)").action(async()=>{let t=W(),e=Object.keys(t.agents||{});if(!e.length){console.log(m.red(" No agents configured. Run: agentx agent add"));return}let n=e.map(s=>({title:`${s} (${t.agents[s].name})`,value:s})),{channelType:o}=await _({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(o){if(t.channels=t.channels||{},o==="telegram"){let s=await _([{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:n}]);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(m.green(` Bot verified: @${r.result.username}`));let c=`@${r.result.username}`,i=t.agents[s.agentBinding].mentions||[];i.includes(c)||(i.push(c,r.result.username),t.agents[s.agentBinding].mentions=i)}catch(a){console.log(m.red(` Invalid token: ${a.message}`));return}t.channels.telegram=t.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},t.channels.telegram.enabled=!0,t.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await F(t),console.log(m.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(o==="whatsapp"){let s=await _([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:n},{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 a=[],r=s.addRoute;for(;r;){let c=await _([{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:i=>i==="contact"?"Phone number (e.g. +21624309128)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:n},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);c.value&&c.agent&&a.push({[c.type]:c.value,agent:c.agent}),r=c.more}t.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:a},await F(t),ie(C(process.cwd(),s.sessionDir),{recursive:!0}),console.log(m.green(` WhatsApp enabled (${a.length} routes, default: ${s.defaultAgent})`)),console.log(m.dim(" Start daemon to scan QR code: agentx daemon start"))}if(o==="discord"){let s=await _([{type:"text",name:"token",message:"Discord bot token (from developer portal)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:n}]);if(!s.token)return;t.channels.discord={enabled:!0,token:s.token,agentBinding:s.agentBinding},await F(t),console.log(m.green(` Discord added -> ${s.agentBinding}`))}if(o==="gitlab"){let s=await _([{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 a=[],r=s.addRoute;for(;r;){let c=await _([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:n},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);c.project&&c.agent&&a.push({project:c.project,agent:c.agent}),r=c.more}t.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:a},await F(t),console.log(m.green(` GitLab enabled (${a.length} routes, webhook :${s.webhookPort})`)),console.log(m.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(m.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(m.dim(` Secret token: ${s.webhookSecret}`)),console.log(m.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(m.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var re=new X().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");re.command("list").alias("ls").description("list cron jobs").action(()=>{let t=W();console.log();for(let[e,n]of Object.entries(t.crons||{})){let o=n.enabled?m.green("\u25CF"):m.dim("\u25CB");console.log(` ${o} ${m.cyan(e)} \u2014 ${n.schedule} (${n.timezone})`),console.log(m.dim(` agent: ${n.agent} | timeout: ${n.timeout}s`))}Object.keys(t.crons||{}).length||console.log(m.dim(" No cron jobs configured")),console.log()});re.command("add").description("add a cron job").action(async()=>{let t=W(),e=Object.keys(t.agents||{}),n=await _([{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:e.map(o=>({title:o,value:o}))},{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}]);!n.id||!n.schedule||(t.crons=t.crons||{},t.crons[n.id]={enabled:n.enabled,schedule:n.schedule,timezone:n.timezone,agent:n.agent,prompt:n.prompt,timeout:n.timeout,onError:["log"]},await F(t),console.log(m.green(` Cron "${n.id}" added (${n.enabled?"enabled":"disabled"})`)),console.log())});re.command("enable <id>").description("enable a cron job").action(async t=>{let e=W();if(!e.crons?.[t]){console.log(m.red(` Cron "${t}" not found`));return}e.crons[t].enabled=!0,await F(e),console.log(m.green(` Cron "${t}" enabled`))});re.command("disable <id>").description("disable a cron job").action(async t=>{let e=W();if(!e.crons?.[t]){console.log(m.red(` Cron "${t}" not found`));return}e.crons[t].enabled=!1,await F(e),console.log(m.green(` Cron "${t}" disabled`))});var me=new X().name("mesh").description("manage mesh peers \u2014 add, list, remove");me.command("list").alias("ls").description("list mesh peers").action(async()=>{let t=W();if(console.log(),!t.mesh?.enabled)console.log(m.dim(" Mesh: disabled"));else{console.log(m.bold(" Mesh peers:"));for(let e of t.mesh.peers||[]){let n=m.red("unreachable");try{let s=await(await fetch(`${e.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();n=m.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${m.cyan(e.name)} ${m.dim(e.url)} ${n}`)}}console.log()});me.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let t=W(),e=await _([{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(!(!e.name||!e.url)){try{let o=await(await fetch(`${e.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(m.green(` Connected: ${o.name} (${o.skills?.length||0} agents)`))}catch{console.log(m.yellow(" Could not reach peer (adding anyway)"))}t.mesh=t.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},t.mesh.enabled=!0,t.mesh.peers=t.mesh.peers||[],t.mesh.peers.push({url:e.url,name:e.name,...e.token?{token:e.token}:{}}),await F(t),console.log(m.green(` Peer "${e.name}" added`)),console.log()}});me.command("remove <name>").alias("rm").description("remove a mesh peer").action(async t=>{let e=W();e.mesh?.peers&&(e.mesh.peers=e.mesh.peers.filter(n=>n.name!==t),e.mesh.peers.length===0&&(e.mesh.enabled=!1),await F(e),console.log(m.green(` Peer "${t}" removed`)))});var ve=new X().name("skill").description("manage skills \u2014 add to agent(s), list");ve.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(t,e)=>{let n=W(),o=C(t);if(!M(o)){console.log(m.red(` Skill not found: ${o}`));return}let s=M(we(o,"SKILL.md"))?o.split("/").pop():o.replace(/\/SKILL\.md$/,"").split("/").pop(),a;if(e.all)a=Object.keys(n.agents||{});else if(e.agent)a=e.agent;else{let r=Object.keys(n.agents||{});a=(await _({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(i=>({title:`${i} (${n.agents[i].name})`,value:i}))})).agents||[]}for(let r of a){let c=n.agents[r];if(!c){console.log(m.yellow(` Agent "${r}" not found, skipping`));continue}let i=C(c.workspace,".claude/skills",s);ie(i,{recursive:!0}),M(we(o,"SKILL.md"))?Re(o,i,{recursive:!0}):o.endsWith(".md")&&Re(o,we(i,"SKILL.md")),console.log(m.green(` ${s} -> ${r} (${c.workspace})`))}console.log()});ve.command("list").alias("ls").description("list skills per agent").action(()=>{let t=W();console.log();for(let[e,n]of Object.entries(t.agents||{})){let o=C(n.workspace,".claude/skills"),s=M(o)?Qe(o).filter(a=>!a.startsWith(".")):[];console.log(` ${m.cyan(e)}: ${s.length?s.join(", "):m.dim("(none)")}`)}console.log()});var De=new X().name("hook").description("manage hooks \u2014 add to agent workspace");De.command("add <agent>").description("add a hook to an agent's workspace settings").action(async t=>{let n=W().agents?.[t];if(!n){console.log(m.red(` Agent "${t}" not found`));return}let o=C(n.workspace,".claude/settings.json"),s=M(o)?JSON.parse($e(o,"utf-8")):{},a=await _([{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:i=>i==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!a.event||!a.value)return;s.hooks=s.hooks||{},s.hooks[a.event]=s.hooks[a.event]||[];let c={hooks:[{type:a.type,...a.type==="command"?{command:a.value}:{url:a.value}}]};a.matcher&&(c.matcher=a.matcher),s.hooks[a.event].push(c),ie(C(n.workspace,".claude"),{recursive:!0}),vt(o,JSON.stringify(s,null,2)),console.log(m.green(` Hook added to ${t}: ${a.event} -> ${a.type}`)),console.log()});var Ne=new X().name("migrate").description("import configuration from OpenClaw or other tools");Ne.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(t,e)=>{let n=[t,C(process.env.HOME||"",".openclaw/openclaw.json"),C(process.env.HOME||"",".openclaw/clawdbot.json")].filter(Boolean),o;for(let u of n)if(u&&M(u)){o=u;break}if(!o){console.log(m.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(m.dim(` Reading: ${o}`));let s=JSON.parse($e(o,"utf-8")),a=M(C(process.cwd(),"agentx.json"))?W():{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||[],c=s.bindings||[],i={};for(let u of c)u.match?.channel==="telegram"&&(i[u.match.accountId]=u.agentId);r.find(u=>u.id==="main"||u.default)&&(i.default="main");let d=0;for(let u of r){if(u.workspace?.startsWith("/data"))continue;let h=u.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),b=u.groupChat?.mentionPatterns||[];if(b.some(w=>w===h)||b.push(h),a.agents[h]={name:u.name,workspace:u.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:b,maxConcurrent:u.id==="main"?2:1,systemPrompt:`You are ${u.name} on AgentX.`,permissionMode:"bypassPermissions"},d++,!e.dryRun){ie(C(u.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-QQTCJY4B.js");w(h,a.agents[h])}}console.log(` ${m.green(d)} agents imported (workspaces set up with Claude Code best practices)`);let p=s.channels?.telegram?.accounts||{},g=0;for(let[u,h]of Object.entries(p)){if(!h.botToken)continue;let w=i[u]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";a.channels.telegram.accounts[u]={token:h.botToken,agentBinding:w},a.channels.telegram.enabled=!0,g++}console.log(` ${m.green(g)} Telegram accounts imported`);let l=C(o,"../cron/jobs.json");if(M(l)){let u=JSON.parse($e(l,"utf-8")),h=0;for(let b of u.jobs||[]){let w=b.name||b.id,k=b.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";a.crons[w]={enabled:b.enabled||!1,schedule:b.schedule?.expr||"0 9 * * *",timezone:b.schedule?.tz||"UTC",agent:k,prompt:b.payload?.message||"",timeout:b.payload?.timeoutSeconds||600,onError:["log"]},h++}console.log(` ${m.green(h)} cron jobs imported`)}e.dryRun?(console.log(m.yellow(`
|
|
8
|
-
|
|
9
|
-
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var te=new X().name("config").description("validate and inspect configuration");te.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async t=>{console.log();try{let e=z(t.config);console.log(m.green(" \u2713 Config valid")),console.log(m.dim(` Node: ${e.node.name} (${e.node.id})`)),console.log(m.dim(` Bind: ${e.node.bind}`)),console.log(m.dim(` Agents: ${Object.keys(e.agents).length}`)),console.log(m.dim(` Crons: ${Object.keys(e.crons).length}`)),console.log(m.dim(` Mesh peers: ${e.mesh.peers.length}`));let n=Object.keys(e.channels.telegram.accounts).length;console.log(m.dim(` Telegram: ${e.channels.telegram.enabled?`${n} accounts`:"disabled"}`)),console.log(m.dim(` WhatsApp: ${e.channels.whatsapp.enabled?`${e.channels.whatsapp.routes.length} routes`:"disabled"}`)),console.log(m.dim(` Discord: ${e.channels.discord?.enabled?"enabled":"disabled"}`));let o=be(e);if(o.length){console.log(),console.log(m.yellow(" Warnings:"));for(let s of o)console.log(m.yellow(` \u26A0 ${s}`))}else console.log(m.green(" \u2713 All workspaces valid"));console.log();for(let[s,a]of Object.entries(e.agents)){let r=a.workspace,c=M(C(r,".claude")),i=M(C(r,"CLAUDE.md")),d=M(C(r,".claude/settings.json")),p=M(C(r,".claude/skills"))?Qe(C(r,".claude/skills")).filter(l=>!l.startsWith(".")).length:0,g=[c?m.green("\u2713"):m.red("\u2717"),".claude",i?m.green("\u2713"):m.yellow("\u25CB"),"CLAUDE.md",d?m.green("\u2713"):m.yellow("\u25CB"),"settings",`${p} skills`];console.log(` ${m.cyan(s)}: ${g.join(" ")}`)}}catch(e){console.log(m.red(` \u2717 ${e.message}`))}console.log()});te.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(t=>{try{let e=z(t.config);console.log(JSON.stringify(e,null,2))}catch(e){console.log(m.red(e.message))}});function xt(t,e){if(e)return t;try{return JSON.parse(t)}catch{}return t.includes(",")&&!t.includes(" ")?t.split(",").map(n=>n.trim()).filter(Boolean):t}function Oe(t){return t===void 0?m.dim("(unset)"):typeof t=="string"?t:JSON.stringify(t,null,2)}te.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(t,e)=>{let{readFileSync:n,existsSync:o}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:a}=await import("./config-mutator-GAEVGHDD.js"),{expandEnvVars:r}=await import("./config-7QJ2QJIC.js"),c=e.config||s(process.cwd(),"agentx.json");o(c)||(console.log(m.red(` No config at ${c}`)),process.exit(1));let i=JSON.parse(n(c,"utf-8")),d=e.raw?i:r(i),p=a(d,t);e.json?console.log(JSON.stringify(p)):console.log(Oe(p))});te.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(t,e,n)=>{let{applyConfigMutation:o,setAtPath:s,getAtPath:a}=await import("./config-mutator-GAEVGHDD.js"),r=xt(e,!!n.string),c=await o(d=>{s(d,t,r)},{configPath:n.config,dryRun:!!n.dryRun});c.success||(console.log(m.red(` \u2717 ${c.error}`)),process.exit(1));let i=a(c.after,t);n.dryRun?console.log(m.yellow(` (dry-run) ${m.cyan(t)} would become: ${Oe(i)}`)):(console.log(m.green(` \u2713 ${m.cyan(t)} = ${Oe(i)}`)),c.reloaded?console.log(m.dim(" Daemon hot-reloaded.")):c.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(c.reloadSkipped)&&console.log(m.dim(` (daemon reload skipped: ${c.reloadSkipped})`)))});te.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(t,e)=>{let{applyConfigMutation:n,getAtPath:o,unsetAtPath:s}=await import("./config-mutator-GAEVGHDD.js"),a=await n(c=>{o(c,t)!==void 0&&s(c,t)},{configPath:e.config,dryRun:!!e.dryRun});if(a.success||(console.log(m.red(` \u2717 ${a.error}`)),process.exit(1)),o(a.after,t)!==void 0){console.log(m.dim(` (no-op) ${m.cyan(t)} was not set`));return}e.dryRun?console.log(m.yellow(` (dry-run) ${m.cyan(t)} would be removed`)):(console.log(m.green(` \u2713 ${m.cyan(t)} removed`)),a.reloaded&&console.log(m.dim(" Daemon hot-reloaded.")))});import{Command as It}from"commander";import S from"chalk";import{existsSync as Et,readFileSync as Ct}from"fs";import{resolve as Tt}from"path";import jt from"prompts";import St from"cronstrue";var We={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},xe={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 G(t){try{return St.toString(t,{use24HourTimeFormat:!1})}catch{return t}}function At(t){if(/\b(noon|midday)\b/.test(t))return xe.noon;if(/\bmidnight\b/.test(t))return xe.midnight;let e=t.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(e){let n=parseInt(e[1],10),o=e[2]?parseInt(e[2],10):0,s=e[3];return s==="pm"&&n<12&&(n+=12),s==="am"&&n===12&&(n=0),n>23||o>59?null:{h:n,m:o}}return null}function Me(t){let e=t.trim().toLowerCase();if(!e)return null;let n;if(n=e.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let g=parseInt(n[1],10);return g<1||g>59?null:{cron:`*/${g} * * * *`,human:G(`*/${g} * * * *`),matched:n[0]}}if(/\bevery\s+minute\b/.test(e))return{cron:"* * * * *",human:G("* * * * *"),matched:"every minute"};if(n=e.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let g=parseInt(n[1],10);return g<1||g>23?null:{cron:`0 */${g} * * *`,human:G(`0 */${g} * * *`),matched:n[0]}}if(/\b(every hour|hourly)\b/.test(e))return{cron:"0 * * * *",human:G("0 * * * *"),matched:"every hour"};let o=At(e),s=null;for(let[g,l]of Object.entries(xe))if(!(g==="noon"||g==="midnight")&&new RegExp(`\\b(every\\s+)?${g}s?\\b`).test(e)){s=l;break}let a=o||s,r=e.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 g=r[1],l=1;if(g==="last"||(/^\d+(st|nd|rd|th)?$/.test(g)?l=parseInt(g,10):g==="first"||g==="1st"?l=1:g==="2nd"?l=2:g==="3rd"&&(l=3),l<1||l>31))return null;let u=a||{h:9,m:0},h=`${u.m} ${u.h} ${l} * *`;return{cron:h,human:G(h),matched:r[0]}}let c=[],i=Object.keys(We).join("|"),d=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${i})s?(?:\\s*(?:,|and|&)\\s*(?:${i})s?)*)\\b`),p=e.match(d);if(p){let g=p[1];for(let l of Object.keys(We))if(new RegExp(`\\b${l}s?\\b`).test(g)){let u=We[l];c.includes(u)||c.push(u)}}if(c.length){let g=a||{h:9,m:0};c.sort((h,b)=>h-b);let l=c.join(","),u=`${g.m} ${g.h} * * ${l}`;return{cron:u,human:G(u),matched:`on ${l}`}}if(/\b(weekday|workday|business day)s?\b/.test(e)){let g=a||{h:9,m:0},l=`${g.m} ${g.h} * * 1-5`;return{cron:l,human:G(l),matched:"weekdays"}}if(/\bweekends?\b/.test(e)){let g=a||{h:9,m:0},l=`${g.m} ${g.h} * * 0,6`;return{cron:l,human:G(l),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(e)||s){let g=a||{h:9,m:0},l=`${g.m} ${g.h} * * *`;return{cron:l,human:G(l),matched:s&&Object.entries(xe).find(([,u])=>u===s)?.[0]||"daily"}}if(o){let g=`${o.m} ${o.h} * * *`;return{cron:g,human:G(g),matched:`at ${o.h}:${String(o.m).padStart(2,"0")}`}}return null}function Ze(t,e){return`${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${e}`}function et(t){let e=t||Tt(process.cwd(),"agentx.json");return Et(e)||(console.log(S.red(` No config at ${e}. Run: agentx init`)),process.exit(1)),JSON.parse(Ct(e,"utf-8"))}function Pt(t){return t?t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e==="log"||e==="notify"||e==="disable"):["log"]}async function Rt(t,e){if(!t)return;if(t==="me"){let o=e?.notifications?.destination;if(o?.channel&&o?.chatId)return{channel:o.channel,chatId:o.chatId,accountId:o.accountId};console.log(S.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:a,accountId:r}=await jt([{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||!a?void 0:{channel:s,chatId:a,accountId:r||void 0}}let n=t.split(":");if(n.length>=2)return{channel:n[0],chatId:n[1],accountId:n[2]};console.log(S.red(` Unrecognized --notify value: ${t} (use "me" or "channel:chatId[:account]")`))}var Q=new It().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');Q.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(t,e)=>{if(!t){Q.help();return}e.agent||(console.log(S.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!e.do&&!e.id&&(console.log(S.red(' --do "<prompt>" is required')),process.exit(1));let n=Me(t);n||(console.log(S.red(` Couldn't parse: "${t}"`)),console.log(S.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(S.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(S.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let o=et(e.config),s=Ke(o);o.agents?.[e.agent]||(console.log(S.red(` Agent "${e.agent}" not found in agentx.json`)),console.log(S.dim(` Available: ${Object.keys(o.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let a=Pt(e.onError),r=await Rt(e.notify,s);r&&!a.includes("notify")&&a.push("notify");let c=e.id||Ze(n.matched,e.agent),i={enabled:!e.disabled,schedule:n.cron,timezone:e.timezone,agent:e.agent,prompt:e.do,timeout:parseInt(e.timeout,10),onError:a};e.model&&(i.model=e.model),r&&(i.notify=r);let d=await N(g=>P(g,`crons.${c}`,i),{configPath:e.config,dryRun:!!e.dryRun});d.success||(console.log(S.red(` \u2717 ${d.error}`)),process.exit(1));let p=e.dryRun?"would add":"Added";console.log(S.green(` \u2713 ${p} cron ${S.cyan(c)}`)),console.log(S.dim(` Schedule: ${n.cron} (${n.human}, ${e.timezone})`)),console.log(S.dim(` Agent: ${e.agent}`)),r&&console.log(S.dim(` Notify: ${r.channel} ${r.chatId}`)),a.length&&console.log(S.dim(` On error: ${a.join(", ")}`)),!e.dryRun&&d.reloaded&&console.log(S.dim(" Daemon hot-reloaded."))});Q.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async t=>{let n=et(t.config).crons||{},o=Object.entries(n);if(!o.length){console.log(S.dim(" No scheduled jobs"));return}console.log();for(let[s,a]of o){let r=a.enabled?S.green("\u25CF"):S.dim("\u25CB"),c=a.schedule;try{c=(await import("cronstrue")).default.toString(a.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${S.cyan(s.padEnd(32))} ${S.dim(a.schedule.padEnd(14))} ${S.dim("\u2192")} ${a.agent}`),console.log(S.dim(` ${c} (${a.timezone||"UTC"})`)),a.notify&&console.log(S.dim(` notify: ${a.notify.channel} ${a.notify.chatId}`))}console.log()});for(let[t,e]of[["on",!0],["off",!1]])Q.command(`${t} <id>`).description(`${e?"enable":"disable"} a scheduled job`).action(async n=>{let o=await N(s=>{if(!ee(s,`crons.${n}`))throw new Error(`cron "${n}" not found`);P(s,`crons.${n}.enabled`,e)});o.success||(console.log(S.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(S.green(` \u2713 ${n} ${e?"enabled":"disabled"}`)),o.reloaded&&console.log(S.dim(" Daemon hot-reloaded."))});Q.command("remove <id>").alias("rm").description("remove a scheduled job").action(async t=>{let e=await N(n=>{if(!ee(n,`crons.${t}`))throw new Error(`cron "${t}" not found`);Ge(n,`crons.${t}`)});e.success||(console.log(S.red(` \u2717 ${e.error}`)),process.exit(1)),console.log(S.green(` \u2713 ${t} removed`)),e.reloaded&&console.log(S.dim(" Daemon hot-reloaded."))});Q.command("parse <when...>").description("preview a natural-language parse without writing anything").action(t=>{let e=t.join(" "),n=Me(e);n||(console.log(S.red(` \u2717 could not parse: "${e}"`)),process.exit(1)),console.log(S.green(` "${e}"`)),console.log(S.dim(` \u2192 ${n.cron}`)),console.log(S.dim(` \u2192 ${n.human}`))});import{Command as on}from"commander";import oe from"chalk";import E from"chalk";import pe from"prompts";import{readFileSync as Ot,writeFileSync as Dt,existsSync as Nt}from"fs";import{resolve as tt}from"path";var Wt=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Mt(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Ue(t){return/[\s#"'\\]/.test(t)||t===""?JSON.stringify(t):t}function nt(t=".env"){let e=tt(t);if(!Nt(e))return[];let n=Ot(e,"utf-8"),o=[];for(let s of n.split(/\r?\n/)){if(s.trim()===""){o.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){o.push({kind:"comment",raw:s});continue}let a=s.match(Wt);a?o.push({kind:"kv",key:a[1],value:Mt(a[2]),raw:s}):o.push({kind:"comment",raw:s})}return o.length&&o[o.length-1].kind==="blank"&&o.pop(),o}function Ut(t){return t.map(e=>e.kind==="kv"?`${e.key}=${Ue(e.value)}`:e.raw).join(`
|
|
4
|
+
`);c=p.pop()||"";for(let g of p)if(g.startsWith("data: "))try{let l=JSON.parse(g.slice(6)),u=new Date(l.time).toLocaleTimeString(),h=l.message?.replace(/^\[agentx\]\s*/,"")||"";h.includes("executing")?console.log(`${f.dim(u)} ${f.cyan("\u25B6")} ${h}`):h.includes("completed")?console.log(`${f.dim(u)} ${f.green("\u2713")} ${h}`):h.includes("error")||h.includes("Error")?console.log(`${f.dim(u)} ${f.red("\u2717")} ${h}`):h.includes("Routing")?console.log(`${f.dim(u)} ${f.yellow("\u2192")} ${h}`):h.includes("mention")?console.log(`${f.dim(u)} ${f.magenta("@")} ${h}`):h.includes("Skipping")?console.log(`${f.dim(u)} ${f.dim("\u2298")} ${f.dim(h)}`):console.log(`${f.dim(u)} ${h}`)}catch{}else g.startsWith("event: status")}}catch(s){console.log(f.red(` Connection failed: ${s.message}`)),console.log(f.dim(" Is the daemon running? Try: agentx daemon status"))}});Y.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(t,e,n)=>{let o=e.join(" ");try{let s=N(n.config),[a,r]=s.node.bind.split(":"),c=`http://${a||"127.0.0.1"}:${r}`,i,d;n.peer?(i=`${c}/mesh/task`,d={peer:n.peer,message:o,agent:t}):(i=`${c}/task`,d={agent:t,message:o}),console.log(f.dim(` Sending to ${n.peer?`${n.peer}/${t}`:t}...`));let g=await(await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)})).json();n.json?console.log(JSON.stringify(g,null,2)):g.error?console.log(f.red(` Error: ${g.error}`)):(console.log(),console.log(g.content||g.response||"No response"),g.duration&&console.log(f.dim(`
|
|
5
|
+
(${(g.duration/1e3).toFixed(1)}s)`)))}catch(s){console.log(f.red(` Failed: ${s.message}`)),console.log(f.dim(" Is the daemon running? Try: agentx daemon status"))}});Y.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(t,e)=>{let{execSync:n}=await import("child_process"),o=e.identity?`-e "ssh -i ${e.identity}"`:"",s=`${e.user}@${t}:${e.path}/dist/`;if(!e.skipChecks){try{console.log(f.dim(" Running tests...")),n("npx vitest run --reporter=dot",{stdio:"pipe",cwd:process.cwd()}),console.log(f.green(" \u2713 Tests passed"))}catch{console.log(f.red(" \u2717 Tests failed \u2014 aborting deploy")),console.log(f.dim(" Use --skip-checks to deploy anyway"));return}let{existsSync:a,statSync:r}=await import("fs"),{resolve:c}=await import("path"),i=c(process.cwd(),"dist/cli.js");if(!a(i)){console.log(f.red(" \u2717 dist/ not found \u2014 run build first"));return}Date.now()-r(i).mtimeMs>3e5&&(console.log(f.yellow(" \u26A0 dist/ is older than 5 minutes \u2014 rebuilding...")),n("npx tsup --no-dts",{stdio:"pipe",cwd:process.cwd()}),console.log(f.green(" \u2713 Build complete")))}console.log(f.dim(` Deploying to ${e.user}@${t}:${e.path}...`));try{if(n(`rsync -avzL --delete ${o} dist/ ${s}`,{stdio:"inherit",cwd:process.cwd()}),console.log(f.green(" \u2713 Deploy complete")),e.restart){console.log(f.dim(" Restarting remote daemon..."));let a=e.identity?`ssh -i ${e.identity}`:"ssh";n(`${a} ${e.user}@${t} "pkill -f 'node dist/cli.js daemon' 2>/dev/null; sleep 2; cd ${e.path} && nohup node dist/cli.js daemon start > /tmp/agentx-daemon.log 2>&1 &"`,{stdio:"inherit"}),console.log(f.green(" Remote daemon restarted"))}}catch(a){console.log(f.red(` Deploy failed: ${a.message}`))}});Y.action(async t=>{await new Ue(t.config).start()});function Mt(t){return t<60?`${Math.round(t)}s`:t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h ${Math.round(t%3600/60)}m`:`${Math.round(t/86400)}d ${Math.round(t%86400/3600)}h`}import{Command as Lt}from"commander";import q from"chalk";import{existsSync as ue,readFileSync as zt,writeFileSync as rt,mkdirSync as ct}from"fs";import{resolve as ce}from"path";var lt=new Lt().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async t=>{let e=process.cwd(),n=ce(e,"agentx.json"),o=ce(e,".env"),s=ce(e,".agentx/sessions");if(console.log(),console.log(q.bold(" agentx init")),console.log(),ue(n)&&!t.force){console.log(q.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let a=[ce(e,"agentx.example.json"),ce(e,"node_modules/agentix-cli/agentx.example.json")],r;for(let i of a)if(ue(i)){r=zt(i,"utf-8");break}r||(r=JSON.stringify({node:{id:We("os").hostname().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:We("os").hostname(),bind:"127.0.0.1:18800"},providers:{claude:{apiKey:"${ANTHROPIC_API_KEY}"}},agents:{assistant:{name:"Assistant",workspace:e,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)),rt(n,r),console.log(q.green(" \u2713 Created agentx.json")),ue(o)||(rt(o,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
|
|
6
|
+
`)),console.log(q.green(" \u2713 Created .env template"))),ue(s)||(ct(s,{recursive:!0}),console.log(q.green(" \u2713 Created .agentx/sessions/")));let c=ce(e,".claude");ue(c)||(ct(c,{recursive:!0}),console.log(q.green(" \u2713 Created .claude/"))),console.log(),console.log(q.bold(" Next steps:")),console.log(` 1. Edit ${q.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${q.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${q.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${q.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as Ht}from"commander";import he from"chalk";import{spawn as gt}from"child_process";import{existsSync as Bt}from"fs";import{resolve as _t}from"path";ne();var mt=new Ht().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 t=>{let e=it(),n=t.port?parseInt(t.port,10):Ft(),o=`http://127.0.0.1:${n}/setup`;if(console.log(),e.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 ${o}`)),console.log(),await Gt(o).catch(()=>!1))console.log(he.dim(" Dashboard is already running.")),t.open!==!1&&dt(o);else{console.log(he.dim(` Starting dashboard server on port ${n} (Ctrl-C to quit)\u2026`));let a=Jt(),r=gt(process.execPath,[a,"board","serve","--port",String(n)],{stdio:"inherit",detached:!1});await new Promise(c=>setTimeout(c,1200)),t.open!==!1&&dt(o),await new Promise(c=>r.on("exit",()=>c()))}});function Ft(){try{return N().dashboard.port||4202}catch{return 4202}}function Jt(){let t=_t(__dirname,"cli.js");return Bt(t)?t:process.argv[1]||t}async function Gt(t){try{let e=await fetch(t,{method:"GET"});return e.ok||e.status===302}catch{return!1}}function dt(t){let e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{gt(e,[t],{stdio:"ignore",detached:!0}).unref()}catch{}}import{Command as Kt}from"commander";import D from"chalk";var fe=new Kt().name("token").description("scoped API tokens for external access (mesh peers, integrations)");fe.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(t=>{try{let e=new Ae,n=String(t.scope).split(",").map(r=>r.trim()).filter(Boolean),o=t.expires?parseInt(t.expires,10):void 0;if(t.expires&&(!o||o<1))throw new Error("--expires must be a positive integer (days)");let{token:s,record:a}=e.create({name:t.name,scopes:n,expiresInDays:o});console.log(),console.log(D.bold(" Token created.")),console.log(),console.log(` id: ${D.cyan(a.id)}`),console.log(` name: ${a.name}`),console.log(` scopes: ${a.scopes.join(", ")}`),console.log(` expires: ${a.expiresAt||D.dim("never")}`),console.log(),console.log(D.yellow(" \u26A0 This is the only time the full secret will be shown.")),console.log(),console.log(` ${D.green.bold(s)}`),console.log(),console.log(D.dim(" Use it via the Authorization header:")),console.log(D.dim(` curl -H "Authorization: Bearer ${s.slice(0,16)}..." ...`)),console.log()}catch(e){console.log(D.red(` ${e.message}`)),process.exit(1)}});fe.command("list").alias("ls").description("show all issued tokens (secrets not included)").action(()=>{try{let t=new Ae().list();if(t.length===0){console.log(D.dim(`
|
|
7
|
+
No tokens issued.
|
|
8
|
+
`));return}console.log();for(let e of t){let n=e.revokedAt?D.red("revoked"):e.expiresAt&&Date.parse(e.expiresAt)<Date.now()?D.red("expired"):D.green("active");console.log(` ${D.cyan(e.id)} ${n} ${e.name}`),console.log(D.dim(` prefix: ${e.prefix}\u2026 scopes: ${e.scopes.join(", ")}`)),console.log(D.dim(` created: ${e.createdAt}${e.expiresAt?` expires: ${e.expiresAt}`:""}${e.lastUsedAt?` last used: ${e.lastUsedAt}`:""}`))}console.log()}catch(t){console.log(D.red(` ${t.message}`)),process.exit(1)}});fe.command("revoke <id>").description("immediately invalidate a token").action(t=>{try{let e=new Ae().revoke(t);e||(console.log(D.red(` Token ${t} not found.`)),process.exit(1)),console.log(D.green(`
|
|
9
|
+
\u2713 Revoked ${t} (${e.name})
|
|
10
|
+
`))}catch(e){console.log(D.red(` ${e.message}`)),process.exit(1)}});ne();import{Command as qt}from"commander";import J from"chalk";import{execFileSync as Me}from"child_process";import{existsSync as pt,readFileSync as ut,statSync as Yt}from"fs";import{resolve as He}from"path";var ht=new qt().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let e=[];await Vt(e);let n=Xt(e);n&&Qt(e,n),n&&Zt(e,n),t.running!==!1&&n&&await en(e,n),t.json?process.stdout.write(JSON.stringify({checks:e,summary:ze(e)},null,2)+`
|
|
11
|
+
`):tn(e);let{errors:o}=ze(e);process.exit(o>0?1:0)});async function Vt(t){let e=Number(process.versions.node.split(".")[0]);t.push({severity:e>=20?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:e>=20?void 0:"AgentX needs Node 20 or newer.",fix:e>=20?void 0:"Install a newer Node (nvm install 20 && nvm use 20)"});let n=a=>{try{return Me(process.platform==="win32"?"where":"which",[a],{encoding:"utf-8"}).trim().split(`
|
|
12
|
+
`)[0]}catch{return null}},o=n("npm");t.push({severity:o?"ok":"fail",group:"Environment",title:o?"npm on PATH":"npm not found",detail:o||void 0});let s=n("claude");if(s){let a;try{a=Me("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${a||"installed"}`,detail:s})}else t.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"})}function Xt(t){let e=He(process.cwd(),"agentx.json");if(!pt(e))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${e}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let n;try{n=JSON.parse(ut(e,"utf-8"))}catch(s){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:s.message}),null}try{N(e),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(n.agents||{}).length} agents, ${Object.keys(n.crons||{}).length} schedules)`})}catch(s){t.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:s.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let o=Object.entries(n.agents||{}).filter(([,s])=>s.tier==="claude-code");return o.length>0&&((()=>{try{return Me(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use claude-code tier but claude CLI is missing`,detail:o.map(([a])=>a).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."})),n}function Qt(t,e){let n=new Set;if(Le(e,n),n.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let o=He(process.cwd(),".env"),s={};if(pt(o))for(let c of ut(o,"utf-8").split(/\r?\n/)){let i=c.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);i&&(s[i[1]]=i[2])}let a=[],r=[];for(let c of n){let i=process.env[c]??s[c];i===void 0?a.push(c):(!i.trim()||/^["']?\s*["']?$/.test(i))&&r.push(c)}a.length===0&&r.length===0?t.push({severity:"ok",group:"Secrets",title:`${n.size} env reference(s) resolved`}):(a.length>0&&t.push({severity:"fail",group:"Secrets",title:`${a.length} env var(s) referenced in agentx.json but missing`,detail:a.join(", "),fix:`Add to .env \u2014 e.g. ${a[0]}=<value>`}),r.length>0&&t.push({severity:"warn",group:"Secrets",title:`${r.length} env var(s) set but empty`,detail:r.join(", ")}))}function Le(t,e){if(typeof t=="string")for(let n of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))e.add(n[1]);else if(Array.isArray(t))for(let n of t)Le(n,e);else if(t&&typeof t=="object")for(let n of Object.values(t))Le(n,e)}function Zt(t,e){let n=[];for(let[o,s]of Object.entries(e.agents||{})){if(!s.workspace)continue;let a=s.workspace.startsWith("/")?s.workspace:He(process.cwd(),s.workspace);try{Yt(a).isDirectory()||n.push(`${o}: ${a} (exists but not a directory)`)}catch{n.push(`${o}: ${a}`)}}n.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.push({severity:"warn",group:"Workspaces",title:`${n.length} agent workspace(s) missing`,detail:n.join(`
|
|
13
|
+
`),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}async function en(t,e){let n=e.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",o={};e.dashboard?.token&&(o.Authorization=`Bearer ${e.dashboard.token}`);try{let s=new AbortController,a=setTimeout(()=>s.abort(),2e3),r=await fetch(n+"/health",{headers:o,signal:s.signal});if(clearTimeout(a),!r.ok){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${r.status}`,detail:n});return}let c=await r.json();t.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${c.agents?.length??0} agents live, uptime ${Math.round((c.uptime??0)/60)}m`,detail:n})}catch{t.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:n,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function ze(t){return{errors:t.filter(e=>e.severity==="fail").length,warnings:t.filter(e=>e.severity==="warn").length,ok:t.filter(e=>e.severity==="ok").length}}function tn(t){console.log(),console.log(J.bold(" agentx doctor")),console.log();let e=new Map;for(let o of t)e.has(o.group)||e.set(o.group,[]),e.get(o.group).push(o);for(let[o,s]of e){console.log(J.bold(" "+o));for(let a of s){let r=a.severity==="ok"?J.green("\u2713"):a.severity==="warn"?J.yellow("!"):J.red("\u2717");console.log(` ${r} ${a.title}`),a.detail&&console.log(J.dim(" "+a.detail.replace(/\n/g,`
|
|
14
|
+
`))),a.fix&&console.log(J.dim(" \u2192 "+a.fix))}console.log()}let n=ze(t);n.errors>0?console.log(J.red.bold(` ${n.errors} error${n.errors===1?"":"s"}`)+(n.warnings?J.yellow(`, ${n.warnings} warning${n.warnings===1?"":"s"}`):"")+`. Fix the error${n.errors===1?"":"s"} and rerun.`):n.warnings>0?console.log(J.yellow.bold(` ${n.warnings} warning${n.warnings===1?"":"s"}.`)+J.dim(" Review but not blocking.")):console.log(J.green.bold(` All checks passed (${n.ok}).`)),console.log()}ne();import{Command as Z}from"commander";import m from"chalk";import G from"prompts";import{readFileSync as Ie,writeFileSync as nn,existsSync as L,mkdirSync as le,cpSync as Be,readdirSync as ft}from"fs";import{resolve as j,join as Ce}from"path";function M(){let t=j(process.cwd(),"agentx.json");if(!L(t))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse(Ie(t,"utf-8"))}function K(t){return U(e=>{for(let n of Object.keys(e))delete e[n];Object.assign(e,t)}).then(e=>{if(!e.success){console.error(m.red(` Config save failed: ${e.error}`));return}e.reloaded?console.error(m.dim(" (daemon hot-reloaded)")):e.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(e.reloadSkipped)&&console.error(m.dim(` (daemon reload skipped: ${e.reloadSkipped})`))})}var ye=new Z().name("agent").description("manage agents \u2014 add, list, remove");ye.command("list").alias("ls").description("list configured agents").action(()=>{let t=M();console.log();for(let[e,n]of Object.entries(t.agents||{})){let o=n.mentions?.join(", ")||"";console.log(` ${m.cyan(e)} \u2014 ${n.name} (${n.tier})`),console.log(m.dim(` workspace: ${n.workspace}`)),o&&console.log(m.dim(` mentions: ${o}`))}console.log()});ye.command("add").description("add a new agent interactively").action(async()=>{let t=M(),e=await G([{type:"text",name:"id",message:"Agent ID (kebab-case)",validate:d=>/^[a-z0-9-]+$/.test(d)||"Use lowercase, numbers, hyphens"},{type:"text",name:"name",message:"Display name"},{type:"text",name:"workspace",message:"Workspace path",initial:j(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(!e.id)return;let n=e.workspace.endsWith(e.id)?e.workspace:Ce(e.workspace,e.id);le(j(n,".claude/skills"),{recursive:!0});let o={name:e.name,workspace:n,tier:e.tier,model:e.model,mentions:e.mentions?.map(d=>d.trim()).filter(Boolean)||[],maxConcurrent:e.maxConcurrent,systemPrompt:e.systemPrompt,permissionMode:"default"},{setupWorkspace:s}=await import("./workspace-setup-ZWTT42XT.js"),a=s(e.id,o,"19900",(...d)=>{console.log(m.dim(` ${d.join(" ")}`))}),r=j(process.cwd(),"src/wiki/SKILL.md"),c=j(__dirname,"../wiki/SKILL.md"),i=L(r)?r:c;L(i)&&(le(j(n,".claude/skills/wiki"),{recursive:!0}),Be(i,j(n,".claude/skills/wiki/SKILL.md"))),t.agents=t.agents||{},t.agents[e.id]=o,await K(t),console.log(m.green(`
|
|
15
|
+
Agent "${e.id}" added`)),console.log(m.dim(` Workspace: ${n}`)),console.log(m.dim(` Created: ${a.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});ye.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(async t=>{let e=M();if(!e.agents?.[t]){console.log(m.red(` Agent "${t}" not found`));return}delete e.agents[t],await K(e),console.log(m.green(` Agent "${t}" removed from config (workspace preserved)`))});var je=new Z().name("channel").description("manage channels \u2014 add telegram/whatsapp/discord, list");je.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let t=M();console.log();let e=t.channels?.telegram;if(e?.enabled){console.log(m.bold(" Telegram:"));for(let[a,r]of Object.entries(e.accounts||{}))console.log(` ${m.cyan(a)} -> agent: ${r.agentBinding}`)}else console.log(m.dim(" Telegram: disabled"));let n=t.channels?.whatsapp;if(n?.enabled){console.log(m.bold(" WhatsApp:")),console.log(` default agent: ${n.defaultAgent||"(none)"}`),console.log(` session: ${n.sessionDir||".agentx/whatsapp-sessions"}`);for(let a of n.routes||[]){let r=a.contact?`contact ${a.contact}`:`group "${a.group}"`;console.log(` ${r} -> agent: ${a.agent}`)}}else console.log(m.dim(" WhatsApp: disabled"));let o=t.channels?.discord;o?.enabled?(console.log(m.bold(" Discord:")),console.log(` agent: ${o.agentBinding||"(none)"}`)):console.log(m.dim(" Discord: disabled"));let s=t.channels?.gitlab;if(s?.enabled){console.log(m.bold(" GitLab:")),console.log(` host: ${s.host}`),console.log(` webhook: :${s.webhookPort}`);for(let a of s.routes||[])console.log(` ${a.project} -> agent: ${a.agent}`)}else console.log(m.dim(" GitLab: disabled"));console.log()});je.command("add").description("add a channel (telegram, whatsapp, or discord)").action(async()=>{let t=M(),e=Object.keys(t.agents||{});if(!e.length){console.log(m.red(" No agents configured. Run: agentx agent add"));return}let n=e.map(s=>({title:`${s} (${t.agents[s].name})`,value:s})),{channelType:o}=await G({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(o){if(t.channels=t.channels||{},o==="telegram"){let s=await G([{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:n}]);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(m.green(` Bot verified: @${r.result.username}`));let c=`@${r.result.username}`,i=t.agents[s.agentBinding].mentions||[];i.includes(c)||(i.push(c,r.result.username),t.agents[s.agentBinding].mentions=i)}catch(a){console.log(m.red(` Invalid token: ${a.message}`));return}t.channels.telegram=t.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},t.channels.telegram.enabled=!0,t.channels.telegram.accounts[s.accountName]={token:s.token,agentBinding:s.agentBinding},await K(t),console.log(m.green(` Telegram "${s.accountName}" added -> ${s.agentBinding}`))}if(o==="whatsapp"){let s=await G([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:n},{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 a=[],r=s.addRoute;for(;r;){let c=await G([{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:i=>i==="contact"?"Phone number (e.g. +21624309128)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:n},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);c.value&&c.agent&&a.push({[c.type]:c.value,agent:c.agent}),r=c.more}t.channels.whatsapp={enabled:!0,sessionDir:s.sessionDir,defaultAgent:s.defaultAgent,routes:a},await K(t),le(j(process.cwd(),s.sessionDir),{recursive:!0}),console.log(m.green(` WhatsApp enabled (${a.length} routes, default: ${s.defaultAgent})`)),console.log(m.dim(" Start daemon to scan QR code: agentx daemon start"))}if(o==="discord"){let s=await G([{type:"text",name:"token",message:"Discord bot token (from developer portal)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:n}]);if(!s.token)return;t.channels.discord={enabled:!0,token:s.token,agentBinding:s.agentBinding},await K(t),console.log(m.green(` Discord added -> ${s.agentBinding}`))}if(o==="gitlab"){let s=await G([{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 a=[],r=s.addRoute;for(;r;){let c=await G([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:n},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);c.project&&c.agent&&a.push({project:c.project,agent:c.agent}),r=c.more}t.channels.gitlab={enabled:!0,host:s.host,token:s.token,webhookPort:s.webhookPort,webhookSecret:s.webhookSecret||void 0,routes:a},await K(t),console.log(m.green(` GitLab enabled (${a.length} routes, webhook :${s.webhookPort})`)),console.log(m.dim(` Add webhook in GitLab: ${s.host}/<project>/-/hooks`)),console.log(m.dim(` URL: http://your-server:${s.webhookPort}/`)),s.webhookSecret&&console.log(m.dim(` Secret token: ${s.webhookSecret}`)),console.log(m.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(m.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var de=new Z().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");de.command("list").alias("ls").description("list cron jobs").action(()=>{let t=M();console.log();for(let[e,n]of Object.entries(t.crons||{})){let o=n.enabled?m.green("\u25CF"):m.dim("\u25CB");console.log(` ${o} ${m.cyan(e)} \u2014 ${n.schedule} (${n.timezone})`),console.log(m.dim(` agent: ${n.agent} | timeout: ${n.timeout}s`))}Object.keys(t.crons||{}).length||console.log(m.dim(" No cron jobs configured")),console.log()});de.command("add").description("add a cron job").action(async()=>{let t=M(),e=Object.keys(t.agents||{}),n=await G([{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:e.map(o=>({title:o,value:o}))},{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}]);!n.id||!n.schedule||(t.crons=t.crons||{},t.crons[n.id]={enabled:n.enabled,schedule:n.schedule,timezone:n.timezone,agent:n.agent,prompt:n.prompt,timeout:n.timeout,onError:["log"]},await K(t),console.log(m.green(` Cron "${n.id}" added (${n.enabled?"enabled":"disabled"})`)),console.log())});de.command("enable <id>").description("enable a cron job").action(async t=>{let e=M();if(!e.crons?.[t]){console.log(m.red(` Cron "${t}" not found`));return}e.crons[t].enabled=!0,await K(e),console.log(m.green(` Cron "${t}" enabled`))});de.command("disable <id>").description("disable a cron job").action(async t=>{let e=M();if(!e.crons?.[t]){console.log(m.red(` Cron "${t}" not found`));return}e.crons[t].enabled=!1,await K(e),console.log(m.green(` Cron "${t}" disabled`))});var be=new Z().name("mesh").description("manage mesh peers \u2014 add, list, remove");be.command("list").alias("ls").description("list mesh peers").action(async()=>{let t=M();if(console.log(),!t.mesh?.enabled)console.log(m.dim(" Mesh: disabled"));else{console.log(m.bold(" Mesh peers:"));for(let e of t.mesh.peers||[]){let n=m.red("unreachable");try{let s=await(await fetch(`${e.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();n=m.green(`healthy \u2014 ${s.agents?.length||0} agents`)}catch{}console.log(` ${m.cyan(e.name)} ${m.dim(e.url)} ${n}`)}}console.log()});be.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let t=M(),e=await G([{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(!(!e.name||!e.url)){try{let o=await(await fetch(`${e.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(m.green(` Connected: ${o.name} (${o.skills?.length||0} agents)`))}catch{console.log(m.yellow(" Could not reach peer (adding anyway)"))}t.mesh=t.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},t.mesh.enabled=!0,t.mesh.peers=t.mesh.peers||[],t.mesh.peers.push({url:e.url,name:e.name,...e.token?{token:e.token}:{}}),await K(t),console.log(m.green(` Peer "${e.name}" added`)),console.log()}});be.command("remove <name>").alias("rm").description("remove a mesh peer").action(async t=>{let e=M();e.mesh?.peers&&(e.mesh.peers=e.mesh.peers.filter(n=>n.name!==t),e.mesh.peers.length===0&&(e.mesh.enabled=!1),await K(e),console.log(m.green(` Peer "${t}" removed`)))});var Ee=new Z().name("skill").description("manage skills \u2014 add to agent(s), list");Ee.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(t,e)=>{let n=M(),o=j(t);if(!L(o)){console.log(m.red(` Skill not found: ${o}`));return}let s=L(Ce(o,"SKILL.md"))?o.split("/").pop():o.replace(/\/SKILL\.md$/,"").split("/").pop(),a;if(e.all)a=Object.keys(n.agents||{});else if(e.agent)a=e.agent;else{let r=Object.keys(n.agents||{});a=(await G({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(i=>({title:`${i} (${n.agents[i].name})`,value:i}))})).agents||[]}for(let r of a){let c=n.agents[r];if(!c){console.log(m.yellow(` Agent "${r}" not found, skipping`));continue}let i=j(c.workspace,".claude/skills",s);le(i,{recursive:!0}),L(Ce(o,"SKILL.md"))?Be(o,i,{recursive:!0}):o.endsWith(".md")&&Be(o,Ce(i,"SKILL.md")),console.log(m.green(` ${s} -> ${r} (${c.workspace})`))}console.log()});Ee.command("list").alias("ls").description("list skills per agent").action(()=>{let t=M();console.log();for(let[e,n]of Object.entries(t.agents||{})){let o=j(n.workspace,".claude/skills"),s=L(o)?ft(o).filter(a=>!a.startsWith(".")):[];console.log(` ${m.cyan(e)}: ${s.length?s.join(", "):m.dim("(none)")}`)}console.log()});var Fe=new Z().name("hook").description("manage hooks \u2014 add to agent workspace");Fe.command("add <agent>").description("add a hook to an agent's workspace settings").action(async t=>{let n=M().agents?.[t];if(!n){console.log(m.red(` Agent "${t}" not found`));return}let o=j(n.workspace,".claude/settings.json"),s=L(o)?JSON.parse(Ie(o,"utf-8")):{},a=await G([{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:i=>i==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!a.event||!a.value)return;s.hooks=s.hooks||{},s.hooks[a.event]=s.hooks[a.event]||[];let c={hooks:[{type:a.type,...a.type==="command"?{command:a.value}:{url:a.value}}]};a.matcher&&(c.matcher=a.matcher),s.hooks[a.event].push(c),le(j(n.workspace,".claude"),{recursive:!0}),nn(o,JSON.stringify(s,null,2)),console.log(m.green(` Hook added to ${t}: ${a.event} -> ${a.type}`)),console.log()});var Je=new Z().name("migrate").description("import configuration from OpenClaw or other tools");Je.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(t,e)=>{let n=[t,j(process.env.HOME||"",".openclaw/openclaw.json"),j(process.env.HOME||"",".openclaw/clawdbot.json")].filter(Boolean),o;for(let u of n)if(u&&L(u)){o=u;break}if(!o){console.log(m.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(m.dim(` Reading: ${o}`));let s=JSON.parse(Ie(o,"utf-8")),a=L(j(process.cwd(),"agentx.json"))?M():{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||[],c=s.bindings||[],i={};for(let u of c)u.match?.channel==="telegram"&&(i[u.match.accountId]=u.agentId);r.find(u=>u.id==="main"||u.default)&&(i.default="main");let d=0;for(let u of r){if(u.workspace?.startsWith("/data"))continue;let h=u.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),b=u.groupChat?.mentionPatterns||[];if(b.some(w=>w===h)||b.push(h),a.agents[h]={name:u.name,workspace:u.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:b,maxConcurrent:u.id==="main"?2:1,systemPrompt:`You are ${u.name} on AgentX.`,permissionMode:"bypassPermissions"},d++,!e.dryRun){le(j(u.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:w}=await import("./workspace-setup-ZWTT42XT.js");w(h,a.agents[h])}}console.log(` ${m.green(d)} agents imported (workspaces set up with Claude Code best practices)`);let p=s.channels?.telegram?.accounts||{},g=0;for(let[u,h]of Object.entries(p)){if(!h.botToken)continue;let w=i[u]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";a.channels.telegram.accounts[u]={token:h.botToken,agentBinding:w},a.channels.telegram.enabled=!0,g++}console.log(` ${m.green(g)} Telegram accounts imported`);let l=j(o,"../cron/jobs.json");if(L(l)){let u=JSON.parse(Ie(l,"utf-8")),h=0;for(let b of u.jobs||[]){let w=b.name||b.id,k=b.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";a.crons[w]={enabled:b.enabled||!1,schedule:b.schedule?.expr||"0 9 * * *",timezone:b.schedule?.tz||"UTC",agent:k,prompt:b.payload?.message||"",timeout:b.payload?.timeoutSeconds||600,onError:["log"]},h++}console.log(` ${m.green(h)} cron jobs imported`)}e.dryRun?(console.log(m.yellow(`
|
|
16
|
+
Dry run \u2014 nothing written`)),console.log(JSON.stringify(a,null,2))):(await K(a),console.log(m.green(`
|
|
17
|
+
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var se=new Z().name("config").description("validate and inspect configuration");se.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async t=>{console.log();try{let e=N(t.config);console.log(m.green(" \u2713 Config valid")),console.log(m.dim(` Node: ${e.node.name} (${e.node.id})`)),console.log(m.dim(` Bind: ${e.node.bind}`)),console.log(m.dim(` Agents: ${Object.keys(e.agents).length}`)),console.log(m.dim(` Crons: ${Object.keys(e.crons).length}`)),console.log(m.dim(` Mesh peers: ${e.mesh.peers.length}`));let n=Object.keys(e.channels.telegram.accounts).length;console.log(m.dim(` Telegram: ${e.channels.telegram.enabled?`${n} accounts`:"disabled"}`)),console.log(m.dim(` WhatsApp: ${e.channels.whatsapp.enabled?`${e.channels.whatsapp.routes.length} routes`:"disabled"}`)),console.log(m.dim(` Discord: ${e.channels.discord?.enabled?"enabled":"disabled"}`));let o=Se(e);if(o.length){console.log(),console.log(m.yellow(" Warnings:"));for(let s of o)console.log(m.yellow(` \u26A0 ${s}`))}else console.log(m.green(" \u2713 All workspaces valid"));console.log();for(let[s,a]of Object.entries(e.agents)){let r=a.workspace,c=L(j(r,".claude")),i=L(j(r,"CLAUDE.md")),d=L(j(r,".claude/settings.json")),p=L(j(r,".claude/skills"))?ft(j(r,".claude/skills")).filter(l=>!l.startsWith(".")).length:0,g=[c?m.green("\u2713"):m.red("\u2717"),".claude",i?m.green("\u2713"):m.yellow("\u25CB"),"CLAUDE.md",d?m.green("\u2713"):m.yellow("\u25CB"),"settings",`${p} skills`];console.log(` ${m.cyan(s)}: ${g.join(" ")}`)}}catch(e){console.log(m.red(` \u2717 ${e.message}`))}console.log()});se.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(t=>{try{let e=N(t.config);console.log(JSON.stringify(e,null,2))}catch(e){console.log(m.red(e.message))}});function on(t,e){if(e)return t;try{return JSON.parse(t)}catch{}return t.includes(",")&&!t.includes(" ")?t.split(",").map(n=>n.trim()).filter(Boolean):t}function _e(t){return t===void 0?m.dim("(unset)"):typeof t=="string"?t:JSON.stringify(t,null,2)}se.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(t,e)=>{let{readFileSync:n,existsSync:o}=await import("fs"),{resolve:s}=await import("path"),{getAtPath:a}=await import("./config-mutator-6EJHSP3Y.js"),{expandEnvVars:r}=await import("./config-DCJYECL4.js"),c=e.config||s(process.cwd(),"agentx.json");o(c)||(console.log(m.red(` No config at ${c}`)),process.exit(1));let i=JSON.parse(n(c,"utf-8")),d=e.raw?i:r(i),p=a(d,t);e.json?console.log(JSON.stringify(p)):console.log(_e(p))});se.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(t,e,n)=>{let{applyConfigMutation:o,setAtPath:s,getAtPath:a}=await import("./config-mutator-6EJHSP3Y.js"),r=on(e,!!n.string),c=await o(d=>{s(d,t,r)},{configPath:n.config,dryRun:!!n.dryRun});c.success||(console.log(m.red(` \u2717 ${c.error}`)),process.exit(1));let i=a(c.after,t);n.dryRun?console.log(m.yellow(` (dry-run) ${m.cyan(t)} would become: ${_e(i)}`)):(console.log(m.green(` \u2713 ${m.cyan(t)} = ${_e(i)}`)),c.reloaded?console.log(m.dim(" Daemon hot-reloaded.")):c.reloadSkipped&&!/ECONNREFUSED|unreachable|fetch failed/i.test(c.reloadSkipped)&&console.log(m.dim(` (daemon reload skipped: ${c.reloadSkipped})`)))});se.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(t,e)=>{let{applyConfigMutation:n,getAtPath:o,unsetAtPath:s}=await import("./config-mutator-6EJHSP3Y.js"),a=await n(c=>{o(c,t)!==void 0&&s(c,t)},{configPath:e.config,dryRun:!!e.dryRun});if(a.success||(console.log(m.red(` \u2717 ${a.error}`)),process.exit(1)),o(a.after,t)!==void 0){console.log(m.dim(` (no-op) ${m.cyan(t)} was not set`));return}e.dryRun?console.log(m.yellow(` (dry-run) ${m.cyan(t)} would be removed`)):(console.log(m.green(` \u2713 ${m.cyan(t)} removed`)),a.reloaded&&console.log(m.dim(" Daemon hot-reloaded.")))});import{Command as rn}from"commander";import S from"chalk";import{existsSync as cn,readFileSync as ln}from"fs";import{resolve as dn}from"path";import gn from"prompts";ne();import sn from"cronstrue";var Ge={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},Te={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 V(t){try{return sn.toString(t,{use24HourTimeFormat:!1})}catch{return t}}function an(t){if(/\b(noon|midday)\b/.test(t))return Te.noon;if(/\bmidnight\b/.test(t))return Te.midnight;let e=t.match(/\b(?:at|by|@)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/);if(e){let n=parseInt(e[1],10),o=e[2]?parseInt(e[2],10):0,s=e[3];return s==="pm"&&n<12&&(n+=12),s==="am"&&n===12&&(n=0),n>23||o>59?null:{h:n,m:o}}return null}function Ke(t){let e=t.trim().toLowerCase();if(!e)return null;let n;if(n=e.match(/\bevery\s+(\d+)\s*(minutes|mins|m)\b/)){let g=parseInt(n[1],10);return g<1||g>59?null:{cron:`*/${g} * * * *`,human:V(`*/${g} * * * *`),matched:n[0]}}if(/\bevery\s+minute\b/.test(e))return{cron:"* * * * *",human:V("* * * * *"),matched:"every minute"};if(n=e.match(/\bevery\s+(\d+)\s*(hours|hrs|h)\b/)){let g=parseInt(n[1],10);return g<1||g>23?null:{cron:`0 */${g} * * *`,human:V(`0 */${g} * * *`),matched:n[0]}}if(/\b(every hour|hourly)\b/.test(e))return{cron:"0 * * * *",human:V("0 * * * *"),matched:"every hour"};let o=an(e),s=null;for(let[g,l]of Object.entries(Te))if(!(g==="noon"||g==="midnight")&&new RegExp(`\\b(every\\s+)?${g}s?\\b`).test(e)){s=l;break}let a=o||s,r=e.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 g=r[1],l=1;if(g==="last"||(/^\d+(st|nd|rd|th)?$/.test(g)?l=parseInt(g,10):g==="first"||g==="1st"?l=1:g==="2nd"?l=2:g==="3rd"&&(l=3),l<1||l>31))return null;let u=a||{h:9,m:0},h=`${u.m} ${u.h} ${l} * *`;return{cron:h,human:V(h),matched:r[0]}}let c=[],i=Object.keys(Ge).join("|"),d=new RegExp(`\\b(?:every|on|each|by)\\s+((?:${i})s?(?:\\s*(?:,|and|&)\\s*(?:${i})s?)*)\\b`),p=e.match(d);if(p){let g=p[1];for(let l of Object.keys(Ge))if(new RegExp(`\\b${l}s?\\b`).test(g)){let u=Ge[l];c.includes(u)||c.push(u)}}if(c.length){let g=a||{h:9,m:0};c.sort((h,b)=>h-b);let l=c.join(","),u=`${g.m} ${g.h} * * ${l}`;return{cron:u,human:V(u),matched:`on ${l}`}}if(/\b(weekday|workday|business day)s?\b/.test(e)){let g=a||{h:9,m:0},l=`${g.m} ${g.h} * * 1-5`;return{cron:l,human:V(l),matched:"weekdays"}}if(/\bweekends?\b/.test(e)){let g=a||{h:9,m:0},l=`${g.m} ${g.h} * * 0,6`;return{cron:l,human:V(l),matched:"weekends"}}if(/\b(every day|daily|each day)\b/.test(e)||s){let g=a||{h:9,m:0},l=`${g.m} ${g.h} * * *`;return{cron:l,human:V(l),matched:s&&Object.entries(Te).find(([,u])=>u===s)?.[0]||"daily"}}if(o){let g=`${o.m} ${o.h} * * *`;return{cron:g,human:V(g),matched:`at ${o.h}:${String(o.m).padStart(2,"0")}`}}return null}function yt(t,e){return`${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"job"}-${e}`}function bt(t){let e=t||dn(process.cwd(),"agentx.json");return cn(e)||(console.log(S.red(` No config at ${e}. Run: agentx init`)),process.exit(1)),JSON.parse(ln(e,"utf-8"))}function mn(t){return t?t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e==="log"||e==="notify"||e==="disable"):["log"]}async function pn(t,e){if(!t)return;if(t==="me"){let o=e?.notifications?.destination;if(o?.channel&&o?.chatId)return{channel:o.channel,chatId:o.chatId,accountId:o.accountId};console.log(S.yellow(" --notify me: no notifications.destination set yet."));let{channel:s,chatId:a,accountId:r}=await gn([{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||!a?void 0:{channel:s,chatId:a,accountId:r||void 0}}let n=t.split(":");if(n.length>=2)return{channel:n[0],chatId:n[1],accountId:n[2]};console.log(S.red(` Unrecognized --notify value: ${t} (use "me" or "channel:chatId[:account]")`))}var ee=new rn().name("schedule").description('schedule agents with natural-language cron: "every morning at 9" --agent devops --do "Post standup"');ee.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(t,e)=>{if(!t){ee.help();return}e.agent||(console.log(S.red(' --agent is required. Try: agentx schedule "every morning at 9" --agent devops --do "..."')),process.exit(1)),!e.do&&!e.id&&(console.log(S.red(' --do "<prompt>" is required')),process.exit(1));let n=Ke(t);n||(console.log(S.red(` Couldn't parse: "${t}"`)),console.log(S.dim(' Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes",')),console.log(S.dim(' "every monday at 10am", "1st of every month at noon",')),console.log(S.dim(' "daily at 9:30am", "every hour", "hourly"')),process.exit(1));let o=bt(e.config),s=nt(o);o.agents?.[e.agent]||(console.log(S.red(` Agent "${e.agent}" not found in agentx.json`)),console.log(S.dim(` Available: ${Object.keys(o.agents||{}).join(", ")||"(none)"}`)),process.exit(1));let a=mn(e.onError),r=await pn(e.notify,s);r&&!a.includes("notify")&&a.push("notify");let c=e.id||yt(n.matched,e.agent),i={enabled:!e.disabled,schedule:n.cron,timezone:e.timezone,agent:e.agent,prompt:e.do,timeout:parseInt(e.timeout,10),onError:a};e.model&&(i.model=e.model),r&&(i.notify=r);let d=await U(g=>P(g,`crons.${c}`,i),{configPath:e.config,dryRun:!!e.dryRun});d.success||(console.log(S.red(` \u2717 ${d.error}`)),process.exit(1));let p=e.dryRun?"would add":"Added";console.log(S.green(` \u2713 ${p} cron ${S.cyan(c)}`)),console.log(S.dim(` Schedule: ${n.cron} (${n.human}, ${e.timezone})`)),console.log(S.dim(` Agent: ${e.agent}`)),r&&console.log(S.dim(` Notify: ${r.channel} ${r.chatId}`)),a.length&&console.log(S.dim(` On error: ${a.join(", ")}`)),!e.dryRun&&d.reloaded&&console.log(S.dim(" Daemon hot-reloaded."))});ee.command("list").alias("ls").description("list all scheduled jobs with human-readable descriptions").option("-c, --config <path>","path to agentx.json").action(async t=>{let n=bt(t.config).crons||{},o=Object.entries(n);if(!o.length){console.log(S.dim(" No scheduled jobs"));return}console.log();for(let[s,a]of o){let r=a.enabled?S.green("\u25CF"):S.dim("\u25CB"),c=a.schedule;try{c=(await import("cronstrue")).default.toString(a.schedule,{use24HourTimeFormat:!1})}catch{}console.log(` ${r} ${S.cyan(s.padEnd(32))} ${S.dim(a.schedule.padEnd(14))} ${S.dim("\u2192")} ${a.agent}`),console.log(S.dim(` ${c} (${a.timezone||"UTC"})`)),a.notify&&console.log(S.dim(` notify: ${a.notify.channel} ${a.notify.chatId}`))}console.log()});for(let[t,e]of[["on",!0],["off",!1]])ee.command(`${t} <id>`).description(`${e?"enable":"disable"} a scheduled job`).action(async n=>{let o=await U(s=>{if(!oe(s,`crons.${n}`))throw new Error(`cron "${n}" not found`);P(s,`crons.${n}.enabled`,e)});o.success||(console.log(S.red(` \u2717 ${o.error}`)),process.exit(1)),console.log(S.green(` \u2713 ${n} ${e?"enabled":"disabled"}`)),o.reloaded&&console.log(S.dim(" Daemon hot-reloaded."))});ee.command("remove <id>").alias("rm").description("remove a scheduled job").action(async t=>{let e=await U(n=>{if(!oe(n,`crons.${t}`))throw new Error(`cron "${t}" not found`);ot(n,`crons.${t}`)});e.success||(console.log(S.red(` \u2717 ${e.error}`)),process.exit(1)),console.log(S.green(` \u2713 ${t} removed`)),e.reloaded&&console.log(S.dim(" Daemon hot-reloaded."))});ee.command("parse <when...>").description("preview a natural-language parse without writing anything").action(t=>{let e=t.join(" "),n=Ke(e);n||(console.log(S.red(` \u2717 could not parse: "${e}"`)),process.exit(1)),console.log(S.green(` "${e}"`)),console.log(S.dim(` \u2192 ${n.cron}`)),console.log(S.dim(` \u2192 ${n.human}`))});import{Command as Mn}from"commander";import ie from"chalk";import I from"chalk";import we from"prompts";import{readFileSync as un,writeFileSync as hn,existsSync as fn}from"fs";import{resolve as wt}from"path";var yn=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function bn(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function qe(t){return/[\s#"'\\]/.test(t)||t===""?JSON.stringify(t):t}function $t(t=".env"){let e=wt(t);if(!fn(e))return[];let n=un(e,"utf-8"),o=[];for(let s of n.split(/\r?\n/)){if(s.trim()===""){o.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){o.push({kind:"comment",raw:s});continue}let a=s.match(yn);a?o.push({kind:"kv",key:a[1],value:bn(a[2]),raw:s}):o.push({kind:"comment",raw:s})}return o.length&&o[o.length-1].kind==="blank"&&o.pop(),o}function wn(t){return t.map(e=>e.kind==="kv"?`${e.key}=${qe(e.value)}`:e.raw).join(`
|
|
10
18
|
`)+`
|
|
11
|
-
`}function ne(t,e,n=".env"){let o=tt(n),s=nt(o),a=s.findIndex(r=>r.kind==="kv"&&r.key===t);a>=0?s[a]={kind:"kv",key:t,value:e,raw:`${t}=${Ue(e)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:t,value:e,raw:`${t}=${Ue(e)}`})),Dt(o,Ut(s))}function Le(t,e=".env"){return nt(e).find(s=>s.kind==="kv"&&s.key===t)?.value}var ot="https://t.me/BotFather";async function Lt(t){try{let e=await fetch(`https://api.telegram.org/bot${t}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!e.ok)return null;let n=await e.json();return n?.ok?n.result:null}catch{return null}}async function Ht(t,e){let n=Date.now()+e,o=0;try{let a=await(await fetch(`https://api.telegram.org/bot${t}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();a?.result?.length&&(o=a.result[0].update_id+1)}catch{}for(;Date.now()<n;)try{let a=await(await fetch(`https://api.telegram.org/bot${t}/getUpdates?offset=${o}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of a?.result||[]){o=Math.max(o,r.update_id+1);let c=r.message||r.edited_message||r.channel_post;if(c?.chat?.id)return{chatId:c.chat.id,chatTitle:c.chat.title||c.chat.username||c.chat.first_name,from:c.from?.first_name||c.from?.username||"unknown"}}}catch{}return null}async function st(t={}){console.log(),console.log(E.bold(" Connect Telegram")),console.log(),console.log(E.dim(` 1. Open ${ot}`)),console.log(E.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(E.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:e}=await pe({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(e)try{let{spawn:v}=await import("child_process"),$=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";v($,[ot],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:n}=await pe({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:v=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(v.trim())||"That doesn't look like a Telegram token"});n||(console.log(E.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let o=await Lt(n.trim());o||(console.log(E.red("\u2717 invalid or revoked")),process.exit(1)),console.log(E.green(`\u2713 ${o.first_name} (@${o.username})`));let{readFileSync:s,existsSync:a}=await import("fs"),{resolve:r}=await import("path"),c=t.configPath||r(process.cwd(),"agentx.json");a(c)||(console.log(E.red(` No agentx.json at ${c}. Run: agentx init`)),process.exit(1));let i=JSON.parse(s(c,"utf-8")),d=Object.keys(i.agents||{});d.length===0&&(console.log(E.red(" No agents configured. Run: agentx agent add")),process.exit(1));let p=t.agent;p||(p=(await pe({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:d.map($=>({title:$,value:$})),initial:0})).agent),p||(console.log(E.red(" Aborted")),process.exit(1));let g=i.channels?.telegram?.accounts||{},l=t.account||p;g[l]&&g[l].agentBinding!==p&&(l=(await pe({type:"text",name:"account",message:`Account "${l}" is already in use. Pick a different label:`,initial:`${p}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),l||(console.log(E.red(" Aborted")),process.exit(1));let u=`TG_${l.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;ne(u,n.trim()),process.env[u]=n.trim();let h=await N(v=>{P(v,"channels.telegram.enabled",!0),P(v,`channels.telegram.accounts.${l}`,{token:`\${${u}}`,agentBinding:p});let $=ee(v,`agents.${p}.mentions`)||[],I=`@${o.username}`;$.includes(I)||($.push(I),P(v,`agents.${p}.mentions`,$))},{configPath:t.configPath});if(h.success||(console.log(E.red(` \u2717 ${h.error}`)),process.exit(1)),console.log(),console.log(E.green(` \u2713 Bot @${o.username} bound to agent "${p}"`)),console.log(E.dim(` Token stored in .env as ${u}`)),console.log(E.dim(` Mentions updated to include @${o.username}`)),h.reloaded?console.log(E.dim(" Daemon hot-reloaded.")):console.log(E.dim(" Start the daemon to begin polling (agentx daemon start)")),t.skipChatCapture)return;console.log();let{capture:b}=await pe({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!b)return;console.log(),console.log(E.dim(` Send any message to @${o.username} from the chat you want to use.`)),console.log(E.dim(" Waiting up to 90s..."));let w=await Ht(n.trim(),9e4);if(!w){console.log(E.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(E.dim(" agentx config set notifications.destination.channel telegram")),console.log(E.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(E.dim(` agentx config set notifications.destination.accountId ${l}`));return}let k=await N(v=>{P(v,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:l})},{configPath:t.configPath});if(!k.success){console.log(E.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(E.green(" \u2713 Default --notify target set")),console.log(E.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(E.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(E.dim(" Daemon hot-reloaded."))}import j from"chalk";import Se from"prompts";var at="https://discord.com/developers/applications",zt="67584";async function Bt(t){try{let e=await fetch("https://discord.com/api/v10/users/@me",{headers:{Authorization:`Bot ${t}`},signal:AbortSignal.timeout(8e3)});return e.ok?await e.json():null}catch{return null}}function it(t){try{let{spawn:e}=je("child_process"),n=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";e(n,[t],{stdio:"ignore",detached:!0}).unref()}catch{}}async function rt(t={}){console.log(),console.log(j.bold(" Connect Discord")),console.log(),console.log(j.dim(" 1. Open the Discord Developer Portal")),console.log(j.dim(` ${at}`)),console.log(j.dim(" 2. New Application \u2192 Bot \u2192 Reset Token \u2192 copy the token")),console.log(j.dim(" 3. Under Bot \u2192 Privileged Gateway Intents,")),console.log(j.dim(" enable 'MESSAGE CONTENT INTENT'")),console.log();let{openBrowser:e}=await Se({type:"confirm",name:"openBrowser",message:"Open the Developer Portal in your browser?",initial:!0});e&&it(at);let{token:n}=await Se({type:"password",name:"token",message:"Paste the bot token:",validate:w=>w.trim().length>20||"that looks too short for a Discord token"});n||(console.log(j.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let o=await Bt(n.trim());o||(console.log(j.red("\u2717 invalid or revoked \u2014 did you enable MESSAGE CONTENT INTENT and copy the right token?")),process.exit(1));let s=o.discriminator&&o.discriminator!=="0"?`${o.username}#${o.discriminator}`:o.username;console.log(j.green(`\u2713 ${s} (bot id ${o.id})`));let{readFileSync:a,existsSync:r}=await import("fs"),{resolve:c}=await import("path"),i=t.configPath||c(process.cwd(),"agentx.json");r(i)||(console.log(j.red(` No agentx.json at ${i}. Run: agentx init`)),process.exit(1));let d=JSON.parse(a(i,"utf-8")),p=Object.keys(d.agents||{});p.length===0&&(console.log(j.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=t.agent;g||(g=(await Se({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:p.map(k=>({title:k,value:k})),initial:0})).agent),g||(console.log(j.red(" Aborted")),process.exit(1));let l="DISCORD_BOT_TOKEN";ne(l,n.trim()),process.env[l]=n.trim();let u=await N(w=>{P(w,"channels.discord.enabled",!0),P(w,"channels.discord.token",`\${${l}}`),P(w,"channels.discord.agentBinding",g)},{configPath:t.configPath});u.success||(console.log(j.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(j.green(` \u2713 Discord bot ${s} bound to agent "${g}"`)),console.log(j.dim(` Token stored in .env as ${l}`)),u.reloaded?console.log(j.dim(" Daemon hot-reloaded.")):console.log(j.dim(" Restart the daemon to start Discord polling.")),console.log(),console.log(j.bold(" Install the bot to a server")),console.log();let h=`https://discord.com/oauth2/authorize?client_id=${o.id}&scope=bot&permissions=${zt}`;console.log(` ${j.cyan(h)}`),console.log();let{openInstall:b}=await Se({type:"confirm",name:"openInstall",message:"Open the install URL in your browser now?",initial:!0});b&&it(h),console.log(),console.log(j.dim(" After you pick a server, the bot will come online on the next daemon restart.")),console.log(j.dim(" Mention the bot in any channel to route messages to the agent."))}import T from"chalk";import He from"prompts";import{existsSync as Be,mkdirSync as _t,readdirSync as Ft,readFileSync as ct}from"fs";import{resolve as ze}from"path";var Jt=".agentx/whatsapp-sessions";function Kt(){let t=ze(process.cwd(),".agentx/daemon.pid");if(!Be(t))return!1;try{let e=parseInt(ct(t,"utf-8").trim(),10);return e?(process.kill(e,0),!0):!1}catch{return!1}}function Gt(t){if(!Be(t))return!1;try{return Ft(t).some(e=>e.includes("creds")||e.endsWith(".json"))}catch{return!1}}async function qt(t,e){let n;try{n=await import("@whiskeysockets/baileys")}catch{return e(T.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),e(T.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:o,useMultiFileAuthState:s}=n.default||n;_t(t,{recursive:!0});let{state:a,saveCreds:r}=await s(t),c;try{c=(await n.fetchLatestBaileysVersion()).version}catch{}let i={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>i},d=o({auth:{creds:a.creds,keys:n.makeCacheableSignalKeyStore?n.makeCacheableSignalKeyStore(a.keys,i):a.keys},...c?{version:c}:{},logger:i,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return d.ev.on("creds.update",r),await new Promise(p=>{let l=setTimeout(()=>{e(T.yellow(" Timed out waiting for scan (2min)."));try{d.end(void 0)}catch{}p(!1)},12e4);d.ev.on("connection.update",async u=>{if(u.qr){e(T.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),e("");try{let{default:h}=await import("qrcode-terminal");h.generate(u.qr,{small:!0})}catch{e(` QR: ${u.qr}`)}e("")}if(u.connection==="open"){clearTimeout(l),e(T.green(" \u2713 Paired"));try{d.end(void 0)}catch{}p(!0)}u.connection==="close"&&!u.qr&&u.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(l),e(T.red(" \u2717 Authorization failed \u2014 rescan required")),p(!1))})})}async function lt(t={}){if(console.log(),console.log(T.bold(" Connect WhatsApp")),console.log(),Kt()){console.log(T.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(T.dim(" agentx daemon stop")),console.log();let{cont:d}=await He({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});d||(console.log(T.red(" Aborted")),process.exit(1))}let e=t.configPath||ze(process.cwd(),"agentx.json");Be(e)||(console.log(T.red(` No agentx.json at ${e}. Run: agentx init`)),process.exit(1));let n=JSON.parse(ct(e,"utf-8")),o=t.sessionDir||n.channels?.whatsapp?.sessionDir||Jt,s=ze(process.cwd(),o),a=Object.keys(n.agents||{});a.length===0&&(console.log(T.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=t.agent;r||(r=(await He({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:a.map(p=>({title:p,value:p})),initial:0})).agent),r||(console.log(T.red(" Aborted")),process.exit(1));let c=!t.skipPair;if(Gt(s)&&c){let{keep:d}=await He({type:"confirm",name:"keep",message:`An existing session was found at ${o}. Keep it (recommended), or pair again?`,initial:!0});c=!d,d&&console.log(T.dim(" Keeping existing session \u2014 skipping QR pair."))}c&&(await qt(s,p=>console.log(p))||(console.log(T.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let i=await N(d=>{P(d,"channels.whatsapp.enabled",!0),P(d,"channels.whatsapp.sessionDir",o),P(d,"channels.whatsapp.defaultAgent",r)},{configPath:t.configPath});i.success||(console.log(T.red(` \u2717 ${i.error}`)),process.exit(1)),console.log(),console.log(T.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(T.dim(` Session: ${o}`)),console.log(T.dim(" Start the daemon to begin receiving:")),console.log(T.dim(" agentx daemon start")),console.log(T.dim(" Add routes later with:")),console.log(T.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Yt}from"crypto";import R from"chalk";import dt from"prompts";var Ae="agentx-mesh:",Ie="//join/";function Vt(t){return Buffer.from(t,"utf-8").toString("base64url")}function Xt(t){return Buffer.from(t,"base64url").toString("utf-8")}function Qt(t){return`${Ae}${Ie}${Vt(JSON.stringify(t))}`}function Zt(t){if(!t.startsWith(`${Ae}${Ie}`))throw new Error(`Not a mesh invite link \u2014 expected ${Ae}${Ie}\u2026`);let e=t.slice(Ae.length+Ie.length),n=JSON.parse(Xt(e));if(n.version!==1)throw new Error(`Unsupported invite version: ${n.version}`);if(typeof n.url!="string"||typeof n.token!="string"||typeof n.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return n}function en(){return Yt(32).toString("hex")}function tn(t){let e=t?.node?.bind||"127.0.0.1:18800",[n,o]=e.split(":");return`http://${n}:${o}`}function nn(t){return t?.node?.name||t?.node?.id||"node"}async function gt(t){let{readFileSync:e,existsSync:n}=await import("fs"),{resolve:o}=await import("path"),s=t.configPath||o(process.cwd(),"agentx.json");n(s)||(console.log(R.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let a=JSON.parse(e(s,"utf-8")),r=Le("MESH_TOKEN");r||(r=en(),ne("MESH_TOKEN",r),console.log(R.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let c=t.url||tn(a);if((c.includes("0.0.0.0")||c.includes("127.0.0.1")||c.includes("localhost"))&&!t.url){let{url:g}=await dt({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:c,validate:l=>/^https?:\/\//.test(l)||"must start with http:// or https://"});g||(console.log(R.red(" Aborted")),process.exit(1)),c=g}let d=await N(g=>{P(g,"mesh.enabled",!0)},{configPath:t.configPath});d.success||(console.log(R.red(` \u2717 ${d.error}`)),process.exit(1));let p=Qt({url:c,token:r,name:nn(a),version:1});console.log(),console.log(R.bold(" Mesh invite")),console.log(),console.log(` ${R.cyan(p)}`),console.log(),console.log(R.dim(" Run on the other node:")),console.log(R.dim(` agentx connect mesh join "${p}"`)),console.log(),console.log(R.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function mt(t,e={}){let n;try{n=Zt(t)}catch(a){console.log(R.red(` \u2717 ${a.message}`)),process.exit(1)}let o=Le("MESH_TOKEN");if(o&&o!==n.token){let{overwrite:a}=await dt({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});a||(console.log(R.red(" Aborted (keeping existing .env)")),process.exit(1))}ne("MESH_TOKEN",n.token);let s=await N(a=>{P(a,"mesh.enabled",!0);let r=ee(a,"mesh.peers")||[],c=r.findIndex(d=>d.name===n.name),i={name:n.name,url:n.url,token:"${MESH_TOKEN}"};c>=0?r[c]=i:r.push(i),P(a,"mesh.peers",r)},{configPath:e.configPath});s.success||(console.log(R.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(R.green(" \u2713 Joined mesh")),console.log(R.dim(` Peer: ${n.name} @ ${n.url}`)),console.log(R.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(R.dim(" Daemon hot-reloaded.")):console.log(R.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let a=await fetch(`${n.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(a.ok){let r=await a.json(),c=Array.isArray(r.agents)?r.agents.length:"?";console.log(R.dim(` Reachable \u2014 ${n.name} exposes ${c} agents`))}else console.log(R.yellow(` Peer returned HTTP ${a.status} \u2014 double-check the URL`))}catch(a){console.log(R.yellow(` Could not reach ${n.url} right now (${a?.cause?.code||a.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var se=new on().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");se.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 t=>{await st({agent:t.agent,account:t.account,configPath:t.config,skipChatCapture:!!t.skipChatCapture})});se.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 t=>{await rt({agent:t.agent,configPath:t.config})});se.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 t=>{await lt({agent:t.agent,sessionDir:t.sessionDir,skipPair:!!t.skipPair,configPath:t.config})});var pt=se.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");pt.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 t=>{await gt({url:t.url,configPath:t.config})});pt.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(t,e)=>{await mt(t,{configPath:e.config})});se.action(()=>{console.log(),console.log(oe.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${oe.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${oe.cyan("agentx connect discord")} \u2014 pair a Discord bot, emit install URL`),console.log(` ${oe.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${oe.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${oe.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(oe.dim(" GitLab connect is the next slice.")),console.log()});import{Command as sn}from"commander";import B from"chalk";var ue=new sn().name("usage").description("token usage analysis and reporting");ue.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let t=z(),[e,n]=t.node.bind.split(":"),s=await(await fetch(`http://${e||"127.0.0.1"}:${n}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(B.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(B.dim(" No tasks recorded yet")),console.log();return}let a=c=>c.toLocaleString();console.log(` Total: ${B.bold(a(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${a(s.totalInput)}`),console.log(` Output: ${a(s.totalOutput)}`),console.log(` Cache read: ${a(s.totalCacheRead)}`),console.log(` Cache create: ${a(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${B.red(String(s.totalErrors))}`),console.log(),console.log(B.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((c,i)=>i[1].total-c[1].total);for(let[c,i]of r){let d=a(i.total||i.input+i.output+i.cacheRead+i.cacheCreate),p=i.avgDuration?`${(i.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${B.cyan(c)}: ${d} tokens (${i.tasks} tasks) ${B.dim(p)}`)}console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(B.red(" Daemon not running. Start with: agentx daemon start")):console.log(B.red(` ${t.message}`))}});ue.command("serve").description("start a web dashboard for token usage visualization").option("--port <n>","port number","4201").action(async t=>{let{startUsageDashboard:e}=await import("./usage-dashboard-M7AFIGMJ.js");e(parseInt(t.port))});ue.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async t=>{let{execSync:e}=await import("child_process"),{existsSync:n}=await import("fs"),{resolve:o}=await import("path"),s=o(process.cwd(),"scripts/token-report.py");if(!n(s)){console.log(B.red(` Script not found: ${s}`)),console.log(B.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(B.dim(" Analyzing Claude Code sessions..."));try{e(`SINCE_DAYS=${t.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(B.red(" Analysis failed. Is Python 3 installed?"))}});import{Command as an}from"commander";import Y from"chalk";var Ee=new an().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Ee.command("serve",{isDefault:!0}).description("start the kanban board dashboard").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async t=>{try{let e=z();t.port&&(e.dashboard.port=parseInt(t.port,10)),t.bind&&(e.dashboard.bind=t.bind),(!e.boards||e.boards.length===0)&&(console.log(Y.yellow(`
|
|
12
|
-
|
|
13
|
-
`)),process.exit(1));let{startBoardDashboard:n}=await import("./board-dashboard-6TKE6NMV.js");n(e)}catch(e){console.log(Y.red(` ${e.message}`)),process.exit(1)}});Ee.command("list").description("list configured boards").action(()=>{try{let t=z();if(!t.boards?.length){console.log(Y.dim(`
|
|
19
|
+
`}function ae(t,e,n=".env"){let o=wt(n),s=$t(o),a=s.findIndex(r=>r.kind==="kv"&&r.key===t);a>=0?s[a]={kind:"kv",key:t,value:e,raw:`${t}=${qe(e)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:t,value:e,raw:`${t}=${qe(e)}`})),hn(o,wn(s))}function Ye(t,e=".env"){return $t(e).find(s=>s.kind==="kv"&&s.key===t)?.value}var kt="https://t.me/BotFather";async function $n(t){try{let e=await fetch(`https://api.telegram.org/bot${t}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!e.ok)return null;let n=await e.json();return n?.ok?n.result:null}catch{return null}}async function kn(t,e){let n=Date.now()+e,o=0;try{let a=await(await fetch(`https://api.telegram.org/bot${t}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();a?.result?.length&&(o=a.result[0].update_id+1)}catch{}for(;Date.now()<n;)try{let a=await(await fetch(`https://api.telegram.org/bot${t}/getUpdates?offset=${o}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let r of a?.result||[]){o=Math.max(o,r.update_id+1);let c=r.message||r.edited_message||r.channel_post;if(c?.chat?.id)return{chatId:c.chat.id,chatTitle:c.chat.title||c.chat.username||c.chat.first_name,from:c.from?.first_name||c.from?.username||"unknown"}}}catch{}return null}async function vt(t={}){console.log(),console.log(I.bold(" Connect Telegram")),console.log(),console.log(I.dim(` 1. Open ${kt}`)),console.log(I.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(I.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{openBrowser:e}=await we({type:"confirm",name:"openBrowser",message:"Open BotFather in your browser?",initial:!0});if(e)try{let{spawn:v}=await import("child_process"),$=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";v($,[kt],{stdio:"ignore",detached:!0}).unref()}catch{}let{token:n}=await we({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:v=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(v.trim())||"That doesn't look like a Telegram token"});n||(console.log(I.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let o=await $n(n.trim());o||(console.log(I.red("\u2717 invalid or revoked")),process.exit(1)),console.log(I.green(`\u2713 ${o.first_name} (@${o.username})`));let{readFileSync:s,existsSync:a}=await import("fs"),{resolve:r}=await import("path"),c=t.configPath||r(process.cwd(),"agentx.json");a(c)||(console.log(I.red(` No agentx.json at ${c}. Run: agentx init`)),process.exit(1));let i=JSON.parse(s(c,"utf-8")),d=Object.keys(i.agents||{});d.length===0&&(console.log(I.red(" No agents configured. Run: agentx agent add")),process.exit(1));let p=t.agent;p||(p=(await we({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:d.map($=>({title:$,value:$})),initial:0})).agent),p||(console.log(I.red(" Aborted")),process.exit(1));let g=i.channels?.telegram?.accounts||{},l=t.account||p;g[l]&&g[l].agentBinding!==p&&(l=(await we({type:"text",name:"account",message:`Account "${l}" is already in use. Pick a different label:`,initial:`${p}-2`,validate:$=>/^[a-z0-9-]+$/i.test($)||"lowercase letters, digits, hyphens only"})).account),l||(console.log(I.red(" Aborted")),process.exit(1));let u=`TG_${l.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;ae(u,n.trim()),process.env[u]=n.trim();let h=await U(v=>{P(v,"channels.telegram.enabled",!0),P(v,`channels.telegram.accounts.${l}`,{token:`\${${u}}`,agentBinding:p});let $=oe(v,`agents.${p}.mentions`)||[],C=`@${o.username}`;$.includes(C)||($.push(C),P(v,`agents.${p}.mentions`,$))},{configPath:t.configPath});if(h.success||(console.log(I.red(` \u2717 ${h.error}`)),process.exit(1)),console.log(),console.log(I.green(` \u2713 Bot @${o.username} bound to agent "${p}"`)),console.log(I.dim(` Token stored in .env as ${u}`)),console.log(I.dim(` Mentions updated to include @${o.username}`)),h.reloaded?console.log(I.dim(" Daemon hot-reloaded.")):console.log(I.dim(" Start the daemon to begin polling (agentx daemon start)")),t.skipChatCapture)return;console.log();let{capture:b}=await we({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!b)return;console.log(),console.log(I.dim(` Send any message to @${o.username} from the chat you want to use.`)),console.log(I.dim(" Waiting up to 90s..."));let w=await kn(n.trim(),9e4);if(!w){console.log(I.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(I.dim(" agentx config set notifications.destination.channel telegram")),console.log(I.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(I.dim(` agentx config set notifications.destination.accountId ${l}`));return}let k=await U(v=>{P(v,"notifications.destination",{channel:"telegram",chatId:String(w.chatId),accountId:l})},{configPath:t.configPath});if(!k.success){console.log(I.red(` \u2717 failed to save destination: ${k.error}`));return}console.log(I.green(" \u2713 Default --notify target set")),console.log(I.dim(` Chat: ${w.chatTitle||w.chatId} (from ${w.from})`)),console.log(I.dim(" From now on, --notify me resolves to this chat.")),k.reloaded&&console.log(I.dim(" Daemon hot-reloaded."))}import T from"chalk";import Pe from"prompts";var xt="https://discord.com/developers/applications",vn="67584";async function xn(t){try{let e=await fetch("https://discord.com/api/v10/users/@me",{headers:{Authorization:`Bot ${t}`},signal:AbortSignal.timeout(8e3)});return e.ok?await e.json():null}catch{return null}}function St(t){try{let{spawn:e}=We("child_process"),n=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";e(n,[t],{stdio:"ignore",detached:!0}).unref()}catch{}}async function At(t={}){console.log(),console.log(T.bold(" Connect Discord")),console.log(),console.log(T.dim(" 1. Open the Discord Developer Portal")),console.log(T.dim(` ${xt}`)),console.log(T.dim(" 2. New Application \u2192 Bot \u2192 Reset Token \u2192 copy the token")),console.log(T.dim(" 3. Under Bot \u2192 Privileged Gateway Intents,")),console.log(T.dim(" enable 'MESSAGE CONTENT INTENT'")),console.log();let{openBrowser:e}=await Pe({type:"confirm",name:"openBrowser",message:"Open the Developer Portal in your browser?",initial:!0});e&&St(xt);let{token:n}=await Pe({type:"password",name:"token",message:"Paste the bot token:",validate:w=>w.trim().length>20||"that looks too short for a Discord token"});n||(console.log(T.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let o=await xn(n.trim());o||(console.log(T.red("\u2717 invalid or revoked \u2014 did you enable MESSAGE CONTENT INTENT and copy the right token?")),process.exit(1));let s=o.discriminator&&o.discriminator!=="0"?`${o.username}#${o.discriminator}`:o.username;console.log(T.green(`\u2713 ${s} (bot id ${o.id})`));let{readFileSync:a,existsSync:r}=await import("fs"),{resolve:c}=await import("path"),i=t.configPath||c(process.cwd(),"agentx.json");r(i)||(console.log(T.red(` No agentx.json at ${i}. Run: agentx init`)),process.exit(1));let d=JSON.parse(a(i,"utf-8")),p=Object.keys(d.agents||{});p.length===0&&(console.log(T.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=t.agent;g||(g=(await Pe({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:p.map(k=>({title:k,value:k})),initial:0})).agent),g||(console.log(T.red(" Aborted")),process.exit(1));let l="DISCORD_BOT_TOKEN";ae(l,n.trim()),process.env[l]=n.trim();let u=await U(w=>{P(w,"channels.discord.enabled",!0),P(w,"channels.discord.token",`\${${l}}`),P(w,"channels.discord.agentBinding",g)},{configPath:t.configPath});u.success||(console.log(T.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(T.green(` \u2713 Discord bot ${s} bound to agent "${g}"`)),console.log(T.dim(` Token stored in .env as ${l}`)),u.reloaded?console.log(T.dim(" Daemon hot-reloaded.")):console.log(T.dim(" Restart the daemon to start Discord polling.")),console.log(),console.log(T.bold(" Install the bot to a server")),console.log();let h=`https://discord.com/oauth2/authorize?client_id=${o.id}&scope=bot&permissions=${vn}`;console.log(` ${T.cyan(h)}`),console.log();let{openInstall:b}=await Pe({type:"confirm",name:"openInstall",message:"Open the install URL in your browser now?",initial:!0});b&&St(h),console.log(),console.log(T.dim(" After you pick a server, the bot will come online on the next daemon restart.")),console.log(T.dim(" Mention the bot in any channel to route messages to the agent."))}import E from"chalk";import Ve from"prompts";import{existsSync as Qe,mkdirSync as Sn,readdirSync as An,readFileSync as Ct}from"fs";import{resolve as Xe}from"path";var Cn=".agentx/whatsapp-sessions";function In(){let t=Xe(process.cwd(),".agentx/daemon.pid");if(!Qe(t))return!1;try{let e=parseInt(Ct(t,"utf-8").trim(),10);return e?(process.kill(e,0),!0):!1}catch{return!1}}function jn(t){if(!Qe(t))return!1;try{return An(t).some(e=>e.includes("creds")||e.endsWith(".json"))}catch{return!1}}async function En(t,e){let n;try{n=await import("@whiskeysockets/baileys")}catch{return e(E.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),e(E.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:o,useMultiFileAuthState:s}=n.default||n;Sn(t,{recursive:!0});let{state:a,saveCreds:r}=await s(t),c;try{c=(await n.fetchLatestBaileysVersion()).version}catch{}let i={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>i},d=o({auth:{creds:a.creds,keys:n.makeCacheableSignalKeyStore?n.makeCacheableSignalKeyStore(a.keys,i):a.keys},...c?{version:c}:{},logger:i,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return d.ev.on("creds.update",r),await new Promise(p=>{let l=setTimeout(()=>{e(E.yellow(" Timed out waiting for scan (2min)."));try{d.end(void 0)}catch{}p(!1)},12e4);d.ev.on("connection.update",async u=>{if(u.qr){e(E.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),e("");try{let{default:h}=await import("qrcode-terminal");h.generate(u.qr,{small:!0})}catch{e(` QR: ${u.qr}`)}e("")}if(u.connection==="open"){clearTimeout(l),e(E.green(" \u2713 Paired"));try{d.end(void 0)}catch{}p(!0)}u.connection==="close"&&!u.qr&&u.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(l),e(E.red(" \u2717 Authorization failed \u2014 rescan required")),p(!1))})})}async function It(t={}){if(console.log(),console.log(E.bold(" Connect WhatsApp")),console.log(),In()){console.log(E.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(E.dim(" agentx daemon stop")),console.log();let{cont:d}=await Ve({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});d||(console.log(E.red(" Aborted")),process.exit(1))}let e=t.configPath||Xe(process.cwd(),"agentx.json");Qe(e)||(console.log(E.red(` No agentx.json at ${e}. Run: agentx init`)),process.exit(1));let n=JSON.parse(Ct(e,"utf-8")),o=t.sessionDir||n.channels?.whatsapp?.sessionDir||Cn,s=Xe(process.cwd(),o),a=Object.keys(n.agents||{});a.length===0&&(console.log(E.red(" No agents configured. Run: agentx agent add")),process.exit(1));let r=t.agent;r||(r=(await Ve({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:a.map(p=>({title:p,value:p})),initial:0})).agent),r||(console.log(E.red(" Aborted")),process.exit(1));let c=!t.skipPair;if(jn(s)&&c){let{keep:d}=await Ve({type:"confirm",name:"keep",message:`An existing session was found at ${o}. Keep it (recommended), or pair again?`,initial:!0});c=!d,d&&console.log(E.dim(" Keeping existing session \u2014 skipping QR pair."))}c&&(await En(s,p=>console.log(p))||(console.log(E.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let i=await U(d=>{P(d,"channels.whatsapp.enabled",!0),P(d,"channels.whatsapp.sessionDir",o),P(d,"channels.whatsapp.defaultAgent",r)},{configPath:t.configPath});i.success||(console.log(E.red(` \u2717 ${i.error}`)),process.exit(1)),console.log(),console.log(E.green(` \u2713 WhatsApp bound to agent "${r}"`)),console.log(E.dim(` Session: ${o}`)),console.log(E.dim(" Start the daemon to begin receiving:")),console.log(E.dim(" agentx daemon start")),console.log(E.dim(" Add routes later with:")),console.log(E.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${r}"}]'`)),console.log()}import{randomBytes as Tn}from"crypto";import R from"chalk";import jt from"prompts";var Re="agentx-mesh:",De="//join/";function Pn(t){return Buffer.from(t,"utf-8").toString("base64url")}function Rn(t){return Buffer.from(t,"base64url").toString("utf-8")}function Dn(t){return`${Re}${De}${Pn(JSON.stringify(t))}`}function On(t){if(!t.startsWith(`${Re}${De}`))throw new Error(`Not a mesh invite link \u2014 expected ${Re}${De}\u2026`);let e=t.slice(Re.length+De.length),n=JSON.parse(Rn(e));if(n.version!==1)throw new Error(`Unsupported invite version: ${n.version}`);if(typeof n.url!="string"||typeof n.token!="string"||typeof n.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return n}function Nn(){return Tn(32).toString("hex")}function Wn(t){let e=t?.node?.bind||"127.0.0.1:18800",[n,o]=e.split(":");return`http://${n}:${o}`}function Un(t){return t?.node?.name||t?.node?.id||"node"}async function Et(t){let{readFileSync:e,existsSync:n}=await import("fs"),{resolve:o}=await import("path"),s=t.configPath||o(process.cwd(),"agentx.json");n(s)||(console.log(R.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let a=JSON.parse(e(s,"utf-8")),r=Ye("MESH_TOKEN");r||(r=Nn(),ae("MESH_TOKEN",r),console.log(R.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let c=t.url||Wn(a);if((c.includes("0.0.0.0")||c.includes("127.0.0.1")||c.includes("localhost"))&&!t.url){let{url:g}=await jt({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:c,validate:l=>/^https?:\/\//.test(l)||"must start with http:// or https://"});g||(console.log(R.red(" Aborted")),process.exit(1)),c=g}let d=await U(g=>{P(g,"mesh.enabled",!0)},{configPath:t.configPath});d.success||(console.log(R.red(` \u2717 ${d.error}`)),process.exit(1));let p=Dn({url:c,token:r,name:Un(a),version:1});console.log(),console.log(R.bold(" Mesh invite")),console.log(),console.log(` ${R.cyan(p)}`),console.log(),console.log(R.dim(" Run on the other node:")),console.log(R.dim(` agentx connect mesh join "${p}"`)),console.log(),console.log(R.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function Tt(t,e={}){let n;try{n=On(t)}catch(a){console.log(R.red(` \u2717 ${a.message}`)),process.exit(1)}let o=Ye("MESH_TOKEN");if(o&&o!==n.token){let{overwrite:a}=await jt({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});a||(console.log(R.red(" Aborted (keeping existing .env)")),process.exit(1))}ae("MESH_TOKEN",n.token);let s=await U(a=>{P(a,"mesh.enabled",!0);let r=oe(a,"mesh.peers")||[],c=r.findIndex(d=>d.name===n.name),i={name:n.name,url:n.url,token:"${MESH_TOKEN}"};c>=0?r[c]=i:r.push(i),P(a,"mesh.peers",r)},{configPath:e.configPath});s.success||(console.log(R.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(R.green(" \u2713 Joined mesh")),console.log(R.dim(` Peer: ${n.name} @ ${n.url}`)),console.log(R.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(R.dim(" Daemon hot-reloaded.")):console.log(R.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let a=await fetch(`${n.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(a.ok){let r=await a.json(),c=Array.isArray(r.agents)?r.agents.length:"?";console.log(R.dim(` Reachable \u2014 ${n.name} exposes ${c} agents`))}else console.log(R.yellow(` Peer returned HTTP ${a.status} \u2014 double-check the URL`))}catch(a){console.log(R.yellow(` Could not reach ${n.url} right now (${a?.cause?.code||a.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var re=new Mn().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");re.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 t=>{await vt({agent:t.agent,account:t.account,configPath:t.config,skipChatCapture:!!t.skipChatCapture})});re.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 t=>{await At({agent:t.agent,configPath:t.config})});re.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 t=>{await It({agent:t.agent,sessionDir:t.sessionDir,skipPair:!!t.skipPair,configPath:t.config})});var Pt=re.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");Pt.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 t=>{await Et({url:t.url,configPath:t.config})});Pt.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(t,e)=>{await Tt(t,{configPath:e.config})});re.action(()=>{console.log(),console.log(ie.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${ie.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${ie.cyan("agentx connect discord")} \u2014 pair a Discord bot, emit install URL`),console.log(` ${ie.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${ie.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${ie.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(ie.dim(" GitLab connect is the next slice.")),console.log()});ne();import{Command as Ln}from"commander";import F from"chalk";var $e=new Ln().name("usage").description("token usage analysis and reporting");$e.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let t=N(),[e,n]=t.node.bind.split(":"),s=await(await fetch(`http://${e||"127.0.0.1"}:${n}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(F.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(F.dim(" No tasks recorded yet")),console.log();return}let a=c=>c.toLocaleString();console.log(` Total: ${F.bold(a(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${a(s.totalInput)}`),console.log(` Output: ${a(s.totalOutput)}`),console.log(` Cache read: ${a(s.totalCacheRead)}`),console.log(` Cache create: ${a(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${F.red(String(s.totalErrors))}`),console.log(),console.log(F.bold(" By Agent:"));let r=Object.entries(s.byAgent||{});r.sort((c,i)=>i[1].total-c[1].total);for(let[c,i]of r){let d=a(i.total||i.input+i.output+i.cacheRead+i.cacheCreate),p=i.avgDuration?`${(i.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${F.cyan(c)}: ${d} tokens (${i.tasks} tasks) ${F.dim(p)}`)}console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(F.red(" Daemon not running. Start with: agentx daemon start")):console.log(F.red(` ${t.message}`))}});$e.command("serve").description("start a web dashboard for token usage visualization").option("--port <n>","port number","4201").action(async t=>{let{startUsageDashboard:e}=await import("./usage-dashboard-QX3CF6KK.js");e(parseInt(t.port))});$e.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async t=>{let{execSync:e}=await import("child_process"),{existsSync:n}=await import("fs"),{resolve:o}=await import("path"),s=o(process.cwd(),"scripts/token-report.py");if(!n(s)){console.log(F.red(` Script not found: ${s}`)),console.log(F.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(F.dim(" Analyzing Claude Code sessions..."));try{e(`SINCE_DAYS=${t.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(F.red(" Analysis failed. Is Python 3 installed?"))}});ne();import{Command as zn}from"commander";import z from"chalk";var ge=new zn().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");ge.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async t=>{try{let e=Hn(t.port,t.bind),{startBoardDashboard:n}=await import("./board-dashboard-DAPHL6W2.js");n(e)}catch(e){console.log(z.red(` ${e.message}`)),process.env.DEBUG&&e.stack&&console.log(z.dim(e.stack)),process.exit(1)}});function Hn(t,e){try{let n=N();return t&&(n.dashboard.port=parseInt(t,10)),e&&(n.dashboard.bind=e),n}catch{return console.log(z.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(z.dim(" Visit http://127.0.0.1:"+(t||"4202")+` to run the wizard.
|
|
20
|
+
`)),{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:t?parseInt(t,10):4202,bind:e||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}ge.command("list").description("list configured boards").action(()=>{try{let t=N();if(!t.boards?.length){console.log(z.dim(`
|
|
14
21
|
No boards configured.
|
|
15
|
-
`));return}console.log();for(let e of t.boards){console.log(` ${
|
|
16
|
-
|
|
22
|
+
`));return}console.log();for(let e of t.boards){console.log(` ${z.cyan(e.id)} \u2014 ${e.name}`);let n=e.source;console.log(z.dim(` source: ${n.type}${n.projects?" ("+n.projects.join(", ")+")":""}`)),e.primaryToolLabel&&console.log(z.dim(` primary label: ${e.primaryToolLabel}`)),console.log(z.dim(` window: ${e.timeRangeDays} days`))}console.log()}catch(t){console.log(z.red(` ${t.message}`)),process.exit(1)}});ge.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'mtgl/system,mtgl/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((t,e)=>{try{Rt(n=>{if(Array.isArray(n.boards)||(n.boards=[]),n.boards.find(a=>a.id===t))throw new Error(`board "${t}" already exists`);let o=String(e.projects).split(",").map(a=>a.trim()).filter(Boolean);if(o.length===0)throw new Error("--projects must include at least one path");let s={id:t,name:e.name,source:{type:"gitlab",projects:o},timeRangeDays:parseInt(e.days,10)||30,closedWindowDays:parseInt(e.closedDays,10)||30};return e.label&&(s.primaryToolLabel=e.label),n.boards.push(s),`added board "${t}" (${o.join(", ")})`})}catch(n){console.log(z.red(` ${n.message}`)),process.exit(1)}});ge.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(t=>{try{Rt(e=>{if(!Array.isArray(e.boards)||e.boards.length===0)throw new Error("no boards configured");let n=e.boards.length;if(e.boards=e.boards.filter(o=>o.id!==t),e.boards.length===n)throw new Error(`board "${t}" not found`);return`removed board "${t}"`})}catch(e){console.log(z.red(` ${e.message}`)),process.exit(1)}});function Rt(t){let{summary:e,backupPath:n}=at(o=>t(o));console.log(z.green(`
|
|
23
|
+
\u2713 ${e}
|
|
24
|
+
`)),n&&console.log(z.dim(` Backup: ${n}`)),console.log(z.dim(` Restart the dashboard to pick up the change if not auto-reloading.
|
|
25
|
+
`))}import{Command as Qn}from"commander";import y from"chalk";import{createServer as Bn}from"http";var Oe=class{peers;cache=new Map;ttl=3e4;constructor(e){this.peers=e.map(n=>({url:n.replace(/\/$/,"")}))}async getRemoteAgents(){let e=[];return await Promise.all(this.peers.map(async n=>{try{let o=await this.fetchJson(`${n.url}/wiki/agents`);n.nodeId=o.nodeId;for(let s of o.agents||[])(s.totalEntries>0||s.totalArticles>0)&&e.push({...s,nodeId:o.nodeId,peerUrl:n.url})}catch{}})),e}async getRemoteArticles(e,n){try{return(await this.fetchJson(`${e}/wiki/articles?agent=${encodeURIComponent(n)}`)).articles||[]}catch{return[]}}async getRemoteArticle(e,n,o){try{let s=await this.fetchJson(`${e}/wiki/article?agent=${encodeURIComponent(n)}&path=${encodeURIComponent(o)}`);return{meta:{title:s.title,tags:s.tags||[],owner:s.owner,access:"public",created:s.created,lastUpdated:s.lastUpdated,sources:s.sources||[]},content:s.content,path:s.path}}catch{return null}}async fetchJson(e){let n=this.cache.get(e);if(n&&Date.now()-n.ts<this.ttl)return n.data;let o=await fetch(e,{signal:AbortSignal.timeout(5e3)});if(!o.ok)throw new Error(`HTTP ${o.status}`);let s=await o.json();return this.cache.set(e,{data:s,ts:Date.now()}),s}};function x(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Ne(t,e,n=""){let o=x(t);return o=o.replace(/```(\w*)\n([\s\S]*?)```/g,(s,a,r)=>`<pre><code class="lang-${a}">${r.trim()}</code></pre>`),o=o.replace(/`([^`]+)`/g,"<code>$1</code>"),o=o.replace(/^(\|.+\|)\n(\|[-| :]+\|)\n((?:\|.+\|\n?)*)/gm,(s,a,r,c)=>{let i=a.split("|").filter(p=>p.trim()).map(p=>`<th>${p.trim()}</th>`).join(""),d=c.trim().split(`
|
|
26
|
+
`).map(p=>`<tr>${p.split("|").filter(l=>l.trim()).map(l=>`<td>${l.trim()}</td>`).join("")}</tr>`).join("");return`<table><thead><tr>${i}</tr></thead><tbody>${d}</tbody></table>`}),o=o.replace(/^#### (.+)$/gm,"<h4>$1</h4>"),o=o.replace(/^### (.+)$/gm,"<h3>$1</h3>"),o=o.replace(/^## (.+)$/gm,"<h2>$1</h2>"),o=o.replace(/^# (.+)$/gm,"<h1>$1</h1>"),o=o.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),o=o.replace(/\*(.+?)\*/g,"<em>$1</em>"),o=o.replace(/\[\[([^\]]+)\]\]/g,(s,a)=>{let r=e.get(a);return r?`<a href="${n}/article/${encodeURIComponent(r)}" class="wikilink">${a}</a>`:`<a href="${n}/search?q=${encodeURIComponent(a)}" class="wikilink broken">${a}</a>`}),o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank">$1</a>'),o=o.replace(/^- (.+)$/gm,"<li>$1</li>"),o=o.replace(/(<li>.*<\/li>\n?)+/g,"<ul>$&</ul>"),o=o.replace(/^---$/gm,"<hr>"),o=o.replace(/\n\n+/g,"</p><p>"),o=`<p>${o}</p>`,o=o.replace(/<p>(<(?:h[1-4]|pre|table|ul|hr|div))/g,"$1"),o=o.replace(/(<\/(?:h[1-4]|pre|table|ul|hr|div)>)<\/p>/g,"$1"),o=o.replace(/<p>\s*<\/p>/g,""),o}var _n=`
|
|
17
27
|
:root {
|
|
18
28
|
--bg: #f8f9fa; --card: #ffffff; --border: #a2a9b1;
|
|
19
29
|
--link: #0645ad; --link-visited: #0b0080; --link-broken: #ba0000;
|
|
@@ -72,13 +82,13 @@ p code { background: #f5f5f5; padding: 1px 4px; border-radius: 2px; }
|
|
|
72
82
|
.breadcrumb { font-size: 13px; color: var(--text-dim); margin-bottom: 12px; }
|
|
73
83
|
.breadcrumb a { color: var(--link); text-decoration: none; }
|
|
74
84
|
@media (max-width: 768px) { .layout { grid-template-columns: 1fr; } .sidebar { position: static; height: auto; } .main { padding: 20px; } }
|
|
75
|
-
`;function
|
|
85
|
+
`;function B(t,e,n){return`<!DOCTYPE html>
|
|
76
86
|
<html lang="en">
|
|
77
87
|
<head>
|
|
78
88
|
<meta charset="utf-8">
|
|
79
89
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
80
90
|
<title>${x(t)} \u2014 AgentX Wiki</title>
|
|
81
|
-
<style>${
|
|
91
|
+
<style>${_n}</style>
|
|
82
92
|
</head>
|
|
83
93
|
<body>
|
|
84
94
|
<div class="layout">
|
|
@@ -86,27 +96,27 @@ p code { background: #f5f5f5; padding: 1px 4px; border-radius: 2px; }
|
|
|
86
96
|
<main class="main">${n}</main>
|
|
87
97
|
</div>
|
|
88
98
|
</body>
|
|
89
|
-
</html>`}function
|
|
99
|
+
</html>`}function Dt(t){let e=new Map;for(let n of t){let o=n.path.includes("/")?n.path.split("/").slice(0,-1).join("/"):"/",s=e.get(o)||[];s.push(n),e.set(o,s)}return new Map([...e].sort((n,o)=>n[0].localeCompare(o[0])))}function Ot(t){return t==="/"?"Root":t.split("/").pop().replace(/-/g," ")}function Q(t,e){let n='<a href="/" class="logo">AgentX Wiki</a>';n+='<form action="/search" method="get"><input type="text" name="q" class="search-box" placeholder="Search all wikis..."></form>',n+="<h2>Hub</h2>",n+=`<a href="/"${e?"":' class="active"'}>Home</a>`,n+='<a href="/entries">All Entries</a>';for(let o of t){let s=`/agent/${encodeURIComponent(o.agentId)}`;n+=`<h2><a href="${s}" style="color:inherit;text-decoration:none">${x(o.agentId)}</a> <span class="agent-badge">${o.totalArticles}</span></h2>`;let a=Dt(o.articles);for(let[r,c]of a){n+=`<div style="font-size:11px;text-transform:uppercase;letter-spacing:0.3px;color:#888;margin:8px 8px 2px;font-weight:600">${Ot(r)}</div>`;for(let i of c){let p=`${o.agentId}/${i.path}`===e;n+=`<a href="${s}/article/${encodeURIComponent(i.path)}"${p?' class="active"':""} style="padding-left:16px;font-size:13px">${x(i.title)}</a>`}}}return n}function Fn(t,e,n){let o=e||t.summary(),a=t.getSharedStore().listEntries().length,r=o.reduce((p,g)=>p+g.totalArticles,0),c=o.reduce((p,g)=>p+g.unabsorbed,0),i=new Set((n||[]).map(p=>p.agentId)),d="<h1>AgentX Wiki Hub</h1>";if(d+='<div class="stats">',d+=`<div class="stat-card"><div class="number">${o.length}</div><div class="label">Agents</div></div>`,d+=`<div class="stat-card"><div class="number">${r}</div><div class="label">Articles</div></div>`,d+=`<div class="stat-card"><div class="number">${a}</div><div class="label">Raw Entries</div></div>`,n&&n.length>0){let p=new Set(n.map(g=>g.nodeId));d+=`<div class="stat-card"><div class="number">${p.size}</div><div class="label">Mesh Nodes</div></div>`}d+="</div>",d+="<h2>Agent Wikis</h2>";for(let p of o){let g=p.unabsorbed>0?`<span style="color: #e6a700;">${p.unabsorbed} unabsorbed</span>`:'<span style="color: green;">up to date</span>',u=i.has(p.agentId)&&!t.listAgents().includes(p.agentId)?' <span class="tag" style="background:#fff3cd;color:#856404">remote</span>':"";if(d+='<div class="agent-card">',d+=`<h3><a href="/agent/${encodeURIComponent(p.agentId)}">${x(p.agentId)}</a>${u}</h3>`,d+=`<div class="agent-stats">
|
|
90
100
|
<span><strong>${p.totalArticles}</strong> articles</span>
|
|
91
101
|
<span><strong>${p.totalEntries}</strong> entries</span>
|
|
92
102
|
<span>${g}</span>
|
|
93
|
-
</div>`,p.articles.length>0){d+='<div class="article-list">';for(let h of p.articles)d+=`<a href="/agent/${encodeURIComponent(p.agentId)}/article/${encodeURIComponent(h.path)}"><span class="tag">${(h.tags||[]).slice(0,3).join(", ")}</span> ${x(h.title)}</a> `;d+="</div>"}d+="</div>"}return
|
|
103
|
+
</div>`,p.articles.length>0){d+='<div class="article-list">';for(let h of p.articles)d+=`<a href="/agent/${encodeURIComponent(p.agentId)}/article/${encodeURIComponent(h.path)}"><span class="tag">${(h.tags||[]).slice(0,3).join(", ")}</span> ${x(h.title)}</a> `;d+="</div>"}d+="</div>"}return B("Hub",Q(o),d)}function Jn(t,e,n){let o=n||t.summary(),s=o.find(l=>l.agentId===e);if(!s)return B("Not Found",Q(o),"<h1>Agent not found</h1>");let a=s.peerUrl!==void 0,r=t.getAgentEntries(e),c=s.articles||[],i=`<div class="breadcrumb"><a href="/">Hub</a> / ${x(e)}</div>`;if(i+=`<h1>${x(e)}</h1>`,a&&(i+=`<p><span class="tag" style="background:#fff3cd;color:#856404">remote @ ${x(s.nodeId)}</span></p>`),i+='<div class="stats">',i+=`<div class="stat-card"><div class="number">${s.totalArticles}</div><div class="label">Articles</div></div>`,i+=`<div class="stat-card"><div class="number">${s.totalEntries}</div><div class="label">Entries</div></div>`,i+=`<div class="stat-card"><div class="number">${s.unabsorbed}</div><div class="label">Unabsorbed</div></div>`,i+="</div>",c.length>0){i+="<h2>Articles</h2><table>",i+="<tr><th>Title</th><th>Tags</th></tr>";for(let l of c)i+=`<tr>
|
|
94
104
|
<td><a href="/agent/${encodeURIComponent(e)}/article/${encodeURIComponent(l.path)}">${x(l.title)}</a></td>
|
|
95
105
|
<td>${(l.tags||[]).slice(0,4).map(u=>`<span class="tag">${u}</span>`).join(" ")}</td>
|
|
96
106
|
</tr>`;i+="</table>"}let d=r.slice(-5).reverse();if(d.length>0){i+="<h2>Recent Entries</h2>";for(let l of d)i+=`<div class="entry-card">
|
|
97
107
|
<div class="meta-line">${l.date} via ${l.source} · <code>${l.id}</code></div>
|
|
98
108
|
<p>${x(l.content.slice(0,300))}${l.content.length>300?"...":""}</p>
|
|
99
|
-
</div>`}let g=t.getAgentWiki(e).lint();if(g.length>0){i+=`<h2>Health Issues (${g.length})</h2><table>`,i+="<tr><th>Type</th><th>Article</th><th>Issue</th></tr>";for(let l of g)i+=`<tr><td><span class="tag">${l.type}</span></td><td>${x(l.article)}</td><td>${x(l.message)}</td></tr>`;i+="</table>"}return
|
|
109
|
+
</div>`}let g=t.getAgentWiki(e).lint();if(g.length>0){i+=`<h2>Health Issues (${g.length})</h2><table>`,i+="<tr><th>Type</th><th>Article</th><th>Issue</th></tr>";for(let l of g)i+=`<tr><td><span class="tag">${l.type}</span></td><td>${x(l.article)}</td><td>${x(l.message)}</td></tr>`;i+="</table>"}return B(e,Q(o,e),i)}function Gn(t,e,n,o){let s=t.getAgentWiki(e),a=s.readArticle(n);if(!a)return null;let r=o||t.summary(),c=s.rebuildIndex(),i=new Map;for(let u of c.articles)i.set(u.title,u.path);let d=`/agent/${encodeURIComponent(e)}`,g=s.buildBacklinks()[a.meta.title]||[],l=`<div class="breadcrumb"><a href="/">Hub</a> / <a href="${d}">${x(e)}</a> / ${x(a.meta.title)}</div>`;if(l+=`<h1>${x(a.meta.title)}</h1>`,l+='<dl class="meta">',l+=`<dt>Tags</dt><dd>${(a.meta.tags||[]).map(u=>`<span class="tag">${u}</span>`).join(" ")}</dd>`,l+=`<dt>Owner</dt><dd>${x(a.meta.owner)}</dd>`,l+=`<dt>Created</dt><dd>${a.meta.created}</dd>`,l+=`<dt>Updated</dt><dd>${a.meta.lastUpdated}</dd>`,a.meta.sources?.length&&(l+=`<dt>Sources</dt><dd>${a.meta.sources.length} entries</dd>`),l+="</dl>",l+=Ne(a.content,i,d),g.length>0){l+='<div class="backlinks"><h4>Pages that link here:</h4><ul>';for(let u of g){let h=s.readArticle(u);l+=`<li><a href="${d}/article/${encodeURIComponent(u)}">${x(h?.meta.title||u)}</a></li>`}l+="</ul></div>"}return B(a.meta.title,Q(r,`${e}/${n}`),l)}function Kn(t,e){let n=e||t.summary(),s=t.getSharedStore().listEntries(),a='<div class="breadcrumb"><a href="/">Hub</a> / Entries</div>';a+=`<h1>All Raw Entries (${s.length})</h1>`;let r=new Map;for(let c of s){let i=r.get(c.date)||[];i.push(c),r.set(c.date,i)}for(let[c,i]of[...r].reverse()){a+=`<h2>${c} (${i.length})</h2>`;for(let d of i)a+=`<div class="entry-card">
|
|
100
110
|
<div class="meta-line">
|
|
101
111
|
<a href="/agent/${encodeURIComponent(d.agentId)}">${x(d.agentId)}</a>
|
|
102
112
|
via ${d.source} · <code>${d.id}</code>
|
|
103
113
|
</div>
|
|
104
114
|
<p>${x(d.content.slice(0,400))}${d.content.length>400?"...":""}</p>
|
|
105
|
-
</div>`}return
|
|
115
|
+
</div>`}return B("All Entries",Q(n),a)}function qn(t,e,n){let o=n||t.summary(),s=`<h1>Search: "${x(e)}"</h1>`,a=0;for(let r of o){let i=t.getAgentWiki(r.agentId).findRelevant(e,void 0,10);if(i.length>0){s+=`<h2>${x(r.agentId)} (${i.length})</h2>`;for(let d of i){let p=`/agent/${encodeURIComponent(r.agentId)}`;s+=`<div class="entry-card">
|
|
106
116
|
<div class="meta-line">${(d.meta.tags||[]).slice(0,3).map(g=>`<span class="tag">${g}</span>`).join(" ")}</div>
|
|
107
117
|
<h3><a href="${p}/article/${encodeURIComponent(d.path)}">${x(d.meta.title)}</a></h3>
|
|
108
118
|
<p>${x(d.content.slice(0,200))}...</p>
|
|
109
|
-
</div>`}a+=i.length}}return a===0&&(s+="<p>No matching articles found.</p>"),
|
|
119
|
+
</div>`}a+=i.length}}return a===0&&(s+="<p>No matching articles found.</p>"),B(`Search: ${e}`,Q(o),s)}function ke(t,e,n){let o=t.rebuildIndex(),s=Dt(o.articles.map(r=>({title:r.title,path:r.path,tags:r.tags}))),a=`<a href="/" class="logo">${x(e)}</a>`;a+='<form action="/search" method="get"><input type="text" name="q" class="search-box" placeholder="Search..."></form>',a+="<h2>Navigation</h2>",a+=`<a href="/"${n?"":' class="active"'}>Home</a>`,a+='<a href="/lint">Health Check</a>';for(let[r,c]of s){a+=`<h2>${Ot(r)}</h2>`;for(let i of c){let d=i.path===n;a+=`<a href="/article/${encodeURIComponent(i.path)}"${d?' class="active"':""}>${x(i.title)}</a>`}}return a}function Nt(t,e=4200,n,o=[],s="unified"){let a=new pe(t,void 0,s),r=o.length>0?new Oe(o):null;Bn(async(i,d)=>{let p=new URL(i.url||"/",`http://localhost:${e}`),g=decodeURIComponent(p.pathname),l=null,u=200;try{if(g.startsWith("/remote/")&&r){let h=g.slice(8).split("/article/");if(h.length===2){let[b,w]=h,k=b.indexOf("/"),v=decodeURIComponent(b.slice(0,k)),$=b.slice(k+1),C=await r.getRemoteArticle(v,$,w);if(C){let _=await r.getRemoteAgents(),te=[...a.summary(),..._.map(O=>({...O,agentId:`${O.agentId} @${O.nodeId}`}))],W=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote</span> ${x($)} @ ${x(v)}</div>`;W+=`<h1>${x(C.meta.title)}</h1>`,W+='<dl class="meta">',W+=`<dt>Tags</dt><dd>${(C.meta.tags||[]).map(O=>`<span class="tag">${O}</span>`).join(" ")}</dd>`,W+=`<dt>Owner</dt><dd>${x(C.meta.owner)}</dd>`,W+=`<dt>Source</dt><dd><span class="tag">remote</span> ${x(v)}</dd>`,W+=`<dt>Updated</dt><dd>${C.meta.lastUpdated}</dd>`,W+="</dl>";let H=new Map;W+=Ne(C.content,H),l=B(C.meta.title,Q(te),W)}}}if(!l&&n){let h=a.getAgentWiki(n);if(g==="/"||g===""){let b=h.rebuildIndex(),w=a.getAgentEntries(n),k=`<h1>${x(n)}</h1>`;if(k+='<div class="stats">',k+=`<div class="stat-card"><div class="number">${b.articles.length}</div><div class="label">Articles</div></div>`,k+=`<div class="stat-card"><div class="number">${w.length}</div><div class="label">Entries</div></div>`,k+="</div>",b.articles.length>0){k+="<h2>Articles</h2><table><tr><th>Title</th><th>Type</th><th>Updated</th></tr>";for(let v of b.articles)k+=`<tr><td><a href="/article/${encodeURIComponent(v.path)}">${x(v.title)}</a></td><td><span class="tag">${(v.tags||[]).slice(0,3).join(", ")}</span></td><td>${v.lastUpdated||""}</td></tr>`;k+="</table>"}l=B(n,ke(h,n),k)}else if(g.startsWith("/article/")){let b=g.slice(9),w=h.readArticle(b);if(w){let k=h.rebuildIndex(),v=new Map;for(let C of k.articles)v.set(C.title,C.path);let $=`<h1>${x(w.meta.title)}</h1>`;$+='<dl class="meta">',$+=`<dt>Tags</dt><dd>${(w.meta.tags||[]).map(C=>`<span class="tag">${C}</span>`).join(" ")}</dd>`,$+=`<dt>Updated</dt><dd>${w.meta.lastUpdated}</dd>`,w.meta.sources?.length&&($+=`<dt>Sources</dt><dd>${w.meta.sources.length} entries</dd>`),$+="</dl>",$+=Ne(w.content,v),l=B(w.meta.title,ke(h,n,b),$)}}else if(g==="/lint"){let b=h.lint(),w="<h1>Health Check</h1>";if(b.length===0)w+='<p style="color:green;">No issues.</p>';else{w+="<table><tr><th>Type</th><th>Article</th><th>Issue</th></tr>";for(let k of b)w+=`<tr><td><span class="tag">${k.type}</span></td><td>${x(k.article)}</td><td>${x(k.message)}</td></tr>`;w+="</table>"}l=B("Health Check",ke(h,n),w)}else if(g==="/search"){let b=p.searchParams.get("q")||"",w=h.findRelevant(b,void 0,20),k=`<h1>Search: "${x(b)}"</h1>`;for(let v of w)k+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent(v.path)}">${x(v.meta.title)}</a></h3><p>${x(v.content.slice(0,200))}...</p></div>`;w.length===0&&(k+="<p>No results.</p>"),l=B(`Search: ${b}`,ke(h,n),k)}}else{let h=r?await r.getRemoteAgents():[],b=a.summary(),w=new Map(b.map($=>[$.agentId,$])),k=[],v=new Set;for(let $ of b){let C=h.find(_=>_.agentId===$.agentId);C&&C.totalArticles>$.totalArticles?k.push({...C,totalEntries:Math.max($.totalEntries,C.totalEntries),unabsorbed:Math.max($.unabsorbed,C.unabsorbed)}):k.push($),v.add($.agentId)}for(let $ of h)v.has($.agentId)||(k.push($),v.add($.agentId));if(g==="/"||g==="")l=Fn(a,k,h);else if(g==="/entries")l=Kn(a,k);else if(g==="/search")l=qn(a,p.searchParams.get("q")||"",k);else if(g.startsWith("/agent/")){let $=g.slice(7),C=$.indexOf("/article/");if(C===-1)l=Jn(a,$,k);else{let _=$.slice(0,C),te=$.slice(C+9);if(l=Gn(a,_,te,k),!l&&r){let W=h.find(H=>H.agentId===_);if(W){let H=await r.getRemoteArticle(W.peerUrl,_,te);if(H){let O=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote @ ${x(W.nodeId)}</span> / ${x(_)}</div>`;O+=`<h1>${x(H.meta.title)}</h1>`,O+='<dl class="meta">',O+=`<dt>Tags</dt><dd>${(H.meta.tags||[]).map(xe=>`<span class="tag">${xe}</span>`).join(" ")}</dd>`,O+=`<dt>Source</dt><dd><span class="tag">remote</span> ${x(W.nodeId)}</dd>`,O+=`<dt>Updated</dt><dd>${H.meta.lastUpdated}</dd>`,O+="</dl>",O+=Ne(H.content,new Map),l=B(H.meta.title,Q(k),O)}}}}}}if(!l){u=404;let h=n?ke(a.getAgentWiki(n),n):Q(a.summary());l=B("Not Found",h,"<h1>Page not found</h1>")}}catch(h){u=500,l=B("Error","",`<h1>Error</h1><pre>${x(h.message)}</pre>`)}d.writeHead(u,{"Content-Type":"text/html; charset=utf-8"}),d.end(l)}).listen(e)}function Wt(t,e,n,o,s,a){let r=o.length>0?`
|
|
110
120
|
Existing articles:
|
|
111
121
|
${o.map(i=>`- ${i.title} [${(i.tags||[]).join(", ")}] (${i.path})`).join(`
|
|
112
122
|
`)}
|
|
@@ -114,7 +124,7 @@ ${o.map(i=>`- ${i.title} [${(i.tags||[]).join(", ")}] (${i.path})`).join(`
|
|
|
114
124
|
## Worldview
|
|
115
125
|
|
|
116
126
|
${n}
|
|
117
|
-
`:"";return t==="flat"?
|
|
127
|
+
`:"";return t==="flat"?Yn(e,c,r,s,a):t==="graph"?Vn(e,c,r,s,a):Xn(e,c,r,s,a)}function Yn(t,e,n,o,s){return`You are a wiki editor for the "${t}" agent. Compile raw entries into a personal wiki.
|
|
118
128
|
|
|
119
129
|
## Karpathy Pattern
|
|
120
130
|
|
|
@@ -156,7 +166,7 @@ After compiling, add a "gaps" array \u2014 topics MENTIONED but not yet covered.
|
|
|
156
166
|
|
|
157
167
|
ENTRIES (${s}):
|
|
158
168
|
|
|
159
|
-
${o}`}function
|
|
169
|
+
${o}`}function Vn(t,e,n,o,s){return`You are building a knowledge graph for the "${t}" agent. Compile raw entries into a structured wiki.
|
|
160
170
|
|
|
161
171
|
## Knowledge Graph Model
|
|
162
172
|
|
|
@@ -221,7 +231,7 @@ After compiling, add a "gaps" array \u2014 entities or events MENTIONED but miss
|
|
|
221
231
|
|
|
222
232
|
ENTRIES (${s}):
|
|
223
233
|
|
|
224
|
-
${o}`}function
|
|
234
|
+
${o}`}function Xn(t,e,n,o,s){return`You are compiling a personal wiki for the "${t}" agent.
|
|
225
235
|
|
|
226
236
|
## Your Job
|
|
227
237
|
|
|
@@ -286,9 +296,9 @@ Be specific. "X is undocumented" is useless. "Alice \u2014 stakeholder who issue
|
|
|
286
296
|
|
|
287
297
|
ENTRIES (${s}):
|
|
288
298
|
|
|
289
|
-
${o}`}import{resolve as
|
|
299
|
+
${o}`}import{resolve as ve}from"path";import{execSync as Zn}from"child_process";import{writeFileSync as eo,mkdirSync as to}from"fs";function me(t,e){return new pe(t||ve(process.cwd(),".agentx/wiki"),void 0,e||"graph")}function Ze(t){return t==="graph"?"Knowledge Graph":t==="flat"?"Karpathy Flat":"Unified"}var X=new Qn().name("wiki").description("wiki knowledge base management");X.command("status").description("show wiki status per agent").option("--dir <path>","wiki directory").option("--mode <mode>","unified (default), graph, or flat","unified").action(t=>{let e=t.mode,n=me(t.dir,e),o=n.summary(),a=n.getSharedStore().listEntries().length;console.log(),console.log(y.bold(` Wiki Hub Status [${Ze(e)}]`)),console.log(),console.log(` Total raw entries: ${a}`),console.log(` Agents: ${o.length}`),console.log();for(let c of o){let i=c.unabsorbed>0?y.yellow(`${c.unabsorbed} unabsorbed`):y.green("up to date");if(console.log(` ${y.cyan(c.agentId)}`),console.log(` Entries: ${c.totalEntries} Articles: ${c.totalArticles} ${i}`),c.articles.length>0){for(let d of c.articles.slice(0,3))console.log(y.dim(` - ${d.title} [${(d.tags||[]).slice(0,3).join(", ")}]`));c.articles.length>3&&console.log(y.dim(` ... and ${c.articles.length-3} more`))}console.log()}o.reduce((c,i)=>c+i.unabsorbed,0)>0&&(console.log(y.dim(" Run 'agentx wiki absorb' to compile all, or 'agentx wiki absorb --agent <id>' for one agent")),console.log())});X.command("lint").description("check wiki for issues per agent").option("--dir <path>","wiki directory").option("--mode <mode>","unified (default), graph, or flat","unified").option("--agent <id>","lint a specific agent's wiki").action(t=>{let e=me(t.dir,t.mode),n=t.agent?[t.agent]:e.listAgents(),o=0;console.log();for(let s of n){let r=e.getAgentWiki(s).lint();if(o+=r.length,r.length===0)console.log(` ${y.cyan(s)}: ${y.green("healthy")}`);else{console.log(` ${y.cyan(s)}: ${y.yellow(`${r.length} issues`)}`);for(let c of r){let i=c.type==="broken-link"?"x":c.type==="orphan"?"?":"!";console.log(` [${i}] ${y.dim(c.type)} ${c.article}: ${c.message}`)}}}console.log(),o===0&&console.log(y.green(" All agent wikis are healthy")),console.log()});X.command("absorb").description("compile unabsorbed entries into per-agent wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","unified (default), graph, or flat","unified").option("--agent <id>","absorb only this agent").option("--dry-run","preview without running").option("--max <n>","max entries per agent","20").action(async t=>{let e=t.mode,n=me(t.dir,e),o=t.agent?[t.agent]:n.listAgents(),s=parseInt(t.max),a=0;for(let r of o){let c=n.getUnabsorbedEntries(r).slice(0,s);if(c.length===0){console.log(` ${y.cyan(r)}: ${y.green("all absorbed")}`);continue}console.log(),console.log(y.bold(` ${y.cyan(r)}: ${c.length} entries to absorb`));for(let b of c.slice(0,3))console.log(y.dim(` [${b.date} via ${b.source}] ${b.content.slice(0,80)}...`));if(c.length>3&&console.log(y.dim(` ... and ${c.length-3} more`)),t.dryRun)continue;let i=n.getAgentWiki(r),d=i.rebuildIndex(),p=i.getWorldview()||n.getSharedStore().getWorldview()||"",g=c.map(b=>`--- ENTRY ${b.id} [${b.date} ${b.agentId} via ${b.source}] ---
|
|
290
300
|
${b.content}
|
|
291
301
|
--- END ENTRY ---`).join(`
|
|
292
302
|
|
|
293
|
-
`),l=
|
|
303
|
+
`),l=Wt(e,r,p,d.articles,g,c.length);console.log(y.dim(` Mode: ${Ze(e)}`));let u=ve(i.baseDir,"_tmp");to(u,{recursive:!0});let h=ve(u,"absorb-prompt.txt");eo(h,l),console.log(y.dim(" Compiling with Claude..."));try{let b;try{b=Zn(`cat '${h}' | 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:3e5,maxBuffer:10*1024*1024})}catch(A){if(b=A.stdout||"",!b)throw A}let w=b;try{let A=JSON.parse(b);w=A.result||A.content||"",w||(console.log(y.dim(` Claude envelope keys: ${Object.keys(A).join(", ")}`)),console.log(y.dim(` is_error: ${A.is_error}, stop_reason: ${A.stop_reason}`)))}catch{}let k,v=[],$=w.indexOf("{"),C=w.indexOf("["),_=$>=0&&(C<0||$<C)?$:C;if(_===-1){console.log(y.red(" No JSON found in response")),console.log(y.dim(w.slice(0,500)));continue}let te=w[_],W=te==="{"?"}":"]",H=0,O=-1;for(let A=_;A<w.length;A++)if(w[A]===te)H++;else if(w[A]===W&&(H--,H===0)){O=A+1;break}if(O===-1){console.log(y.red(" Unbalanced JSON"));continue}let xe=w.slice(_,O);try{let A=JSON.parse(xe);Array.isArray(A)?k=A:(k=A.articles||[],v=A.gaps||[])}catch(A){console.log(y.red(` JSON parse error: ${A.message}`)),console.log(y.dim(` First 300 chars: ${xe.slice(0,300)}`));continue}for(let A of k){let et=new Date().toISOString().slice(0,10);i.writeArticle(A.path,{title:A.title,tags:A.tags||[],owner:r,access:"public",created:et,lastUpdated:et,sources:A.sources||[]},A.content,r);let tt=(A.tags||[]).slice(0,5).join(", ");console.log(` ${y.green("+")} ${A.path}: ${A.title}`),tt&&console.log(y.dim(` [${tt}]`)),a++}if(v.length>0){console.log(),console.log(y.yellow(` Gaps detected (${v.length} missing pieces):`));for(let A of v)console.log(y.yellow(` ? ${A}`))}i.rebuildIndex()}catch(b){console.log(y.red(` Absorb failed: ${b.message?.slice(0,200)}`)),b.stderr&&console.log(y.dim(String(b.stderr).slice(0,300))),b.stdout&&console.log(y.dim("stdout: "+String(b.stdout).slice(0,300)))}}console.log(),t.dryRun?console.log(y.dim(" Dry run \u2014 no changes made")):a>0&&console.log(y.green(` ${a} articles compiled across ${o.length} agent(s)`)),console.log()});X.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(t=>{let o=me(t.dir).getSharedStore().listEntries();t.agent&&(o=o.filter(s=>s.agentId===t.agent)),console.log(),console.log(y.bold(` ${o.length} raw entries`)),console.log();for(let s of o.slice(-20))console.log(` ${y.dim(s.date)} ${y.cyan(s.agentId)} via ${s.source}: ${s.content.slice(0,80)}...`);o.length>20&&console.log(y.dim(` ... showing last 20 of ${o.length}`)),console.log()});X.command("serve").description("start a local web server to browse agent wikis (local + mesh)").option("--dir <path>","wiki directory").option("--mode <mode>","unified (default), graph, or flat","unified").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 t=>{let e=t.dir||ve(process.cwd(),".agentx/wiki"),n=parseInt(t.port),o=t.peer||[];if(o.length===0)try{let{loadDaemonConfig:s}=await import("./config-DCJYECL4.js");o=(s().mesh?.peers||[]).map(r=>r.url)}catch{}console.log(),console.log(y.bold(" AgentX Wiki Server")),console.log(),console.log(` ${y.green(">")} http://localhost:${n}`),t.agent?console.log(` Agent: ${y.cyan(t.agent)}`):console.log(` Mode: ${y.cyan("Hub")} (all agents)`),o.length>0&&console.log(` Mesh: ${y.cyan(o.length+" peer(s)")} \u2014 ${o.join(", ")}`),console.log(y.dim(` Wiki: ${e}`)),console.log(y.dim(" Press Ctrl+C to stop")),console.log(),Nt(e,n,t.agent,o,t.mode)});X.command("search <query>").description("search wiki articles").option("--dir <path>","wiki directory").option("--mode <mode>","unified (default), graph, or flat","unified").option("--agent <id>","search specific agent's wiki").action((t,e)=>{let n=me(e.dir,e.mode),o=e.agent?[e.agent]:n.listAgents();console.log();let s=0;for(let a of o){let c=n.getAgentWiki(a).findRelevant(t,void 0,10);if(c.length>0){console.log(y.bold(` ${y.cyan(a)}:`));for(let i of c)console.log(` ${i.meta.title} [${(i.meta.tags||[]).slice(0,3).join(", ")}]`),console.log(y.dim(` ${i.path} \u2014 ${i.content.slice(0,100)}...`));s+=c.length}}s===0&&console.log(y.dim(" No matching articles")),console.log()});X.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 t=>{let n=me(t.dir).getSharedStore(),o=[];if(t.peer)o=[t.peer];else try{let{loadDaemonConfig:r}=await import("./config-DCJYECL4.js");o=(r().mesh?.peers||[]).map(i=>i.url)}catch{console.log(y.red(" No --peer specified and no daemon config found")),console.log(y.dim(" Usage: agentx wiki sync --peer http://100.67.108.119:19900"));return}if(o.length===0){console.log(y.dim(" No mesh peers configured"));return}let s=new Set(n.listEntries().map(r=>r.id)),a=0;for(let r of o){console.log(),console.log(y.bold(` Syncing from ${r}...`));try{let c=await fetch(`${r}/wiki/entries`,{signal:AbortSignal.timeout(1e4)});if(!c.ok){console.log(y.red(` HTTP ${c.status}`));continue}let i=await c.json(),d=i.entries||[],p=i.nodeId||"unknown";console.log(y.dim(` Node: ${p} \u2014 ${d.length} entries`));let g=0;for(let l of d)s.has(l.id)||(t.dryRun||(n.addEntry({id:l.id,date:l.date,agentId:l.agentId,source:`${l.source}@${p}`,sourceContext:l.sourceContext,content:l.content}),s.add(l.id)),g++);g>0?console.log(y.green(` ${g} new entries${t.dryRun?" (dry run)":" synced"}`)):console.log(y.dim(" Already up to date")),a+=g;try{let l=await fetch(`${r}/wiki/agents`,{signal:AbortSignal.timeout(5e3)});if(l.ok){let u=await l.json();for(let h of u.agents||[])h.totalEntries>0&&console.log(y.dim(` ${h.agentId}: ${h.totalEntries} entries, ${h.totalArticles} articles`))}}catch{}}catch(c){c.cause?.code==="ECONNREFUSED"?console.log(y.red(" Connection refused")):console.log(y.red(` ${c.message}`))}}console.log(),a>0&&!t.dryRun?console.log(y.green(` ${a} entries synced. Run 'agentx wiki absorb' to compile.`)):a>0?console.log(y.dim(` ${a} entries would be synced (dry run)`)):console.log(y.dim(" All peers up to date")),console.log()});X.command("compare").description("compare all wiki compilation modes for an agent").option("--dir <path>","wiki directory").requiredOption("--agent <id>","agent to compare").action(t=>{let e=t.dir||ve(process.cwd(),".agentx/wiki"),n=t.agent,s=["flat","graph","unified"].map(i=>{let d=new pe(e,void 0,i),g=d.getAgentWiki(n).rebuildIndex(),l=d.getAgentEntries(n),u=d.getUnabsorbedEntries(n),h=new Set,b=0,w=new Set;for(let v of g.articles){for(let $ of v.tags||[])h.add($);b+=v.tags?.length||0;for(let $ of v.sources||[])w.add($)}let k=new Set(g.articles.map(v=>v.path.includes("/")?v.path.split("/")[0]:"/"));return{mode:i,label:Ze(i),articles:g.articles.length,entries:l.length,unabsorbed:u.length,uniqueTags:h.size,avgTags:g.articles.length>0?(b/g.articles.length).toFixed(1):"0",dirs:k.size,coverage:w.size,articleList:g.articles}});console.log(),console.log(y.bold(` Wiki Compare: ${n}`)),console.log(` Raw entries: ${s[0].entries}`),console.log();let a=22;console.log(` ${"".padEnd(20)} ${s.map(i=>i.label.padEnd(a)).join(" ")}`),console.log(` ${"\u2500".repeat(20)} ${s.map(()=>"\u2500".repeat(a)).join(" ")}`);let r=[["Articles",i=>String(i.articles)],["Unabsorbed",i=>String(i.unabsorbed)],["Unique tags",i=>String(i.uniqueTags)],["Avg tags/article",i=>i.avgTags],["Directories",i=>String(i.dirs)],["Entry coverage",i=>`${i.coverage}/${i.entries}`]];for(let[i,d]of r){let p=s.map(g=>d(g).padEnd(a));console.log(` ${i.padEnd(20)} ${p.join(" ")}`)}console.log();let c=(i,d)=>{let p=Math.max(...s.map(l=>l[i])),g=s.filter(l=>l[i]===p).map(l=>l.label);p>0&&console.log(y.dim(` Best ${d}: ${g.join(", ")} (${p})`))};c("uniqueTags","tag richness"),c("articles","article count"),c("coverage","entry coverage"),console.log()});process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function oo(){let t=await st(),e=new no().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(t.version||"1.0.0","-v, --version","display the version number");if(e.addCommand(Y).addCommand(mt).addCommand(lt).addCommand(ye).addCommand(je).addCommand(re).addCommand(de).addCommand(ee).addCommand(be).addCommand(Ee).addCommand(Fe).addCommand(Je).addCommand(se).addCommand($e).addCommand(ge).addCommand(X).addCommand(fe).addCommand(ht),process.argv.slice(2).length===0){e.outputHelp();return}e.parse()}oo();
|
|
294
304
|
//# sourceMappingURL=cli.js.map
|