agentix-cli 0.13.0 → 0.14.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 +50 -493
- package/dist/{agent-5KIMJI3F.js → agent-DW3NYIIL.js} +2 -2
- package/dist/board-dashboard-6TKE6NMV.js +1435 -0
- package/dist/board-dashboard-6TKE6NMV.js.map +1 -0
- package/dist/chunk-6U2XOQHU.js +7 -0
- package/dist/chunk-6U2XOQHU.js.map +1 -0
- package/dist/chunk-DYOBFJLX.js +11 -0
- package/dist/chunk-DYOBFJLX.js.map +1 -0
- package/dist/chunk-ITZEVXZ4.js +2 -0
- package/dist/chunk-ITZEVXZ4.js.map +1 -0
- package/dist/chunk-M33CB2H4.js +6 -0
- package/dist/chunk-M33CB2H4.js.map +1 -0
- package/dist/chunk-NJR5WF5E.js +5 -0
- package/dist/chunk-NJR5WF5E.js.map +1 -0
- package/dist/chunk-O72LPMBR.js +12 -0
- package/dist/chunk-O72LPMBR.js.map +1 -0
- package/dist/chunk-RB73FZXJ.js +133 -0
- package/dist/chunk-RB73FZXJ.js.map +1 -0
- package/dist/{chunk-VH23CDHL.js → chunk-UPT2UMF6.js} +42 -40
- package/dist/chunk-UPT2UMF6.js.map +1 -0
- package/dist/{chunk-D6EDMQRV.js → chunk-XVYMZ4M7.js} +3 -3
- package/dist/cli.js +54 -48
- package/dist/cli.js.map +1 -1
- package/dist/config-7QJ2QJIC.js +2 -0
- package/dist/config-mutator-GAEVGHDD.js +2 -0
- package/dist/index.d.ts +670 -69
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/registry-YVAG4EO5.js +2 -0
- package/dist/registry-YVAG4EO5.js.map +1 -0
- package/dist/{usage-dashboard-2TJQBFSH.js → usage-dashboard-M7AFIGMJ.js} +2 -2
- package/package.json +9 -1
- package/dist/chunk-34UAFPK4.js +0 -10
- package/dist/chunk-34UAFPK4.js.map +0 -1
- package/dist/chunk-CJ45Y2IR.js +0 -12
- package/dist/chunk-CJ45Y2IR.js.map +0 -1
- package/dist/chunk-T25UEXVK.js +0 -126
- package/dist/chunk-T25UEXVK.js.map +0 -1
- package/dist/chunk-VH23CDHL.js.map +0 -1
- package/dist/chunk-WJ6ZF6EZ.js +0 -6
- package/dist/chunk-WJ6ZF6EZ.js.map +0 -1
- package/dist/config-HAD5E4YX.js +0 -2
- package/dist/registry-CDWY7CLL.js +0 -2
- /package/dist/{agent-5KIMJI3F.js.map → agent-DW3NYIIL.js.map} +0 -0
- /package/dist/{chunk-D6EDMQRV.js.map → chunk-XVYMZ4M7.js.map} +0 -0
- /package/dist/{config-HAD5E4YX.js.map → config-7QJ2QJIC.js.map} +0 -0
- /package/dist/{registry-CDWY7CLL.js.map → config-mutator-GAEVGHDD.js.map} +0 -0
- /package/dist/{usage-dashboard-2TJQBFSH.js.map → usage-dashboard-M7AFIGMJ.js.map} +0 -0
package/dist/cli.js
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{g as
|
|
3
|
-
`));try{let
|
|
4
|
-
`);c=
|
|
5
|
-
(${(
|
|
6
|
-
`)),console.log(
|
|
7
|
-
Agent "${t.id}" added`)),console.log(d.dim(` Workspace: ${s}`)),console.log(d.dim(` Created: ${i.created.length} files (CLAUDE.md, AGENTS.md, settings, rules)`)),console.log()});X.command("remove <id>").alias("rm").description("remove an agent from config (keeps workspace)").action(e=>{let t=j();if(!t.agents?.[e]){console.log(d.red(` Agent "${e}" not found`));return}delete t.agents[e],O(t),console.log(d.green(` Agent "${e}" removed from config (workspace preserved)`))});var ae=new B().name("channel").description("manage channels \u2014 add telegram/whatsapp/discord, list");ae.command("list").alias("ls").description("list configured channels and bindings").action(()=>{let e=j();console.log();let t=e.channels?.telegram;if(t?.enabled){console.log(d.bold(" Telegram:"));for(let[i,r]of Object.entries(t.accounts||{}))console.log(` ${d.cyan(i)} -> agent: ${r.agentBinding}`)}else console.log(d.dim(" Telegram: disabled"));let s=e.channels?.whatsapp;if(s?.enabled){console.log(d.bold(" WhatsApp:")),console.log(` default agent: ${s.defaultAgent||"(none)"}`),console.log(` session: ${s.sessionDir||".agentx/whatsapp-sessions"}`);for(let i of s.routes||[]){let r=i.contact?`contact ${i.contact}`:`group "${i.group}"`;console.log(` ${r} -> agent: ${i.agent}`)}}else console.log(d.dim(" WhatsApp: disabled"));let o=e.channels?.discord;o?.enabled?(console.log(d.bold(" Discord:")),console.log(` agent: ${o.agentBinding||"(none)"}`)):console.log(d.dim(" Discord: disabled"));let n=e.channels?.gitlab;if(n?.enabled){console.log(d.bold(" GitLab:")),console.log(` host: ${n.host}`),console.log(` webhook: :${n.webhookPort}`);for(let i of n.routes||[])console.log(` ${i.project} -> agent: ${i.agent}`)}else console.log(d.dim(" GitLab: disabled"));console.log()});ae.command("add").description("add a channel (telegram, whatsapp, or discord)").action(async()=>{let e=j(),t=Object.keys(e.agents||{});if(!t.length){console.log(d.red(" No agents configured. Run: agentx agent add"));return}let s=t.map(n=>({title:`${n} (${e.agents[n].name})`,value:n})),{channelType:o}=await N({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(e.channels=e.channels||{},o==="telegram"){let n=await N([{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:s}]);if(!n.accountName||!n.token)return;try{let r=await(await fetch(`https://api.telegram.org/bot${n.token}/getMe`)).json();if(!r.ok)throw new Error(r.description);console.log(d.green(` Bot verified: @${r.result.username}`));let c=`@${r.result.username}`,a=e.agents[n.agentBinding].mentions||[];a.includes(c)||(a.push(c,r.result.username),e.agents[n.agentBinding].mentions=a)}catch(i){console.log(d.red(` Invalid token: ${i.message}`));return}e.channels.telegram=e.channels.telegram||{enabled:!1,accounts:{},policy:{dm:"pair",group:"mention-required"}},e.channels.telegram.enabled=!0,e.channels.telegram.accounts[n.accountName]={token:n.token,agentBinding:n.agentBinding},O(e),console.log(d.green(` Telegram "${n.accountName}" added -> ${n.agentBinding}`))}if(o==="whatsapp"){let n=await N([{type:"select",name:"defaultAgent",message:"Default agent for WhatsApp messages",choices:s},{type:"text",name:"sessionDir",message:"Session directory",initial:".agentx/whatsapp-sessions"},{type:"confirm",name:"addRoute",message:"Add a contact/group route?",initial:!0}]);if(!n.defaultAgent)return;let i=[],r=n.addRoute;for(;r;){let c=await N([{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:a=>a==="contact"?"Phone number (e.g. +21624309128)":"Group name (partial match)"},{type:"select",name:"agent",message:"Route to agent",choices:s},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);c.value&&c.agent&&i.push({[c.type]:c.value,agent:c.agent}),r=c.more}e.channels.whatsapp={enabled:!0,sessionDir:n.sessionDir,defaultAgent:n.defaultAgent,routes:i},O(e),_(I(process.cwd(),n.sessionDir),{recursive:!0}),console.log(d.green(` WhatsApp enabled (${i.length} routes, default: ${n.defaultAgent})`)),console.log(d.dim(" Start daemon to scan QR code: agentx daemon start"))}if(o==="discord"){let n=await N([{type:"text",name:"token",message:"Discord bot token (from developer portal)"},{type:"select",name:"agentBinding",message:"Bind to agent",choices:s}]);if(!n.token)return;e.channels.discord={enabled:!0,token:n.token,agentBinding:n.agentBinding},O(e),console.log(d.green(` Discord added -> ${n.agentBinding}`))}if(o==="gitlab"){let n=await N([{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(!n.token)return;let i=[],r=n.addRoute;for(;r;){let c=await N([{type:"text",name:"project",message:"GitLab project path (e.g. group/project, or * for default)"},{type:"select",name:"agent",message:"Route to agent",choices:s},{type:"confirm",name:"more",message:"Add another route?",initial:!1}]);c.project&&c.agent&&i.push({project:c.project,agent:c.agent}),r=c.more}e.channels.gitlab={enabled:!0,host:n.host,token:n.token,webhookPort:n.webhookPort,webhookSecret:n.webhookSecret||void 0,routes:i},O(e),console.log(d.green(` GitLab enabled (${i.length} routes, webhook :${n.webhookPort})`)),console.log(d.dim(` Add webhook in GitLab: ${n.host}/<project>/-/hooks`)),console.log(d.dim(` URL: http://your-server:${n.webhookPort}/`)),n.webhookSecret&&console.log(d.dim(` Secret token: ${n.webhookSecret}`)),console.log(d.dim(" Events: Comments, Issues, Merge requests, Pipeline"))}console.log(d.dim(" Restart daemon to apply: agentx daemon stop && agentx daemon start")),console.log()}});var Y=new B().name("cron").description("manage cron jobs \u2014 add, list, enable, disable");Y.command("list").alias("ls").description("list cron jobs").action(()=>{let e=j();console.log();for(let[t,s]of Object.entries(e.crons||{})){let o=s.enabled?d.green("\u25CF"):d.dim("\u25CB");console.log(` ${o} ${d.cyan(t)} \u2014 ${s.schedule} (${s.timezone})`),console.log(d.dim(` agent: ${s.agent} | timeout: ${s.timeout}s`))}Object.keys(e.crons||{}).length||console.log(d.dim(" No cron jobs configured")),console.log()});Y.command("add").description("add a cron job").action(async()=>{let e=j(),t=Object.keys(e.agents||{}),s=await N([{type:"text",name:"id",message:"Job ID (kebab-case)"},{type:"text",name:"schedule",message:"Cron expression (e.g. '0 9 * * *')"},{type:"text",name:"timezone",message:"Timezone",initial:"UTC"},{type:"select",name:"agent",message:"Agent",choices:t.map(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}]);!s.id||!s.schedule||(e.crons=e.crons||{},e.crons[s.id]={enabled:s.enabled,schedule:s.schedule,timezone:s.timezone,agent:s.agent,prompt:s.prompt,timeout:s.timeout,onError:["log"]},O(e),console.log(d.green(` Cron "${s.id}" added (${s.enabled?"enabled":"disabled"})`)),console.log())});Y.command("enable <id>").description("enable a cron job").action(e=>{let t=j();if(!t.crons?.[e]){console.log(d.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!0,O(t),console.log(d.green(` Cron "${e}" enabled`))});Y.command("disable <id>").description("disable a cron job").action(e=>{let t=j();if(!t.crons?.[e]){console.log(d.red(` Cron "${e}" not found`));return}t.crons[e].enabled=!1,O(t),console.log(d.green(` Cron "${e}" disabled`))});var V=new B().name("mesh").description("manage mesh peers \u2014 add, list, remove");V.command("list").alias("ls").description("list mesh peers").action(async()=>{let e=j();if(console.log(),!e.mesh?.enabled)console.log(d.dim(" Mesh: disabled"));else{console.log(d.bold(" Mesh peers:"));for(let t of e.mesh.peers||[]){let s=d.red("unreachable");try{let n=await(await fetch(`${t.url}/health`,{signal:AbortSignal.timeout(3e3)})).json();s=d.green(`healthy \u2014 ${n.agents?.length||0} agents`)}catch{}console.log(` ${d.cyan(t.name)} ${d.dim(t.url)} ${s}`)}}console.log()});V.command("add").description("add a mesh peer (another agentx server)").action(async()=>{let e=j(),t=await N([{type:"text",name:"name",message:"Peer name (e.g. 'server-2')"},{type:"text",name:"url",message:"Peer URL (e.g. 'http://100.67.108.119:18800')"},{type:"text",name:"token",message:"Auth token (optional, press enter to skip)"}]);if(!(!t.name||!t.url)){try{let o=await(await fetch(`${t.url}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)})).json();console.log(d.green(` Connected: ${o.name} (${o.skills?.length||0} agents)`))}catch{console.log(d.yellow(" Could not reach peer (adding anyway)"))}e.mesh=e.mesh||{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},e.mesh.enabled=!0,e.mesh.peers=e.mesh.peers||[],e.mesh.peers.push({url:t.url,name:t.name,...t.token?{token:t.token}:{}}),O(e),console.log(d.green(` Peer "${t.name}" added`)),console.log()}});V.command("remove <name>").alias("rm").description("remove a mesh peer").action(e=>{let t=j();t.mesh?.peers&&(t.mesh.peers=t.mesh.peers.filter(s=>s.name!==e),t.mesh.peers.length===0&&(t.mesh.enabled=!1),O(t),console.log(d.green(` Peer "${e}" removed`)))});var ie=new B().name("skill").description("manage skills \u2014 add to agent(s), list");ie.command("add <skillPath>").description("add a skill to agent(s)").option("-a, --agent <agents...>","target agent ID(s)").option("--all","add to all agents").action(async(e,t)=>{let s=j(),o=I(e);if(!R(o)){console.log(d.red(` Skill not found: ${o}`));return}let n=R(oe(o,"SKILL.md"))?o.split("/").pop():o.replace(/\/SKILL\.md$/,"").split("/").pop(),i;if(t.all)i=Object.keys(s.agents||{});else if(t.agent)i=t.agent;else{let r=Object.keys(s.agents||{});i=(await N({type:"multiselect",name:"agents",message:"Install to which agents?",choices:r.map(a=>({title:`${a} (${s.agents[a].name})`,value:a}))})).agents||[]}for(let r of i){let c=s.agents[r];if(!c){console.log(d.yellow(` Agent "${r}" not found, skipping`));continue}let a=I(c.workspace,".claude/skills",n);_(a,{recursive:!0}),R(oe(o,"SKILL.md"))?ge(o,a,{recursive:!0}):o.endsWith(".md")&&ge(o,oe(a,"SKILL.md")),console.log(d.green(` ${n} -> ${r} (${c.workspace})`))}console.log()});ie.command("list").alias("ls").description("list skills per agent").action(()=>{let e=j();console.log();for(let[t,s]of Object.entries(e.agents||{})){let o=I(s.workspace,".claude/skills"),n=R(o)?xe(o).filter(i=>!i.startsWith(".")):[];console.log(` ${d.cyan(t)}: ${n.length?n.join(", "):d.dim("(none)")}`)}console.log()});var pe=new B().name("hook").description("manage hooks \u2014 add to agent workspace");pe.command("add <agent>").description("add a hook to an agent's workspace settings").action(async e=>{let s=j().agents?.[e];if(!s){console.log(d.red(` Agent "${e}" not found`));return}let o=I(s.workspace,".claude/settings.json"),n=R(o)?JSON.parse(se(o,"utf-8")):{},i=await N([{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:a=>a==="command"?"Shell command":"URL"},{type:"text",name:"matcher",message:"Matcher regex (optional, e.g. 'Bash' to match tool)"}]);if(!i.event||!i.value)return;n.hooks=n.hooks||{},n.hooks[i.event]=n.hooks[i.event]||[];let c={hooks:[{type:i.type,...i.type==="command"?{command:i.value}:{url:i.value}}]};i.matcher&&(c.matcher=i.matcher),n.hooks[i.event].push(c),_(I(s.workspace,".claude"),{recursive:!0}),ve(o,JSON.stringify(n,null,2)),console.log(d.green(` Hook added to ${e}: ${i.event} -> ${i.type}`)),console.log()});var me=new B().name("migrate").description("import configuration from OpenClaw or other tools");me.command("openclaw [configPath]").description("import agents, channels, and crons from OpenClaw config").option("--dry-run","show what would be imported without writing").action(async(e,t)=>{let s=[e,I(process.env.HOME||"",".openclaw/openclaw.json"),I(process.env.HOME||"",".openclaw/clawdbot.json")].filter(Boolean),o;for(let y of s)if(y&&R(y)){o=y;break}if(!o){console.log(d.red(" OpenClaw config not found. Pass the path: agentx migrate openclaw /path/to/config.json"));return}console.log(d.dim(` Reading: ${o}`));let n=JSON.parse(se(o,"utf-8")),i=R(I(process.cwd(),"agentx.json"))?j():{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=n.agents?.list||[],c=n.bindings||[],a={};for(let y of c)y.match?.channel==="telegram"&&(a[y.match.accountId]=y.agentId);r.find(y=>y.id==="main"||y.default)&&(a.default="main");let l=0;for(let y of r){if(y.workspace?.startsWith("/data"))continue;let f=y.id.replace(/-agent$/,"").replace(/^main$/,"main-agent"),b=y.groupChat?.mentionPatterns||[];if(b.some($=>$===f)||b.push(f),i.agents[f]={name:y.name,workspace:y.workspace,tier:"claude-code",model:"claude-sonnet-4-6",mentions:b,maxConcurrent:y.id==="main"?2:1,systemPrompt:`You are ${y.name} on AgentX.`,permissionMode:"bypassPermissions"},l++,!t.dryRun){_(I(y.workspace,".claude/skills"),{recursive:!0});let{setupWorkspace:$}=await import("./workspace-setup-QQTCJY4B.js");$(f,i.agents[f])}}console.log(` ${d.green(l)} agents imported (workspaces set up with Claude Code best practices)`);let h=n.channels?.telegram?.accounts||{},p=0;for(let[y,f]of Object.entries(h)){if(!f.botToken)continue;let $=a[y]?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.channels.telegram.accounts[y]={token:f.botToken,agentBinding:$},i.channels.telegram.enabled=!0,p++}console.log(` ${d.green(p)} Telegram accounts imported`);let g=I(o,"../cron/jobs.json");if(R(g)){let y=JSON.parse(se(g,"utf-8")),f=0;for(let b of y.jobs||[]){let $=b.name||b.id,k=b.agentId?.replace(/-agent$/,"").replace(/^main$/,"main-agent")||"default";i.crons[$]={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"]},f++}console.log(` ${d.green(f)} cron jobs imported`)}t.dryRun?(console.log(d.yellow(`
|
|
8
|
-
Dry run \u2014 nothing written`)),console.log(JSON.stringify(
|
|
9
|
-
Migration complete! Review agentx.json and run: agentx daemon start`))),console.log()});var re=new B().name("config").description("validate and inspect configuration");re.command("check").description("validate agentx.json and check all workspaces").option("-c, --config <path>","path to agentx.json").action(async e=>{console.log();try{let t=M(e.config);console.log(d.green(" \u2713 Config valid")),console.log(d.dim(` Node: ${t.node.name} (${t.node.id})`)),console.log(d.dim(` Bind: ${t.node.bind}`)),console.log(d.dim(` Agents: ${Object.keys(t.agents).length}`)),console.log(d.dim(` Crons: ${Object.keys(t.crons).length}`)),console.log(d.dim(` Mesh peers: ${t.mesh.peers.length}`));let s=Object.keys(t.channels.telegram.accounts).length;console.log(d.dim(` Telegram: ${t.channels.telegram.enabled?`${s} accounts`:"disabled"}`)),console.log(d.dim(` WhatsApp: ${t.channels.whatsapp.enabled?`${t.channels.whatsapp.routes.length} routes`:"disabled"}`)),console.log(d.dim(` Discord: ${t.channels.discord?.enabled?"enabled":"disabled"}`));let o=ne(t);if(o.length){console.log(),console.log(d.yellow(" Warnings:"));for(let n of o)console.log(d.yellow(` \u26A0 ${n}`))}else console.log(d.green(" \u2713 All workspaces valid"));console.log();for(let[n,i]of Object.entries(t.agents)){let r=i.workspace,c=R(I(r,".claude")),a=R(I(r,"CLAUDE.md")),l=R(I(r,".claude/settings.json")),h=R(I(r,".claude/skills"))?xe(I(r,".claude/skills")).filter(g=>!g.startsWith(".")).length:0,p=[c?d.green("\u2713"):d.red("\u2717"),".claude",a?d.green("\u2713"):d.yellow("\u25CB"),"CLAUDE.md",l?d.green("\u2713"):d.yellow("\u25CB"),"settings",`${h} skills`];console.log(` ${d.cyan(n)}: ${p.join(" ")}`)}}catch(t){console.log(d.red(` \u2717 ${t.message}`))}console.log()});re.command("show").description("print the resolved configuration").option("-c, --config <path>","path to agentx.json").action(e=>{try{let t=M(e.config);console.log(JSON.stringify(t,null,2))}catch(t){console.log(d.red(t.message))}});import{Command as We}from"commander";import U from"chalk";var Q=new We().name("usage").description("token usage analysis and reporting");Q.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=M(),[t,s]=e.node.bind.split(":"),n=await(await fetch(`http://${t||"127.0.0.1"}:${s}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(U.bold(" Token Usage (last 7 days)")),console.log(),n.totalTasks===0){console.log(U.dim(" No tasks recorded yet")),console.log();return}let i=c=>c.toLocaleString();console.log(` Total: ${U.bold(i(n.totalTokens))} tokens across ${n.totalTasks} tasks`),console.log(` Input: ${i(n.totalInput)}`),console.log(` Output: ${i(n.totalOutput)}`),console.log(` Cache read: ${i(n.totalCacheRead)}`),console.log(` Cache create: ${i(n.totalCacheCreate)}`),n.cacheHitRatio>0&&console.log(` Cache hit: ${(n.cacheHitRatio*100).toFixed(1)}%`),n.totalErrors>0&&console.log(` Errors: ${U.red(String(n.totalErrors))}`),console.log(),console.log(U.bold(" By Agent:"));let r=Object.entries(n.byAgent||{});r.sort((c,a)=>a[1].total-c[1].total);for(let[c,a]of r){let l=i(a.total||a.input+a.output+a.cacheRead+a.cacheCreate),h=a.avgDuration?`${(a.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${U.cyan(c)}: ${l} tokens (${a.tasks} tasks) ${U.dim(h)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(U.red(" Daemon not running. Start with: agentx daemon start")):console.log(U.red(` ${e.message}`))}});Q.command("serve").description("start a web dashboard for token usage visualization").option("--port <n>","port number","4201").action(async e=>{let{startUsageDashboard:t}=await import("./usage-dashboard-2TJQBFSH.js");t(parseInt(e.port))});Q.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:s}=await import("fs"),{resolve:o}=await import("path"),n=o(process.cwd(),"scripts/token-report.py");if(!s(n)){console.log(U.red(` Script not found: ${n}`)),console.log(U.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(U.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${n}"`,{stdio:"inherit"})}catch{console.log(U.red(" Analysis failed. Is Python 3 installed?"))}});import{Command as Ge}from"commander";import u from"chalk";import{createServer as Pe}from"http";var ce=class{peers;cache=new Map;ttl=3e4;constructor(t){this.peers=t.map(s=>({url:s.replace(/\/$/,"")}))}async getRemoteAgents(){let t=[];return await Promise.all(this.peers.map(async s=>{try{let o=await this.fetchJson(`${s.url}/wiki/agents`);s.nodeId=o.nodeId;for(let n of o.agents||[])(n.totalEntries>0||n.totalArticles>0)&&t.push({...n,nodeId:o.nodeId,peerUrl:s.url})}catch{}})),t}async getRemoteArticles(t,s){try{return(await this.fetchJson(`${t}/wiki/articles?agent=${encodeURIComponent(s)}`)).articles||[]}catch{return[]}}async getRemoteArticle(t,s,o){try{let n=await this.fetchJson(`${t}/wiki/article?agent=${encodeURIComponent(s)}&path=${encodeURIComponent(o)}`);return{meta:{title:n.title,tags:n.tags||[],owner:n.owner,access:"public",created:n.created,lastUpdated:n.lastUpdated,sources:n.sources||[]},content:n.content,path:n.path}}catch{return null}}async fetchJson(t){let s=this.cache.get(t);if(s&&Date.now()-s.ts<this.ttl)return s.data;let o=await fetch(t,{signal:AbortSignal.timeout(5e3)});if(!o.ok)throw new Error(`HTTP ${o.status}`);let n=await o.json();return this.cache.set(t,{data:n,ts:Date.now()}),n}};function w(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function le(e,t,s=""){let o=w(e);return o=o.replace(/```(\w*)\n([\s\S]*?)```/g,(n,i,r)=>`<pre><code class="lang-${i}">${r.trim()}</code></pre>`),o=o.replace(/`([^`]+)`/g,"<code>$1</code>"),o=o.replace(/^(\|.+\|)\n(\|[-| :]+\|)\n((?:\|.+\|\n?)*)/gm,(n,i,r,c)=>{let a=i.split("|").filter(h=>h.trim()).map(h=>`<th>${h.trim()}</th>`).join(""),l=c.trim().split(`
|
|
10
|
-
`)
|
|
2
|
+
import{g as Pe,h as qe}from"./chunk-RB73FZXJ.js";import{f as le}from"./chunk-UPT2UMF6.js";import"./chunk-O72LPMBR.js";import{a as N,b as P,c as ee,d as Ge}from"./chunk-NJR5WF5E.js";import{b as Ke,c as z,d as be}from"./chunk-M33CB2H4.js";import"./chunk-QZP65I2H.js";import"./chunk-HI24KAEY.js";import"./chunk-DYOBFJLX.js";import"./chunk-6U2XOQHU.js";import"./chunk-ITZEVXZ4.js";import"./chunk-M7HKBG3V.js";import"./chunk-DSYKYZMT.js";import"./chunk-ZRYBSI5G.js";import"./chunk-QOYAX2FT.js";import{a as je}from"./chunk-4YCH6IZV.js";import{Command as kn}from"commander";import{Command as bt}from"commander";import f from"chalk";var K=new bt().name("daemon").description("manage the agentx daemon \u2014 start, stop, status, logs");K.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 Pe(t.config).start()});K.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"))}});K.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=z(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 ${wt(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=z(t.config),o=be(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}`))}}});K.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"})});K.command("watch").description("stream live agent activity (SSE)").option("-c, --config <path>","path to agentx.json").action(async t=>{let o=`http://${(z(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
|
+
`));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"))}});K.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=z(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"))}});K.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}`))}});K.action(async t=>{await new Pe(t.config).start()});function wt(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 $t}from"commander";import J from"chalk";import{existsSync as de,readFileSync as kt,writeFileSync as Ye,mkdirSync as Ve}from"fs";import{resolve as ae}from"path";var Xe=new $t().name("init").description("initialize agentx configuration in the current directory").option("--force","overwrite existing config").action(async t=>{let e=process.cwd(),n=ae(e,"agentx.json"),o=ae(e,".env"),s=ae(e,".agentx/sessions");if(console.log(),console.log(J.bold(" agentx init")),console.log(),de(n)&&!t.force){console.log(J.yellow(" agentx.json already exists. Use --force to overwrite.")),console.log();return}let a=[ae(e,"agentx.example.json"),ae(e,"node_modules/agentix-cli/agentx.example.json")],r;for(let i of a)if(de(i)){r=kt(i,"utf-8");break}r||(r=JSON.stringify({node:{id:je("os").hostname().toLowerCase().replace(/[^a-z0-9-]/g,"-"),name:je("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)),Ye(n,r),console.log(J.green(" \u2713 Created agentx.json")),de(o)||(Ye(o,["# AgentX environment variables","# ANTHROPIC_API_KEY=sk-ant-...","# TG_BOT_TOKEN=123456:ABC...","# MESH_TOKEN=your-mesh-secret",""].join(`
|
|
6
|
+
`)),console.log(J.green(" \u2713 Created .env template"))),de(s)||(Ve(s,{recursive:!0}),console.log(J.green(" \u2713 Created .agentx/sessions/")));let c=ae(e,".claude");de(c)||(Ve(c,{recursive:!0}),console.log(J.green(" \u2713 Created .claude/"))),console.log(),console.log(J.bold(" Next steps:")),console.log(` 1. Edit ${J.cyan("agentx.json")} \u2014 configure agents, channels, crons`),console.log(` 2. Edit ${J.cyan(".env")} \u2014 add API keys and bot tokens`),console.log(` 3. Run ${J.cyan("agentx daemon start")} \u2014 start the daemon`),console.log(` 4. Run ${J.cyan("agentx daemon status")} \u2014 verify everything`),console.log()});import{Command as X}from"commander";import m from"chalk";import _ from"prompts";import{readFileSync as $e,writeFileSync as vt,existsSync as M,mkdirSync as ie,cpSync as Re,readdirSync as Qe}from"fs";import{resolve as C,join as we}from"path";function W(){let t=C(process.cwd(),"agentx.json");if(!M(t))throw new Error("No agentx.json found. Run: agentx init");return JSON.parse($e(t,"utf-8"))}function F(t){return N(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 ge=new X().name("agent").description("manage agents \u2014 add, list, remove");ge.command("list").alias("ls").description("list configured agents").action(()=>{let t=W();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()});ge.command("add").description("add a new agent interactively").action(async()=>{let t=W(),e=await _([{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:C(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:we(e.workspace,e.id);ie(C(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-QQTCJY4B.js"),a=s(e.id,o,"19900",(...d)=>{console.log(m.dim(` ${d.join(" ")}`))}),r=C(process.cwd(),"src/wiki/SKILL.md"),c=C(__dirname,"../wiki/SKILL.md"),i=M(r)?r:c;M(i)&&(ie(C(n,".claude/skills/wiki"),{recursive:!0}),Re(i,C(n,".claude/skills/wiki/SKILL.md"))),t.agents=t.agents||{},t.agents[e.id]=o,await F(t),console.log(m.green(`
|
|
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
|
+
Dry run \u2014 nothing written`)),console.log(JSON.stringify(a,null,2))):(await F(a),console.log(m.green(`
|
|
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(`
|
|
10
|
+
`)+`
|
|
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
|
+
No boards configured in agentx.json.`)),console.log(Y.dim(` Add a 'boards' array \u2014 see docs/reference/boards.md for the schema.
|
|
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(`
|
|
14
|
+
No boards configured.
|
|
15
|
+
`));return}console.log();for(let e of t.boards){console.log(` ${Y.cyan(e.id)} \u2014 ${e.name}`);let n=e.source;console.log(Y.dim(` source: ${n.type}${n.projects?" ("+n.projects.join(", ")+")":""}`)),e.primaryToolLabel&&console.log(Y.dim(` primary label: ${e.primaryToolLabel}`)),console.log(Y.dim(` window: ${e.timeRangeDays} days`))}console.log()}catch(t){console.log(Y.red(` ${t.message}`)),process.exit(1)}});import{Command as yn}from"commander";import y from"chalk";import{createServer as rn}from"http";var Ce=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 Te(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(`
|
|
16
|
+
`).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 cn=`
|
|
11
17
|
:root {
|
|
12
18
|
--bg: #f8f9fa; --card: #ffffff; --border: #a2a9b1;
|
|
13
19
|
--link: #0645ad; --link-visited: #0b0080; --link-broken: #ba0000;
|
|
@@ -66,49 +72,49 @@ p code { background: #f5f5f5; padding: 1px 4px; border-radius: 2px; }
|
|
|
66
72
|
.breadcrumb { font-size: 13px; color: var(--text-dim); margin-bottom: 12px; }
|
|
67
73
|
.breadcrumb a { color: var(--link); text-decoration: none; }
|
|
68
74
|
@media (max-width: 768px) { .layout { grid-template-columns: 1fr; } .sidebar { position: static; height: auto; } .main { padding: 20px; } }
|
|
69
|
-
`;function
|
|
75
|
+
`;function L(t,e,n){return`<!DOCTYPE html>
|
|
70
76
|
<html lang="en">
|
|
71
77
|
<head>
|
|
72
78
|
<meta charset="utf-8">
|
|
73
79
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
74
|
-
<title>${
|
|
75
|
-
<style>${
|
|
80
|
+
<title>${x(t)} \u2014 AgentX Wiki</title>
|
|
81
|
+
<style>${cn}</style>
|
|
76
82
|
</head>
|
|
77
83
|
<body>
|
|
78
84
|
<div class="layout">
|
|
79
|
-
<nav class="sidebar">${
|
|
80
|
-
<main class="main">${
|
|
85
|
+
<nav class="sidebar">${e}</nav>
|
|
86
|
+
<main class="main">${n}</main>
|
|
81
87
|
</div>
|
|
82
88
|
</body>
|
|
83
|
-
</html>`}function
|
|
84
|
-
<span><strong>${
|
|
85
|
-
<span><strong>${
|
|
86
|
-
<span>${
|
|
87
|
-
</div>`,
|
|
88
|
-
<td><a href="/agent/${encodeURIComponent(
|
|
89
|
-
<td>${(
|
|
90
|
-
</tr>`;
|
|
91
|
-
<div class="meta-line">${
|
|
92
|
-
<p>${
|
|
93
|
-
</div>`}let
|
|
89
|
+
</html>`}function ut(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 ht(t){return t==="/"?"Root":t.split("/").pop().replace(/-/g," ")}function V(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=ut(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">${ht(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 ln(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
|
+
<span><strong>${p.totalArticles}</strong> articles</span>
|
|
91
|
+
<span><strong>${p.totalEntries}</strong> entries</span>
|
|
92
|
+
<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 L("Hub",V(o),d)}function dn(t,e,n){let o=n||t.summary(),s=o.find(l=>l.agentId===e);if(!s)return L("Not Found",V(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
|
+
<td><a href="/agent/${encodeURIComponent(e)}/article/${encodeURIComponent(l.path)}">${x(l.title)}</a></td>
|
|
95
|
+
<td>${(l.tags||[]).slice(0,4).map(u=>`<span class="tag">${u}</span>`).join(" ")}</td>
|
|
96
|
+
</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
|
+
<div class="meta-line">${l.date} via ${l.source} · <code>${l.id}</code></div>
|
|
98
|
+
<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 L(e,V(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+=Te(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 L(a.meta.title,V(r,`${e}/${n}`),l)}function mn(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">
|
|
94
100
|
<div class="meta-line">
|
|
95
|
-
<a href="/agent/${encodeURIComponent(
|
|
96
|
-
via ${
|
|
101
|
+
<a href="/agent/${encodeURIComponent(d.agentId)}">${x(d.agentId)}</a>
|
|
102
|
+
via ${d.source} · <code>${d.id}</code>
|
|
97
103
|
</div>
|
|
98
|
-
<p>${
|
|
99
|
-
</div>`}return
|
|
100
|
-
<div class="meta-line">${(
|
|
101
|
-
<h3><a href="${
|
|
102
|
-
<p>${
|
|
103
|
-
</div>`}i
|
|
104
|
+
<p>${x(d.content.slice(0,400))}${d.content.length>400?"...":""}</p>
|
|
105
|
+
</div>`}return L("All Entries",V(n),a)}function pn(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
|
+
<div class="meta-line">${(d.meta.tags||[]).slice(0,3).map(g=>`<span class="tag">${g}</span>`).join(" ")}</div>
|
|
107
|
+
<h3><a href="${p}/article/${encodeURIComponent(d.path)}">${x(d.meta.title)}</a></h3>
|
|
108
|
+
<p>${x(d.content.slice(0,200))}...</p>
|
|
109
|
+
</div>`}a+=i.length}}return a===0&&(s+="<p>No matching articles found.</p>"),L(`Search: ${e}`,V(o),s)}function he(t,e,n){let o=t.rebuildIndex(),s=ut(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>${ht(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 ft(t,e=4200,n,o=[],s="unified"){let a=new le(t,void 0,s),r=o.length>0?new Ce(o):null;rn(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),I=await r.getRemoteArticle(v,$,w);if(I){let H=await r.getRemoteAgents(),Z=[...a.summary(),...H.map(O=>({...O,agentId:`${O.agentId} @${O.nodeId}`}))],D=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote</span> ${x($)} @ ${x(v)}</div>`;D+=`<h1>${x(I.meta.title)}</h1>`,D+='<dl class="meta">',D+=`<dt>Tags</dt><dd>${(I.meta.tags||[]).map(O=>`<span class="tag">${O}</span>`).join(" ")}</dd>`,D+=`<dt>Owner</dt><dd>${x(I.meta.owner)}</dd>`,D+=`<dt>Source</dt><dd><span class="tag">remote</span> ${x(v)}</dd>`,D+=`<dt>Updated</dt><dd>${I.meta.lastUpdated}</dd>`,D+="</dl>";let U=new Map;D+=Te(I.content,U),l=L(I.meta.title,V(Z),D)}}}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=L(n,he(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 I of k.articles)v.set(I.title,I.path);let $=`<h1>${x(w.meta.title)}</h1>`;$+='<dl class="meta">',$+=`<dt>Tags</dt><dd>${(w.meta.tags||[]).map(I=>`<span class="tag">${I}</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>",$+=Te(w.content,v),l=L(w.meta.title,he(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=L("Health Check",he(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=L(`Search: ${b}`,he(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 I=h.find(H=>H.agentId===$.agentId);I&&I.totalArticles>$.totalArticles?k.push({...I,totalEntries:Math.max($.totalEntries,I.totalEntries),unabsorbed:Math.max($.unabsorbed,I.unabsorbed)}):k.push($),v.add($.agentId)}for(let $ of h)v.has($.agentId)||(k.push($),v.add($.agentId));if(g==="/"||g==="")l=ln(a,k,h);else if(g==="/entries")l=mn(a,k);else if(g==="/search")l=pn(a,p.searchParams.get("q")||"",k);else if(g.startsWith("/agent/")){let $=g.slice(7),I=$.indexOf("/article/");if(I===-1)l=dn(a,$,k);else{let H=$.slice(0,I),Z=$.slice(I+9);if(l=gn(a,H,Z,k),!l&&r){let D=h.find(U=>U.agentId===H);if(D){let U=await r.getRemoteArticle(D.peerUrl,H,Z);if(U){let O=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote @ ${x(D.nodeId)}</span> / ${x(H)}</div>`;O+=`<h1>${x(U.meta.title)}</h1>`,O+='<dl class="meta">',O+=`<dt>Tags</dt><dd>${(U.meta.tags||[]).map(ye=>`<span class="tag">${ye}</span>`).join(" ")}</dd>`,O+=`<dt>Source</dt><dd><span class="tag">remote</span> ${x(D.nodeId)}</dd>`,O+=`<dt>Updated</dt><dd>${U.meta.lastUpdated}</dd>`,O+="</dl>",O+=Te(U.content,new Map),l=L(U.meta.title,V(k),O)}}}}}}if(!l){u=404;let h=n?he(a.getAgentWiki(n),n):V(a.summary());l=L("Not Found",h,"<h1>Page not found</h1>")}}catch(h){u=500,l=L("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 yt(t,e,n,o,s,a){let r=o.length>0?`
|
|
104
110
|
Existing articles:
|
|
105
|
-
${o.map(
|
|
111
|
+
${o.map(i=>`- ${i.title} [${(i.tags||[]).join(", ")}] (${i.path})`).join(`
|
|
106
112
|
`)}
|
|
107
|
-
`:"",c=
|
|
113
|
+
`:"",c=n?`
|
|
108
114
|
## Worldview
|
|
109
115
|
|
|
110
|
-
${
|
|
111
|
-
`:"";return
|
|
116
|
+
${n}
|
|
117
|
+
`:"";return t==="flat"?un(e,c,r,s,a):t==="graph"?hn(e,c,r,s,a):fn(e,c,r,s,a)}function un(t,e,n,o,s){return`You are a wiki editor for the "${t}" agent. Compile raw entries into a personal wiki.
|
|
112
118
|
|
|
113
119
|
## Karpathy Pattern
|
|
114
120
|
|
|
@@ -117,7 +123,7 @@ ${s}
|
|
|
117
123
|
- Use [[wikilinks]] to cross-reference between articles.
|
|
118
124
|
- Synthesize \u2014 distill conversations into factual wiki articles, don't copy-paste.
|
|
119
125
|
- If an existing article covers the topic, produce an UPDATE with full merged content.
|
|
120
|
-
${
|
|
126
|
+
${e}${n}
|
|
121
127
|
## Tagging Rules
|
|
122
128
|
|
|
123
129
|
Tag every article with ALL relevant dimensions:
|
|
@@ -148,9 +154,9 @@ After compiling, add a "gaps" array \u2014 topics MENTIONED but not yet covered.
|
|
|
148
154
|
"gaps": ["Production server \u2014 mentioned but no article exists"]
|
|
149
155
|
}
|
|
150
156
|
|
|
151
|
-
ENTRIES (${
|
|
157
|
+
ENTRIES (${s}):
|
|
152
158
|
|
|
153
|
-
${o}`}function
|
|
159
|
+
${o}`}function hn(t,e,n,o,s){return`You are building a knowledge graph for the "${t}" agent. Compile raw entries into a structured wiki.
|
|
154
160
|
|
|
155
161
|
## Knowledge Graph Model
|
|
156
162
|
|
|
@@ -178,7 +184,7 @@ process, pattern, concept, report
|
|
|
178
184
|
6. Synthesize \u2014 distill conversations into factual wiki content
|
|
179
185
|
7. If an existing article covers the topic, produce an UPDATE with full merged content
|
|
180
186
|
8. Tag aggressively too \u2014 tags help narrow context
|
|
181
|
-
${
|
|
187
|
+
${e}${n}
|
|
182
188
|
## Gap Detection
|
|
183
189
|
|
|
184
190
|
After compiling, add a "gaps" array \u2014 entities or events MENTIONED but missing.
|
|
@@ -213,13 +219,13 @@ After compiling, add a "gaps" array \u2014 entities or events MENTIONED but miss
|
|
|
213
219
|
"gaps": ["Production server \u2014 entity mentioned but missing"]
|
|
214
220
|
}
|
|
215
221
|
|
|
216
|
-
ENTRIES (${
|
|
222
|
+
ENTRIES (${s}):
|
|
217
223
|
|
|
218
|
-
${o}`}function
|
|
224
|
+
${o}`}function fn(t,e,n,o,s){return`You are compiling a personal wiki for the "${t}" agent.
|
|
219
225
|
|
|
220
226
|
## Your Job
|
|
221
227
|
|
|
222
|
-
Read ${
|
|
228
|
+
Read ${s} raw conversation entries. For each, ask:
|
|
223
229
|
1. **Who** is mentioned? (people, agents, companies, teams)
|
|
224
230
|
2. **What** is this about? (project, server, tool, concept)
|
|
225
231
|
3. **What happened?** (deploy, incident, decision, report)
|
|
@@ -233,7 +239,7 @@ Then compile articles \u2014 one topic per article, synthesized (not copy-pasted
|
|
|
233
239
|
- Use whatever directory names make sense: projects/, incidents/, agents/ \u2014 your call.
|
|
234
240
|
- Use [[wikilinks]] to cross-reference between articles.
|
|
235
241
|
- If an existing article covers the topic, produce an UPDATE with full merged content.
|
|
236
|
-
${
|
|
242
|
+
${e}${n}
|
|
237
243
|
## How to Tag (CRITICAL)
|
|
238
244
|
|
|
239
245
|
Tags are how agents find relevant context. Tag EVERY article with ALL dimensions:
|
|
@@ -278,11 +284,11 @@ Be specific. "X is undocumented" is useless. "Alice \u2014 stakeholder who issue
|
|
|
278
284
|
]
|
|
279
285
|
}
|
|
280
286
|
|
|
281
|
-
ENTRIES (${
|
|
287
|
+
ENTRIES (${s}):
|
|
282
288
|
|
|
283
|
-
${o}`}import{resolve as
|
|
289
|
+
${o}`}import{resolve as fe}from"path";import{execSync as bn}from"child_process";import{writeFileSync as wn,mkdirSync as $n}from"fs";function ce(t,e){return new le(t||fe(process.cwd(),".agentx/wiki"),void 0,e||"graph")}function _e(t){return t==="graph"?"Knowledge Graph":t==="flat"?"Karpathy Flat":"Unified"}var q=new yn().name("wiki").description("wiki knowledge base management");q.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=ce(t.dir,e),o=n.summary(),a=n.getSharedStore().listEntries().length;console.log(),console.log(y.bold(` Wiki Hub Status [${_e(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())});q.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=ce(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()});q.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=ce(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}] ---
|
|
284
290
|
${b.content}
|
|
285
291
|
--- END ENTRY ---`).join(`
|
|
286
292
|
|
|
287
|
-
`),
|
|
293
|
+
`),l=yt(e,r,p,d.articles,g,c.length);console.log(y.dim(` Mode: ${_e(e)}`));let u=fe(i.baseDir,"_tmp");$n(u,{recursive:!0});let h=fe(u,"absorb-prompt.txt");wn(h,l),console.log(y.dim(" Compiling with Claude..."));try{let b;try{b=bn(`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("{"),I=w.indexOf("["),H=$>=0&&(I<0||$<I)?$:I;if(H===-1){console.log(y.red(" No JSON found in response")),console.log(y.dim(w.slice(0,500)));continue}let Z=w[H],D=Z==="{"?"}":"]",U=0,O=-1;for(let A=H;A<w.length;A++)if(w[A]===Z)U++;else if(w[A]===D&&(U--,U===0)){O=A+1;break}if(O===-1){console.log(y.red(" Unbalanced JSON"));continue}let ye=w.slice(H,O);try{let A=JSON.parse(ye);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: ${ye.slice(0,300)}`));continue}for(let A of k){let Fe=new Date().toISOString().slice(0,10);i.writeArticle(A.path,{title:A.title,tags:A.tags||[],owner:r,access:"public",created:Fe,lastUpdated:Fe,sources:A.sources||[]},A.content,r);let Je=(A.tags||[]).slice(0,5).join(", ");console.log(` ${y.green("+")} ${A.path}: ${A.title}`),Je&&console.log(y.dim(` [${Je}]`)),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()});q.command("entries").description("list raw entries").option("--dir <path>","wiki directory").option("--agent <id>","filter by agent").action(t=>{let o=ce(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()});q.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||fe(process.cwd(),".agentx/wiki"),n=parseInt(t.port),o=t.peer||[];if(o.length===0)try{let{loadDaemonConfig:s}=await import("./config-7QJ2QJIC.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(),ft(e,n,t.agent,o,t.mode)});q.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=ce(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()});q.command("sync").description("pull raw entries from mesh peers into local wiki").option("--dir <path>","wiki directory").option("--peer <url>","sync from a specific peer URL (e.g., http://100.67.108.119:19900)").option("--dry-run","show what would be synced without writing").action(async t=>{let n=ce(t.dir).getSharedStore(),o=[];if(t.peer)o=[t.peer];else try{let{loadDaemonConfig:r}=await import("./config-7QJ2QJIC.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()});q.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||fe(process.cwd(),".agentx/wiki"),n=t.agent,s=["flat","graph","unified"].map(i=>{let d=new le(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:_e(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 vn(){let t=await qe(),e=new kn().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(K).addCommand(Xe).addCommand(ge).addCommand(ke).addCommand(se).addCommand(re).addCommand(Q).addCommand(me).addCommand(ve).addCommand(De).addCommand(Ne).addCommand(te).addCommand(ue).addCommand(Ee).addCommand(q),process.argv.slice(2).length===0){e.outputHelp();return}e.parse()}vn();
|
|
288
294
|
//# sourceMappingURL=cli.js.map
|